@andocorp/cli 0.5.15 → 0.5.17
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +14 -8
- package/dist/cli.js +54 -39
- package/package.json +3 -3
package/dist/cli.js
CHANGED
|
@@ -2,12 +2,12 @@
|
|
|
2
2
|
import { createRequire as __createRequire } from "node:module";
|
|
3
3
|
const require = __createRequire(import.meta.url);
|
|
4
4
|
var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __getProtoOf=Object.getPrototypeOf,__hasOwnProp=Object.prototype.hasOwnProperty;var __require=(x=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(x,{get:(a,b)=>(typeof require<"u"?require:a)[b]}):x)(function(x){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+x+'" is not supported')});var __esm=(fn,res,err)=>function(){if(err)throw err[0];try{return fn&&(res=(0,fn[__getOwnPropNames(fn)[0]])(fn=0)),res}catch(e){throw err=[e],e}};var __commonJS=(cb,mod)=>function(){try{return mod||(0,cb[__getOwnPropNames(cb)[0]])((mod={exports:{}}).exports,mod),mod.exports}catch(e){throw mod=0,e}};var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to};var __toESM=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target,mod)),__toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod);var require_polyfills=__commonJS({"../../node_modules/graceful-fs/polyfills.js"(exports,module){var constants2=__require("constants"),origCwd=process.cwd,cwd=null,platform=process.env.GRACEFUL_FS_PLATFORM||process.platform;process.cwd=function(){return cwd||(cwd=origCwd.call(process)),cwd};try{process.cwd()}catch{}typeof process.chdir=="function"&&(chdir=process.chdir,process.chdir=function(d){cwd=null,chdir.call(process,d)},Object.setPrototypeOf&&Object.setPrototypeOf(process.chdir,chdir));var chdir;module.exports=patch;function patch(fs){constants2.hasOwnProperty("O_SYMLINK")&&process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)&&patchLchmod(fs),fs.lutimes||patchLutimes(fs),fs.chown=chownFix(fs.chown),fs.fchown=chownFix(fs.fchown),fs.lchown=chownFix(fs.lchown),fs.chmod=chmodFix(fs.chmod),fs.fchmod=chmodFix(fs.fchmod),fs.lchmod=chmodFix(fs.lchmod),fs.chownSync=chownFixSync(fs.chownSync),fs.fchownSync=chownFixSync(fs.fchownSync),fs.lchownSync=chownFixSync(fs.lchownSync),fs.chmodSync=chmodFixSync(fs.chmodSync),fs.fchmodSync=chmodFixSync(fs.fchmodSync),fs.lchmodSync=chmodFixSync(fs.lchmodSync),fs.stat=statFix(fs.stat),fs.fstat=statFix(fs.fstat),fs.lstat=statFix(fs.lstat),fs.statSync=statFixSync(fs.statSync),fs.fstatSync=statFixSync(fs.fstatSync),fs.lstatSync=statFixSync(fs.lstatSync),fs.chmod&&!fs.lchmod&&(fs.lchmod=function(path,mode,cb){cb&&process.nextTick(cb)},fs.lchmodSync=function(){}),fs.chown&&!fs.lchown&&(fs.lchown=function(path,uid,gid,cb){cb&&process.nextTick(cb)},fs.lchownSync=function(){}),platform==="win32"&&(fs.rename=typeof fs.rename!="function"?fs.rename:(function(fs$rename){function rename7(from,to,cb){var start=Date.now(),backoff=0;fs$rename(from,to,function CB(er){if(er&&(er.code==="EACCES"||er.code==="EPERM"||er.code==="EBUSY")&&Date.now()-start<6e4){setTimeout(function(){fs.stat(to,function(stater,st){stater&&stater.code==="ENOENT"?fs$rename(from,to,CB):cb(er)})},backoff),backoff<100&&(backoff+=10);return}cb&&cb(er)})}return Object.setPrototypeOf&&Object.setPrototypeOf(rename7,fs$rename),rename7})(fs.rename)),fs.read=typeof fs.read!="function"?fs.read:(function(fs$read){function read(fd,buffer,offset,length,position,callback_){var callback;if(callback_&&typeof callback_=="function"){var eagCounter=0;callback=function(er,_,__){if(er&&er.code==="EAGAIN"&&eagCounter<10)return eagCounter++,fs$read.call(fs,fd,buffer,offset,length,position,callback);callback_.apply(this,arguments)}}return fs$read.call(fs,fd,buffer,offset,length,position,callback)}return Object.setPrototypeOf&&Object.setPrototypeOf(read,fs$read),read})(fs.read),fs.readSync=typeof fs.readSync!="function"?fs.readSync:(function(fs$readSync){return function(fd,buffer,offset,length,position){for(var eagCounter=0;;)try{return fs$readSync.call(fs,fd,buffer,offset,length,position)}catch(er){if(er.code==="EAGAIN"&&eagCounter<10){eagCounter++;continue}throw er}}})(fs.readSync);function patchLchmod(fs2){fs2.lchmod=function(path,mode,callback){fs2.open(path,constants2.O_WRONLY|constants2.O_SYMLINK,mode,function(err,fd){if(err){callback&&callback(err);return}fs2.fchmod(fd,mode,function(err2){fs2.close(fd,function(err22){callback&&callback(err2||err22)})})})},fs2.lchmodSync=function(path,mode){var fd=fs2.openSync(path,constants2.O_WRONLY|constants2.O_SYMLINK,mode),threw=!0,ret;try{ret=fs2.fchmodSync(fd,mode),threw=!1}finally{if(threw)try{fs2.closeSync(fd)}catch{}else fs2.closeSync(fd)}return ret}}function patchLutimes(fs2){constants2.hasOwnProperty("O_SYMLINK")&&fs2.futimes?(fs2.lutimes=function(path,at,mt,cb){fs2.open(path,constants2.O_SYMLINK,function(er,fd){if(er){cb&&cb(er);return}fs2.futimes(fd,at,mt,function(er2){fs2.close(fd,function(er22){cb&&cb(er2||er22)})})})},fs2.lutimesSync=function(path,at,mt){var fd=fs2.openSync(path,constants2.O_SYMLINK),ret,threw=!0;try{ret=fs2.futimesSync(fd,at,mt),threw=!1}finally{if(threw)try{fs2.closeSync(fd)}catch{}else fs2.closeSync(fd)}return ret}):fs2.futimes&&(fs2.lutimes=function(_a4,_b2,_c,cb){cb&&process.nextTick(cb)},fs2.lutimesSync=function(){})}function chmodFix(orig){return orig&&function(target,mode,cb){return orig.call(fs,target,mode,function(er){chownErOk(er)&&(er=null),cb&&cb.apply(this,arguments)})}}function chmodFixSync(orig){return orig&&function(target,mode){try{return orig.call(fs,target,mode)}catch(er){if(!chownErOk(er))throw er}}}function chownFix(orig){return orig&&function(target,uid,gid,cb){return orig.call(fs,target,uid,gid,function(er){chownErOk(er)&&(er=null),cb&&cb.apply(this,arguments)})}}function chownFixSync(orig){return orig&&function(target,uid,gid){try{return orig.call(fs,target,uid,gid)}catch(er){if(!chownErOk(er))throw er}}}function statFix(orig){return orig&&function(target,options,cb){typeof options=="function"&&(cb=options,options=null);function callback(er,stats){stats&&(stats.uid<0&&(stats.uid+=4294967296),stats.gid<0&&(stats.gid+=4294967296)),cb&&cb.apply(this,arguments)}return options?orig.call(fs,target,options,callback):orig.call(fs,target,callback)}}function statFixSync(orig){return orig&&function(target,options){var stats=options?orig.call(fs,target,options):orig.call(fs,target);return stats&&(stats.uid<0&&(stats.uid+=4294967296),stats.gid<0&&(stats.gid+=4294967296)),stats}}function chownErOk(er){if(!er||er.code==="ENOSYS")return!0;var nonroot=!process.getuid||process.getuid()!==0;return!!(nonroot&&(er.code==="EINVAL"||er.code==="EPERM"))}}}});var require_legacy_streams=__commonJS({"../../node_modules/graceful-fs/legacy-streams.js"(exports,module){var Stream=__require("stream").Stream;module.exports=legacy;function legacy(fs){return{ReadStream,WriteStream};function ReadStream(path,options){if(!(this instanceof ReadStream))return new ReadStream(path,options);Stream.call(this);var self=this;this.path=path,this.fd=null,this.readable=!0,this.paused=!1,this.flags="r",this.mode=438,this.bufferSize=64*1024,options=options||{};for(var keys=Object.keys(options),index=0,length=keys.length;index<length;index++){var key=keys[index];this[key]=options[key]}if(this.encoding&&this.setEncoding(this.encoding),this.start!==void 0){if(typeof this.start!="number")throw TypeError("start must be a Number");if(this.end===void 0)this.end=1/0;else if(typeof this.end!="number")throw TypeError("end must be a Number");if(this.start>this.end)throw new Error("start must be <= end");this.pos=this.start}if(this.fd!==null){process.nextTick(function(){self._read()});return}fs.open(this.path,this.flags,this.mode,function(err,fd){if(err){self.emit("error",err),self.readable=!1;return}self.fd=fd,self.emit("open",fd),self._read()})}function WriteStream(path,options){if(!(this instanceof WriteStream))return new WriteStream(path,options);Stream.call(this),this.path=path,this.fd=null,this.writable=!0,this.flags="w",this.encoding="binary",this.mode=438,this.bytesWritten=0,options=options||{};for(var keys=Object.keys(options),index=0,length=keys.length;index<length;index++){var key=keys[index];this[key]=options[key]}if(this.start!==void 0){if(typeof this.start!="number")throw TypeError("start must be a Number");if(this.start<0)throw new Error("start must be >= zero");this.pos=this.start}this.busy=!1,this._queue=[],this.fd===null&&(this._open=fs.open,this._queue.push([this._open,this.path,this.flags,this.mode,void 0]),this.flush())}}}});var require_clone=__commonJS({"../../node_modules/graceful-fs/clone.js"(exports,module){"use strict";module.exports=clone2;var getPrototypeOf=Object.getPrototypeOf||function(obj){return obj.__proto__};function clone2(obj){if(obj===null||typeof obj!="object")return obj;if(obj instanceof Object)var copy={__proto__:getPrototypeOf(obj)};else var copy=Object.create(null);return Object.getOwnPropertyNames(obj).forEach(function(key){Object.defineProperty(copy,key,Object.getOwnPropertyDescriptor(obj,key))}),copy}}});var require_graceful_fs=__commonJS({"../../node_modules/graceful-fs/graceful-fs.js"(exports,module){var fs=__require("fs"),polyfills=require_polyfills(),legacy=require_legacy_streams(),clone2=require_clone(),util=__require("util"),gracefulQueue,previousSymbol;typeof Symbol=="function"&&typeof Symbol.for=="function"?(gracefulQueue=Symbol.for("graceful-fs.queue"),previousSymbol=Symbol.for("graceful-fs.previous")):(gracefulQueue="___graceful-fs.queue",previousSymbol="___graceful-fs.previous");function noop2(){}function publishQueue(context,queue2){Object.defineProperty(context,gracefulQueue,{get:function(){return queue2}})}var debug=noop2;util.debuglog?debug=util.debuglog("gfs4"):/\bgfs4\b/i.test(process.env.NODE_DEBUG||"")&&(debug=function(){var m=util.format.apply(util,arguments);m="GFS4: "+m.split(/\n/).join(`
|
|
5
|
-
GFS4: `),console.error(m)});fs[gracefulQueue]||(queue=global[gracefulQueue]||[],publishQueue(fs,queue),fs.close=(function(fs$close){function close(fd,cb){return fs$close.call(fs,fd,function(err){err||resetQueue(),typeof cb=="function"&&cb.apply(this,arguments)})}return Object.defineProperty(close,previousSymbol,{value:fs$close}),close})(fs.close),fs.closeSync=(function(fs$closeSync){function closeSync(fd){fs$closeSync.apply(fs,arguments),resetQueue()}return Object.defineProperty(closeSync,previousSymbol,{value:fs$closeSync}),closeSync})(fs.closeSync),/\bgfs4\b/i.test(process.env.NODE_DEBUG||"")&&process.on("exit",function(){debug(fs[gracefulQueue]),__require("assert").equal(fs[gracefulQueue].length,0)}));var queue;global[gracefulQueue]||publishQueue(global,fs[gracefulQueue]);module.exports=patch(clone2(fs));process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH&&!fs.__patched&&(module.exports=patch(fs),fs.__patched=!0);function patch(fs2){polyfills(fs2),fs2.gracefulify=patch,fs2.createReadStream=createReadStream,fs2.createWriteStream=createWriteStream;var fs$readFile=fs2.readFile;fs2.readFile=readFile7;function readFile7(path,options,cb){return typeof options=="function"&&(cb=options,options=null),go$readFile(path,options,cb);function go$readFile(path2,options2,cb2,startTime){return fs$readFile(path2,options2,function(err){err&&(err.code==="EMFILE"||err.code==="ENFILE")?enqueue([go$readFile,[path2,options2,cb2],err,startTime||Date.now(),Date.now()]):typeof cb2=="function"&&cb2.apply(this,arguments)})}}var fs$writeFile=fs2.writeFile;fs2.writeFile=writeFile6;function writeFile6(path,data,options,cb){return typeof options=="function"&&(cb=options,options=null),go$writeFile(path,data,options,cb);function go$writeFile(path2,data2,options2,cb2,startTime){return fs$writeFile(path2,data2,options2,function(err){err&&(err.code==="EMFILE"||err.code==="ENFILE")?enqueue([go$writeFile,[path2,data2,options2,cb2],err,startTime||Date.now(),Date.now()]):typeof cb2=="function"&&cb2.apply(this,arguments)})}}var fs$appendFile=fs2.appendFile;fs$appendFile&&(fs2.appendFile=appendFile);function appendFile(path,data,options,cb){return typeof options=="function"&&(cb=options,options=null),go$appendFile(path,data,options,cb);function go$appendFile(path2,data2,options2,cb2,startTime){return fs$appendFile(path2,data2,options2,function(err){err&&(err.code==="EMFILE"||err.code==="ENFILE")?enqueue([go$appendFile,[path2,data2,options2,cb2],err,startTime||Date.now(),Date.now()]):typeof cb2=="function"&&cb2.apply(this,arguments)})}}var fs$copyFile=fs2.copyFile;fs$copyFile&&(fs2.copyFile=copyFile);function copyFile(src,dest,flags,cb){return typeof flags=="function"&&(cb=flags,flags=0),go$copyFile(src,dest,flags,cb);function go$copyFile(src2,dest2,flags2,cb2,startTime){return fs$copyFile(src2,dest2,flags2,function(err){err&&(err.code==="EMFILE"||err.code==="ENFILE")?enqueue([go$copyFile,[src2,dest2,flags2,cb2],err,startTime||Date.now(),Date.now()]):typeof cb2=="function"&&cb2.apply(this,arguments)})}}var fs$readdir=fs2.readdir;fs2.readdir=readdir4;var noReaddirOptionVersions=/^v[0-5]\./;function readdir4(path,options,cb){typeof options=="function"&&(cb=options,options=null);var go$readdir=noReaddirOptionVersions.test(process.version)?function(path2,options2,cb2,startTime){return fs$readdir(path2,fs$readdirCallback(path2,options2,cb2,startTime))}:function(path2,options2,cb2,startTime){return fs$readdir(path2,options2,fs$readdirCallback(path2,options2,cb2,startTime))};return go$readdir(path,options,cb);function fs$readdirCallback(path2,options2,cb2,startTime){return function(err,files){err&&(err.code==="EMFILE"||err.code==="ENFILE")?enqueue([go$readdir,[path2,options2,cb2],err,startTime||Date.now(),Date.now()]):(files&&files.sort&&files.sort(),typeof cb2=="function"&&cb2.call(this,err,files))}}}if(process.version.substr(0,4)==="v0.8"){var legStreams=legacy(fs2);ReadStream=legStreams.ReadStream,WriteStream=legStreams.WriteStream}var fs$ReadStream=fs2.ReadStream;fs$ReadStream&&(ReadStream.prototype=Object.create(fs$ReadStream.prototype),ReadStream.prototype.open=ReadStream$open);var fs$WriteStream=fs2.WriteStream;fs$WriteStream&&(WriteStream.prototype=Object.create(fs$WriteStream.prototype),WriteStream.prototype.open=WriteStream$open),Object.defineProperty(fs2,"ReadStream",{get:function(){return ReadStream},set:function(val){ReadStream=val},enumerable:!0,configurable:!0}),Object.defineProperty(fs2,"WriteStream",{get:function(){return WriteStream},set:function(val){WriteStream=val},enumerable:!0,configurable:!0});var FileReadStream=ReadStream;Object.defineProperty(fs2,"FileReadStream",{get:function(){return FileReadStream},set:function(val){FileReadStream=val},enumerable:!0,configurable:!0});var FileWriteStream=WriteStream;Object.defineProperty(fs2,"FileWriteStream",{get:function(){return FileWriteStream},set:function(val){FileWriteStream=val},enumerable:!0,configurable:!0});function ReadStream(path,options){return this instanceof ReadStream?(fs$ReadStream.apply(this,arguments),this):ReadStream.apply(Object.create(ReadStream.prototype),arguments)}function ReadStream$open(){var that=this;open3(that.path,that.flags,that.mode,function(err,fd){err?(that.autoClose&&that.destroy(),that.emit("error",err)):(that.fd=fd,that.emit("open",fd),that.read())})}function WriteStream(path,options){return this instanceof WriteStream?(fs$WriteStream.apply(this,arguments),this):WriteStream.apply(Object.create(WriteStream.prototype),arguments)}function WriteStream$open(){var that=this;open3(that.path,that.flags,that.mode,function(err,fd){err?(that.destroy(),that.emit("error",err)):(that.fd=fd,that.emit("open",fd))})}function createReadStream(path,options){return new fs2.ReadStream(path,options)}function createWriteStream(path,options){return new fs2.WriteStream(path,options)}var fs$open=fs2.open;fs2.open=open3;function open3(path,flags,mode,cb){return typeof mode=="function"&&(cb=mode,mode=null),go$open(path,flags,mode,cb);function go$open(path2,flags2,mode2,cb2,startTime){return fs$open(path2,flags2,mode2,function(err,fd){err&&(err.code==="EMFILE"||err.code==="ENFILE")?enqueue([go$open,[path2,flags2,mode2,cb2],err,startTime||Date.now(),Date.now()]):typeof cb2=="function"&&cb2.apply(this,arguments)})}}return fs2}function enqueue(elem){debug("ENQUEUE",elem[0].name,elem[1]),fs[gracefulQueue].push(elem),retry()}var retryTimer;function resetQueue(){for(var now=Date.now(),i2=0;i2<fs[gracefulQueue].length;++i2)fs[gracefulQueue][i2].length>2&&(fs[gracefulQueue][i2][3]=now,fs[gracefulQueue][i2][4]=now);retry()}function retry(){if(clearTimeout(retryTimer),retryTimer=void 0,fs[gracefulQueue].length!==0){var elem=fs[gracefulQueue].shift(),fn=elem[0],args=elem[1],err=elem[2],startTime=elem[3],lastTime=elem[4];if(startTime===void 0)debug("RETRY",fn.name,args),fn.apply(null,args);else if(Date.now()-startTime>=6e4){debug("TIMEOUT",fn.name,args);var cb=args.pop();typeof cb=="function"&&cb.call(null,err)}else{var sinceAttempt=Date.now()-lastTime,sinceStart=Math.max(lastTime-startTime,1),desiredDelay=Math.min(sinceStart*1.2,100);sinceAttempt>=desiredDelay?(debug("RETRY",fn.name,args),fn.apply(null,args.concat([startTime]))):fs[gracefulQueue].push(elem)}retryTimer===void 0&&(retryTimer=setTimeout(retry,0))}}}});var require_retry_operation=__commonJS({"../../node_modules/retry/lib/retry_operation.js"(exports,module){function RetryOperation(timeouts,options){typeof options=="boolean"&&(options={forever:options}),this._originalTimeouts=JSON.parse(JSON.stringify(timeouts)),this._timeouts=timeouts,this._options=options||{},this._maxRetryTime=options&&options.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}module.exports=RetryOperation;RetryOperation.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts};RetryOperation.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timeouts=[],this._cachedTimeouts=null};RetryOperation.prototype.retry=function(err){if(this._timeout&&clearTimeout(this._timeout),!err)return!1;var currentTime=new Date().getTime();if(err&¤tTime-this._operationStart>=this._maxRetryTime)return this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(err);var timeout=this._timeouts.shift();if(timeout===void 0)if(this._cachedTimeouts)this._errors.splice(this._errors.length-1,this._errors.length),this._timeouts=this._cachedTimeouts.slice(0),timeout=this._timeouts.shift();else return!1;var self=this,timer=setTimeout(function(){self._attempts++,self._operationTimeoutCb&&(self._timeout=setTimeout(function(){self._operationTimeoutCb(self._attempts)},self._operationTimeout),self._options.unref&&self._timeout.unref()),self._fn(self._attempts)},timeout);return this._options.unref&&timer.unref(),!0};RetryOperation.prototype.attempt=function(fn,timeoutOps){this._fn=fn,timeoutOps&&(timeoutOps.timeout&&(this._operationTimeout=timeoutOps.timeout),timeoutOps.cb&&(this._operationTimeoutCb=timeoutOps.cb));var self=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){self._operationTimeoutCb()},self._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)};RetryOperation.prototype.try=function(fn){console.log("Using RetryOperation.try() is deprecated"),this.attempt(fn)};RetryOperation.prototype.start=function(fn){console.log("Using RetryOperation.start() is deprecated"),this.attempt(fn)};RetryOperation.prototype.start=RetryOperation.prototype.try;RetryOperation.prototype.errors=function(){return this._errors};RetryOperation.prototype.attempts=function(){return this._attempts};RetryOperation.prototype.mainError=function(){if(this._errors.length===0)return null;for(var counts={},mainError=null,mainErrorCount=0,i2=0;i2<this._errors.length;i2++){var error2=this._errors[i2],message=error2.message,count=(counts[message]||0)+1;counts[message]=count,count>=mainErrorCount&&(mainError=error2,mainErrorCount=count)}return mainError}}});var require_retry=__commonJS({"../../node_modules/retry/lib/retry.js"(exports){var RetryOperation=require_retry_operation();exports.operation=function(options){var timeouts=exports.timeouts(options);return new RetryOperation(timeouts,{forever:options&&options.forever,unref:options&&options.unref,maxRetryTime:options&&options.maxRetryTime})};exports.timeouts=function(options){if(options instanceof Array)return[].concat(options);var opts={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var key in options)opts[key]=options[key];if(opts.minTimeout>opts.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var timeouts=[],i2=0;i2<opts.retries;i2++)timeouts.push(this.createTimeout(i2,opts));return options&&options.forever&&!timeouts.length&&timeouts.push(this.createTimeout(i2,opts)),timeouts.sort(function(a,b){return a-b}),timeouts};exports.createTimeout=function(attempt,opts){var random2=opts.randomize?Math.random()+1:1,timeout=Math.round(random2*opts.minTimeout*Math.pow(opts.factor,attempt));return timeout=Math.min(timeout,opts.maxTimeout),timeout};exports.wrap=function(obj,options,methods){if(options instanceof Array&&(methods=options,options=null),!methods){methods=[];for(var key in obj)typeof obj[key]=="function"&&methods.push(key)}for(var i2=0;i2<methods.length;i2++){var method=methods[i2],original=obj[method];obj[method]=function(original2){var op=exports.operation(options),args=Array.prototype.slice.call(arguments,1),callback=args.pop();args.push(function(err){op.retry(err)||(err&&(arguments[0]=op.mainError()),callback.apply(this,arguments))}),op.attempt(function(){original2.apply(obj,args)})}.bind(obj,original),obj[method].options=options}}}});var require_retry2=__commonJS({"../../node_modules/retry/index.js"(exports,module){module.exports=require_retry()}});var require_signals=__commonJS({"../../node_modules/signal-exit/signals.js"(exports,module){module.exports=["SIGABRT","SIGALRM","SIGHUP","SIGINT","SIGTERM"];process.platform!=="win32"&&module.exports.push("SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");process.platform==="linux"&&module.exports.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT","SIGUNUSED")}});var require_signal_exit=__commonJS({"../../node_modules/signal-exit/index.js"(exports,module){var process2=global.process,processOk=function(process3){return process3&&typeof process3=="object"&&typeof process3.removeListener=="function"&&typeof process3.emit=="function"&&typeof process3.reallyExit=="function"&&typeof process3.listeners=="function"&&typeof process3.kill=="function"&&typeof process3.pid=="number"&&typeof process3.on=="function"};processOk(process2)?(assert2=__require("assert"),signals=require_signals(),isWin=/^win/i.test(process2.platform),EE=__require("events"),typeof EE!="function"&&(EE=EE.EventEmitter),process2.__signal_exit_emitter__?emitter=process2.__signal_exit_emitter__:(emitter=process2.__signal_exit_emitter__=new EE,emitter.count=0,emitter.emitted={}),emitter.infinite||(emitter.setMaxListeners(1/0),emitter.infinite=!0),module.exports=function(cb,opts){if(!processOk(global.process))return function(){};assert2.equal(typeof cb,"function","a callback must be provided for exit handler"),loaded===!1&&load();var ev="exit";opts&&opts.alwaysLast&&(ev="afterexit");var remove=function(){emitter.removeListener(ev,cb),emitter.listeners("exit").length===0&&emitter.listeners("afterexit").length===0&&unload()};return emitter.on(ev,cb),remove},unload=function(){!loaded||!processOk(global.process)||(loaded=!1,signals.forEach(function(sig){try{process2.removeListener(sig,sigListeners[sig])}catch{}}),process2.emit=originalProcessEmit,process2.reallyExit=originalProcessReallyExit,emitter.count-=1)},module.exports.unload=unload,emit=function(event,code2,signal){emitter.emitted[event]||(emitter.emitted[event]=!0,emitter.emit(event,code2,signal))},sigListeners={},signals.forEach(function(sig){sigListeners[sig]=function(){if(processOk(global.process)){var listeners=process2.listeners(sig);listeners.length===emitter.count&&(unload(),emit("exit",null,sig),emit("afterexit",null,sig),isWin&&sig==="SIGHUP"&&(sig="SIGINT"),process2.kill(process2.pid,sig))}}}),module.exports.signals=function(){return signals},loaded=!1,load=function(){loaded||!processOk(global.process)||(loaded=!0,emitter.count+=1,signals=signals.filter(function(sig){try{return process2.on(sig,sigListeners[sig]),!0}catch{return!1}}),process2.emit=processEmit,process2.reallyExit=processReallyExit)},module.exports.load=load,originalProcessReallyExit=process2.reallyExit,processReallyExit=function(code2){processOk(global.process)&&(process2.exitCode=code2||0,emit("exit",process2.exitCode,null),emit("afterexit",process2.exitCode,null),originalProcessReallyExit.call(process2,process2.exitCode))},originalProcessEmit=process2.emit,processEmit=function(ev,arg){if(ev==="exit"&&processOk(global.process)){arg!==void 0&&(process2.exitCode=arg);var ret=originalProcessEmit.apply(this,arguments);return emit("exit",process2.exitCode,null),emit("afterexit",process2.exitCode,null),ret}else return originalProcessEmit.apply(this,arguments)}):module.exports=function(){return function(){}};var assert2,signals,isWin,EE,emitter,unload,emit,sigListeners,loaded,load,originalProcessReallyExit,processReallyExit,originalProcessEmit,processEmit}});var require_mtime_precision=__commonJS({"../../node_modules/proper-lockfile/lib/mtime-precision.js"(exports,module){"use strict";var cacheSymbol=Symbol();function probe(file,fs,callback){let cachedPrecision=fs[cacheSymbol];if(cachedPrecision)return fs.stat(file,(err,stat2)=>{if(err)return callback(err);callback(null,stat2.mtime,cachedPrecision)});let mtime=new Date(Math.ceil(Date.now()/1e3)*1e3+5);fs.utimes(file,mtime,mtime,err=>{if(err)return callback(err);fs.stat(file,(err2,stat2)=>{if(err2)return callback(err2);let precision=stat2.mtime.getTime()%1e3===0?"s":"ms";Object.defineProperty(fs,cacheSymbol,{value:precision}),callback(null,stat2.mtime,precision)})})}function getMtime(precision){let now=Date.now();return precision==="s"&&(now=Math.ceil(now/1e3)*1e3),new Date(now)}module.exports.probe=probe;module.exports.getMtime=getMtime}});var require_lockfile=__commonJS({"../../node_modules/proper-lockfile/lib/lockfile.js"(exports,module){"use strict";var path=__require("path"),fs=require_graceful_fs(),retry=require_retry2(),onExit=require_signal_exit(),mtimePrecision=require_mtime_precision(),locks={};function getLockFile(file,options){return options.lockfilePath||`${file}.lock`}function resolveCanonicalPath(file,options,callback){if(!options.realpath)return callback(null,path.resolve(file));options.fs.realpath(file,callback)}function acquireLock(file,options,callback){let lockfilePath=getLockFile(file,options);options.fs.mkdir(lockfilePath,err=>{if(!err)return mtimePrecision.probe(lockfilePath,options.fs,(err2,mtime,mtimePrecision2)=>{if(err2)return options.fs.rmdir(lockfilePath,()=>{}),callback(err2);callback(null,mtime,mtimePrecision2)});if(err.code!=="EEXIST")return callback(err);if(options.stale<=0)return callback(Object.assign(new Error("Lock file is already being held"),{code:"ELOCKED",file}));options.fs.stat(lockfilePath,(err2,stat2)=>{if(err2)return err2.code==="ENOENT"?acquireLock(file,{...options,stale:0},callback):callback(err2);if(!isLockStale(stat2,options))return callback(Object.assign(new Error("Lock file is already being held"),{code:"ELOCKED",file}));removeLock(file,options,err3=>{if(err3)return callback(err3);acquireLock(file,{...options,stale:0},callback)})})})}function isLockStale(stat2,options){return stat2.mtime.getTime()<Date.now()-options.stale}function removeLock(file,options,callback){options.fs.rmdir(getLockFile(file,options),err=>{if(err&&err.code!=="ENOENT")return callback(err);callback()})}function updateLock(file,options){let lock2=locks[file];lock2.updateTimeout||(lock2.updateDelay=lock2.updateDelay||options.update,lock2.updateTimeout=setTimeout(()=>{lock2.updateTimeout=null,options.fs.stat(lock2.lockfilePath,(err,stat2)=>{let isOverThreshold=lock2.lastUpdate+options.stale<Date.now();if(err)return err.code==="ENOENT"||isOverThreshold?setLockAsCompromised(file,lock2,Object.assign(err,{code:"ECOMPROMISED"})):(lock2.updateDelay=1e3,updateLock(file,options));if(!(lock2.mtime.getTime()===stat2.mtime.getTime()))return setLockAsCompromised(file,lock2,Object.assign(new Error("Unable to update lock within the stale threshold"),{code:"ECOMPROMISED"}));let mtime=mtimePrecision.getMtime(lock2.mtimePrecision);options.fs.utimes(lock2.lockfilePath,mtime,mtime,err2=>{let isOverThreshold2=lock2.lastUpdate+options.stale<Date.now();if(!lock2.released){if(err2)return err2.code==="ENOENT"||isOverThreshold2?setLockAsCompromised(file,lock2,Object.assign(err2,{code:"ECOMPROMISED"})):(lock2.updateDelay=1e3,updateLock(file,options));lock2.mtime=mtime,lock2.lastUpdate=Date.now(),lock2.updateDelay=null,updateLock(file,options)}})})},lock2.updateDelay),lock2.updateTimeout.unref&&lock2.updateTimeout.unref())}function setLockAsCompromised(file,lock2,err){lock2.released=!0,lock2.updateTimeout&&clearTimeout(lock2.updateTimeout),locks[file]===lock2&&delete locks[file],lock2.options.onCompromised(err)}function lock(file,options,callback){options={stale:1e4,update:null,realpath:!0,retries:0,fs,onCompromised:err=>{throw err},...options},options.retries=options.retries||0,options.retries=typeof options.retries=="number"?{retries:options.retries}:options.retries,options.stale=Math.max(options.stale||0,2e3),options.update=options.update==null?options.stale/2:options.update||0,options.update=Math.max(Math.min(options.update,options.stale/2),1e3),resolveCanonicalPath(file,options,(err,file2)=>{if(err)return callback(err);let operation=retry.operation(options.retries);operation.attempt(()=>{acquireLock(file2,options,(err2,mtime,mtimePrecision2)=>{if(operation.retry(err2))return;if(err2)return callback(operation.mainError());let lock2=locks[file2]={lockfilePath:getLockFile(file2,options),mtime,mtimePrecision:mtimePrecision2,options,lastUpdate:Date.now()};updateLock(file2,options),callback(null,releasedCallback=>{if(lock2.released)return releasedCallback&&releasedCallback(Object.assign(new Error("Lock is already released"),{code:"ERELEASED"}));unlock(file2,{...options,realpath:!1},releasedCallback)})})})})}function unlock(file,options,callback){options={fs,realpath:!0,...options},resolveCanonicalPath(file,options,(err,file2)=>{if(err)return callback(err);let lock2=locks[file2];if(!lock2)return callback(Object.assign(new Error("Lock is not acquired/owned by you"),{code:"ENOTACQUIRED"}));lock2.updateTimeout&&clearTimeout(lock2.updateTimeout),lock2.released=!0,delete locks[file2],removeLock(file2,options,callback)})}function check2(file,options,callback){options={stale:1e4,realpath:!0,fs,...options},options.stale=Math.max(options.stale||0,2e3),resolveCanonicalPath(file,options,(err,file2)=>{if(err)return callback(err);options.fs.stat(getLockFile(file2,options),(err2,stat2)=>err2?err2.code==="ENOENT"?callback(null,!1):callback(err2):callback(null,!isLockStale(stat2,options)))})}function getLocks(){return locks}onExit(()=>{for(let file in locks){let options=locks[file].options;try{options.fs.rmdirSync(getLockFile(file,options))}catch{}}});module.exports.lock=lock;module.exports.unlock=unlock;module.exports.check=check2;module.exports.getLocks=getLocks}});var require_adapter=__commonJS({"../../node_modules/proper-lockfile/lib/adapter.js"(exports,module){"use strict";var fs=require_graceful_fs();function createSyncFs(fs2){let methods=["mkdir","realpath","stat","rmdir","utimes"],newFs={...fs2};return methods.forEach(method=>{newFs[method]=(...args)=>{let callback=args.pop(),ret;try{ret=fs2[`${method}Sync`](...args)}catch(err){return callback(err)}callback(null,ret)}}),newFs}function toPromise(method){return(...args)=>new Promise((resolve4,reject)=>{args.push((err,result)=>{err?reject(err):resolve4(result)}),method(...args)})}function toSync(method){return(...args)=>{let err,result;if(args.push((_err,_result)=>{err=_err,result=_result}),method(...args),err)throw err;return result}}function toSyncOptions(options){if(options={...options},options.fs=createSyncFs(options.fs||fs),typeof options.retries=="number"&&options.retries>0||options.retries&&typeof options.retries.retries=="number"&&options.retries.retries>0)throw Object.assign(new Error("Cannot use retries with the sync api"),{code:"ESYNC"});return options}module.exports={toPromise,toSync,toSyncOptions}}});var require_proper_lockfile=__commonJS({"../../node_modules/proper-lockfile/index.js"(exports,module){"use strict";var lockfile4=require_lockfile(),{toPromise,toSync,toSyncOptions}=require_adapter();async function lock(file,options){let release=await toPromise(lockfile4.lock)(file,options);return toPromise(release)}function lockSync(file,options){let release=toSync(lockfile4.lock)(file,toSyncOptions(options));return toSync(release)}function unlock(file,options){return toPromise(lockfile4.unlock)(file,options)}function unlockSync(file,options){return toSync(lockfile4.unlock)(file,toSyncOptions(options))}function check2(file,options){return toPromise(lockfile4.check)(file,options)}function checkSync(file,options){return toSync(lockfile4.check)(file,toSyncOptions(options))}module.exports=lock;module.exports.lock=lock;module.exports.unlock=unlock;module.exports.lockSync=lockSync;module.exports.unlockSync=unlockSync;module.exports.check=check2;module.exports.checkSync=checkSync}});function parseArgs4(args){if(args===void 0)return{};if(!isSimpleObject(args))throw new Error(`The arguments to a Convex function must be an object. Received: ${args}`);return args}function validateDeploymentUrl(deploymentUrl){if(typeof deploymentUrl>"u")throw new Error("Client created with undefined deployment address. If you used an environment variable, check that it's set.");if(typeof deploymentUrl!="string")throw new Error(`Invalid deployment address: found ${deploymentUrl}".`);if(!(deploymentUrl.startsWith("http:")||deploymentUrl.startsWith("https:")))throw new Error(`Invalid deployment address: Must start with "https://" or "http://". Found "${deploymentUrl}".`);try{new URL(deploymentUrl)}catch{throw new Error(`Invalid deployment address: "${deploymentUrl}" is not a valid URL. If you believe this URL is correct, use the \`skipConvexDeploymentUrlCheck\` option to bypass this.`)}if(deploymentUrl.endsWith(".convex.site"))throw new Error(`Invalid deployment address: "${deploymentUrl}" ends with .convex.site, which is used for HTTP Actions. Convex deployment URLs typically end with .convex.cloud? If you believe this URL is correct, use the \`skipConvexDeploymentUrlCheck\` option to bypass this.`)}function isSimpleObject(value){let isObject2=typeof value=="object",prototype=Object.getPrototypeOf(value),isSimple=prototype===null||prototype===Object.prototype||prototype?.constructor?.name==="Object";return isObject2&&isSimple}var init_common=__esm({"../../node_modules/convex/dist/esm/common/index.js"(){"use strict"}});var functionName,init_functionName=__esm({"../../node_modules/convex/dist/esm/server/functionName.js"(){"use strict";functionName=Symbol.for("functionName")}});function extractReferencePath(reference){return reference[toReferencePath]??null}function isFunctionHandle(s){return s.startsWith("function://")}function getFunctionAddress(functionReference){let functionAddress;if(typeof functionReference=="string")isFunctionHandle(functionReference)?functionAddress={functionHandle:functionReference}:functionAddress={name:functionReference};else if(functionReference[functionName])functionAddress={name:functionReference[functionName]};else{let referencePath=extractReferencePath(functionReference);if(!referencePath)throw new Error(`${functionReference} is not a functionReference`);functionAddress={reference:referencePath}}return functionAddress}var toReferencePath,init_paths=__esm({"../../node_modules/convex/dist/esm/server/components/paths.js"(){"use strict";init_functionName();toReferencePath=Symbol.for("toReferencePath")}});function getFunctionName(functionReference){let address=getFunctionAddress(functionReference);if(address.name===void 0)throw address.functionHandle!==void 0?new Error(`Expected function reference like "api.file.func" or "internal.file.func", but received function handle ${address.functionHandle}`):address.reference!==void 0?new Error(`Expected function reference in the current component like "api.file.func" or "internal.file.func", but received reference ${address.reference}`):new Error(`Expected function reference like "api.file.func" or "internal.file.func", but received ${JSON.stringify(address)}`);if(typeof functionReference=="string")return functionReference;let name=functionReference[functionName];if(!name)throw new Error(`${functionReference} is not a functionReference`);return name}function createApi(pathParts=[]){let handler={get(_,prop){if(typeof prop=="string"){let newParts=[...pathParts,prop];return createApi(newParts)}else if(prop===functionName){if(pathParts.length<2){let found=["api",...pathParts].join(".");throw new Error(`API path is expected to be of the form \`api.moduleName.functionName\`. Found: \`${found}\``)}let path=pathParts.slice(0,-1).join("/"),exportName=pathParts[pathParts.length-1];return exportName==="default"?path:path+":"+exportName}else return prop===Symbol.toStringTag?"FunctionReference":void 0}};return new Proxy({},handler)}var anyApi,init_api=__esm({"../../node_modules/convex/dist/esm/server/api.js"(){"use strict";init_functionName();init_paths();anyApi=createApi()}});var version,init_esm=__esm({"../../node_modules/convex/dist/esm/index.js"(){"use strict";version="1.50.0"}});var base64_exports={};__export(base64_exports,{byteLength:()=>byteLength,fromByteArray:()=>fromByteArray,fromByteArrayUrlSafeNoPadding:()=>fromByteArrayUrlSafeNoPadding,toByteArray:()=>toByteArray});function getLens(b64){var len2=b64.length;if(len2%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var validLen=b64.indexOf("=");validLen===-1&&(validLen=len2);var placeHoldersLen=validLen===len2?0:4-validLen%4;return[validLen,placeHoldersLen]}function byteLength(b64){var lens=getLens(b64),validLen=lens[0],placeHoldersLen=lens[1];return(validLen+placeHoldersLen)*3/4-placeHoldersLen}function _byteLength(_b64,validLen,placeHoldersLen){return(validLen+placeHoldersLen)*3/4-placeHoldersLen}function toByteArray(b64){var tmp,lens=getLens(b64),validLen=lens[0],placeHoldersLen=lens[1],arr2=new Arr(_byteLength(b64,validLen,placeHoldersLen)),curByte=0,len2=placeHoldersLen>0?validLen-4:validLen,i2;for(i2=0;i2<len2;i2+=4)tmp=revLookup[b64.charCodeAt(i2)]<<18|revLookup[b64.charCodeAt(i2+1)]<<12|revLookup[b64.charCodeAt(i2+2)]<<6|revLookup[b64.charCodeAt(i2+3)],arr2[curByte++]=tmp>>16&255,arr2[curByte++]=tmp>>8&255,arr2[curByte++]=tmp&255;return placeHoldersLen===2&&(tmp=revLookup[b64.charCodeAt(i2)]<<2|revLookup[b64.charCodeAt(i2+1)]>>4,arr2[curByte++]=tmp&255),placeHoldersLen===1&&(tmp=revLookup[b64.charCodeAt(i2)]<<10|revLookup[b64.charCodeAt(i2+1)]<<4|revLookup[b64.charCodeAt(i2+2)]>>2,arr2[curByte++]=tmp>>8&255,arr2[curByte++]=tmp&255),arr2}function tripletToBase64(num){return lookup[num>>18&63]+lookup[num>>12&63]+lookup[num>>6&63]+lookup[num&63]}function encodeChunk(uint8,start,end){for(var tmp,output=[],i2=start;i2<end;i2+=3)tmp=(uint8[i2]<<16&16711680)+(uint8[i2+1]<<8&65280)+(uint8[i2+2]&255),output.push(tripletToBase64(tmp));return output.join("")}function fromByteArray(uint8){for(var tmp,len2=uint8.length,extraBytes=len2%3,parts=[],maxChunkLength=16383,i2=0,len22=len2-extraBytes;i2<len22;i2+=maxChunkLength)parts.push(encodeChunk(uint8,i2,i2+maxChunkLength>len22?len22:i2+maxChunkLength));return extraBytes===1?(tmp=uint8[len2-1],parts.push(lookup[tmp>>2]+lookup[tmp<<4&63]+"==")):extraBytes===2&&(tmp=(uint8[len2-2]<<8)+uint8[len2-1],parts.push(lookup[tmp>>10]+lookup[tmp>>4&63]+lookup[tmp<<2&63]+"=")),parts.join("")}function fromByteArrayUrlSafeNoPadding(uint8){return fromByteArray(uint8).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}var lookup,revLookup,Arr,code,i,len,init_base64=__esm({"../../node_modules/convex/dist/esm/values/base64.js"(){"use strict";lookup=[],revLookup=[],Arr=Uint8Array,code="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(i=0,len=code.length;i<len;++i)lookup[i]=code[i],revLookup[code.charCodeAt(i)]=i;revLookup[45]=62;revLookup[95]=63}});function isSpecial(n){return Number.isNaN(n)||!Number.isFinite(n)||Object.is(n,-0)}function slowBigIntToBase64(value){value<ZERO&&(value-=MIN_INT64+MIN_INT64);let hex=value.toString(16);hex.length%2===1&&(hex="0"+hex);let bytes=new Uint8Array(new ArrayBuffer(8)),i2=0;for(let hexByte of hex.match(/.{2}/g).reverse())bytes.set([parseInt(hexByte,16)],i2++),value>>=EIGHT;return fromByteArray(bytes)}function slowBase64ToBigInt(encoded){let integerBytes=toByteArray(encoded);if(integerBytes.byteLength!==8)throw new Error(`Received ${integerBytes.byteLength} bytes, expected 8 for $integer`);let value=ZERO,power=ZERO;for(let byte of integerBytes)value+=BigInt(byte)*TWOFIFTYSIX**power,power++;return value>MAX_INT64&&(value+=MIN_INT64+MIN_INT64),value}function modernBigIntToBase64(value){if(value<MIN_INT64||MAX_INT64<value)throw new Error(`BigInt ${value} does not fit into a 64-bit signed integer.`);let buffer=new ArrayBuffer(8);return new DataView(buffer).setBigInt64(0,value,!0),fromByteArray(new Uint8Array(buffer))}function modernBase64ToBigInt(encoded){let integerBytes=toByteArray(encoded);if(integerBytes.byteLength!==8)throw new Error(`Received ${integerBytes.byteLength} bytes, expected 8 for $integer`);return new DataView(integerBytes.buffer).getBigInt64(0,!0)}function validateObjectField(k){if(k.length>MAX_IDENTIFIER_LEN)throw new Error(`Field name ${k} exceeds maximum field name length ${MAX_IDENTIFIER_LEN}.`);if(k.startsWith("$"))throw new Error(`Field name ${k} starts with a '$', which is reserved.`);for(let i2=0;i2<k.length;i2+=1){let charCode=k.charCodeAt(i2);if(charCode<32||charCode>=127)throw new Error(`Field name ${k} has invalid character '${k[i2]}': Field names can only contain non-control ASCII characters`)}}function jsonToConvex(value){if(value===null||typeof value=="boolean"||typeof value=="number"||typeof value=="string")return value;if(Array.isArray(value))return value.map(value2=>jsonToConvex(value2));if(typeof value!="object")throw new Error(`Unexpected type of ${value}`);let entries=Object.entries(value);if(entries.length===1){let key=entries[0][0];if(key==="$bytes"){if(typeof value.$bytes!="string")throw new Error(`Malformed $bytes field on ${value}`);return toByteArray(value.$bytes).buffer}if(key==="$integer"){if(typeof value.$integer!="string")throw new Error(`Malformed $integer field on ${value}`);return base64ToBigInt(value.$integer)}if(key==="$float"){if(typeof value.$float!="string")throw new Error(`Malformed $float field on ${value}`);let floatBytes=toByteArray(value.$float);if(floatBytes.byteLength!==8)throw new Error(`Received ${floatBytes.byteLength} bytes, expected 8 for $float`);let float=new DataView(floatBytes.buffer).getFloat64(0,LITTLE_ENDIAN);if(!isSpecial(float))throw new Error(`Float ${float} should be encoded as a number`);return float}if(key==="$commitTs"){if(value.$commitTs!==null)throw new Error(`Malformed $commitTs field on ${value}`);return commitTsPlaceholder}if(key==="$set")throw new Error("Received a Set which is no longer supported as a Convex type.");if(key==="$map")throw new Error("Received a Map which is no longer supported as a Convex type.")}let out={};for(let[k,v2]of Object.entries(value))validateObjectField(k),out[k]=jsonToConvex(v2);return out}function stringifyValueForError(value){let str=JSON.stringify(value,(_key,value2)=>value2===void 0?"undefined":typeof value2=="function"?"[Function]":typeof value2=="symbol"?String(value2):typeof value2=="bigint"?`${value2.toString()}n`:value2);if(str.length>MAX_VALUE_FOR_ERROR_LEN){let rest="[...truncated]",truncateAt=MAX_VALUE_FOR_ERROR_LEN-rest.length,codePoint=str.codePointAt(truncateAt-1);return codePoint!==void 0&&codePoint>65535&&(truncateAt-=1),str.substring(0,truncateAt)+rest}return str}function convexToJsonInternal(value,originalValue,context,includeTopLevelUndefined){if(value===void 0){let contextText=context&&` (present at path ${context} in original object ${stringifyValueForError(originalValue)})`;throw new Error(`undefined is not a valid Convex value${contextText}. To learn about Convex's supported types, see https://docs.convex.dev/using/types.`)}if(value===null)return value;if(typeof value=="bigint"){if(value<MIN_INT64||MAX_INT64<value)throw new Error(`BigInt ${value} does not fit into a 64-bit signed integer.`);return{$integer:bigIntToBase64(value)}}if(typeof value=="number")if(isSpecial(value)){let buffer=new ArrayBuffer(8);return new DataView(buffer).setFloat64(0,value,LITTLE_ENDIAN),{$float:fromByteArray(new Uint8Array(buffer))}}else return value;if(typeof value=="boolean"||typeof value=="string")return value;if(value instanceof ArrayBuffer)return{$bytes:fromByteArray(new Uint8Array(value))};if(value instanceof CommitTsPlaceholder)return{$commitTs:null};if(Array.isArray(value))return value.map((value2,i2)=>convexToJsonInternal(value2,originalValue,context+`[${i2}]`,!1));if(value instanceof Set)throw new Error(errorMessageForUnsupportedType(context,"Set",[...value],originalValue));if(value instanceof Map)throw new Error(errorMessageForUnsupportedType(context,"Map",[...value],originalValue));if(!isSimpleObject(value)){let theType=value?.constructor?.name,typeName=theType?`${theType} `:"";throw new Error(errorMessageForUnsupportedType(context,typeName,value,originalValue))}let out={},entries=Object.entries(value);entries.sort(([k1,_v1],[k2,_v2])=>k1===k2?0:k1<k2?-1:1);for(let[k,v2]of entries)v2!==void 0?(validateObjectField(k),out[k]=convexToJsonInternal(v2,originalValue,context+`.${k}`,!1)):includeTopLevelUndefined&&(validateObjectField(k),out[k]=convexOrUndefinedToJsonInternal(v2,originalValue,context+`.${k}`));return out}function errorMessageForUnsupportedType(context,typeName,value,originalValue){return context?`${typeName}${stringifyValueForError(value)} is not a supported Convex type (present at path ${context} in original object ${stringifyValueForError(originalValue)}). To learn about Convex's supported types, see https://docs.convex.dev/using/types.`:`${typeName}${stringifyValueForError(value)} is not a supported Convex type.`}function convexOrUndefinedToJsonInternal(value,originalValue,context){if(value===void 0)return{$undefined:null};if(originalValue===void 0)throw new Error(`Programming error. Current value is ${stringifyValueForError(value)} but original value is undefined`);return convexToJsonInternal(value,originalValue,context,!1)}function convexToJson(value){return convexToJsonInternal(value,value,"",!1)}var LITTLE_ENDIAN,MIN_INT64,MAX_INT64,ZERO,EIGHT,TWOFIFTYSIX,COMMIT_TS_UNRESOLVED,CommitTsPlaceholder,commitTsPlaceholder,bigIntToBase64,base64ToBigInt,MAX_IDENTIFIER_LEN,MAX_VALUE_FOR_ERROR_LEN,init_value=__esm({"../../node_modules/convex/dist/esm/values/value.js"(){"use strict";init_base64();init_common();LITTLE_ENDIAN=!0,MIN_INT64=BigInt("-9223372036854775808"),MAX_INT64=BigInt("9223372036854775807"),ZERO=BigInt("0"),EIGHT=BigInt("8"),TWOFIFTYSIX=BigInt("256"),COMMIT_TS_UNRESOLVED="This commit timestamp is unresolved: its value is assigned when the mutation commits. Read the document after the mutation completes to get its value.",CommitTsPlaceholder=class{[Symbol.toPrimitive](hint){if(hint==="string")return this.toString();throw new Error(COMMIT_TS_UNRESOLVED)}valueOf(){throw new Error(COMMIT_TS_UNRESOLVED)}toJSON(){throw new Error(COMMIT_TS_UNRESOLVED)}toString(){return"[unresolved commit timestamp]"}},commitTsPlaceholder=new CommitTsPlaceholder;bigIntToBase64=DataView.prototype.setBigInt64?modernBigIntToBase64:slowBigIntToBase64,base64ToBigInt=DataView.prototype.getBigInt64?modernBase64ToBigInt:slowBase64ToBigInt,MAX_IDENTIFIER_LEN=1024;MAX_VALUE_FOR_ERROR_LEN=16384}});var init_validators=__esm({"../../node_modules/convex/dist/esm/values/validators.js"(){"use strict";init_value()}});var init_validator=__esm({"../../node_modules/convex/dist/esm/values/validator.js"(){"use strict";init_validators()}});var __defProp2,__defNormalProp,__publicField,_a,_b,IDENTIFYING_FIELD,ConvexError,init_errors=__esm({"../../node_modules/convex/dist/esm/values/errors.js"(){"use strict";init_value();__defProp2=Object.defineProperty,__defNormalProp=(obj,key,value)=>key in obj?__defProp2(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,__publicField=(obj,key,value)=>__defNormalProp(obj,typeof key!="symbol"?key+"":key,value),IDENTIFYING_FIELD=Symbol.for("ConvexError"),ConvexError=class extends(_b=Error,_a=IDENTIFYING_FIELD,_b){constructor(data){super(typeof data=="string"?data:stringifyValueForError(data)),__publicField(this,"name","ConvexError"),__publicField(this,"data"),__publicField(this,_a,!0),this.data=data}}}});var arr,aBytes,bBytes,init_compare_utf8=__esm({"../../node_modules/convex/dist/esm/values/compare_utf8.js"(){"use strict";arr=()=>Array.from({length:4},()=>0),aBytes=arr(),bBytes=arr()}});var init_compare=__esm({"../../node_modules/convex/dist/esm/values/compare.js"(){"use strict";init_value();init_compare_utf8()}});var init_size=__esm({"../../node_modules/convex/dist/esm/values/size.js"(){"use strict";init_value();init_common()}});var init_values=__esm({"../../node_modules/convex/dist/esm/values/index.js"(){"use strict";init_value();init_validator();init_base64();init_errors();init_compare();init_size()}});function prefix_for_source(source){switch(source){case"query":return"Q";case"mutation":return"M";case"action":return"A";case"any":return"?"}}function instantiateDefaultLogger(options){let logger2=new DefaultLogger(options);return logger2.addLogLineListener((level,...args)=>{switch(level){case"debug":console.debug(...args);break;case"info":console.log(...args);break;case"warn":console.warn(...args);break;case"error":console.error(...args);break;default:console.log(...args)}}),logger2}function instantiateNoopLogger(options){return new DefaultLogger(options)}function logForFunction(logger2,type,source,udfPath,message){let prefix=prefix_for_source(source);if(typeof message=="object"&&(message=`ConvexError ${JSON.stringify(message.errorData,null,2)}`),type==="info"){let match=message.match(/^\[.*?\] /);if(match===null){logger2.error(`[CONVEX ${prefix}(${udfPath})] Could not parse console.log`);return}let level=message.slice(1,match[0].length-2),args=message.slice(match[0].length);logger2.log(`%c[CONVEX ${prefix}(${udfPath})] [${level}]`,INFO_COLOR,args)}else logger2.error(`[CONVEX ${prefix}(${udfPath})] ${message}`)}function logFatalError(logger2,message){let errorMessage=`[CONVEX FATAL ERROR] ${message}`;return logger2.error(errorMessage),new Error(errorMessage)}function createHybridErrorStacktrace(source,udfPath,result){return`[CONVEX ${prefix_for_source(source)}(${udfPath})] ${result.errorMessage}
|
|
6
|
-
Called by client`}function forwardData(result,error2){return error2.data=result.errorData,error2}var __defProp3,__defNormalProp2,__publicField2,INFO_COLOR,DefaultLogger,init_logging=__esm({"../../node_modules/convex/dist/esm/browser/logging.js"(){"use strict";__defProp3=Object.defineProperty,__defNormalProp2=(obj,key,value)=>key in obj?__defProp3(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,__publicField2=(obj,key,value)=>__defNormalProp2(obj,typeof key!="symbol"?key+"":key,value),INFO_COLOR="color:rgb(0, 145, 255)";DefaultLogger=class{constructor(options){__publicField2(this,"_onLogLineFuncs"),__publicField2(this,"_verbose"),this._onLogLineFuncs={},this._verbose=options.verbose}addLogLineListener(func){let id=Math.random().toString(36).substring(2,15);for(let i2=0;i2<10&&this._onLogLineFuncs[id]!==void 0;i2++)id=Math.random().toString(36).substring(2,15);return this._onLogLineFuncs[id]=func,()=>{delete this._onLogLineFuncs[id]}}logVerbose(...args){if(this._verbose)for(let func of Object.values(this._onLogLineFuncs))func("debug",`${new Date().toISOString()}`,...args)}log(...args){for(let func of Object.values(this._onLogLineFuncs))func("info",...args)}warn(...args){for(let func of Object.values(this._onLogLineFuncs))func("warn",...args)}error(...args){for(let func of Object.values(this._onLogLineFuncs))func("error",...args)}}}});function canonicalizeUdfPath(udfPath){let pieces=udfPath.split(":"),moduleName,functionName2;return pieces.length===1?(moduleName=pieces[0],functionName2="default"):(moduleName=pieces.slice(0,pieces.length-1).join(":"),functionName2=pieces[pieces.length-1]),moduleName.endsWith(".js")&&(moduleName=moduleName.slice(0,-3)),`${moduleName}:${functionName2}`}function serializePathAndArgs(udfPath,args){return JSON.stringify({udfPath:canonicalizeUdfPath(udfPath),args:convexToJson(args)})}function serializePaginatedPathAndArgs(udfPath,args,options){let{initialNumItems,id}=options;return JSON.stringify({type:"paginated",udfPath:canonicalizeUdfPath(udfPath),args:convexToJson(args),options:convexToJson({initialNumItems,id})})}function serializedQueryTokenIsPaginated(token){return JSON.parse(token).type==="paginated"}var init_udf_path_utils=__esm({"../../node_modules/convex/dist/esm/browser/sync/udf_path_utils.js"(){"use strict";init_values()}});var __defProp4,__defNormalProp3,__publicField3,LocalSyncState,init_local_state=__esm({"../../node_modules/convex/dist/esm/browser/sync/local_state.js"(){"use strict";init_values();init_udf_path_utils();__defProp4=Object.defineProperty,__defNormalProp3=(obj,key,value)=>key in obj?__defProp4(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,__publicField3=(obj,key,value)=>__defNormalProp3(obj,typeof key!="symbol"?key+"":key,value),LocalSyncState=class{constructor(){__publicField3(this,"nextQueryId"),__publicField3(this,"querySetVersion"),__publicField3(this,"querySet"),__publicField3(this,"queryIdToToken"),__publicField3(this,"identityVersion"),__publicField3(this,"auth"),__publicField3(this,"outstandingQueriesOlderThanRestart"),__publicField3(this,"outstandingAuthOlderThanRestart"),__publicField3(this,"paused"),__publicField3(this,"pendingQuerySetModifications"),this.nextQueryId=0,this.querySetVersion=0,this.identityVersion=0,this.querySet=new Map,this.queryIdToToken=new Map,this.outstandingQueriesOlderThanRestart=new Set,this.outstandingAuthOlderThanRestart=!1,this.paused=!1,this.pendingQuerySetModifications=new Map}hasSyncedPastLastReconnect(){return this.outstandingQueriesOlderThanRestart.size===0&&!this.outstandingAuthOlderThanRestart}markAuthCompletion(){this.outstandingAuthOlderThanRestart=!1}subscribe(udfPath,args,journal,componentPath){let canonicalizedUdfPath=canonicalizeUdfPath(udfPath),queryToken=serializePathAndArgs(canonicalizedUdfPath,args),existingEntry=this.querySet.get(queryToken);if(existingEntry!==void 0)return existingEntry.numSubscribers+=1,{queryToken,modification:null,unsubscribe:()=>this.removeSubscriber(queryToken)};{let queryId=this.nextQueryId++,query={id:queryId,canonicalizedUdfPath,args,numSubscribers:1,journal,componentPath};this.querySet.set(queryToken,query),this.queryIdToToken.set(queryId,queryToken);let baseVersion=this.querySetVersion,newVersion=this.querySetVersion+1,add={type:"Add",queryId,udfPath:canonicalizedUdfPath,args:[convexToJson(args)],journal,componentPath};return this.paused?this.pendingQuerySetModifications.set(queryId,add):this.querySetVersion=newVersion,{queryToken,modification:{type:"ModifyQuerySet",baseVersion,newVersion,modifications:[add]},unsubscribe:()=>this.removeSubscriber(queryToken)}}}transition(transition){for(let modification of transition.modifications)switch(modification.type){case"QueryUpdated":case"QueryFailed":{this.outstandingQueriesOlderThanRestart.delete(modification.queryId);let journal=modification.journal;if(journal!==void 0){let queryToken=this.queryIdToToken.get(modification.queryId);queryToken!==void 0&&(this.querySet.get(queryToken).journal=journal)}break}case"QueryRemoved":{this.outstandingQueriesOlderThanRestart.delete(modification.queryId);break}default:throw new Error(`Invalid modification ${modification.type}`)}}queryId(udfPath,args){let canonicalizedUdfPath=canonicalizeUdfPath(udfPath),queryToken=serializePathAndArgs(canonicalizedUdfPath,args),existingEntry=this.querySet.get(queryToken);return existingEntry!==void 0?existingEntry.id:null}isCurrentOrNewerAuthVersion(version3){return version3>=this.identityVersion}getAuth(){return this.auth}setAuth(value){this.auth={tokenType:"User",value};let baseVersion=this.identityVersion;return this.paused||(this.identityVersion=baseVersion+1),{type:"Authenticate",baseVersion,...this.auth}}setAdminAuth(value,actingAs){let auth2={tokenType:"Admin",value,impersonating:actingAs};this.auth=auth2;let baseVersion=this.identityVersion;return this.paused||(this.identityVersion=baseVersion+1),{type:"Authenticate",baseVersion,...auth2}}clearAuth(){this.auth=void 0,this.markAuthCompletion();let baseVersion=this.identityVersion;return this.paused||(this.identityVersion=baseVersion+1),{type:"Authenticate",tokenType:"None",baseVersion}}hasAuth(){return!!this.auth}isNewAuth(value){return this.auth?.value!==value}queryPath(queryId){let pathAndArgs=this.queryIdToToken.get(queryId);return pathAndArgs?this.querySet.get(pathAndArgs).canonicalizedUdfPath:null}queryArgs(queryId){let pathAndArgs=this.queryIdToToken.get(queryId);return pathAndArgs?this.querySet.get(pathAndArgs).args:null}queryToken(queryId){return this.queryIdToToken.get(queryId)??null}queryJournal(queryToken){return this.querySet.get(queryToken)?.journal}restart(){this.unpause(),this.outstandingQueriesOlderThanRestart.clear();let modifications=[];for(let localQuery of this.querySet.values()){let add={type:"Add",queryId:localQuery.id,udfPath:localQuery.canonicalizedUdfPath,args:[convexToJson(localQuery.args)],journal:localQuery.journal,componentPath:localQuery.componentPath};modifications.push(add),this.outstandingQueriesOlderThanRestart.add(localQuery.id)}this.querySetVersion=1;let querySet={type:"ModifyQuerySet",baseVersion:0,newVersion:1,modifications};if(!this.auth)return this.identityVersion=0,[querySet,void 0];this.outstandingAuthOlderThanRestart=!0;let authenticate={type:"Authenticate",baseVersion:0,...this.auth};return this.identityVersion=1,[querySet,authenticate]}pause(){this.paused=!0}resume(){let querySet=this.pendingQuerySetModifications.size>0?{type:"ModifyQuerySet",baseVersion:this.querySetVersion,newVersion:++this.querySetVersion,modifications:Array.from(this.pendingQuerySetModifications.values())}:void 0,authenticate=this.auth!==void 0?{type:"Authenticate",baseVersion:this.identityVersion++,...this.auth}:void 0;return this.unpause(),[querySet,authenticate]}unpause(){this.paused=!1,this.pendingQuerySetModifications.clear()}removeSubscriber(queryToken){let localQuery=this.querySet.get(queryToken);if(localQuery.numSubscribers>1)return localQuery.numSubscribers-=1,null;{this.querySet.delete(queryToken),this.queryIdToToken.delete(localQuery.id),this.outstandingQueriesOlderThanRestart.delete(localQuery.id);let baseVersion=this.querySetVersion,newVersion=this.querySetVersion+1,remove={type:"Remove",queryId:localQuery.id};return this.paused?this.pendingQuerySetModifications.has(localQuery.id)?this.pendingQuerySetModifications.delete(localQuery.id):this.pendingQuerySetModifications.set(localQuery.id,remove):this.querySetVersion=newVersion,{type:"ModifyQuerySet",baseVersion,newVersion,modifications:[remove]}}}}}});var __defProp5,__defNormalProp4,__publicField4,RequestManager,init_request_manager=__esm({"../../node_modules/convex/dist/esm/browser/sync/request_manager.js"(){"use strict";init_values();init_logging();__defProp5=Object.defineProperty,__defNormalProp4=(obj,key,value)=>key in obj?__defProp5(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,__publicField4=(obj,key,value)=>__defNormalProp4(obj,typeof key!="symbol"?key+"":key,value),RequestManager=class{constructor(logger2,markConnectionStateDirty){this.logger=logger2,this.markConnectionStateDirty=markConnectionStateDirty,__publicField4(this,"inflightRequests"),__publicField4(this,"requestsOlderThanRestart"),__publicField4(this,"inflightMutationsCount",0),__publicField4(this,"inflightActionsCount",0),this.inflightRequests=new Map,this.requestsOlderThanRestart=new Set}request(message,sent){let result=new Promise(resolve4=>{let status=sent?"Requested":"NotSent";this.inflightRequests.set(message.requestId,{message,status:{status,requestedAt:new Date,onResult:resolve4}}),message.type==="Mutation"?this.inflightMutationsCount++:message.type==="Action"&&this.inflightActionsCount++});return this.markConnectionStateDirty(),result}onResponse(response){let requestInfo=this.inflightRequests.get(response.requestId);if(requestInfo===void 0||requestInfo.status.status==="Completed")return null;let udfType=requestInfo.message.type==="Mutation"?"mutation":"action",udfPath=requestInfo.message.udfPath;for(let line of response.logLines)logForFunction(this.logger,"info",udfType,udfPath,line);let status=requestInfo.status,result,onResolve;if(response.success)result={success:!0,logLines:response.logLines,value:jsonToConvex(response.result)},onResolve=()=>status.onResult(result);else{let errorMessage=response.result,{errorData}=response;logForFunction(this.logger,"error",udfType,udfPath,errorMessage),result={success:!1,errorMessage,errorData:errorData!==void 0?jsonToConvex(errorData):void 0,logLines:response.logLines},onResolve=()=>status.onResult(result)}return response.type==="ActionResponse"||!response.success?(onResolve(),this.inflightRequests.delete(response.requestId),this.requestsOlderThanRestart.delete(response.requestId),requestInfo.message.type==="Action"?this.inflightActionsCount--:requestInfo.message.type==="Mutation"&&this.inflightMutationsCount--,this.markConnectionStateDirty(),{requestId:response.requestId,result}):(requestInfo.status={status:"Completed",result,ts:response.ts,onResolve},null)}removeCompleted(ts){let completeRequests=new Map;for(let[requestId,requestInfo]of this.inflightRequests.entries()){let status=requestInfo.status;status.status==="Completed"&&status.ts.lessThanOrEqual(ts)&&(status.onResolve(),completeRequests.set(requestId,status.result),requestInfo.message.type==="Mutation"?this.inflightMutationsCount--:requestInfo.message.type==="Action"&&this.inflightActionsCount--,this.inflightRequests.delete(requestId),this.requestsOlderThanRestart.delete(requestId))}return completeRequests.size>0&&this.markConnectionStateDirty(),completeRequests}restart(){this.requestsOlderThanRestart=new Set(this.inflightRequests.keys());let allMessages=[];for(let[requestId,value]of this.inflightRequests){if(value.status.status==="NotSent"){value.status.status="Requested",allMessages.push(value.message);continue}if(value.message.type==="Mutation")allMessages.push(value.message);else if(value.message.type==="Action"){if(this.inflightRequests.delete(requestId),this.requestsOlderThanRestart.delete(requestId),this.inflightActionsCount--,value.status.status==="Completed")throw new Error("Action should never be in 'Completed' state");value.status.onResult({success:!1,errorMessage:"Connection lost while action was in flight",logLines:[]})}}return this.markConnectionStateDirty(),allMessages}resume(){let allMessages=[];for(let[,value]of this.inflightRequests)if(value.status.status==="NotSent"){value.status.status="Requested",allMessages.push(value.message);continue}return allMessages}hasIncompleteRequests(){for(let requestInfo of this.inflightRequests.values())if(requestInfo.status.status==="Requested")return!0;return!1}hasInflightRequests(){return this.inflightRequests.size>0}hasSyncedPastLastReconnect(){return this.requestsOlderThanRestart.size===0}timeOfOldestInflightRequest(){if(this.inflightRequests.size===0)return null;let oldestInflightRequest=Date.now();for(let request of this.inflightRequests.values())request.status.status!=="Completed"&&request.status.requestedAt.getTime()<oldestInflightRequest&&(oldestInflightRequest=request.status.requestedAt.getTime());return new Date(oldestInflightRequest)}inflightMutations(){return this.inflightMutationsCount}inflightActions(){return this.inflightActionsCount}}}});var __defProp6,__defNormalProp5,__publicField5,OptimisticLocalStoreImpl,OptimisticQueryResults,init_optimistic_updates_impl=__esm({"../../node_modules/convex/dist/esm/browser/sync/optimistic_updates_impl.js"(){"use strict";init_api();init_common();init_logging();init_udf_path_utils();init_errors();__defProp6=Object.defineProperty,__defNormalProp5=(obj,key,value)=>key in obj?__defProp6(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,__publicField5=(obj,key,value)=>__defNormalProp5(obj,typeof key!="symbol"?key+"":key,value),OptimisticLocalStoreImpl=class _OptimisticLocalStoreImpl{constructor(queryResults){__publicField5(this,"queryResults"),__publicField5(this,"modifiedQueries"),this.queryResults=queryResults,this.modifiedQueries=[]}getQuery(query,...args){let queryArgs=parseArgs4(args[0]),name=getFunctionName(query),queryResult=this.queryResults.get(serializePathAndArgs(name,queryArgs));if(queryResult!==void 0)return _OptimisticLocalStoreImpl.queryValue(queryResult.result)}getAllQueries(query){let queriesWithName=[],name=getFunctionName(query);for(let queryResult of this.queryResults.values())queryResult.udfPath===canonicalizeUdfPath(name)&&queriesWithName.push({args:queryResult.args,value:_OptimisticLocalStoreImpl.queryValue(queryResult.result)});return queriesWithName}setQuery(queryReference,args,value){let queryArgs=parseArgs4(args),name=getFunctionName(queryReference),queryToken=serializePathAndArgs(name,queryArgs),result;value===void 0?result=void 0:result={success:!0,value,logLines:[]};let query={udfPath:name,args:queryArgs,result};this.queryResults.set(queryToken,query),this.modifiedQueries.push(queryToken)}static queryValue(result){if(result!==void 0)return result.success?result.value:void 0}},OptimisticQueryResults=class{constructor(){__publicField5(this,"queryResults"),__publicField5(this,"optimisticUpdates"),this.queryResults=new Map,this.optimisticUpdates=[]}ingestQueryResultsFromServer(serverQueryResults,optimisticUpdatesToDrop){this.optimisticUpdates=this.optimisticUpdates.filter(updateAndId=>!optimisticUpdatesToDrop.has(updateAndId.mutationId));let oldQueryResults=this.queryResults;this.queryResults=new Map(serverQueryResults);let localStore=new OptimisticLocalStoreImpl(this.queryResults);for(let updateAndId of this.optimisticUpdates)updateAndId.update(localStore);let changedQueries=[];for(let[queryToken,query]of this.queryResults){let oldQuery=oldQueryResults.get(queryToken);(oldQuery===void 0||oldQuery.result!==query.result)&&changedQueries.push(queryToken)}return changedQueries}applyOptimisticUpdate(update2,mutationId){this.optimisticUpdates.push({update:update2,mutationId});let localStore=new OptimisticLocalStoreImpl(this.queryResults);return update2(localStore),localStore.modifiedQueries}rawQueryResult(queryToken){let query=this.queryResults.get(queryToken);if(query!==void 0)return query.result}queryResult(queryToken){let query=this.queryResults.get(queryToken);if(query===void 0)return;let result=query.result;if(result!==void 0){if(result.success)return result.value;throw result.errorData!==void 0?forwardData(result,new ConvexError(createHybridErrorStacktrace("query",query.udfPath,result))):new Error(createHybridErrorStacktrace("query",query.udfPath,result))}}hasQueryResult(queryToken){return this.queryResults.get(queryToken)!==void 0}queryLogs(queryToken){return this.queryResults.get(queryToken)?.result?.logLines}}}});var __defProp7,__defNormalProp6,__publicField6,Long,UZERO,TWO_PWR_16_DBL,TWO_PWR_32_DBL,TWO_PWR_64_DBL,MAX_UNSIGNED_VALUE,init_long=__esm({"../../node_modules/convex/dist/esm/vendor/long.js"(){"use strict";__defProp7=Object.defineProperty,__defNormalProp6=(obj,key,value)=>key in obj?__defProp7(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,__publicField6=(obj,key,value)=>__defNormalProp6(obj,typeof key!="symbol"?key+"":key,value),Long=class _Long{constructor(low,high){__publicField6(this,"low"),__publicField6(this,"high"),__publicField6(this,"__isUnsignedLong__"),this.low=low|0,this.high=high|0,this.__isUnsignedLong__=!0}static isLong(obj){return(obj&&obj.__isUnsignedLong__)===!0}static fromBytesLE(bytes){return new _Long(bytes[0]|bytes[1]<<8|bytes[2]<<16|bytes[3]<<24,bytes[4]|bytes[5]<<8|bytes[6]<<16|bytes[7]<<24)}toBytesLE(){let hi=this.high,lo=this.low;return[lo&255,lo>>>8&255,lo>>>16&255,lo>>>24,hi&255,hi>>>8&255,hi>>>16&255,hi>>>24]}static fromNumber(value){return isNaN(value)||value<0?UZERO:value>=TWO_PWR_64_DBL?MAX_UNSIGNED_VALUE:new _Long(value%TWO_PWR_32_DBL|0,value/TWO_PWR_32_DBL|0)}toString(){return(BigInt(this.high)*BigInt(TWO_PWR_32_DBL)+BigInt(this.low)).toString()}equals(other){return _Long.isLong(other)||(other=_Long.fromValue(other)),this.high>>>31===1&&other.high>>>31===1?!1:this.high===other.high&&this.low===other.low}notEquals(other){return!this.equals(other)}comp(other){return _Long.isLong(other)||(other=_Long.fromValue(other)),this.equals(other)?0:other.high>>>0>this.high>>>0||other.high===this.high&&other.low>>>0>this.low>>>0?-1:1}lessThanOrEqual(other){return this.comp(other)<=0}static fromValue(val){return typeof val=="number"?_Long.fromNumber(val):new _Long(val.low,val.high)}},UZERO=new Long(0,0),TWO_PWR_16_DBL=65536,TWO_PWR_32_DBL=TWO_PWR_16_DBL*TWO_PWR_16_DBL,TWO_PWR_64_DBL=TWO_PWR_32_DBL*TWO_PWR_32_DBL,MAX_UNSIGNED_VALUE=new Long(-1,-1)}});var __defProp8,__defNormalProp7,__publicField7,RemoteQuerySet,init_remote_query_set=__esm({"../../node_modules/convex/dist/esm/browser/sync/remote_query_set.js"(){"use strict";init_values();init_long();init_logging();__defProp8=Object.defineProperty,__defNormalProp7=(obj,key,value)=>key in obj?__defProp8(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,__publicField7=(obj,key,value)=>__defNormalProp7(obj,typeof key!="symbol"?key+"":key,value),RemoteQuerySet=class{constructor(queryPath,logger2){__publicField7(this,"version"),__publicField7(this,"remoteQuerySet"),__publicField7(this,"queryPath"),__publicField7(this,"logger"),this.version={querySet:0,ts:Long.fromNumber(0),identity:0},this.remoteQuerySet=new Map,this.queryPath=queryPath,this.logger=logger2}transition(transition){let start=transition.startVersion;if(this.version.querySet!==start.querySet||this.version.ts.notEquals(start.ts)||this.version.identity!==start.identity)throw new Error(`Invalid start version: ${start.ts.toString()}:${start.querySet}:${start.identity}, transitioning from ${this.version.ts.toString()}:${this.version.querySet}:${this.version.identity}`);for(let modification of transition.modifications)switch(modification.type){case"QueryUpdated":{let queryPath=this.queryPath(modification.queryId);if(queryPath)for(let line of modification.logLines)logForFunction(this.logger,"info","query",queryPath,line);let value=jsonToConvex(modification.value??null);this.remoteQuerySet.set(modification.queryId,{success:!0,value,logLines:modification.logLines});break}case"QueryFailed":{let queryPath=this.queryPath(modification.queryId);if(queryPath)for(let line of modification.logLines)logForFunction(this.logger,"info","query",queryPath,line);let{errorData}=modification;this.remoteQuerySet.set(modification.queryId,{success:!1,errorMessage:modification.errorMessage,errorData:errorData!==void 0?jsonToConvex(errorData):void 0,logLines:modification.logLines});break}case"QueryRemoved":{this.remoteQuerySet.delete(modification.queryId);break}default:throw new Error(`Invalid modification ${modification.type}`)}this.version=transition.endVersion}remoteQueryResults(){return this.remoteQuerySet}timestamp(){return this.version.ts}}}});function u64ToLong(encoded){let integerBytes=base64_exports.toByteArray(encoded);return Long.fromBytesLE(Array.from(integerBytes))}function longToU64(raw){let integerBytes=new Uint8Array(raw.toBytesLE());return base64_exports.fromByteArray(integerBytes)}function parseServerMessage(encoded){switch(encoded.type){case"FatalError":case"AuthError":case"ActionResponse":case"TransitionChunk":case"Ping":return{...encoded};case"MutationResponse":return encoded.success?{...encoded,ts:u64ToLong(encoded.ts)}:{...encoded};case"Transition":return{...encoded,startVersion:{...encoded.startVersion,ts:u64ToLong(encoded.startVersion.ts)},endVersion:{...encoded.endVersion,ts:u64ToLong(encoded.endVersion.ts)}};default:}}function encodeClientMessage(message){switch(message.type){case"Authenticate":case"ModifyQuerySet":case"Mutation":case"Action":case"Event":return{...message};case"Connect":return message.maxObservedTimestamp!==void 0?{...message,maxObservedTimestamp:longToU64(message.maxObservedTimestamp)}:{...message,maxObservedTimestamp:void 0};default:}}var init_protocol=__esm({"../../node_modules/convex/dist/esm/browser/sync/protocol.js"(){"use strict";init_values();init_long()}});function monotonicMillis(){return typeof performance>"u"||!performance.now?Date.now():((firstTime===void 0||firstPerformanceNow===void 0)&&(firstTime=Date.now(),firstPerformanceNow=performance.now()),Math.round(firstTime+performance.now()-firstPerformanceNow))}function prettyNow(){return`t=${Math.round((monotonicMillis()-firstTime)/100)/10}s`}function classifyDisconnectError(s){if(s===void 0)return"Unknown";for(let prefix of Object.keys(serverDisconnectErrors))if(s.startsWith(prefix))return prefix;return"Unknown"}var __defProp9,__defNormalProp8,__publicField8,CLOSE_NORMAL,CLOSE_GOING_AWAY,CLOSE_NO_STATUS,CLOSE_NOT_FOUND,firstTime,firstPerformanceNow,serverDisconnectErrors,WebSocketManager,init_web_socket_manager=__esm({"../../node_modules/convex/dist/esm/browser/sync/web_socket_manager.js"(){"use strict";init_protocol();__defProp9=Object.defineProperty,__defNormalProp8=(obj,key,value)=>key in obj?__defProp9(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,__publicField8=(obj,key,value)=>__defNormalProp8(obj,typeof key!="symbol"?key+"":key,value),CLOSE_NORMAL=1e3,CLOSE_GOING_AWAY=1001,CLOSE_NO_STATUS=1005,CLOSE_NOT_FOUND=4040;serverDisconnectErrors={InternalServerError:{timeout:1e3},SubscriptionsWorkerFullError:{timeout:3e3},TooManyConcurrentRequests:{timeout:3e3},CommitterFullError:{timeout:3e3},AwsTooManyRequestsException:{timeout:3e3},ExecuteFullError:{timeout:3e3},SystemTimeoutError:{timeout:3e3},ExpiredInQueue:{timeout:3e3},VectorIndexesUnavailable:{timeout:1e3},SearchIndexesUnavailable:{timeout:1e3},TableSummariesUnavailable:{timeout:1e3},VectorIndexTooLarge:{timeout:3e3},SearchIndexTooLarge:{timeout:3e3},TooManyWritesInTimePeriod:{timeout:3e3}};WebSocketManager=class{constructor(uri,callbacks,webSocketConstructor,logger2,markConnectionStateDirty,debug){this.markConnectionStateDirty=markConnectionStateDirty,this.debug=debug,__publicField8(this,"socket"),__publicField8(this,"connectionCount"),__publicField8(this,"_hasEverConnected",!1),__publicField8(this,"lastCloseReason"),__publicField8(this,"transitionChunkBuffer",null),__publicField8(this,"defaultInitialBackoff"),__publicField8(this,"maxBackoff"),__publicField8(this,"retries"),__publicField8(this,"serverInactivityThreshold"),__publicField8(this,"reconnectDueToServerInactivityTimeout"),__publicField8(this,"scheduledReconnect",null),__publicField8(this,"networkOnlineHandler",null),__publicField8(this,"pendingNetworkRecoveryInfo",null),__publicField8(this,"uri"),__publicField8(this,"onOpen"),__publicField8(this,"onResume"),__publicField8(this,"onMessage"),__publicField8(this,"webSocketConstructor"),__publicField8(this,"logger"),__publicField8(this,"onServerDisconnectError"),this.webSocketConstructor=webSocketConstructor,this.socket={state:"disconnected"},this.connectionCount=0,this.lastCloseReason="InitialConnect",this.defaultInitialBackoff=1e3,this.maxBackoff=16e3,this.retries=0,this.serverInactivityThreshold=6e4,this.reconnectDueToServerInactivityTimeout=null,this.uri=uri,this.onOpen=callbacks.onOpen,this.onResume=callbacks.onResume,this.onMessage=callbacks.onMessage,this.onServerDisconnectError=callbacks.onServerDisconnectError,this.logger=logger2,this.setupNetworkListener(),this.connect()}setSocketState(state){this.socket=state,this._logVerbose(`socket state changed: ${this.socket.state}, paused: ${"paused"in this.socket?this.socket.paused:void 0}`),this.markConnectionStateDirty()}setupNetworkListener(){typeof window>"u"||typeof window.addEventListener!="function"||this.networkOnlineHandler===null&&(this.networkOnlineHandler=()=>{this._logVerbose("network online event detected"),this.tryReconnectImmediately()},window.addEventListener("online",this.networkOnlineHandler),this._logVerbose("network online event listener registered"))}cleanupNetworkListener(){this.networkOnlineHandler&&typeof window<"u"&&typeof window.removeEventListener=="function"&&(window.removeEventListener("online",this.networkOnlineHandler),this.networkOnlineHandler=null,this._logVerbose("network online event listener removed"))}assembleTransition(chunk){if(chunk.partNumber<0||chunk.partNumber>=chunk.totalParts||chunk.totalParts===0||this.transitionChunkBuffer&&(this.transitionChunkBuffer.totalParts!==chunk.totalParts||this.transitionChunkBuffer.transitionId!==chunk.transitionId))throw this.transitionChunkBuffer=null,new Error("Invalid TransitionChunk");if(this.transitionChunkBuffer===null&&(this.transitionChunkBuffer={chunks:[],totalParts:chunk.totalParts,transitionId:chunk.transitionId}),chunk.partNumber!==this.transitionChunkBuffer.chunks.length){let expectedLength=this.transitionChunkBuffer.chunks.length;throw this.transitionChunkBuffer=null,new Error(`TransitionChunk received out of order: expected part ${expectedLength}, got ${chunk.partNumber}`)}if(this.transitionChunkBuffer.chunks.push(chunk.chunk),this.transitionChunkBuffer.chunks.length===chunk.totalParts){let fullJson=this.transitionChunkBuffer.chunks.join("");this.transitionChunkBuffer=null;let transition=parseServerMessage(JSON.parse(fullJson));if(transition.type!=="Transition")throw new Error(`Expected Transition, got ${transition.type} after assembling chunks`);return transition}return null}connect(){if(this.socket.state==="terminated")return;if(this.socket.state!=="disconnected"&&this.socket.state!=="stopped")throw new Error("Didn't start connection from disconnected state: "+this.socket.state);let ws=new this.webSocketConstructor(this.uri);this._logVerbose("constructed WebSocket"),this.setSocketState({state:"connecting",ws,paused:"no"}),this.resetServerInactivityTimeout(),ws.onopen=()=>{if(this.logger.logVerbose("begin ws.onopen"),this.socket.state!=="connecting")throw new Error("onopen called with socket not in connecting state");if(this.setSocketState({state:"ready",ws,paused:this.socket.paused==="yes"?"uninitialized":"no"}),this.resetServerInactivityTimeout(),this.socket.paused==="no"&&(this._hasEverConnected=!0,this.onOpen({connectionCount:this.connectionCount,lastCloseReason:this.lastCloseReason,clientTs:monotonicMillis()})),this.lastCloseReason!=="InitialConnect"&&(this.lastCloseReason?this.logger.log("WebSocket reconnected at",prettyNow(),"after disconnect due to",this.lastCloseReason):this.logger.log("WebSocket reconnected at",prettyNow())),this.connectionCount+=1,this.lastCloseReason=null,this.pendingNetworkRecoveryInfo!==null){let{timeSavedMs}=this.pendingNetworkRecoveryInfo;this.pendingNetworkRecoveryInfo=null,this.sendMessage({type:"Event",eventType:"NetworkRecoveryReconnect",event:{timeSavedMs}}),this.logger.log(`Network recovery reconnect saved ~${Math.round(timeSavedMs/1e3)}s of waiting`)}},ws.onerror=error2=>{this.transitionChunkBuffer=null;let message=error2.message;message&&this.logger.log(`WebSocket error message: ${message}`)},ws.onmessage=message=>{this.resetServerInactivityTimeout();let messageLength=message.data.length,serverMessage=parseServerMessage(JSON.parse(message.data));if(this._logVerbose(`received ws message with type ${serverMessage.type}`),serverMessage.type==="Ping")return;if(serverMessage.type==="TransitionChunk"){let transition=this.assembleTransition(serverMessage);if(!transition)return;serverMessage=transition,this._logVerbose(`assembled full ws message of type ${serverMessage.type}`)}this.transitionChunkBuffer!==null&&(this.transitionChunkBuffer=null,this.logger.log(`Received unexpected ${serverMessage.type} while buffering TransitionChunks`)),serverMessage.type==="Transition"&&this.reportLargeTransition({messageLength,transition:serverMessage}),this.onMessage(serverMessage).hasSyncedPastLastReconnect&&(this.retries=0,this.markConnectionStateDirty())},ws.onclose=event=>{if(this._logVerbose("begin ws.onclose"),this.transitionChunkBuffer=null,this.lastCloseReason===null&&(this.lastCloseReason=event.reason||`closed with code ${event.code}`),event.code!==CLOSE_NORMAL&&event.code!==CLOSE_GOING_AWAY&&event.code!==CLOSE_NO_STATUS&&event.code!==CLOSE_NOT_FOUND){let msg=`WebSocket closed with code ${event.code}`;event.reason&&(msg+=`: ${event.reason}`),this.logger.log(msg),this.onServerDisconnectError&&event.reason&&this.onServerDisconnectError(msg)}let reason=classifyDisconnectError(event.reason);this.scheduleReconnect(reason)}}socketState(){return this.socket.state}sendMessage(message){let messageForLog={type:message.type,...message.type==="Authenticate"&&message.tokenType==="User"?{value:`...${message.value.slice(-7)}`}:{}};if(this.socket.state==="ready"&&this.socket.paused==="no"){let encodedMessage=encodeClientMessage(message),request=JSON.stringify(encodedMessage),sent=!1;try{this.socket.ws.send(request),sent=!0}catch(error2){this.logger.log(`Failed to send message on WebSocket, reconnecting: ${error2}`),this.closeAndReconnect("FailedToSendMessage")}return this._logVerbose(`${sent?"sent":"failed to send"} message with type ${message.type}: ${JSON.stringify(messageForLog)}`),!0}return this._logVerbose(`message not sent (socket state: ${this.socket.state}, paused: ${"paused"in this.socket?this.socket.paused:void 0}): ${JSON.stringify(messageForLog)}`),!1}resetServerInactivityTimeout(){this.socket.state!=="terminated"&&(this.reconnectDueToServerInactivityTimeout!==null&&(clearTimeout(this.reconnectDueToServerInactivityTimeout),this.reconnectDueToServerInactivityTimeout=null),this.reconnectDueToServerInactivityTimeout=setTimeout(()=>{this.closeAndReconnect("InactiveServer")},this.serverInactivityThreshold))}scheduleReconnect(reason){this.scheduledReconnect&&(clearTimeout(this.scheduledReconnect.timeout),this.scheduledReconnect=null),this.socket={state:"disconnected"};let backoff=this.nextBackoff(reason);this.markConnectionStateDirty(),this.logger.log(`Attempting reconnect in ${Math.round(backoff)}ms`);let scheduledAt=monotonicMillis(),timeoutId=setTimeout(()=>{this.scheduledReconnect?.timeout===timeoutId&&(this.scheduledReconnect=null,this.connect())},backoff);this.scheduledReconnect={timeout:timeoutId,scheduledAt,backoffMs:backoff}}closeAndReconnect(closeReason){switch(this._logVerbose(`begin closeAndReconnect with reason ${closeReason}`),this.socket.state){case"disconnected":case"terminated":case"stopped":return;case"connecting":case"ready":{this.lastCloseReason=closeReason,this.close(),this.scheduleReconnect("client");return}default:this.socket}}close(){switch(this.transitionChunkBuffer=null,this.socket.state){case"disconnected":case"terminated":case"stopped":return Promise.resolve();case"connecting":{let ws=this.socket.ws;return ws.onmessage=_message=>{this._logVerbose("Ignoring message received after close")},new Promise(r=>{ws.onclose=()=>{this._logVerbose("Closed after connecting"),r()},ws.onopen=()=>{this._logVerbose("Opened after connecting"),ws.close()}})}case"ready":{this._logVerbose("ws.close called");let ws=this.socket.ws;ws.onmessage=_message=>{this._logVerbose("Ignoring message received after close")};let result=new Promise(r=>{ws.onclose=()=>{r()}});return ws.close(),result}default:return this.socket,Promise.resolve()}}terminate(){switch(this.reconnectDueToServerInactivityTimeout&&clearTimeout(this.reconnectDueToServerInactivityTimeout),this.scheduledReconnect&&(clearTimeout(this.scheduledReconnect.timeout),this.scheduledReconnect=null),this.cleanupNetworkListener(),this.socket.state){case"terminated":case"stopped":case"disconnected":case"connecting":case"ready":{let result=this.close();return this.setSocketState({state:"terminated"}),result}default:throw this.socket,new Error(`Invalid websocket state: ${this.socket.state}`)}}stop(){switch(this.socket.state){case"terminated":return Promise.resolve();case"connecting":case"stopped":case"disconnected":case"ready":{this.cleanupNetworkListener();let result=this.close();return this.socket={state:"stopped"},result}default:return this.socket,Promise.resolve()}}tryRestart(){switch(this.socket.state){case"stopped":break;case"terminated":case"connecting":case"ready":case"disconnected":this.logger.logVerbose("Restart called without stopping first");return;default:this.socket}this.setupNetworkListener(),this.connect()}pause(){switch(this.socket.state){case"disconnected":case"stopped":case"terminated":return;case"connecting":case"ready":{this.socket={...this.socket,paused:"yes"};return}default:{this.socket;return}}}tryReconnectImmediately(){if(this._logVerbose("tryReconnectImmediately called"),this.socket.state!=="disconnected"){this._logVerbose(`tryReconnectImmediately called but socket state is ${this.socket.state}, no action taken`);return}let timeSavedMs=null;if(this.scheduledReconnect){let elapsed=monotonicMillis()-this.scheduledReconnect.scheduledAt;timeSavedMs=Math.max(0,this.scheduledReconnect.backoffMs-elapsed),this._logVerbose(`would have waited ${Math.round(timeSavedMs)}ms more (backoff was ${Math.round(this.scheduledReconnect.backoffMs)}ms, elapsed ${Math.round(elapsed)}ms)`),clearTimeout(this.scheduledReconnect.timeout),this.scheduledReconnect=null,this._logVerbose("canceled scheduled reconnect")}this.logger.log("Network recovery detected, reconnecting immediately"),this.pendingNetworkRecoveryInfo=timeSavedMs!==null?{timeSavedMs}:null,this.connect()}resume(){switch(this.socket.state){case"connecting":this.socket={...this.socket,paused:"no"};return;case"ready":this.socket.paused==="uninitialized"?(this.socket={...this.socket,paused:"no"},this._hasEverConnected=!0,this.onOpen({connectionCount:this.connectionCount,lastCloseReason:this.lastCloseReason,clientTs:monotonicMillis()})):this.socket.paused==="yes"&&(this.socket={...this.socket,paused:"no"},this.onResume());return;case"terminated":case"stopped":case"disconnected":return;default:this.socket}this.connect()}connectionState(){return{isConnected:this.socket.state==="ready",hasEverConnected:this._hasEverConnected,connectionCount:this.connectionCount,connectionRetries:this.retries}}_logVerbose(message){this.logger.logVerbose(message)}nextBackoff(reason){let baseBackoff=(reason==="client"?100:reason==="Unknown"?this.defaultInitialBackoff:serverDisconnectErrors[reason].timeout)*Math.pow(2,this.retries);this.retries+=1;let actualBackoff=Math.min(baseBackoff,this.maxBackoff),jitter=actualBackoff*(Math.random()-.5);return actualBackoff+jitter}reportLargeTransition({transition,messageLength}){if(transition.clientClockSkew===void 0||transition.serverTs===void 0)return;let transitionTransitTime=monotonicMillis()-transition.clientClockSkew-transition.serverTs/1e6,prettyTransitionTime=`${Math.round(transitionTransitTime)}ms`,prettyMessageMB=`${Math.round(messageLength/1e4)/100}MB`,bytesPerSecond=messageLength/(transitionTransitTime/1e3),prettyBytesPerSecond=`${Math.round(bytesPerSecond/1e4)/100}MB per second`;this._logVerbose(`received ${prettyMessageMB} transition in ${prettyTransitionTime} at ${prettyBytesPerSecond}`),messageLength>2e7?this.logger.log(`received query results totaling more that 20MB (${prettyMessageMB}) which will take a long time to download on slower connections`):transitionTransitTime>2e4&&this.logger.log(`received query results totaling ${prettyMessageMB} which took more than 20s to arrive (${prettyTransitionTime})`),this.debug&&this.sendMessage({type:"Event",eventType:"ClientReceivedTransition",event:{transitionTransitTime,messageLength}})}}}});function newSessionId(){return uuidv4()}function uuidv4(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,c=>{let r=Math.random()*16|0;return(c==="x"?r:r&3|8).toString(16)})}var init_session=__esm({"../../node_modules/convex/dist/esm/browser/sync/session.js"(){"use strict"}});function b64DecodeUnicode(str){return decodeURIComponent(atob(str).replace(/(.)/g,(_m,p)=>{let code2=p.charCodeAt(0).toString(16).toUpperCase();return code2.length<2&&(code2="0"+code2),"%"+code2}))}function base64UrlDecode(str){let output=str.replace(/-/g,"+").replace(/_/g,"/");switch(output.length%4){case 0:break;case 2:output+="==";break;case 3:output+="=";break;default:throw new Error("base64 string is not of the correct length")}try{return b64DecodeUnicode(output)}catch{return atob(output)}}function jwtDecode(token,options){if(typeof token!="string")throw new InvalidTokenError("Invalid token specified: must be a string");options||(options={});let pos=options.header===!0?0:1,part=token.split(".")[pos];if(typeof part!="string")throw new InvalidTokenError(`Invalid token specified: missing part #${pos+1}`);let decoded;try{decoded=base64UrlDecode(part)}catch(e){throw new InvalidTokenError(`Invalid token specified: invalid base64 for part #${pos+1} (${e.message})`)}try{return JSON.parse(decoded)}catch(e){throw new InvalidTokenError(`Invalid token specified: invalid json for part #${pos+1} (${e.message})`)}}var InvalidTokenError,init_jwt_decode=__esm({"../../node_modules/convex/dist/esm/vendor/jwt-decode/index.js"(){"use strict";InvalidTokenError=class extends Error{};InvalidTokenError.prototype.name="InvalidTokenError"}});var __defProp10,__defNormalProp9,__publicField9,MAXIMUM_REFRESH_DELAY,MAX_TOKEN_CONFIRMATION_ATTEMPTS,AuthenticationManager,init_authentication_manager=__esm({"../../node_modules/convex/dist/esm/browser/sync/authentication_manager.js"(){"use strict";init_jwt_decode();__defProp10=Object.defineProperty,__defNormalProp9=(obj,key,value)=>key in obj?__defProp10(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,__publicField9=(obj,key,value)=>__defNormalProp9(obj,typeof key!="symbol"?key+"":key,value),MAXIMUM_REFRESH_DELAY=480*60*60*1e3,MAX_TOKEN_CONFIRMATION_ATTEMPTS=2,AuthenticationManager=class{constructor(syncState,callbacks,config2){__publicField9(this,"authState",{state:"noAuth"}),__publicField9(this,"configVersion",0),__publicField9(this,"syncState"),__publicField9(this,"authenticate"),__publicField9(this,"stopSocket"),__publicField9(this,"tryRestartSocket"),__publicField9(this,"pauseSocket"),__publicField9(this,"resumeSocket"),__publicField9(this,"clearAuth"),__publicField9(this,"logger"),__publicField9(this,"refreshTokenLeewaySeconds"),__publicField9(this,"initialAuthTokenReuse"),__publicField9(this,"lastRefreshChange"),__publicField9(this,"tokenConfirmationAttempts",0),this.syncState=syncState,this.authenticate=callbacks.authenticate,this.stopSocket=callbacks.stopSocket,this.tryRestartSocket=callbacks.tryRestartSocket,this.pauseSocket=callbacks.pauseSocket,this.resumeSocket=callbacks.resumeSocket,this.clearAuth=callbacks.clearAuth,this.logger=config2.logger,this.refreshTokenLeewaySeconds=config2.refreshTokenLeewaySeconds,this.initialAuthTokenReuse=config2.initialAuthTokenReuse,this.lastRefreshChange=!1}notifyRefreshChange(isRefreshing){this.authState.state!=="noAuth"&&this.authState.state!=="initialRefetch"&&this.authState.config.onRefreshChange&&this.lastRefreshChange!==isRefreshing&&(this.lastRefreshChange=isRefreshing,this.authState.config.onRefreshChange(isRefreshing))}async setConfig(fetchToken2,onChange,onRefreshChange){this.resetAuthState(),this._logVerbose("pausing WS for auth token fetch"),this.pauseSocket();let token=await this.fetchTokenAndGuardAgainstRace(fetchToken2,{forceRefreshToken:!1});if(token.isFromOutdatedConfig)return;let config2={fetchToken:fetchToken2,onAuthChange:onChange,onRefreshChange};token.value?(this.setAuthState({state:"waitingForServerConfirmationOfCachedToken",config:config2,hasRetried:!1}),this.authenticate(token.value)):(this.setAuthState({state:"initialRefetch",config:config2}),await this.refetchToken()),this._logVerbose("resuming WS after auth token fetch"),this.resumeSocket()}onTransition(serverMessage){if(this.syncState.isCurrentOrNewerAuthVersion(serverMessage.endVersion.identity)&&!(serverMessage.endVersion.identity<=serverMessage.startVersion.identity)){if(this._logVerbose(`auth state is ${this.authState.state} when handling transition`),this.syncState.markAuthCompletion(),this.authState.state==="waitingForServerConfirmationOfCachedToken"){this._logVerbose("server confirmed auth token is valid");let cachedToken=this.syncState.getAuth()?.value;this.initialAuthTokenReuse&&cachedToken?this.scheduleTokenRefetch(cachedToken,serverMessage.clientClockSkew):this.refetchToken(),this.authState.config.onAuthChange(!0);return}this.authState.state==="waitingForServerConfirmationOfFreshToken"&&(this._logVerbose("server confirmed new auth token is valid"),this.notifyRefreshChange(!1),this.scheduleTokenRefetch(this.authState.token),this.tokenConfirmationAttempts=0,this.authState.hadAuth||this.authState.config.onAuthChange(!0))}}onAuthError(serverMessage){if(serverMessage.authUpdateAttempted===!1&&(this.authState.state==="waitingForServerConfirmationOfFreshToken"||this.authState.state==="waitingForServerConfirmationOfCachedToken")){this._logVerbose("ignoring non-auth token expired error");return}let{baseVersion}=serverMessage;if(!this.syncState.isCurrentOrNewerAuthVersion(baseVersion+1)){this._logVerbose("ignoring auth error for previous auth attempt");return}this.tryToReauthenticate(serverMessage)}async tryToReauthenticate(serverMessage){if(this._logVerbose(`attempting to reauthenticate: ${serverMessage.error}`),this.authState.state==="noAuth"||this.authState.state==="waitingForServerConfirmationOfFreshToken"&&this.tokenConfirmationAttempts>=MAX_TOKEN_CONFIRMATION_ATTEMPTS){this.logger.error(`Failed to authenticate: "${serverMessage.error}", check your server auth config`),this.syncState.hasAuth()&&this.syncState.clearAuth(),this.authState.state!=="noAuth"&&this.setAndReportAuthFailed(this.authState.config.onAuthChange);return}if(this.authState.state==="waitingForServerConfirmationOfFreshToken"&&(this.tokenConfirmationAttempts++,this._logVerbose(`retrying reauthentication, ${MAX_TOKEN_CONFIRMATION_ATTEMPTS-this.tokenConfirmationAttempts} attempts remaining`)),this.notifyRefreshChange(!0),await this.stopSocket(),this.authState.state==="noAuth")return;let token=await this.fetchTokenAndGuardAgainstRace(this.authState.config.fetchToken,{forceRefreshToken:!0});token.isFromOutdatedConfig||(token.value&&this.syncState.isNewAuth(token.value)?(this.authenticate(token.value),this.setAuthState({state:"waitingForServerConfirmationOfFreshToken",config:this.authState.config,token:token.value,hadAuth:this.authState.state==="notRefetching"||this.authState.state==="waitingForScheduledRefetch"})):(this._logVerbose("reauthentication failed, could not fetch a new token"),this.syncState.hasAuth()&&this.syncState.clearAuth(),this.setAndReportAuthFailed(this.authState.config.onAuthChange)),this.tryRestartSocket())}async refetchToken(){if(this.authState.state==="noAuth")return;this._logVerbose("refetching auth token");let token=await this.fetchTokenAndGuardAgainstRace(this.authState.config.fetchToken,{forceRefreshToken:!0});token.isFromOutdatedConfig||(token.value?this.syncState.isNewAuth(token.value)?(this.setAuthState({state:"waitingForServerConfirmationOfFreshToken",hadAuth:this.syncState.hasAuth(),token:token.value,config:this.authState.config}),this.authenticate(token.value)):this.setAuthState({state:"notRefetching",config:this.authState.config}):(this._logVerbose("refetching token failed"),this.syncState.hasAuth()&&this.clearAuth(),this.setAndReportAuthFailed(this.authState.config.onAuthChange)),this._logVerbose("restarting WS after auth token fetch (if currently stopped)"),this.tryRestartSocket())}scheduleTokenRefetch(token,clientClockSkewMs){if(this.authState.state==="noAuth")return;let decodedToken=this.decodeToken(token);if(!decodedToken){this.logger.error("Auth token is not a valid JWT, cannot refetch the token");return}let{iat,exp}=decodedToken;if(!iat||!exp){this.logger.error("Auth token does not have required fields, cannot refetch the token");return}let fullLifetimeSeconds=exp-iat;if(fullLifetimeSeconds<=2){this.logger.error("Auth token does not live long enough, cannot refetch the token");return}let tokenValiditySeconds;if(clientClockSkewMs!==void 0){let estimatedServerNowSeconds=(Date.now()-clientClockSkewMs)/1e3;tokenValiditySeconds=exp-estimatedServerNowSeconds,tokenValiditySeconds<=0&&(tokenValiditySeconds=0)}else tokenValiditySeconds=fullLifetimeSeconds;let delay=Math.min(MAXIMUM_REFRESH_DELAY,(tokenValiditySeconds-this.refreshTokenLeewaySeconds)*1e3);delay<=0&&(this.logger.warn(`Refetching auth token immediately, configured leeway ${this.refreshTokenLeewaySeconds}s is larger than the token's lifetime ${tokenValiditySeconds}s`),delay=0);let refetchTokenTimeoutId=setTimeout(()=>{this._logVerbose("running scheduled token refetch"),this.refetchToken()},delay);this.setAuthState({state:"waitingForScheduledRefetch",refetchTokenTimeoutId,config:this.authState.config}),this._logVerbose(`scheduled preemptive auth token refetching in ${delay}ms`)}async fetchTokenAndGuardAgainstRace(fetchToken2,fetchArgs){let originalConfigVersion=++this.configVersion;this._logVerbose(`fetching token with config version ${originalConfigVersion}`);let token=await fetchToken2(fetchArgs);return this.configVersion!==originalConfigVersion?(this._logVerbose(`stale config version, expected ${originalConfigVersion}, got ${this.configVersion}`),{isFromOutdatedConfig:!0}):{isFromOutdatedConfig:!1,value:token}}stop(){this.resetAuthState(),this.configVersion++,this._logVerbose(`config version bumped to ${this.configVersion}`)}setAndReportAuthFailed(onAuthChange){onAuthChange(!1),this.resetAuthState()}resetAuthState(){this.notifyRefreshChange(!1),this.setAuthState({state:"noAuth"})}setAuthState(newAuth){let authStateForLog=newAuth.state==="waitingForServerConfirmationOfFreshToken"?{hadAuth:newAuth.hadAuth,state:newAuth.state,token:`...${newAuth.token.slice(-7)}`}:{state:newAuth.state};switch(this._logVerbose(`setting auth state to ${JSON.stringify(authStateForLog)}`),newAuth.state){case"waitingForScheduledRefetch":case"notRefetching":case"noAuth":this.tokenConfirmationAttempts=0;break;case"waitingForServerConfirmationOfFreshToken":case"waitingForServerConfirmationOfCachedToken":case"initialRefetch":break;default:}this.authState.state==="waitingForScheduledRefetch"&&clearTimeout(this.authState.refetchTokenTimeoutId),this.authState=newAuth}decodeToken(token){try{return jwtDecode(token)}catch(e){return this._logVerbose(`Error decoding token: ${e instanceof Error?e.message:"Unknown error"}`),null}}_logVerbose(message){this.logger.logVerbose(`${message} [v${this.configVersion}]`)}}}});function mark(name,sessionId){let detail={sessionId};typeof performance>"u"||!performance.mark||performance.mark(name,{detail})}function performanceMarkToJson(mark2){let name=mark2.name.slice(6);return name=name.charAt(0).toLowerCase()+name.slice(1),{name,startTime:mark2.startTime}}function getMarksReport(sessionId){if(typeof performance>"u"||!performance.getEntriesByName)return[];let allMarks=[];for(let name of markNames){let marks=performance.getEntriesByName(name).filter(entry=>entry.entryType==="mark").filter(mark2=>mark2.detail.sessionId===sessionId);allMarks.push(...marks)}return allMarks.map(performanceMarkToJson)}var markNames,init_metrics=__esm({"../../node_modules/convex/dist/esm/browser/sync/metrics.js"(){"use strict";markNames=["convexClientConstructed","convexWebSocketOpen","convexFirstMessageReceived"]}});var __defProp11,__defNormalProp10,__publicField10,BaseConvexClient,init_client=__esm({"../../node_modules/convex/dist/esm/browser/sync/client.js"(){"use strict";init_esm();init_values();init_logging();init_local_state();init_request_manager();init_optimistic_updates_impl();init_remote_query_set();init_udf_path_utils();init_web_socket_manager();init_session();init_authentication_manager();init_metrics();init_common();init_errors();init_jwt_decode();__defProp11=Object.defineProperty,__defNormalProp10=(obj,key,value)=>key in obj?__defProp11(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,__publicField10=(obj,key,value)=>__defNormalProp10(obj,typeof key!="symbol"?key+"":key,value),BaseConvexClient=class{constructor(address,onTransition,options){if(__publicField10(this,"address"),__publicField10(this,"state"),__publicField10(this,"requestManager"),__publicField10(this,"webSocketManager"),__publicField10(this,"authenticationManager"),__publicField10(this,"remoteQuerySet"),__publicField10(this,"optimisticQueryResults"),__publicField10(this,"_transitionHandlerCounter",0),__publicField10(this,"_nextRequestId"),__publicField10(this,"_onTransitionFns",new Map),__publicField10(this,"_sessionId"),__publicField10(this,"firstMessageReceived",!1),__publicField10(this,"debug"),__publicField10(this,"logger"),__publicField10(this,"maxObservedTimestamp"),__publicField10(this,"connectionStateSubscribers",new Map),__publicField10(this,"nextConnectionStateSubscriberId",0),__publicField10(this,"_lastPublishedConnectionState"),__publicField10(this,"markConnectionStateDirty",()=>{Promise.resolve().then(()=>{let curConnectionState=this.connectionState();if(JSON.stringify(curConnectionState)!==JSON.stringify(this._lastPublishedConnectionState)){this._lastPublishedConnectionState=curConnectionState;for(let cb of this.connectionStateSubscribers.values())cb(curConnectionState)}})}),__publicField10(this,"mark",name=>{this.debug&&mark(name,this.sessionId)}),typeof address=="object")throw new Error("Passing a ClientConfig object is no longer supported. Pass the URL of the Convex deployment as a string directly.");options?.skipConvexDeploymentUrlCheck!==!0&&validateDeploymentUrl(address),options={...options};let authRefreshTokenLeewaySeconds=options.authRefreshTokenLeewaySeconds??10,webSocketConstructor=options.webSocketConstructor;if(!webSocketConstructor&&typeof WebSocket>"u")throw new Error("No WebSocket global variable defined! To use Convex in an environment without WebSocket try the HTTP client: https://docs.convex.dev/api/classes/browser.ConvexHttpClient");webSocketConstructor=webSocketConstructor||WebSocket,this.debug=options.reportDebugInfoToConvex??!1,this.address=address,this.logger=options.logger===!1?instantiateNoopLogger({verbose:options.verbose??!1}):options.logger!==!0&&options.logger?options.logger:instantiateDefaultLogger({verbose:options.verbose??!1});let i2=address.search("://");if(i2===-1)throw new Error("Provided address was not an absolute URL.");let origin=address.substring(i2+3),protocol=address.substring(0,i2),wsProtocol;if(protocol==="http")wsProtocol="ws";else if(protocol==="https")wsProtocol="wss";else throw new Error(`Unknown parent protocol ${protocol}`);let wsUri=`${wsProtocol}://${origin}/api/${version}/sync`;this.state=new LocalSyncState,this.remoteQuerySet=new RemoteQuerySet(queryId=>this.state.queryPath(queryId),this.logger),this.requestManager=new RequestManager(this.logger,this.markConnectionStateDirty);let pauseSocket=()=>{this.webSocketManager.pause(),this.state.pause()};this.authenticationManager=new AuthenticationManager(this.state,{authenticate:token=>{let message=this.state.setAuth(token);return this.webSocketManager.sendMessage(message),message.baseVersion},stopSocket:()=>this.webSocketManager.stop(),tryRestartSocket:()=>this.webSocketManager.tryRestart(),pauseSocket,resumeSocket:()=>this.webSocketManager.resume(),clearAuth:()=>{this.clearAuth()}},{logger:this.logger,refreshTokenLeewaySeconds:authRefreshTokenLeewaySeconds,initialAuthTokenReuse:options.initialAuthTokenReuse??!1}),this.optimisticQueryResults=new OptimisticQueryResults,this.addOnTransitionHandler(transition=>{onTransition(transition.queries.map(q=>q.token))}),this._nextRequestId=0,this._sessionId=newSessionId();let{unsavedChangesWarning}=options;if(typeof window>"u"||typeof window.addEventListener>"u"){if(unsavedChangesWarning===!0)throw new Error("unsavedChangesWarning requested, but window.addEventListener not found! Remove {unsavedChangesWarning: true} from Convex client options.")}else unsavedChangesWarning!==!1&&window.addEventListener("beforeunload",e=>{if(this.requestManager.hasIncompleteRequests()){e.preventDefault();let confirmationMessage="Are you sure you want to leave? Your changes may not be saved.";return(e||window.event).returnValue=confirmationMessage,confirmationMessage}});this.webSocketManager=new WebSocketManager(wsUri,{onOpen:reconnectMetadata=>{this.mark("convexWebSocketOpen"),this.webSocketManager.sendMessage({...reconnectMetadata,type:"Connect",sessionId:this._sessionId,maxObservedTimestamp:this.maxObservedTimestamp}),this.remoteQuerySet=new RemoteQuerySet(queryId=>this.state.queryPath(queryId),this.logger);let[querySetModification,authModification]=this.state.restart();authModification&&this.webSocketManager.sendMessage(authModification),this.webSocketManager.sendMessage(querySetModification);for(let message of this.requestManager.restart())this.webSocketManager.sendMessage(message)},onResume:()=>{let[querySetModification,authModification]=this.state.resume();authModification&&this.webSocketManager.sendMessage(authModification),querySetModification&&this.webSocketManager.sendMessage(querySetModification);for(let message of this.requestManager.resume())this.webSocketManager.sendMessage(message)},onMessage:serverMessage=>{switch(this.firstMessageReceived||(this.firstMessageReceived=!0,this.mark("convexFirstMessageReceived"),this.reportMarks()),serverMessage.type){case"Transition":{this.observedTimestamp(serverMessage.endVersion.ts),this.authenticationManager.onTransition(serverMessage),this.remoteQuerySet.transition(serverMessage),this.state.transition(serverMessage);let completedRequests=this.requestManager.removeCompleted(this.remoteQuerySet.timestamp());this.notifyOnQueryResultChanges(completedRequests);break}case"MutationResponse":{serverMessage.success&&this.observedTimestamp(serverMessage.ts);let completedMutationInfo=this.requestManager.onResponse(serverMessage);completedMutationInfo!==null&&this.notifyOnQueryResultChanges(new Map([[completedMutationInfo.requestId,completedMutationInfo.result]]));break}case"ActionResponse":{this.requestManager.onResponse(serverMessage);break}case"AuthError":{this.authenticationManager.onAuthError(serverMessage);break}case"FatalError":{let error2=logFatalError(this.logger,serverMessage.error);throw this.webSocketManager.terminate(),error2}default:}return{hasSyncedPastLastReconnect:this.hasSyncedPastLastReconnect()}},onServerDisconnectError:options.onServerDisconnectError},webSocketConstructor,this.logger,this.markConnectionStateDirty,this.debug),this.mark("convexClientConstructed"),options.expectAuth&&pauseSocket()}hasSyncedPastLastReconnect(){return this.requestManager.hasSyncedPastLastReconnect()&&this.state.hasSyncedPastLastReconnect()}observedTimestamp(observedTs){(this.maxObservedTimestamp===void 0||this.maxObservedTimestamp.lessThanOrEqual(observedTs))&&(this.maxObservedTimestamp=observedTs)}getMaxObservedTimestamp(){return this.maxObservedTimestamp}notifyOnQueryResultChanges(completedRequests){let remoteQueryResults=this.remoteQuerySet.remoteQueryResults(),queryTokenToValue=new Map;for(let[queryId,result]of remoteQueryResults){let queryToken=this.state.queryToken(queryId);if(queryToken!==null){let query={result,udfPath:this.state.queryPath(queryId),args:this.state.queryArgs(queryId)};queryTokenToValue.set(queryToken,query)}}let changedQueryTokens=this.optimisticQueryResults.ingestQueryResultsFromServer(queryTokenToValue,new Set(completedRequests.keys()));this.handleTransition({queries:changedQueryTokens.map(token=>{let optimisticResult=this.optimisticQueryResults.rawQueryResult(token);return{token,modification:{kind:"Updated",result:optimisticResult}}}),reflectedMutations:Array.from(completedRequests).map(([requestId,result])=>({requestId,result})),timestamp:this.remoteQuerySet.timestamp()})}handleTransition(transition){for(let fn of this._onTransitionFns.values())fn(transition)}addOnTransitionHandler(fn){let id=this._transitionHandlerCounter++;return this._onTransitionFns.set(id,fn),()=>this._onTransitionFns.delete(id)}getCurrentAuthClaims(){let authToken=this.state.getAuth(),decoded={};if(authToken&&authToken.tokenType==="User")try{decoded=authToken?jwtDecode(authToken.value):{}}catch{decoded={}}else return;return{token:authToken.value,decoded}}setAuth(fetchToken2,onChange,onRefreshChange){this.authenticationManager.setConfig(fetchToken2,onChange,onRefreshChange)}hasAuth(){return this.state.hasAuth()}setAdminAuth(value,fakeUserIdentity){let message=this.state.setAdminAuth(value,fakeUserIdentity);this.webSocketManager.sendMessage(message)}clearAuth(){let message=this.state.clearAuth();this.webSocketManager.sendMessage(message)}subscribe(name,args,options){let argsObject=parseArgs4(args),{modification,queryToken,unsubscribe}=this.state.subscribe(name,argsObject,options?.journal,options?.componentPath);return modification!==null&&this.webSocketManager.sendMessage(modification),{queryToken,unsubscribe:()=>{let modification2=unsubscribe();modification2&&this.webSocketManager.sendMessage(modification2)}}}localQueryResult(udfPath,args){let argsObject=parseArgs4(args),queryToken=serializePathAndArgs(udfPath,argsObject);return this.optimisticQueryResults.queryResult(queryToken)}localQueryResultByToken(queryToken){return this.optimisticQueryResults.queryResult(queryToken)}hasLocalQueryResultByToken(queryToken){return this.optimisticQueryResults.hasQueryResult(queryToken)}localQueryLogs(udfPath,args){let argsObject=parseArgs4(args),queryToken=serializePathAndArgs(udfPath,argsObject);return this.optimisticQueryResults.queryLogs(queryToken)}queryJournal(name,args){let argsObject=parseArgs4(args),queryToken=serializePathAndArgs(name,argsObject);return this.state.queryJournal(queryToken)}connectionState(){let wsConnectionState=this.webSocketManager.connectionState();return{hasInflightRequests:this.requestManager.hasInflightRequests(),isWebSocketConnected:wsConnectionState.isConnected,hasEverConnected:wsConnectionState.hasEverConnected,connectionCount:wsConnectionState.connectionCount,connectionRetries:wsConnectionState.connectionRetries,timeOfOldestInflightRequest:this.requestManager.timeOfOldestInflightRequest(),inflightMutations:this.requestManager.inflightMutations(),inflightActions:this.requestManager.inflightActions()}}subscribeToConnectionState(cb){let id=this.nextConnectionStateSubscriberId++;return this.connectionStateSubscribers.set(id,cb),()=>{this.connectionStateSubscribers.delete(id)}}async mutation(name,args,options){let result=await this.mutationInternal(name,args,options);if(!result.success)throw result.errorData!==void 0?forwardData(result,new ConvexError(createHybridErrorStacktrace("mutation",name,result))):new Error(createHybridErrorStacktrace("mutation",name,result));return result.value}async mutationInternal(udfPath,args,options,componentPath){let{mutationPromise}=this.enqueueMutation(udfPath,args,options,componentPath);return mutationPromise}enqueueMutation(udfPath,args,options,componentPath){let mutationArgs=parseArgs4(args);this.tryReportLongDisconnect();let requestId=this.nextRequestId;if(this._nextRequestId++,options!==void 0){let optimisticUpdate=options.optimisticUpdate;if(optimisticUpdate!==void 0){let wrappedUpdate=localQueryStore=>{optimisticUpdate(localQueryStore,mutationArgs)instanceof Promise&&this.logger.warn("Optimistic update handler returned a Promise. Optimistic updates should be synchronous.")},changedQueries=this.optimisticQueryResults.applyOptimisticUpdate(wrappedUpdate,requestId).map(token=>{let localResult=this.localQueryResultByToken(token);return{token,modification:{kind:"Updated",result:localResult===void 0?void 0:{success:!0,value:localResult,logLines:[]}}}});this.handleTransition({queries:changedQueries,reflectedMutations:[],timestamp:this.remoteQuerySet.timestamp()})}}let message={type:"Mutation",requestId,udfPath,componentPath,args:[convexToJson(mutationArgs)]},mightBeSent=this.webSocketManager.sendMessage(message),mutationPromise=this.requestManager.request(message,mightBeSent);return{requestId,mutationPromise}}async action(name,args){let result=await this.actionInternal(name,args);if(!result.success)throw result.errorData!==void 0?forwardData(result,new ConvexError(createHybridErrorStacktrace("action",name,result))):new Error(createHybridErrorStacktrace("action",name,result));return result.value}async actionInternal(udfPath,args,componentPath){let actionArgs=parseArgs4(args),requestId=this.nextRequestId;this._nextRequestId++,this.tryReportLongDisconnect();let message={type:"Action",requestId,udfPath,componentPath,args:[convexToJson(actionArgs)]},mightBeSent=this.webSocketManager.sendMessage(message);return this.requestManager.request(message,mightBeSent)}async close(){return this.authenticationManager.stop(),this.webSocketManager.terminate()}get url(){return this.address}get nextRequestId(){return this._nextRequestId}get sessionId(){return this._sessionId}reportMarks(){if(this.debug){let report=getMarksReport(this.sessionId);this.webSocketManager.sendMessage({type:"Event",eventType:"ClientConnect",event:report})}}tryReportLongDisconnect(){if(!this.debug)return;let timeOfOldestRequest=this.connectionState().timeOfOldestInflightRequest;if(timeOfOldestRequest===null||Date.now()-timeOfOldestRequest.getTime()<=60*1e3)return;let endpoint=`${this.address}/api/debug_event`;fetch(endpoint,{method:"POST",headers:{"Content-Type":"application/json","Convex-Client":`npm-${version}`},body:JSON.stringify({event:"LongWebsocketDisconnect"})}).then(response=>{response.ok||this.logger.warn("Analytics request failed with response:",response.body)}).catch(error2=>{this.logger.warn("Analytics response failed with error:",error2)})}}}});function asPaginationResult(value){if(typeof value!="object"||value===null||!Array.isArray(value.page)||typeof value.isDone!="boolean"||typeof value.continueCursor!="string")throw new Error(`Not a valid paginated query result: ${value?.toString()}`);return value}var init_pagination=__esm({"../../node_modules/convex/dist/esm/browser/sync/pagination.js"(){"use strict"}});var __defProp12,__defNormalProp11,__publicField11,PaginatedQueryClient,init_paginated_query_client=__esm({"../../node_modules/convex/dist/esm/browser/sync/paginated_query_client.js"(){"use strict";init_udf_path_utils();init_pagination();init_long();__defProp12=Object.defineProperty,__defNormalProp11=(obj,key,value)=>key in obj?__defProp12(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,__publicField11=(obj,key,value)=>__defNormalProp11(obj,typeof key!="symbol"?key+"":key,value),PaginatedQueryClient=class{constructor(client,onTransition){this.client=client,this.onTransition=onTransition,__publicField11(this,"paginatedQuerySet",new Map),__publicField11(this,"lastTransitionTs"),this.lastTransitionTs=Long.fromNumber(0),this.client.addOnTransitionHandler(transition=>this.onBaseTransition(transition))}subscribe(name,args,options){let canonicalizedUdfPath=canonicalizeUdfPath(name),token=serializePaginatedPathAndArgs(canonicalizedUdfPath,args,options),unsubscribe=()=>this.removePaginatedQuerySubscriber(token),existingEntry=this.paginatedQuerySet.get(token);return existingEntry?(existingEntry.numSubscribers+=1,{paginatedQueryToken:token,unsubscribe}):(this.paginatedQuerySet.set(token,{token,canonicalizedUdfPath,args,numSubscribers:1,options:{initialNumItems:options.initialNumItems},nextPageKey:0,pageKeys:[],pageKeyToQuery:new Map,ongoingSplits:new Map,skip:!1,id:options.id}),this.addPageToPaginatedQuery(token,null,options.initialNumItems),{paginatedQueryToken:token,unsubscribe})}localQueryResult(name,args,options){let canonicalizedUdfPath=canonicalizeUdfPath(name),token=serializePaginatedPathAndArgs(canonicalizedUdfPath,args,options);return this.localQueryResultByToken(token)}localQueryResultByToken(token){let paginatedQuery=this.paginatedQuerySet.get(token);if(!paginatedQuery)return;let activePages=this.activePageQueryTokens(paginatedQuery);if(activePages.length===0)return{results:[],status:"LoadingFirstPage",loadMore:numItems=>this.loadMoreOfPaginatedQuery(token,numItems)};let allResults=[],hasUndefined=!1,isDone=!1;for(let pageToken of activePages){let result=this.client.localQueryResultByToken(pageToken);if(result===void 0){hasUndefined=!0,isDone=!1;continue}let paginationResult=asPaginationResult(result);allResults=allResults.concat(paginationResult.page),isDone=!!paginationResult.isDone}let status;return hasUndefined?status=allResults.length===0?"LoadingFirstPage":"LoadingMore":isDone?status="Exhausted":status="CanLoadMore",{results:allResults,status,loadMore:numItems=>this.loadMoreOfPaginatedQuery(token,numItems)}}onBaseTransition(transition){let changedBaseTokens=transition.queries.map(q=>q.token),changed=this.queriesContainingTokens(changedBaseTokens),paginatedQueries=[];changed.length>0&&(this.processPaginatedQuerySplits(changed,token=>this.client.localQueryResultByToken(token)),paginatedQueries=changed.map(token=>({token,modification:{kind:"Updated",result:this.localQueryResultByToken(token)}})));let extendedTransition={...transition,paginatedQueries};this.onTransition(extendedTransition)}loadMoreOfPaginatedQuery(token,numItems){this.mustGetPaginatedQuery(token);let lastPageToken=this.queryTokenForLastPageOfPaginatedQuery(token),lastPageResult=this.client.localQueryResultByToken(lastPageToken);if(!lastPageResult)return!1;let paginationResult=asPaginationResult(lastPageResult);if(paginationResult.isDone)return!1;this.addPageToPaginatedQuery(token,paginationResult.continueCursor,numItems);let loadMoreTransition={timestamp:this.lastTransitionTs,reflectedMutations:[],queries:[],paginatedQueries:[{token,modification:{kind:"Updated",result:this.localQueryResultByToken(token)}}]};return this.onTransition(loadMoreTransition),!0}queriesContainingTokens(queryTokens){if(queryTokens.length===0)return[];let changed=[],queryTokenSet=new Set(queryTokens);for(let[paginatedToken,paginatedQuery]of this.paginatedQuerySet)for(let pageToken of this.allQueryTokens(paginatedQuery))if(queryTokenSet.has(pageToken)){changed.push(paginatedToken);break}return changed}processPaginatedQuerySplits(changed,getResult){for(let paginatedQueryToken of changed){let paginatedQuery=this.mustGetPaginatedQuery(paginatedQueryToken),{ongoingSplits,pageKeyToQuery,pageKeys}=paginatedQuery;for(let[pageKey,[splitKey1,splitKey2]]of ongoingSplits)getResult(pageKeyToQuery.get(splitKey1).queryToken)!==void 0&&getResult(pageKeyToQuery.get(splitKey2).queryToken)!==void 0&&this.completePaginatedQuerySplit(paginatedQuery,pageKey,splitKey1,splitKey2);for(let pageKey of pageKeys){if(ongoingSplits.has(pageKey))continue;let pageEntry=pageKeyToQuery.get(pageKey);if(!pageEntry)throw new Error(`No page query for active pageKey ${pageKey}`);let pageResult=getResult(pageEntry.queryToken);if(!pageResult)continue;let result=asPaginationResult(pageResult);result.splitCursor&&(result.pageStatus==="SplitRecommended"||result.pageStatus==="SplitRequired"||result.page.length>paginatedQuery.options.initialNumItems*2)&&this.splitPaginatedQueryPage(paginatedQuery,pageKey,pageEntry.cursor,result.splitCursor,result.continueCursor)}}}splitPaginatedQueryPage(paginatedQuery,pageKey,startCursor,splitCursor,continueCursor){let splitKey1=paginatedQuery.nextPageKey++,splitKey2=paginatedQuery.nextPageKey++,paginationOpts={numItems:paginatedQuery.options.initialNumItems,id:paginatedQuery.id},firstSubscription=this.client.subscribe(paginatedQuery.canonicalizedUdfPath,{...paginatedQuery.args,paginationOpts:{...paginationOpts,cursor:startCursor,endCursor:splitCursor}});paginatedQuery.pageKeyToQuery.set(splitKey1,{...firstSubscription,cursor:startCursor});let secondSubscription=this.client.subscribe(paginatedQuery.canonicalizedUdfPath,{...paginatedQuery.args,paginationOpts:{...paginationOpts,cursor:splitCursor,endCursor:continueCursor}});paginatedQuery.pageKeyToQuery.set(splitKey2,{...secondSubscription,cursor:splitCursor}),paginatedQuery.ongoingSplits.set(pageKey,[splitKey1,splitKey2])}addPageToPaginatedQuery(token,continueCursor,numItems){let paginatedQuery=this.mustGetPaginatedQuery(token),pageKey=paginatedQuery.nextPageKey++,paginationOpts={cursor:continueCursor,numItems,id:paginatedQuery.id},pageArgs={...paginatedQuery.args,paginationOpts},subscription=this.client.subscribe(paginatedQuery.canonicalizedUdfPath,pageArgs);return paginatedQuery.pageKeys.push(pageKey),paginatedQuery.pageKeyToQuery.set(pageKey,{...subscription,cursor:continueCursor}),subscription}removePaginatedQuerySubscriber(token){let paginatedQuery=this.paginatedQuerySet.get(token);if(paginatedQuery&&(paginatedQuery.numSubscribers-=1,!(paginatedQuery.numSubscribers>0))){for(let subscription of paginatedQuery.pageKeyToQuery.values())subscription.unsubscribe();this.paginatedQuerySet.delete(token)}}completePaginatedQuerySplit(paginatedQuery,pageKey,splitKey1,splitKey2){let originalQuery=paginatedQuery.pageKeyToQuery.get(pageKey);paginatedQuery.pageKeyToQuery.delete(pageKey);let pageIndex=paginatedQuery.pageKeys.indexOf(pageKey);paginatedQuery.pageKeys.splice(pageIndex,1,splitKey1,splitKey2),paginatedQuery.ongoingSplits.delete(pageKey),originalQuery.unsubscribe()}activePageQueryTokens(paginatedQuery){return paginatedQuery.pageKeys.map(pageKey=>paginatedQuery.pageKeyToQuery.get(pageKey).queryToken)}allQueryTokens(paginatedQuery){return Array.from(paginatedQuery.pageKeyToQuery.values()).map(sub=>sub.queryToken)}queryTokenForLastPageOfPaginatedQuery(token){let paginatedQuery=this.mustGetPaginatedQuery(token),lastPageKey=paginatedQuery.pageKeys[paginatedQuery.pageKeys.length-1];if(lastPageKey===void 0)throw new Error(`No pages for paginated query ${token}`);return paginatedQuery.pageKeyToQuery.get(lastPageKey).queryToken}mustGetPaginatedQuery(token){let paginatedQuery=this.paginatedQuerySet.get(token);if(!paginatedQuery)throw new Error("paginated query no longer exists for token "+token);return paginatedQuery}}}});var __defProp13,__defNormalProp12,__publicField12,defaultWebSocketConstructor,ConvexClient,init_simple_client=__esm({"../../node_modules/convex/dist/esm/browser/simple_client.js"(){"use strict";init_common();init_api();init_client();init_paginated_query_client();init_udf_path_utils();__defProp13=Object.defineProperty,__defNormalProp12=(obj,key,value)=>key in obj?__defProp13(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,__publicField12=(obj,key,value)=>__defNormalProp12(obj,typeof key!="symbol"?key+"":key,value),ConvexClient=class{constructor(address,options={}){__publicField12(this,"listeners"),__publicField12(this,"_client"),__publicField12(this,"_paginatedClient"),__publicField12(this,"callNewListenersWithCurrentValuesTimer"),__publicField12(this,"_closed"),__publicField12(this,"_disabled"),options.skipConvexDeploymentUrlCheck!==!0&&validateDeploymentUrl(address);let{disabled,...baseOptions}=options;this._closed=!1,this._disabled=!!disabled,defaultWebSocketConstructor&&!("webSocketConstructor"in baseOptions)&&typeof WebSocket>"u"&&(baseOptions.webSocketConstructor=defaultWebSocketConstructor),typeof window>"u"&&!("unsavedChangesWarning"in baseOptions)&&(baseOptions.unsavedChangesWarning=!1),this.disabled||(this._client=new BaseConvexClient(address,()=>{},baseOptions),this._paginatedClient=new PaginatedQueryClient(this._client,transition=>this._transition(transition))),this.listeners=new Set}get closed(){return this._closed}get client(){if(this._client)return this._client;throw new Error("ConvexClient is disabled")}get paginatedClient(){if(this._paginatedClient)return this._paginatedClient;throw new Error("ConvexClient is disabled")}get disabled(){return this._disabled}onUpdate(query,args,callback,onError){if(this.disabled)return this.createDisabledUnsubscribe();let{queryToken,unsubscribe}=this.client.subscribe(getFunctionName(query),args),queryInfo={queryToken,callback,onError,unsubscribe,hasEverRun:!1,query,args,paginationOptions:void 0};this.listeners.add(queryInfo),this.queryResultReady(queryToken)&&this.callNewListenersWithCurrentValuesTimer===void 0&&(this.callNewListenersWithCurrentValuesTimer=setTimeout(()=>this.callNewListenersWithCurrentValues(),0));let unsubscribeProps={unsubscribe:()=>{this.closed||(this.listeners.delete(queryInfo),unsubscribe())},getCurrentValue:()=>this.client.localQueryResultByToken(queryToken),getQueryLogs:()=>this.client.localQueryLogs(queryToken)},ret=unsubscribeProps.unsubscribe;return Object.assign(ret,unsubscribeProps),ret}onPaginatedUpdate_experimental(query,args,options,callback,onError){if(this.disabled)return this.createDisabledUnsubscribe();let paginationOptions={initialNumItems:options.initialNumItems,id:-1},{paginatedQueryToken,unsubscribe}=this.paginatedClient.subscribe(getFunctionName(query),args,paginationOptions),queryInfo={queryToken:paginatedQueryToken,callback,onError,unsubscribe,hasEverRun:!1,query,args,paginationOptions};this.listeners.add(queryInfo),this.paginatedClient.localQueryResultByToken(paginatedQueryToken)&&this.callNewListenersWithCurrentValuesTimer===void 0&&(this.callNewListenersWithCurrentValuesTimer=setTimeout(()=>this.callNewListenersWithCurrentValues(),0));let unsubscribeProps={unsubscribe:()=>{this.closed||(this.listeners.delete(queryInfo),unsubscribe())},getCurrentValue:()=>this.paginatedClient.localQueryResult(getFunctionName(query),args,paginationOptions),getQueryLogs:()=>[]},ret=unsubscribeProps.unsubscribe;return Object.assign(ret,unsubscribeProps),ret}callNewListenersWithCurrentValues(){this.callNewListenersWithCurrentValuesTimer=void 0,this._transition({queries:[],paginatedQueries:[]},!0)}queryResultReady(queryToken){return this.client.hasLocalQueryResultByToken(queryToken)}createDisabledUnsubscribe(){let disabledUnsubscribe=(()=>{});return Object.assign(disabledUnsubscribe,{unsubscribe:disabledUnsubscribe,getCurrentValue:()=>{},getQueryLogs:()=>{}}),disabledUnsubscribe}async close(){if(!this.disabled)return this.listeners.clear(),this._closed=!0,this._paginatedClient&&(this._paginatedClient=void 0),this.client.close()}getAuth(){if(!this.disabled)return this.client.getCurrentAuthClaims()}setAuth(fetchToken2,onChange){this.disabled||this.client.setAuth(fetchToken2,onChange??(()=>{}))}setAdminAuth(token,identity){if(this.closed)throw new Error("ConvexClient has already been closed.");this.disabled||this.client.setAdminAuth(token,identity)}_transition({queries,paginatedQueries},callNewListeners=!1){let updatedQueries=[...queries.map(q=>q.token),...paginatedQueries.map(q=>q.token)];for(let queryInfo of this.listeners){let{callback,queryToken,onError,hasEverRun}=queryInfo,isPaginatedQuery=serializedQueryTokenIsPaginated(queryToken),hasResultReady=isPaginatedQuery?!!this.paginatedClient.localQueryResultByToken(queryToken):this.client.hasLocalQueryResultByToken(queryToken);if(updatedQueries.includes(queryToken)||callNewListeners&&!hasEverRun&&hasResultReady){queryInfo.hasEverRun=!0;let newValue;try{isPaginatedQuery?newValue=this.paginatedClient.localQueryResultByToken(queryToken):newValue=this.client.localQueryResultByToken(queryToken)}catch(error2){if(!(error2 instanceof Error))throw error2;onError?onError(error2,"Second argument to onUpdate onError is reserved for later use"):Promise.reject(error2);continue}callback(newValue,"Second argument to onUpdate callback is reserved for later use")}}}async mutation(mutation,args,options){if(this.disabled)throw new Error("ConvexClient is disabled");return await this.client.mutation(getFunctionName(mutation),args,options)}async action(action,args){if(this.disabled)throw new Error("ConvexClient is disabled");return await this.client.action(getFunctionName(action),args)}async query(query,args){if(this.disabled)throw new Error("ConvexClient is disabled");let value=this.client.localQueryResult(getFunctionName(query),args);return value!==void 0?Promise.resolve(value):new Promise((resolve4,reject)=>{let{unsubscribe}=this.onUpdate(query,args,value2=>{unsubscribe(),resolve4(value2)},e=>{unsubscribe(),reject(e)})})}connectionState(){if(this.disabled)throw new Error("ConvexClient is disabled");return this.client.connectionState()}subscribeToConnectionState(cb){return this.disabled?()=>{}:this.client.subscribeToConnectionState(cb)}}}});var require_device_mcp_runner=__commonJS({"../../apps/web/electron/local-tools/device-mcp-runner.js"(exports,module){"use strict";function startDeviceMcpRunner2({registry:registry2,localScope,client,web:web2,scope,log:log2}){let active=new Map,subscriptions=new Map,lifetime=new AbortController,refreshing=!1;async function handle(requestId){if(!(active.has(requestId)||lifetime.signal.aborted)){active.set(requestId,!0);try{let claimed=await client.mutation(web2.claimDeviceMcp,{scope,requestId});if(!claimed||lifetime.signal.aborted)return;let signal=AbortSignal.any([lifetime.signal,AbortSignal.timeout(Math.max(1,claimed.expiresAt-Date.now()))]),sequence=0,lastProgress=0,result;try{result=await registry2.run(localScope,claimed.registrationId,JSON.parse(claimed.operation),{signal,onprogress(progress){Date.now()-lastProgress<250||(lastProgress=Date.now(),client.mutation(web2.reportDeviceMcp,{scope,requestId,event:{seq:++sequence,progress:JSON.stringify({progress:progress.progress,total:progress.total})}}).catch(log2))}})}catch{result={isError:!0,content:[{type:"text",text:"Device MCP call failed. Check the server on the device."}]}}await client.mutation(web2.reportDeviceMcp,{scope,requestId,event:{result:JSON.stringify(result)}})}catch(error2){log2(error2)}finally{active.delete(requestId)}}}async function listTools(entry){let cursor,tools=[];do{let page=await registry2.run(localScope,entry.registrationId,{method:"tools/list",cursor},{signal:lifetime.signal});if(tools.push(...page.tools.map(t=>({name:t.name,description:t.description??"",schema:t.inputSchema}))),cursor=page.nextCursor,tools.length>100||cursor&&!page.tools.length)throw new Error("Device MCP catalog exceeds limit.")}while(cursor);return tools}async function refreshServer(entry){if(lifetime.signal.aborted)return;let subscription=subscriptions.get(entry.registrationId),serverId=subscription?.id??await client.mutation("token"in scope?web2.machineRegisterMcpServer:web2.studioRegisterDeviceMcpServer,{...scope,...entry});if(subscription){await client.mutation(web2.deviceMcpHeartbeat,{scope,serverId});try{let tools2=await listTools(entry),catalog2=JSON.stringify(tools2);if(catalog2===subscription.catalog)return;await client.mutation(web2.publishDeviceMcpCatalog,{scope,serverId,tools:tools2}),subscription.catalog=catalog2}catch(error2){log2(error2)}return}let tools=await listTools(entry),catalog=JSON.stringify(tools);if(await client.mutation(web2.publishDeviceMcpCatalog,{scope,serverId,tools}),lifetime.signal.aborted)return;let off=client.onUpdate(web2.deviceMcpPending,{scope,serverId},ids=>{for(let id of ids)handle(id)},log2);subscriptions.set(entry.registrationId,{id:serverId,off,catalog}),await client.mutation(web2.deviceMcpHeartbeat,{scope,serverId})}async function refresh(){if(!(refreshing||lifetime.signal.aborted)){refreshing=!0;try{let entries=await registry2.list(localScope);await Promise.all(entries.map(entry=>refreshServer(entry).catch(log2)))}catch(error2){log2(error2)}finally{refreshing=!1}}}refresh();let timer=setInterval(refresh,3e4);return()=>{lifetime.abort(),clearInterval(timer);for(let{off}of subscriptions.values())off()}}module.exports={startDeviceMcpRunner:startDeviceMcpRunner2}}});var require_device_mcp_fetch=__commonJS({"../../apps/web/electron/local-tools/device-mcp-fetch.js"(exports,module){"use strict";function deviceMcpFetch(endpoint,signal){let allowed=new URL(endpoint);if(!["http:","https:"].includes(allowed.protocol)||allowed.username||allowed.password||allowed.hash)throw new Error("Choose an HTTP or HTTPS MCP endpoint without embedded credentials or a fragment.");let received=0;return async(input,init)=>{let request=new Request(input,init);if(request.url!==allowed.href)throw new Error("MCP request left the configured device endpoint.");let response=await fetch(request,{redirect:"error",credentials:"omit",signal:AbortSignal.any([signal,request.signal])});if(!response.body)return response;let body=response.body.pipeThrough(new TransformStream({transform(chunk,controller){if(received+=chunk.byteLength,received>512*1024)throw new Error("Device MCP response exceeds 512 KiB.");controller.enqueue(chunk)}}));return new Response(body,{status:response.status,statusText:response.statusText,headers:response.headers})}}module.exports={deviceMcpFetch}}});var util_exports={};__export(util_exports,{BIGINT_FORMAT_RANGES:()=>BIGINT_FORMAT_RANGES,CONSTANT_CATCH:()=>CONSTANT_CATCH,Class:()=>Class,NUMBER_FORMAT_RANGES:()=>NUMBER_FORMAT_RANGES,aborted:()=>aborted,allowsEval:()=>allowsEval,assert:()=>assert,assertEqual:()=>assertEqual,assertIs:()=>assertIs,assertNever:()=>assertNever,assertNotEqual:()=>assertNotEqual,assignProp:()=>assignProp,attachSchema:()=>attachSchema,base64ToUint8Array:()=>base64ToUint8Array,base64urlToUint8Array:()=>base64urlToUint8Array,cached:()=>cached,captureStackTrace:()=>captureStackTrace,cleanEnum:()=>cleanEnum,cleanRegex:()=>cleanRegex,clone:()=>clone,cloneDef:()=>cloneDef,codePointLength:()=>codePointLength,constantCatch:()=>constantCatch,createTransparentProxy:()=>createTransparentProxy,defineLazy:()=>defineLazy,defineLazyInternal:()=>defineLazyInternal,derived:()=>derived,esc:()=>esc,escapeRegex:()=>escapeRegex,explicitlyAborted:()=>explicitlyAborted,extend:()=>extend,finalizeIssue:()=>finalizeIssue,floatSafeRemainder:()=>floatSafeRemainder,getElementAtPath:()=>getElementAtPath,getEnumValues:()=>getEnumValues,getLengthableOrigin:()=>getLengthableOrigin,getParsedType:()=>getParsedType,getSizableOrigin:()=>getSizableOrigin,hexToUint8Array:()=>hexToUint8Array,hide:()=>hide,installLazyProp:()=>installLazyProp,isObject:()=>isObject,isPlainObject:()=>isPlainObject,issue:()=>issue,joinValues:()=>joinValues,jsonStringifyReplacer:()=>jsonStringifyReplacer,members:()=>members,merge:()=>merge,mergeDefs:()=>mergeDefs,normalizeParams:()=>normalizeParams,nullish:()=>nullish,numKeys:()=>numKeys,objectClone:()=>objectClone,omit:()=>omit,optionalKeys:()=>optionalKeys,own:()=>own,parsedType:()=>parsedType,partial:()=>partial,pick:()=>pick,prefixIssues:()=>prefixIssues,primitiveTypes:()=>primitiveTypes,promiseAllObject:()=>promiseAllObject,propertyKeyTypes:()=>propertyKeyTypes,randomString:()=>randomString,rawShape:()=>rawShape,required:()=>required,safeExtend:()=>safeExtend,shallowClone:()=>shallowClone,sizeCaps:()=>sizeCaps,slugify:()=>slugify,stringifyPrimitive:()=>stringifyPrimitive,toZod:()=>toZod,uint8ArrayToBase64:()=>uint8ArrayToBase64,uint8ArrayToBase64url:()=>uint8ArrayToBase64url,uint8ArrayToHex:()=>uint8ArrayToHex,unwrapMessage:()=>unwrapMessage});function assertEqual(val){return val}function assertNotEqual(val){return val}function toZod(){return schema=>schema}function assertIs(_arg){}function assertNever(_x){throw new Error("Unexpected value in exhaustive check")}function assert(_){}function getEnumValues(entries){let numericValues=Object.values(entries).filter(v2=>typeof v2=="number");return Object.entries(entries).filter(([k,_])=>numericValues.indexOf(+k)===-1).map(([_,v2])=>v2)}function joinValues(array2,separator="|"){return array2.map(val=>stringifyPrimitive(val)).join(separator)}function jsonStringifyReplacer(_,value){return typeof value=="bigint"?value.toString():value}function cached(getter){return new Cached(getter)}function nullish(input){return input==null}function cleanRegex(source){let start=source.startsWith("^")?1:0,end=source.endsWith("$")?source.length-1:source.length;return source.slice(start,end)}function floatSafeRemainder(val,step){let ratio=val/step,roundedRatio=Math.round(ratio),tolerance=4*Number.EPSILON*Math.max(Math.abs(ratio),1);return Math.abs(ratio-roundedRatio)<tolerance?0:ratio-roundedRatio}function defineLazy(object3,key,getter){let value;Object.defineProperty(object3,key,{get(){if(value!==EVALUATING)return value===void 0&&(value=EVALUATING,value=getter()),value},set(v2){Object.defineProperty(object3,key,{value:v2})},configurable:!0})}function objectClone(obj){return Object.create(Object.getPrototypeOf(obj),Object.getOwnPropertyDescriptors(obj))}function assignProp(target,prop,value){Object.defineProperty(target,prop,{value,writable:!0,enumerable:!0,configurable:!0})}function rawShape(def){let desc=Object.getOwnPropertyDescriptor(def,"shape");return desc?.get?desc.get.raw:desc?.value}function sourceShape(schema){return rawShape(schema._zod.def)??schema._zod.def.shape}function deferProp(target,key,getter){Object.defineProperty(target,key,{get(){let value=getter();return assignProp(this,key,value),value},enumerable:!0,configurable:!0})}function putProp(target,key,value){key in target?assignProp(target,key,value):target[key]=value}function mirrorShape(target,source,keys,wrap){let raw=sourceShape(source);for(let key of keys){let desc=Object.getOwnPropertyDescriptor(raw,key);desc.enumerable&&(desc.get?deferProp(target,key,()=>{let value=source._zod.def.shape[key];return wrap?wrap(value,key):value}):putProp(target,key,wrap?wrap(desc.value,key):desc.value))}}function mirrorProps(target,source){for(let key of Reflect.ownKeys(source)){let desc=Object.getOwnPropertyDescriptor(source,key);desc.enumerable&&(desc.get?deferProp(target,key,()=>source[key]):putProp(target,key,desc.value))}}function mergeDefs(...defs){let mergedDescriptors={};for(let def of defs){let descriptors=Object.getOwnPropertyDescriptors(def);Object.assign(mergedDescriptors,descriptors)}return Object.defineProperties({},mergedDescriptors)}function cloneDef(schema){return mergeDefs(schema._zod.def)}function getElementAtPath(obj,path){return path?path.reduce((acc,key)=>acc?.[key],obj):obj}function promiseAllObject(promisesObj){let keys=Object.keys(promisesObj),promises=keys.map(key=>promisesObj[key]);return Promise.all(promises).then(results=>{let resolvedObj={};for(let i2=0;i2<keys.length;i2++)resolvedObj[keys[i2]]=results[i2];return resolvedObj})}function randomString(length=10){let chars="abcdefghijklmnopqrstuvwxyz",str="";for(let i2=0;i2<length;i2++)str+=chars[Math.floor(Math.random()*chars.length)];return str}function esc(str){return JSON.stringify(str)}function slugify(input){return input.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}function isObject(data){return typeof data=="object"&&data!==null&&!Array.isArray(data)}function isPlainObject(o){if(isObject(o)===!1)return!1;let ctor=o.constructor;if(ctor===void 0||typeof ctor!="function")return!0;let prot=ctor.prototype;return!(isObject(prot)===!1||Object.prototype.hasOwnProperty.call(prot,"isPrototypeOf")===!1)}function shallowClone(o){return isPlainObject(o)?{...o}:Array.isArray(o)?[...o]:o instanceof Map?new Map(o):o instanceof Set?new Set(o):o}function numKeys(data){let keyCount=0;for(let key in data)Object.prototype.hasOwnProperty.call(data,key)&&keyCount++;return keyCount}function escapeRegex(str){return str.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function clone(inst,def,params){let cl=new inst._zod.constr(def??inst._zod.def);return(!def||params?.parent)&&(cl._zod.parent=inst),cl}function normalizeParams(_params){let params=_params;if(!params)return{};if(typeof params=="string")return{error:()=>params};if(params?.message!==void 0){if(params?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");params.error=params.message}return delete params.message,typeof params.error=="string"?{...params,error:()=>params.error}:params}function createTransparentProxy(getter){let target;return new Proxy({},{get(_,prop,receiver){return target??(target=getter()),Reflect.get(target,prop,receiver)},set(_,prop,value,receiver){return target??(target=getter()),Reflect.set(target,prop,value,receiver)},has(_,prop){return target??(target=getter()),Reflect.has(target,prop)},deleteProperty(_,prop){return target??(target=getter()),Reflect.deleteProperty(target,prop)},ownKeys(_){return target??(target=getter()),Reflect.ownKeys(target)},getOwnPropertyDescriptor(_,prop){return target??(target=getter()),Reflect.getOwnPropertyDescriptor(target,prop)},defineProperty(_,prop,descriptor){return target??(target=getter()),Reflect.defineProperty(target,prop,descriptor)}})}function stringifyPrimitive(value){return typeof value=="bigint"?value.toString()+"n":typeof value=="string"?`"${value}"`:`${value}`}function optionalKeys(shape){return Object.keys(shape).filter(k=>shape[k]._zod.optin!==void 0&&shape[k]._zod.optout==="optional")}function pick(schema,mask){let currDef=schema._zod.def,checks=currDef.checks;if(checks&&checks.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");let newShape={};return mirrorShape(newShape,schema,maskedKeys(schema,mask)),clone(schema,mergeDefs(currDef,{shape:newShape,checks:[]}))}function maskedKeys(schema,mask){let raw=sourceShape(schema),keys=[];for(let key of Reflect.ownKeys(mask)){if(!Object.getOwnPropertyDescriptor(raw,key)?.enumerable)throw new Error(`Unrecognized key: "${String(key)}"`);mask[key]&&keys.push(key)}return keys}function omit(schema,mask){let currDef=schema._zod.def,checks=currDef.checks;if(checks&&checks.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");let omitted=new Set(maskedKeys(schema,mask)),newShape={};return mirrorShape(newShape,schema,Reflect.ownKeys(sourceShape(schema)).filter(key=>!omitted.has(key))),clone(schema,mergeDefs(currDef,{shape:newShape,checks:[]}))}function extend(schema,shape){if(!isPlainObject(shape))throw new Error("Invalid input to extend: expected a plain object");let checks=schema._zod.def.checks;if(checks&&checks.length>0){let existingShape=sourceShape(schema);for(let key of Reflect.ownKeys(shape))if(Object.getOwnPropertyDescriptor(existingShape,key)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return clone(schema,mergeDefs(schema._zod.def,{shape:extended(schema,shape)}))}function extended(schema,shape){let newShape={};return mirrorShape(newShape,schema,Reflect.ownKeys(sourceShape(schema))),mirrorProps(newShape,shape),newShape}function safeExtend(schema,shape){if(!isPlainObject(shape))throw new Error("Invalid input to safeExtend: expected a plain object");return clone(schema,mergeDefs(schema._zod.def,{shape:extended(schema,shape)}))}function merge(a,b){if(!b?._zod?.def)throw new Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`.");if(a._zod.def.checks?.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let newShape={};mirrorShape(newShape,a,Reflect.ownKeys(sourceShape(a))),mirrorShape(newShape,b,Reflect.ownKeys(sourceShape(b)));let def=mergeDefs(a._zod.def,{shape:newShape,get catchall(){return b._zod.def.catchall},checks:b._zod.def.checks??[]});return clone(a,def)}function partial(Class2,schema,mask,name="partial"){let checks=schema._zod.def.checks;if(checks&&checks.length>0)throw new Error(`.${name}() cannot be used on object schemas containing refinements`);let selected=mask?new Set(maskedKeys(schema,mask)):void 0,newShape={};return mirrorShape(newShape,schema,Reflect.ownKeys(sourceShape(schema)),Class2&&((value,key)=>selected&&!selected.has(key)?value:new Class2({type:"optional",innerType:value}))),clone(schema,mergeDefs(schema._zod.def,{shape:newShape,checks:[]}))}function required(Class2,schema,mask){let selected=mask?new Set(maskedKeys(schema,mask)):void 0,newShape={};return mirrorShape(newShape,schema,Reflect.ownKeys(sourceShape(schema)),(value,key)=>selected&&!selected.has(key)?value:new Class2({type:"nonoptional",innerType:value})),clone(schema,mergeDefs(schema._zod.def,{shape:newShape}))}function aborted(x,startIndex=0){if(x.aborted===!0)return!0;for(let i2=startIndex;i2<x.issues.length;i2++)if(x.issues[i2]?.continue!==!0)return!0;return!1}function explicitlyAborted(x,startIndex=0){if(x.aborted===!0)return!0;for(let i2=startIndex;i2<x.issues.length;i2++)if(x.issues[i2]?.continue===!1)return!0;return!1}function prefixIssues(path,issues){return issues.map(iss=>{var _a4;return(_a4=iss).path??(_a4.path=[]),iss.path.unshift(path),iss})}function unwrapMessage(message){return typeof message=="string"?message:message?.message}function sizeCaps(defChecks){let caps=[];for(let ch of defChecks??[]){let d=ch._zod.def;if(!/_(length|size)$|_equals$/.test(d.check))break;let max=d.maximum??d.length??d.size;max>=0&&caps.push([max,ch])}return caps}function attachSchema(issues,start,inst){var _a4;for(let i2=start;i2<issues.length;i2++)(_a4=issues[i2]).schema??(_a4.schema=inst)}function finalizeIssue(iss,ctx,config2){var _a4;let traits=iss.inst?._zod?.traits;traits?.has("$ZodType")&&(traits.has("$ZodCheck")?(_a4=iss).schema??(_a4.schema=iss.inst):iss.schema=iss.inst);let schemaError=iss.schema!==iss.inst?iss.schema?._zod.def?.error:void 0,message=iss.message?iss.message:unwrapMessage(iss.inst?._zod.def?.error?.(iss))??unwrapMessage(schemaError?.(iss))??unwrapMessage(ctx?.error?.(iss))??unwrapMessage(config2.customError?.(iss))??unwrapMessage(config2.localeError?.(iss))??"Invalid input",full={};for(let k of Object.keys(iss))k==="inst"||k==="schema"||k==="continue"||k==="input"||k==="__proto__"||(full[k]=iss[k]);return full.path??(full.path=[]),full.message=message,ctx?.reportInput&&(full.input=iss.input),full}function getSizableOrigin(input){return input instanceof Set?"set":input instanceof Map?"map":input instanceof File?"file":"unknown"}function codePointLength(str){let units=str.length;if(!highSurrogate.test(str))return units;let count=units;for(let i2=0;i2<units-1;i2++)(str.charCodeAt(i2)&64512)===55296&&(str.charCodeAt(i2+1)&64512)===56320&&(count--,i2++);return count}function getLengthableOrigin(input){return Array.isArray(input)?"array":typeof input=="string"?"string":"unknown"}function parsedType(data){let t=typeof data;switch(t){case"number":return Number.isNaN(data)?"nan":"number";case"object":{if(data===null)return"null";if(Array.isArray(data))return"array";let obj=data;if(obj&&Object.getPrototypeOf(obj)!==Object.prototype&&"constructor"in obj&&obj.constructor)return obj.constructor.name}}return t}function issue(...args){let[iss,input,inst]=args;return typeof iss=="string"?{message:iss,code:"custom",input,inst}:{...iss}}function cleanEnum(obj){return Object.entries(obj).filter(([k,_])=>Number.isNaN(Number.parseInt(k,10))).map(el=>el[1])}function base64ToUint8Array(base642){let binaryString=atob(base642),bytes=new Uint8Array(binaryString.length);for(let i2=0;i2<binaryString.length;i2++)bytes[i2]=binaryString.charCodeAt(i2);return bytes}function uint8ArrayToBase64(bytes){let binaryString="";for(let i2=0;i2<bytes.length;i2++)binaryString+=String.fromCharCode(bytes[i2]);return btoa(binaryString)}function base64urlToUint8Array(base64url2){let base642=base64url2.replace(/-/g,"+").replace(/_/g,"/"),padding="=".repeat((4-base642.length%4)%4);return base64ToUint8Array(base642+padding)}function uint8ArrayToBase64url(bytes){return uint8ArrayToBase64(bytes).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function hexToUint8Array(hex){let cleanHex=hex.replace(/^0x/,"");if(cleanHex.length%2!==0)throw new Error("Invalid hex string length");let bytes=new Uint8Array(cleanHex.length/2);for(let i2=0;i2<cleanHex.length;i2+=2)bytes[i2/2]=Number.parseInt(cleanHex.slice(i2,i2+2),16);return bytes}function uint8ArrayToHex(bytes){return Array.from(bytes).map(b=>b.toString(16).padStart(2,"0")).join("")}function members(proto,table){for(let key in table){let desc=Object.getOwnPropertyDescriptor(table,key);desc.get?Object.defineProperty(proto,key,{...desc,enumerable:!1}):defineBound(proto,key,desc.value)}}function own(inst,key,value,enumerable=!0){return Object.defineProperty(inst,key,{configurable:!0,writable:!0,enumerable,value}),value}function hide(inst,key,value){return own(inst,key,value,!1)}function derived(computes,table){for(let key in computes){let compute=computes[key];Object.defineProperty(table,key,{configurable:!0,enumerable:!0,get(){return own(this,key,compute(this))},set(value){own(this,key,value)}})}return table}function defineBound(proto,key,fn){Object.defineProperty(proto,key,{configurable:!0,get(){return this==null?fn:own(this,key,fn.bind(this))},set(value){own(this,key,value)}})}function claim(inst,sentinel){let proto=Object.getPrototypeOf(inst);return sentinel in proto?void 0:proto}function defineLazyInternal(inst,key,compute){let proto=Object.getPrototypeOf(inst._zod);if(key in proto&&installing!==inst._zod){installing=void 0;return}installing=inst._zod,Object.defineProperty(proto,key,{configurable:!0,get(){Object.defineProperty(this,key,breaker);let outer=broke;broke=!1;try{let value=compute(this);return broke?delete this[key]:Object.defineProperty(this,key,{configurable:!0,writable:!0,value}),broke=broke||outer,value}catch(err){throw delete this[key],broke=broke||outer,err}},set(value){Object.defineProperty(this,key,{configurable:!0,writable:!0,value})}})}function installLazyProp(inst,key,make,enumerable){let proto=claim(inst,key);proto&&Object.defineProperty(proto,key,{configurable:!0,get(){let desc={configurable:!0,writable:!0,enumerable,value:void 0};return Object.defineProperty(this,key,desc),desc.value=make(this),Object.defineProperty(this,key,desc),desc.value},set(value){Object.defineProperty(this,key,{configurable:!0,writable:!0,enumerable,value})}})}function constantCatch(value){let fn=()=>value;return fn[CONSTANT_CATCH]=!0,fn}var Cached,EVALUATING,captureStackTrace,allowsEval,getParsedType,propertyKeyTypes,primitiveTypes,NUMBER_FORMAT_RANGES,BIGINT_FORMAT_RANGES,highSurrogate,Class,installing,broke,breaker,CONSTANT_CATCH,init_util=__esm({"../../node_modules/zod/v4/core/util.js"(){init_core();Cached=class{constructor(getter){this._getter=getter,this._value=void 0}get value(){let getter=this._getter;return getter!==void 0&&(this._value=getter(),this._getter=void 0),this._value}};EVALUATING=Symbol("evaluating");captureStackTrace="captureStackTrace"in Error?Error.captureStackTrace:(..._args)=>{};allowsEval=cached(()=>{if(globalConfig.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let F=Function;return new F(""),!0}catch{return!1}});getParsedType=data=>{let t=typeof data;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(data)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(data)?"array":data===null?"null":data.then&&typeof data.then=="function"&&data.catch&&typeof data.catch=="function"?"promise":typeof Map<"u"&&data instanceof Map?"map":typeof Set<"u"&&data instanceof Set?"set":typeof Date<"u"&&data instanceof Date?"date":typeof File<"u"&&data instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${t}`)}},propertyKeyTypes=new Set(["string","number","symbol"]),primitiveTypes=new Set(["string","number","bigint","boolean","symbol","undefined"]);NUMBER_FORMAT_RANGES={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},BIGINT_FORMAT_RANGES={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};highSurrogate=/[\uD800-\uDBFF]/;Class=class{constructor(..._args){}};broke=!1,breaker={configurable:!0,get(){broke=!0}};CONSTANT_CATCH="~constantCatch"}});function newError(Definition){let E=_E;if(E){let saved=E.stackTraceLimit;if(typeof saved=="number"){try{E.stackTraceLimit=0}catch{return _E=null,new Definition}try{return new Definition}finally{E.stackTraceLimit=saved}}}return new Definition}function $constructor(name,initializer3,proto,params){let zodProto={};function Internals(def){this.def=def,this.constr=_,this.traits=new Set}Internals.prototype=zodProto;let protoMembers=proto,initialized=protoMembers&&new WeakSet;function init(inst,def){if(inst._zod){if(inst._zod.traits.has(name))return}else{_zodDesc.value=new Internals(def);try{Object.defineProperty(inst,"_zod",_zodDesc)}finally{_zodDesc.value=void 0}}if(inst._zod.traits.add(name),initializer3(inst,def),initialized){let own2=Object.getPrototypeOf(inst),ctorProto=inst._zod.constr.prototype,up=own2;for(;up&&up!==ctorProto;)up=Object.getPrototypeOf(up);let target=up??own2;initialized.has(target)||(initialized.add(target),members(target,protoMembers))}let proto2=_.prototype;for(let k in proto2)Object.prototype.hasOwnProperty.call(proto2,k)&&(k in inst||(inst[k]=proto2[k].bind(inst)))}let Parent=params?.Parent??Object;class Definition extends Parent{}Object.defineProperty(Definition,"name",{value:name});function _(def){let inst=params?.Parent?newError(Definition):this;init(inst,def);let deferred=inst._zod.deferred;if(deferred){for(let fn of deferred)fn();inst._zod.deferred=void 0}let pp=globalThis.__zod_globalConfig?.postProcessor;return pp&&pp(inst),inst}return Object.defineProperty(_,"init",{value:init}),Object.defineProperty(_,Symbol.hasInstance,{value:inst=>params?.Parent&&inst instanceof params.Parent?!0:inst?._zod?.traits?.has(name)}),Object.defineProperty(_,"name",{value:name}),_}function config(newConfig){return newConfig&&Object.assign(globalConfig,newConfig),globalConfig}var _a2,NEVER,_zodDesc,_E,$ZodAsyncError,$ZodEncodeError,globalConfig,init_core=__esm({"../../node_modules/zod/v4/core/core.js"(){init_util();NEVER=Object.freeze({status:"aborted"}),_zodDesc={value:void 0,enumerable:!1},_E="captureStackTrace"in Error?Error:null;$ZodAsyncError=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},$ZodEncodeError=class extends Error{constructor(name){super(`Encountered unidirectional transform during encode: ${name}`),this.name="ZodEncodeError"}};(_a2=globalThis).__zod_globalConfig??(_a2.__zod_globalConfig={});globalConfig=globalThis.__zod_globalConfig}});function _getMessage(){let internals=this._zod;return internals.message??(internals.message=JSON.stringify(internals.def,jsonStringifyReplacer,2)),internals.message}function _setMessage(value){this._zod.message=value}function node(obj,key,make){return Object.prototype.hasOwnProperty.call(obj,key)||(key==="__proto__"?Object.defineProperty(obj,key,{value:make(),writable:!0,enumerable:!0,configurable:!0}):obj[key]=make()),obj[key]}function flattenError(error2,mapper=issue2=>issue2.message){let fieldErrors={},formErrors=[];for(let sub of error2.issues)sub.path.length>0?node(fieldErrors,sub.path[0],()=>[]).push(mapper(sub)):formErrors.push(mapper(sub));return{formErrors,fieldErrors}}function formatError(error2,mapper=issue2=>issue2.message){let fieldErrors={_errors:[]},processError=(error3,path=[])=>{for(let issue2 of error3.issues)if(issue2.code==="invalid_union"&&issue2.errors.length)issue2.errors.map(issues=>processError({issues},[...path,...issue2.path]));else if(issue2.code==="invalid_key")processError({issues:issue2.issues},[...path,...issue2.path]);else if(issue2.code==="invalid_element")processError({issues:issue2.issues},[...path,...issue2.path]);else{let fullpath=[...path,...issue2.path];if(fullpath.length===0)fieldErrors._errors.push(mapper(issue2));else{let curr=fieldErrors,i2=0;for(;i2<fullpath.length;){let el=fullpath[i2],terminal2=i2===fullpath.length-1;if(el==="_errors"){terminal2&&curr._errors.push(mapper(issue2)),i2++;continue}Object.prototype.hasOwnProperty.call(curr,el)||Object.defineProperty(curr,el,{value:{_errors:[]},enumerable:!0,writable:!0,configurable:!0});let node2=curr[el];terminal2&&node2._errors.push(mapper(issue2)),curr=node2,i2++}}}};return processError(error2),fieldErrors}var _messageDesc,_issuesDesc,_installedToString,initializer,$ZodError,$ZodRealError,init_errors2=__esm({"../../node_modules/zod/v4/core/errors.js"(){init_core();init_util();_messageDesc={get:_getMessage,set:_setMessage,enumerable:!0,configurable:!0},_issuesDesc={value:void 0,enumerable:!1},_installedToString=new WeakSet([Object.prototype,Error.prototype]),initializer=(inst,def)=>{inst.name="$ZodError",_issuesDesc.value=def,Object.defineProperty(inst,"issues",_issuesDesc),_issuesDesc.value=void 0,Object.defineProperty(inst,"message",_messageDesc);let proto=Object.getPrototypeOf(inst);_installedToString.has(proto)||(_installedToString.add(proto),Object.defineProperty(proto,"toString",{configurable:!0,enumerable:!1,get(){let value=()=>this.message;return Object.defineProperty(this,"toString",{value,configurable:!0,writable:!0}),value},set(value){Object.defineProperty(this,"toString",{value,configurable:!0,writable:!0})}}))},$ZodError=$constructor("$ZodError",initializer),$ZodRealError=$constructor("$ZodError",initializer,void 0,{Parent:Error})}});function finalizeParams(callee,params){return{callee:params?.callee??callee,Err:params?.Err}}function failure(Err,issues,ctx){let error2;return{success:!1,get error(){return error2||(error2=new Err(issues.map(iss=>finalizeIssue(iss,ctx,config()))),issues=void 0,ctx=void 0),error2},set error(e){error2=e,issues=void 0,ctx=void 0}}}function validateFallback(schema,value,_ctx){let ctx=_ctx?{..._ctx,async:!1,abortEarly:!0}:{async:!1,abortEarly:!0},fallbackRun=schema._zod.bag.fallbackRun,result;if(fallbackRun?(ctx[COMPILE_FALLBACK]=!0,result=fallbackRun({value,issues:[]},ctx)):result=schema._zod.run({value,issues:[]},ctx),result instanceof Promise)throw new $ZodAsyncError;return result.issues.length===0}var _parse,_parseAsync,_safeParse,safeParse,_safeParseAsync,COMPILE_INVALID,COMPILE_FALLBACK,validate,validateAsync,_encode,_decode,_encodeAsync,_decodeAsync,_safeEncode,_safeDecode,_safeEncodeAsync,_safeDecodeAsync,init_parse=__esm({"../../node_modules/zod/v4/core/parse.js"(){init_core();init_errors2();init_util();_parse=_Err=>{let fn=(schema,value,_ctx,_params)=>{let ctx=_ctx?{..._ctx,async:!1}:{async:!1},result=schema._zod.run({value,issues:[]},ctx);if(result instanceof Promise)throw new $ZodAsyncError;if(result.issues.length){let e=new(_params?.Err??_Err)(result.issues.map(iss=>finalizeIssue(iss,ctx,config())));throw captureStackTrace(e,_params?.callee??fn),e}return result.value};return fn},_parseAsync=_Err=>{let fn=async(schema,value,_ctx,params)=>{let ctx=_ctx?{..._ctx,async:!0}:{async:!0},result=schema._zod.run({value,issues:[]},ctx);if(result instanceof Promise&&(result=await result),result.issues.length){let e=new(params?.Err??_Err)(result.issues.map(iss=>finalizeIssue(iss,ctx,config())));throw captureStackTrace(e,params?.callee??fn),e}return result.value};return fn},_safeParse=_Err=>(schema,value,_ctx)=>{let ctx=_ctx?{..._ctx,async:!1}:{async:!1},result=schema._zod.run({value,issues:[]},ctx);if(result instanceof Promise)throw new $ZodAsyncError;return result.issues.length?failure(_Err,result.issues,ctx):{success:!0,data:result.value}},safeParse=_safeParse($ZodRealError);_safeParseAsync=_Err=>async(schema,value,_ctx)=>{let ctx=_ctx?{..._ctx,async:!0}:{async:!0},result=schema._zod.run({value,issues:[]},ctx);return result instanceof Promise&&(result=await result),result.issues.length?failure(_Err,result.issues,ctx):{success:!0,data:result.value}},COMPILE_INVALID=Symbol.for("zod.compile.invalid"),COMPILE_FALLBACK=Symbol.for("zod.compile.fallback"),validate=((schema,value,_ctx)=>{let validator=schema._zod.bag.validator;if(validator!==void 0){if(validator(value)!==COMPILE_INVALID)return!0;if(validator.definite===!0&&_ctx===void 0)return!1}return validateFallback(schema,value,_ctx)});validateAsync=async(schema,value,_ctx)=>{let ctx=_ctx?{..._ctx,async:!0,abortEarly:!0}:{async:!0,abortEarly:!0},result=schema._zod.run({value,issues:[]},ctx);return result instanceof Promise&&(result=await result),result.issues.length===0},_encode=_Err=>{let parse4=_parse(_Err),fn=(schema,value,_ctx,_params)=>{let ctx=_ctx?{..._ctx,direction:"backward"}:{direction:"backward"};return parse4(schema,value,ctx,finalizeParams(fn,_params))};return fn},_decode=_Err=>{let parse4=_parse(_Err),fn=(schema,value,_ctx,_params)=>parse4(schema,value,_ctx,finalizeParams(fn,_params));return fn},_encodeAsync=_Err=>{let parseAsync3=_parseAsync(_Err),fn=async(schema,value,_ctx,_params)=>{let ctx=_ctx?{..._ctx,direction:"backward"}:{direction:"backward"};return await parseAsync3(schema,value,ctx,finalizeParams(fn,_params))};return fn},_decodeAsync=_Err=>{let parseAsync3=_parseAsync(_Err),fn=async(schema,value,_ctx,_params)=>await parseAsync3(schema,value,_ctx,finalizeParams(fn,_params));return fn},_safeEncode=_Err=>(schema,value,_ctx)=>{let ctx=_ctx?{..._ctx,direction:"backward"}:{direction:"backward"};return _safeParse(_Err)(schema,value,ctx)},_safeDecode=_Err=>(schema,value,_ctx)=>_safeParse(_Err)(schema,value,_ctx),_safeEncodeAsync=_Err=>async(schema,value,_ctx)=>{let ctx=_ctx?{..._ctx,direction:"backward"}:{direction:"backward"};return _safeParseAsync(_Err)(schema,value,ctx)},_safeDecodeAsync=_Err=>async(schema,value,_ctx)=>_safeParseAsync(_Err)(schema,value,_ctx)}});function nanoidOfLength(length){return new RegExp(`^[a-zA-Z0-9_-]{${length}}$`)}function emoji(){return new RegExp(_emoji,"u")}function anchor(source){return new RegExp(`^${source}$`)}function timeSource(args){let hhmm="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof args.precision=="number"?args.precision===-1?`${hhmm}`:args.precision===0?`${hhmm}:[0-5]\\d`:`${hhmm}:[0-5]\\d\\.\\d{${args.precision}}`:args.seconds?`${hhmm}:[0-5]\\d(?:\\.\\d+)?`:`${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`}function time(args){return new RegExp(`^${timeSource(args)}$`)}function datetime(args){let opts=["Z"];args.offset&&opts.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let qualified=`${timeSource({precision:args.precision,seconds:!0})}(?:${opts.join("|")})`,timeRegex=args.local?`${qualified}|${timeSource({precision:args.precision})}`:qualified;return new RegExp(`^${dateSource}T(?:${timeRegex})$`)}var cuid,cuid2,ulid,xid,ksuid,nanoid,duration,guid,uuid,email,_emoji,ipv4,ipv6,cidrv4,cidrv6,base64,base64url,httpProtocol,e164,dateSource,date,anyString,bigint,integer,number,boolean,_null,lowercase,uppercase,init_regexes=__esm({"../../node_modules/zod/v4/core/regexes.js"(){cuid=/^[cC][0-9a-z]{6,}$/,cuid2=/^[0-9a-z]+$/,ulid=/^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/,xid=/^[0-9a-vA-V]{20}$/,ksuid=/^[A-Za-z0-9]{27}$/,nanoid=/^[a-zA-Z0-9_-]{21}$/;duration=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,guid=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,uuid=version3=>version3?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version3}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,email=/^(?:[A-Za-z0-9_'+\-]+\.)*[A-Za-z0-9_'+\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,_emoji="^(?=[\\s\\S]*[\\p{Extended_Pictographic}\\p{Regional_Indicator}\\u20E3])[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$";ipv4=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv6=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,cidrv4=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,cidrv6=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,base64url=/^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/,httpProtocol=/^https?$/,e164=/^\+[1-9]\d{6,14}$/,dateSource="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))";date=anchor(dateSource);anyString=/^[\s\S]{0,}$/,bigint=/^-?\d+n?$/,integer=/^-?\d+$/,number=/^-?\d+(?:\.\d+)?$/,boolean=/^(?:true|false)$/i,_null=/^null$/i,lowercase=/^[^A-Z]*$/,uppercase=/^[^a-z]*$/}});var $ZodCheck,_whenHasLength,numericOriginMap,$ZodCheckLessThan,$ZodCheckGreaterThan,$ZodCheckMultipleOf,$ZodCheckNumberFormat,$ZodCheckMaxLength,$ZodCheckMinLength,$ZodCheckLengthEquals,$ZodCheckStringFormat,$ZodCheckRegex,$ZodCheckLowerCase,$ZodCheckUpperCase,$ZodCheckIncludes,$ZodCheckStartsWith,$ZodCheckEndsWith,$ZodCheckOverwrite,init_checks=__esm({"../../node_modules/zod/v4/core/checks.js"(){init_core();init_regexes();init_util();$ZodCheck=$constructor("$ZodCheck",(inst,def)=>{var _a4;inst._zod??(inst._zod={}),inst._zod.def=def,(_a4=inst._zod).onattach??(_a4.onattach=[])}),_whenHasLength=payload=>{let val=payload.value;return!nullish(val)&&val.length!==void 0},numericOriginMap={number:"number",bigint:"bigint",object:"date"},$ZodCheckLessThan=$constructor("$ZodCheckLessThan",(inst,def)=>{$ZodCheck.init(inst,def);let origin=numericOriginMap[typeof def.value];inst._zod.check=payload=>{(def.inclusive?payload.value<=def.value:payload.value<def.value)||payload.issues.push({origin:numericOriginMap[typeof payload.value]??origin,code:"too_big",maximum:typeof def.value=="object"?def.value.getTime():def.value,input:payload.value,inclusive:def.inclusive,inst,continue:!def.abort})}}),$ZodCheckGreaterThan=$constructor("$ZodCheckGreaterThan",(inst,def)=>{$ZodCheck.init(inst,def);let origin=numericOriginMap[typeof def.value];inst._zod.check=payload=>{(def.inclusive?payload.value>=def.value:payload.value>def.value)||payload.issues.push({origin:numericOriginMap[typeof payload.value]??origin,code:"too_small",minimum:typeof def.value=="object"?def.value.getTime():def.value,input:payload.value,inclusive:def.inclusive,inst,continue:!def.abort})}}),$ZodCheckMultipleOf=$constructor("$ZodCheckMultipleOf",(inst,def)=>{$ZodCheck.init(inst,def),inst._zod.check=payload=>{if(typeof payload.value!=typeof def.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof payload.value=="bigint"?def.value!==BigInt(0)&&payload.value%def.value===BigInt(0):floatSafeRemainder(payload.value,def.value)===0)||payload.issues.push({origin:typeof payload.value,code:"not_multiple_of",divisor:def.value,input:payload.value,inst,continue:!def.abort})}}),$ZodCheckNumberFormat=$constructor("$ZodCheckNumberFormat",(inst,def)=>{$ZodCheck.init(inst,def),def.format=def.format||"float64";let isInt=def.format?.includes("int"),origin=isInt?"int":"number",[minimum,maximum]=NUMBER_FORMAT_RANGES[def.format];inst._zod.check=payload=>{let input=payload.value;if(isInt){if(!Number.isInteger(input)){payload.issues.push({expected:origin,format:def.format,code:"invalid_type",continue:!1,input,inst});return}if(!Number.isSafeInteger(input)){input>0?payload.issues.push({input,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst,origin,inclusive:!0,continue:!def.abort}):payload.issues.push({input,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst,origin,inclusive:!0,continue:!def.abort});return}}input<minimum&&payload.issues.push({origin:"number",input,code:"too_small",minimum,inclusive:!0,inst,continue:!def.abort}),input>maximum&&payload.issues.push({origin:"number",input,code:"too_big",maximum,inclusive:!0,inst,continue:!def.abort})}}),$ZodCheckMaxLength=$constructor("$ZodCheckMaxLength",(inst,def)=>{var _a4;$ZodCheck.init(inst,def),(_a4=inst._zod.def).when??(_a4.when=_whenHasLength),inst._zod.check=payload=>{let input=payload.value,units=input.length;if((typeof input=="string"&&units>def.maximum?codePointLength(input):units)<=def.maximum)return;let origin=getLengthableOrigin(input);payload.issues.push({origin,code:"too_big",maximum:def.maximum,inclusive:!0,input,inst,continue:!def.abort})}}),$ZodCheckMinLength=$constructor("$ZodCheckMinLength",(inst,def)=>{var _a4;$ZodCheck.init(inst,def),(_a4=inst._zod.def).when??(_a4.when=_whenHasLength),inst._zod.check=payload=>{let input=payload.value,units=input.length;if((typeof input=="string"&&units>=def.minimum&&units<def.minimum*2?codePointLength(input):units)>=def.minimum)return;let origin=getLengthableOrigin(input);payload.issues.push({origin,code:"too_small",minimum:def.minimum,inclusive:!0,input,inst,continue:!def.abort})}}),$ZodCheckLengthEquals=$constructor("$ZodCheckLengthEquals",(inst,def)=>{var _a4;$ZodCheck.init(inst,def),(_a4=inst._zod.def).when??(_a4.when=_whenHasLength),inst._zod.check=payload=>{let input=payload.value,units=input.length,length=typeof input=="string"&&units>=def.length&&units<=def.length*2?codePointLength(input):units;if(length===def.length)return;let origin=getLengthableOrigin(input),tooBig=length>def.length;payload.issues.push({origin,...tooBig?{code:"too_big",maximum:def.length}:{code:"too_small",minimum:def.length},inclusive:!0,exact:!0,input:payload.value,inst,continue:!def.abort})}}),$ZodCheckStringFormat=$constructor("$ZodCheckStringFormat",(inst,def)=>{var _a4,_b2;$ZodCheck.init(inst,def),def.pattern?(_a4=inst._zod).check??(_a4.check=payload=>{def.pattern.lastIndex=0,!def.pattern.test(payload.value)&&payload.issues.push({origin:"string",code:"invalid_format",format:def.format,input:payload.value,...def.pattern?{pattern:def.pattern.toString()}:{},inst,continue:!def.abort})}):(_b2=inst._zod).check??(_b2.check=()=>{})}),$ZodCheckRegex=$constructor("$ZodCheckRegex",(inst,def)=>{$ZodCheckStringFormat.init(inst,def),inst._zod.check=payload=>{def.pattern.lastIndex=0,!def.pattern.test(payload.value)&&payload.issues.push({origin:"string",code:"invalid_format",format:"regex",input:payload.value,pattern:def.pattern.toString(),inst,continue:!def.abort})}}),$ZodCheckLowerCase=$constructor("$ZodCheckLowerCase",(inst,def)=>{def.pattern??(def.pattern=lowercase),$ZodCheckStringFormat.init(inst,def)}),$ZodCheckUpperCase=$constructor("$ZodCheckUpperCase",(inst,def)=>{def.pattern??(def.pattern=uppercase),$ZodCheckStringFormat.init(inst,def)}),$ZodCheckIncludes=$constructor("$ZodCheckIncludes",(inst,def)=>{$ZodCheck.init(inst,def);let escapedRegex=escapeRegex(def.includes),pattern=new RegExp(typeof def.position=="number"?`^.{${def.position},}${escapedRegex}`:escapedRegex);def.pattern=pattern,inst._zod.check=payload=>{payload.value.includes(def.includes,def.position)||payload.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:def.includes,input:payload.value,inst,continue:!def.abort})}}),$ZodCheckStartsWith=$constructor("$ZodCheckStartsWith",(inst,def)=>{$ZodCheck.init(inst,def);let pattern=new RegExp(`^${escapeRegex(def.prefix)}.*`);def.pattern??(def.pattern=pattern),inst._zod.check=payload=>{payload.value.startsWith(def.prefix)||payload.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:def.prefix,input:payload.value,inst,continue:!def.abort})}}),$ZodCheckEndsWith=$constructor("$ZodCheckEndsWith",(inst,def)=>{$ZodCheck.init(inst,def);let pattern=new RegExp(`.*${escapeRegex(def.suffix)}$`);def.pattern??(def.pattern=pattern),inst._zod.check=payload=>{payload.value.endsWith(def.suffix)||payload.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:def.suffix,input:payload.value,inst,continue:!def.abort})}}),$ZodCheckOverwrite=$constructor("$ZodCheckOverwrite",(inst,def)=>{$ZodCheck.init(inst,def),inst._zod.check=payload=>{payload.value=def.tx(payload.value)}})}});var Doc,init_doc=__esm({"../../node_modules/zod/v4/core/doc.js"(){Doc=class{constructor(args=[],closed={}){this.content=[],this.indent=0,this.args=args,this.closed=closed}indented(fn){this.indent+=1;try{fn(this)}finally{this.indent-=1}}write(arg){if(typeof arg=="function"){arg(this,{execution:"sync"}),arg(this,{execution:"async"});return}let lines=arg.split(`
|
|
5
|
+
GFS4: `),console.error(m)});fs[gracefulQueue]||(queue=global[gracefulQueue]||[],publishQueue(fs,queue),fs.close=(function(fs$close){function close(fd,cb){return fs$close.call(fs,fd,function(err){err||resetQueue(),typeof cb=="function"&&cb.apply(this,arguments)})}return Object.defineProperty(close,previousSymbol,{value:fs$close}),close})(fs.close),fs.closeSync=(function(fs$closeSync){function closeSync(fd){fs$closeSync.apply(fs,arguments),resetQueue()}return Object.defineProperty(closeSync,previousSymbol,{value:fs$closeSync}),closeSync})(fs.closeSync),/\bgfs4\b/i.test(process.env.NODE_DEBUG||"")&&process.on("exit",function(){debug(fs[gracefulQueue]),__require("assert").equal(fs[gracefulQueue].length,0)}));var queue;global[gracefulQueue]||publishQueue(global,fs[gracefulQueue]);module.exports=patch(clone2(fs));process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH&&!fs.__patched&&(module.exports=patch(fs),fs.__patched=!0);function patch(fs2){polyfills(fs2),fs2.gracefulify=patch,fs2.createReadStream=createReadStream,fs2.createWriteStream=createWriteStream;var fs$readFile=fs2.readFile;fs2.readFile=readFile7;function readFile7(path,options,cb){return typeof options=="function"&&(cb=options,options=null),go$readFile(path,options,cb);function go$readFile(path2,options2,cb2,startTime){return fs$readFile(path2,options2,function(err){err&&(err.code==="EMFILE"||err.code==="ENFILE")?enqueue([go$readFile,[path2,options2,cb2],err,startTime||Date.now(),Date.now()]):typeof cb2=="function"&&cb2.apply(this,arguments)})}}var fs$writeFile=fs2.writeFile;fs2.writeFile=writeFile6;function writeFile6(path,data,options,cb){return typeof options=="function"&&(cb=options,options=null),go$writeFile(path,data,options,cb);function go$writeFile(path2,data2,options2,cb2,startTime){return fs$writeFile(path2,data2,options2,function(err){err&&(err.code==="EMFILE"||err.code==="ENFILE")?enqueue([go$writeFile,[path2,data2,options2,cb2],err,startTime||Date.now(),Date.now()]):typeof cb2=="function"&&cb2.apply(this,arguments)})}}var fs$appendFile=fs2.appendFile;fs$appendFile&&(fs2.appendFile=appendFile);function appendFile(path,data,options,cb){return typeof options=="function"&&(cb=options,options=null),go$appendFile(path,data,options,cb);function go$appendFile(path2,data2,options2,cb2,startTime){return fs$appendFile(path2,data2,options2,function(err){err&&(err.code==="EMFILE"||err.code==="ENFILE")?enqueue([go$appendFile,[path2,data2,options2,cb2],err,startTime||Date.now(),Date.now()]):typeof cb2=="function"&&cb2.apply(this,arguments)})}}var fs$copyFile=fs2.copyFile;fs$copyFile&&(fs2.copyFile=copyFile);function copyFile(src,dest,flags,cb){return typeof flags=="function"&&(cb=flags,flags=0),go$copyFile(src,dest,flags,cb);function go$copyFile(src2,dest2,flags2,cb2,startTime){return fs$copyFile(src2,dest2,flags2,function(err){err&&(err.code==="EMFILE"||err.code==="ENFILE")?enqueue([go$copyFile,[src2,dest2,flags2,cb2],err,startTime||Date.now(),Date.now()]):typeof cb2=="function"&&cb2.apply(this,arguments)})}}var fs$readdir=fs2.readdir;fs2.readdir=readdir4;var noReaddirOptionVersions=/^v[0-5]\./;function readdir4(path,options,cb){typeof options=="function"&&(cb=options,options=null);var go$readdir=noReaddirOptionVersions.test(process.version)?function(path2,options2,cb2,startTime){return fs$readdir(path2,fs$readdirCallback(path2,options2,cb2,startTime))}:function(path2,options2,cb2,startTime){return fs$readdir(path2,options2,fs$readdirCallback(path2,options2,cb2,startTime))};return go$readdir(path,options,cb);function fs$readdirCallback(path2,options2,cb2,startTime){return function(err,files){err&&(err.code==="EMFILE"||err.code==="ENFILE")?enqueue([go$readdir,[path2,options2,cb2],err,startTime||Date.now(),Date.now()]):(files&&files.sort&&files.sort(),typeof cb2=="function"&&cb2.call(this,err,files))}}}if(process.version.substr(0,4)==="v0.8"){var legStreams=legacy(fs2);ReadStream=legStreams.ReadStream,WriteStream=legStreams.WriteStream}var fs$ReadStream=fs2.ReadStream;fs$ReadStream&&(ReadStream.prototype=Object.create(fs$ReadStream.prototype),ReadStream.prototype.open=ReadStream$open);var fs$WriteStream=fs2.WriteStream;fs$WriteStream&&(WriteStream.prototype=Object.create(fs$WriteStream.prototype),WriteStream.prototype.open=WriteStream$open),Object.defineProperty(fs2,"ReadStream",{get:function(){return ReadStream},set:function(val){ReadStream=val},enumerable:!0,configurable:!0}),Object.defineProperty(fs2,"WriteStream",{get:function(){return WriteStream},set:function(val){WriteStream=val},enumerable:!0,configurable:!0});var FileReadStream=ReadStream;Object.defineProperty(fs2,"FileReadStream",{get:function(){return FileReadStream},set:function(val){FileReadStream=val},enumerable:!0,configurable:!0});var FileWriteStream=WriteStream;Object.defineProperty(fs2,"FileWriteStream",{get:function(){return FileWriteStream},set:function(val){FileWriteStream=val},enumerable:!0,configurable:!0});function ReadStream(path,options){return this instanceof ReadStream?(fs$ReadStream.apply(this,arguments),this):ReadStream.apply(Object.create(ReadStream.prototype),arguments)}function ReadStream$open(){var that=this;open3(that.path,that.flags,that.mode,function(err,fd){err?(that.autoClose&&that.destroy(),that.emit("error",err)):(that.fd=fd,that.emit("open",fd),that.read())})}function WriteStream(path,options){return this instanceof WriteStream?(fs$WriteStream.apply(this,arguments),this):WriteStream.apply(Object.create(WriteStream.prototype),arguments)}function WriteStream$open(){var that=this;open3(that.path,that.flags,that.mode,function(err,fd){err?(that.destroy(),that.emit("error",err)):(that.fd=fd,that.emit("open",fd))})}function createReadStream(path,options){return new fs2.ReadStream(path,options)}function createWriteStream(path,options){return new fs2.WriteStream(path,options)}var fs$open=fs2.open;fs2.open=open3;function open3(path,flags,mode,cb){return typeof mode=="function"&&(cb=mode,mode=null),go$open(path,flags,mode,cb);function go$open(path2,flags2,mode2,cb2,startTime){return fs$open(path2,flags2,mode2,function(err,fd){err&&(err.code==="EMFILE"||err.code==="ENFILE")?enqueue([go$open,[path2,flags2,mode2,cb2],err,startTime||Date.now(),Date.now()]):typeof cb2=="function"&&cb2.apply(this,arguments)})}}return fs2}function enqueue(elem){debug("ENQUEUE",elem[0].name,elem[1]),fs[gracefulQueue].push(elem),retry()}var retryTimer;function resetQueue(){for(var now=Date.now(),i2=0;i2<fs[gracefulQueue].length;++i2)fs[gracefulQueue][i2].length>2&&(fs[gracefulQueue][i2][3]=now,fs[gracefulQueue][i2][4]=now);retry()}function retry(){if(clearTimeout(retryTimer),retryTimer=void 0,fs[gracefulQueue].length!==0){var elem=fs[gracefulQueue].shift(),fn=elem[0],args=elem[1],err=elem[2],startTime=elem[3],lastTime=elem[4];if(startTime===void 0)debug("RETRY",fn.name,args),fn.apply(null,args);else if(Date.now()-startTime>=6e4){debug("TIMEOUT",fn.name,args);var cb=args.pop();typeof cb=="function"&&cb.call(null,err)}else{var sinceAttempt=Date.now()-lastTime,sinceStart=Math.max(lastTime-startTime,1),desiredDelay=Math.min(sinceStart*1.2,100);sinceAttempt>=desiredDelay?(debug("RETRY",fn.name,args),fn.apply(null,args.concat([startTime]))):fs[gracefulQueue].push(elem)}retryTimer===void 0&&(retryTimer=setTimeout(retry,0))}}}});var require_retry_operation=__commonJS({"../../node_modules/retry/lib/retry_operation.js"(exports,module){function RetryOperation(timeouts,options){typeof options=="boolean"&&(options={forever:options}),this._originalTimeouts=JSON.parse(JSON.stringify(timeouts)),this._timeouts=timeouts,this._options=options||{},this._maxRetryTime=options&&options.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}module.exports=RetryOperation;RetryOperation.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts};RetryOperation.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timeouts=[],this._cachedTimeouts=null};RetryOperation.prototype.retry=function(err){if(this._timeout&&clearTimeout(this._timeout),!err)return!1;var currentTime=new Date().getTime();if(err&¤tTime-this._operationStart>=this._maxRetryTime)return this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(err);var timeout=this._timeouts.shift();if(timeout===void 0)if(this._cachedTimeouts)this._errors.splice(this._errors.length-1,this._errors.length),this._timeouts=this._cachedTimeouts.slice(0),timeout=this._timeouts.shift();else return!1;var self=this,timer=setTimeout(function(){self._attempts++,self._operationTimeoutCb&&(self._timeout=setTimeout(function(){self._operationTimeoutCb(self._attempts)},self._operationTimeout),self._options.unref&&self._timeout.unref()),self._fn(self._attempts)},timeout);return this._options.unref&&timer.unref(),!0};RetryOperation.prototype.attempt=function(fn,timeoutOps){this._fn=fn,timeoutOps&&(timeoutOps.timeout&&(this._operationTimeout=timeoutOps.timeout),timeoutOps.cb&&(this._operationTimeoutCb=timeoutOps.cb));var self=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){self._operationTimeoutCb()},self._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)};RetryOperation.prototype.try=function(fn){console.log("Using RetryOperation.try() is deprecated"),this.attempt(fn)};RetryOperation.prototype.start=function(fn){console.log("Using RetryOperation.start() is deprecated"),this.attempt(fn)};RetryOperation.prototype.start=RetryOperation.prototype.try;RetryOperation.prototype.errors=function(){return this._errors};RetryOperation.prototype.attempts=function(){return this._attempts};RetryOperation.prototype.mainError=function(){if(this._errors.length===0)return null;for(var counts={},mainError=null,mainErrorCount=0,i2=0;i2<this._errors.length;i2++){var error2=this._errors[i2],message=error2.message,count=(counts[message]||0)+1;counts[message]=count,count>=mainErrorCount&&(mainError=error2,mainErrorCount=count)}return mainError}}});var require_retry=__commonJS({"../../node_modules/retry/lib/retry.js"(exports){var RetryOperation=require_retry_operation();exports.operation=function(options){var timeouts=exports.timeouts(options);return new RetryOperation(timeouts,{forever:options&&options.forever,unref:options&&options.unref,maxRetryTime:options&&options.maxRetryTime})};exports.timeouts=function(options){if(options instanceof Array)return[].concat(options);var opts={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var key in options)opts[key]=options[key];if(opts.minTimeout>opts.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var timeouts=[],i2=0;i2<opts.retries;i2++)timeouts.push(this.createTimeout(i2,opts));return options&&options.forever&&!timeouts.length&&timeouts.push(this.createTimeout(i2,opts)),timeouts.sort(function(a,b){return a-b}),timeouts};exports.createTimeout=function(attempt,opts){var random2=opts.randomize?Math.random()+1:1,timeout=Math.round(random2*opts.minTimeout*Math.pow(opts.factor,attempt));return timeout=Math.min(timeout,opts.maxTimeout),timeout};exports.wrap=function(obj,options,methods){if(options instanceof Array&&(methods=options,options=null),!methods){methods=[];for(var key in obj)typeof obj[key]=="function"&&methods.push(key)}for(var i2=0;i2<methods.length;i2++){var method=methods[i2],original=obj[method];obj[method]=function(original2){var op=exports.operation(options),args=Array.prototype.slice.call(arguments,1),callback=args.pop();args.push(function(err){op.retry(err)||(err&&(arguments[0]=op.mainError()),callback.apply(this,arguments))}),op.attempt(function(){original2.apply(obj,args)})}.bind(obj,original),obj[method].options=options}}}});var require_retry2=__commonJS({"../../node_modules/retry/index.js"(exports,module){module.exports=require_retry()}});var require_signals=__commonJS({"../../node_modules/signal-exit/signals.js"(exports,module){module.exports=["SIGABRT","SIGALRM","SIGHUP","SIGINT","SIGTERM"];process.platform!=="win32"&&module.exports.push("SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");process.platform==="linux"&&module.exports.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT","SIGUNUSED")}});var require_signal_exit=__commonJS({"../../node_modules/signal-exit/index.js"(exports,module){var process2=global.process,processOk=function(process3){return process3&&typeof process3=="object"&&typeof process3.removeListener=="function"&&typeof process3.emit=="function"&&typeof process3.reallyExit=="function"&&typeof process3.listeners=="function"&&typeof process3.kill=="function"&&typeof process3.pid=="number"&&typeof process3.on=="function"};processOk(process2)?(assert2=__require("assert"),signals=require_signals(),isWin=/^win/i.test(process2.platform),EE=__require("events"),typeof EE!="function"&&(EE=EE.EventEmitter),process2.__signal_exit_emitter__?emitter=process2.__signal_exit_emitter__:(emitter=process2.__signal_exit_emitter__=new EE,emitter.count=0,emitter.emitted={}),emitter.infinite||(emitter.setMaxListeners(1/0),emitter.infinite=!0),module.exports=function(cb,opts){if(!processOk(global.process))return function(){};assert2.equal(typeof cb,"function","a callback must be provided for exit handler"),loaded===!1&&load();var ev="exit";opts&&opts.alwaysLast&&(ev="afterexit");var remove=function(){emitter.removeListener(ev,cb),emitter.listeners("exit").length===0&&emitter.listeners("afterexit").length===0&&unload()};return emitter.on(ev,cb),remove},unload=function(){!loaded||!processOk(global.process)||(loaded=!1,signals.forEach(function(sig){try{process2.removeListener(sig,sigListeners[sig])}catch{}}),process2.emit=originalProcessEmit,process2.reallyExit=originalProcessReallyExit,emitter.count-=1)},module.exports.unload=unload,emit=function(event,code2,signal){emitter.emitted[event]||(emitter.emitted[event]=!0,emitter.emit(event,code2,signal))},sigListeners={},signals.forEach(function(sig){sigListeners[sig]=function(){if(processOk(global.process)){var listeners=process2.listeners(sig);listeners.length===emitter.count&&(unload(),emit("exit",null,sig),emit("afterexit",null,sig),isWin&&sig==="SIGHUP"&&(sig="SIGINT"),process2.kill(process2.pid,sig))}}}),module.exports.signals=function(){return signals},loaded=!1,load=function(){loaded||!processOk(global.process)||(loaded=!0,emitter.count+=1,signals=signals.filter(function(sig){try{return process2.on(sig,sigListeners[sig]),!0}catch{return!1}}),process2.emit=processEmit,process2.reallyExit=processReallyExit)},module.exports.load=load,originalProcessReallyExit=process2.reallyExit,processReallyExit=function(code2){processOk(global.process)&&(process2.exitCode=code2||0,emit("exit",process2.exitCode,null),emit("afterexit",process2.exitCode,null),originalProcessReallyExit.call(process2,process2.exitCode))},originalProcessEmit=process2.emit,processEmit=function(ev,arg){if(ev==="exit"&&processOk(global.process)){arg!==void 0&&(process2.exitCode=arg);var ret=originalProcessEmit.apply(this,arguments);return emit("exit",process2.exitCode,null),emit("afterexit",process2.exitCode,null),ret}else return originalProcessEmit.apply(this,arguments)}):module.exports=function(){return function(){}};var assert2,signals,isWin,EE,emitter,unload,emit,sigListeners,loaded,load,originalProcessReallyExit,processReallyExit,originalProcessEmit,processEmit}});var require_mtime_precision=__commonJS({"../../node_modules/proper-lockfile/lib/mtime-precision.js"(exports,module){"use strict";var cacheSymbol=Symbol();function probe(file,fs,callback){let cachedPrecision=fs[cacheSymbol];if(cachedPrecision)return fs.stat(file,(err,stat2)=>{if(err)return callback(err);callback(null,stat2.mtime,cachedPrecision)});let mtime=new Date(Math.ceil(Date.now()/1e3)*1e3+5);fs.utimes(file,mtime,mtime,err=>{if(err)return callback(err);fs.stat(file,(err2,stat2)=>{if(err2)return callback(err2);let precision=stat2.mtime.getTime()%1e3===0?"s":"ms";Object.defineProperty(fs,cacheSymbol,{value:precision}),callback(null,stat2.mtime,precision)})})}function getMtime(precision){let now=Date.now();return precision==="s"&&(now=Math.ceil(now/1e3)*1e3),new Date(now)}module.exports.probe=probe;module.exports.getMtime=getMtime}});var require_lockfile=__commonJS({"../../node_modules/proper-lockfile/lib/lockfile.js"(exports,module){"use strict";var path=__require("path"),fs=require_graceful_fs(),retry=require_retry2(),onExit=require_signal_exit(),mtimePrecision=require_mtime_precision(),locks={};function getLockFile(file,options){return options.lockfilePath||`${file}.lock`}function resolveCanonicalPath(file,options,callback){if(!options.realpath)return callback(null,path.resolve(file));options.fs.realpath(file,callback)}function acquireLock(file,options,callback){let lockfilePath=getLockFile(file,options);options.fs.mkdir(lockfilePath,err=>{if(!err)return mtimePrecision.probe(lockfilePath,options.fs,(err2,mtime,mtimePrecision2)=>{if(err2)return options.fs.rmdir(lockfilePath,()=>{}),callback(err2);callback(null,mtime,mtimePrecision2)});if(err.code!=="EEXIST")return callback(err);if(options.stale<=0)return callback(Object.assign(new Error("Lock file is already being held"),{code:"ELOCKED",file}));options.fs.stat(lockfilePath,(err2,stat2)=>{if(err2)return err2.code==="ENOENT"?acquireLock(file,{...options,stale:0},callback):callback(err2);if(!isLockStale(stat2,options))return callback(Object.assign(new Error("Lock file is already being held"),{code:"ELOCKED",file}));removeLock(file,options,err3=>{if(err3)return callback(err3);acquireLock(file,{...options,stale:0},callback)})})})}function isLockStale(stat2,options){return stat2.mtime.getTime()<Date.now()-options.stale}function removeLock(file,options,callback){options.fs.rmdir(getLockFile(file,options),err=>{if(err&&err.code!=="ENOENT")return callback(err);callback()})}function updateLock(file,options){let lock2=locks[file];lock2.updateTimeout||(lock2.updateDelay=lock2.updateDelay||options.update,lock2.updateTimeout=setTimeout(()=>{lock2.updateTimeout=null,options.fs.stat(lock2.lockfilePath,(err,stat2)=>{let isOverThreshold=lock2.lastUpdate+options.stale<Date.now();if(err)return err.code==="ENOENT"||isOverThreshold?setLockAsCompromised(file,lock2,Object.assign(err,{code:"ECOMPROMISED"})):(lock2.updateDelay=1e3,updateLock(file,options));if(!(lock2.mtime.getTime()===stat2.mtime.getTime()))return setLockAsCompromised(file,lock2,Object.assign(new Error("Unable to update lock within the stale threshold"),{code:"ECOMPROMISED"}));let mtime=mtimePrecision.getMtime(lock2.mtimePrecision);options.fs.utimes(lock2.lockfilePath,mtime,mtime,err2=>{let isOverThreshold2=lock2.lastUpdate+options.stale<Date.now();if(!lock2.released){if(err2)return err2.code==="ENOENT"||isOverThreshold2?setLockAsCompromised(file,lock2,Object.assign(err2,{code:"ECOMPROMISED"})):(lock2.updateDelay=1e3,updateLock(file,options));lock2.mtime=mtime,lock2.lastUpdate=Date.now(),lock2.updateDelay=null,updateLock(file,options)}})})},lock2.updateDelay),lock2.updateTimeout.unref&&lock2.updateTimeout.unref())}function setLockAsCompromised(file,lock2,err){lock2.released=!0,lock2.updateTimeout&&clearTimeout(lock2.updateTimeout),locks[file]===lock2&&delete locks[file],lock2.options.onCompromised(err)}function lock(file,options,callback){options={stale:1e4,update:null,realpath:!0,retries:0,fs,onCompromised:err=>{throw err},...options},options.retries=options.retries||0,options.retries=typeof options.retries=="number"?{retries:options.retries}:options.retries,options.stale=Math.max(options.stale||0,2e3),options.update=options.update==null?options.stale/2:options.update||0,options.update=Math.max(Math.min(options.update,options.stale/2),1e3),resolveCanonicalPath(file,options,(err,file2)=>{if(err)return callback(err);let operation=retry.operation(options.retries);operation.attempt(()=>{acquireLock(file2,options,(err2,mtime,mtimePrecision2)=>{if(operation.retry(err2))return;if(err2)return callback(operation.mainError());let lock2=locks[file2]={lockfilePath:getLockFile(file2,options),mtime,mtimePrecision:mtimePrecision2,options,lastUpdate:Date.now()};updateLock(file2,options),callback(null,releasedCallback=>{if(lock2.released)return releasedCallback&&releasedCallback(Object.assign(new Error("Lock is already released"),{code:"ERELEASED"}));unlock(file2,{...options,realpath:!1},releasedCallback)})})})})}function unlock(file,options,callback){options={fs,realpath:!0,...options},resolveCanonicalPath(file,options,(err,file2)=>{if(err)return callback(err);let lock2=locks[file2];if(!lock2)return callback(Object.assign(new Error("Lock is not acquired/owned by you"),{code:"ENOTACQUIRED"}));lock2.updateTimeout&&clearTimeout(lock2.updateTimeout),lock2.released=!0,delete locks[file2],removeLock(file2,options,callback)})}function check2(file,options,callback){options={stale:1e4,realpath:!0,fs,...options},options.stale=Math.max(options.stale||0,2e3),resolveCanonicalPath(file,options,(err,file2)=>{if(err)return callback(err);options.fs.stat(getLockFile(file2,options),(err2,stat2)=>err2?err2.code==="ENOENT"?callback(null,!1):callback(err2):callback(null,!isLockStale(stat2,options)))})}function getLocks(){return locks}onExit(()=>{for(let file in locks){let options=locks[file].options;try{options.fs.rmdirSync(getLockFile(file,options))}catch{}}});module.exports.lock=lock;module.exports.unlock=unlock;module.exports.check=check2;module.exports.getLocks=getLocks}});var require_adapter=__commonJS({"../../node_modules/proper-lockfile/lib/adapter.js"(exports,module){"use strict";var fs=require_graceful_fs();function createSyncFs(fs2){let methods=["mkdir","realpath","stat","rmdir","utimes"],newFs={...fs2};return methods.forEach(method=>{newFs[method]=(...args)=>{let callback=args.pop(),ret;try{ret=fs2[`${method}Sync`](...args)}catch(err){return callback(err)}callback(null,ret)}}),newFs}function toPromise(method){return(...args)=>new Promise((resolve4,reject)=>{args.push((err,result)=>{err?reject(err):resolve4(result)}),method(...args)})}function toSync(method){return(...args)=>{let err,result;if(args.push((_err,_result)=>{err=_err,result=_result}),method(...args),err)throw err;return result}}function toSyncOptions(options){if(options={...options},options.fs=createSyncFs(options.fs||fs),typeof options.retries=="number"&&options.retries>0||options.retries&&typeof options.retries.retries=="number"&&options.retries.retries>0)throw Object.assign(new Error("Cannot use retries with the sync api"),{code:"ESYNC"});return options}module.exports={toPromise,toSync,toSyncOptions}}});var require_proper_lockfile=__commonJS({"../../node_modules/proper-lockfile/index.js"(exports,module){"use strict";var lockfile4=require_lockfile(),{toPromise,toSync,toSyncOptions}=require_adapter();async function lock(file,options){let release=await toPromise(lockfile4.lock)(file,options);return toPromise(release)}function lockSync(file,options){let release=toSync(lockfile4.lock)(file,toSyncOptions(options));return toSync(release)}function unlock(file,options){return toPromise(lockfile4.unlock)(file,options)}function unlockSync(file,options){return toSync(lockfile4.unlock)(file,toSyncOptions(options))}function check2(file,options){return toPromise(lockfile4.check)(file,options)}function checkSync(file,options){return toSync(lockfile4.check)(file,toSyncOptions(options))}module.exports=lock;module.exports.lock=lock;module.exports.unlock=unlock;module.exports.lockSync=lockSync;module.exports.unlockSync=unlockSync;module.exports.check=check2;module.exports.checkSync=checkSync}});function parseArgs4(args){if(args===void 0)return{};if(!isSimpleObject(args))throw new Error(`The arguments to a Convex function must be an object. Received: ${args}`);return args}function validateDeploymentUrl(deploymentUrl){if(typeof deploymentUrl>"u")throw new Error("Client created with undefined deployment address. If you used an environment variable, check that it's set.");if(typeof deploymentUrl!="string")throw new Error(`Invalid deployment address: found ${deploymentUrl}".`);if(!(deploymentUrl.startsWith("http:")||deploymentUrl.startsWith("https:")))throw new Error(`Invalid deployment address: Must start with "https://" or "http://". Found "${deploymentUrl}".`);try{new URL(deploymentUrl)}catch{throw new Error(`Invalid deployment address: "${deploymentUrl}" is not a valid URL. If you believe this URL is correct, use the \`skipConvexDeploymentUrlCheck\` option to bypass this.`)}if(deploymentUrl.endsWith(".convex.site"))throw new Error(`Invalid deployment address: "${deploymentUrl}" ends with .convex.site, which is used for HTTP Actions. Convex deployment URLs typically end with .convex.cloud? If you believe this URL is correct, use the \`skipConvexDeploymentUrlCheck\` option to bypass this.`)}function isSimpleObject(value){let isObject2=typeof value=="object",prototype=Object.getPrototypeOf(value),isSimple=prototype===null||prototype===Object.prototype||prototype?.constructor?.name==="Object";return isObject2&&isSimple}var init_common=__esm({"../../node_modules/convex/dist/esm/common/index.js"(){"use strict"}});var functionName,init_functionName=__esm({"../../node_modules/convex/dist/esm/server/functionName.js"(){"use strict";functionName=Symbol.for("functionName")}});function extractReferencePath(reference){return reference[toReferencePath]??null}function isFunctionHandle(s){return s.startsWith("function://")}function getFunctionAddress(functionReference){let functionAddress;if(typeof functionReference=="string")isFunctionHandle(functionReference)?functionAddress={functionHandle:functionReference}:functionAddress={name:functionReference};else if(functionReference[functionName])functionAddress={name:functionReference[functionName]};else{let referencePath=extractReferencePath(functionReference);if(!referencePath)throw new Error(`${functionReference} is not a functionReference`);functionAddress={reference:referencePath}}return functionAddress}var toReferencePath,init_paths=__esm({"../../node_modules/convex/dist/esm/server/components/paths.js"(){"use strict";init_functionName();toReferencePath=Symbol.for("toReferencePath")}});function getFunctionName(functionReference){let address=getFunctionAddress(functionReference);if(address.name===void 0)throw address.functionHandle!==void 0?new Error(`Expected function reference like "api.file.func" or "internal.file.func", but received function handle ${address.functionHandle}`):address.reference!==void 0?new Error(`Expected function reference in the current component like "api.file.func" or "internal.file.func", but received reference ${address.reference}`):new Error(`Expected function reference like "api.file.func" or "internal.file.func", but received ${JSON.stringify(address)}`);if(typeof functionReference=="string")return functionReference;let name=functionReference[functionName];if(!name)throw new Error(`${functionReference} is not a functionReference`);return name}function createApi(pathParts=[]){let handler={get(_,prop){if(typeof prop=="string"){let newParts=[...pathParts,prop];return createApi(newParts)}else if(prop===functionName){if(pathParts.length<2){let found=["api",...pathParts].join(".");throw new Error(`API path is expected to be of the form \`api.moduleName.functionName\`. Found: \`${found}\``)}let path=pathParts.slice(0,-1).join("/"),exportName=pathParts[pathParts.length-1];return exportName==="default"?path:path+":"+exportName}else return prop===Symbol.toStringTag?"FunctionReference":void 0}};return new Proxy({},handler)}var anyApi,init_api=__esm({"../../node_modules/convex/dist/esm/server/api.js"(){"use strict";init_functionName();init_paths();anyApi=createApi()}});var version,init_esm=__esm({"../../node_modules/convex/dist/esm/index.js"(){"use strict";version="1.51.1"}});var base64_exports={};__export(base64_exports,{byteLength:()=>byteLength,fromByteArray:()=>fromByteArray,fromByteArrayUrlSafeNoPadding:()=>fromByteArrayUrlSafeNoPadding,toByteArray:()=>toByteArray});function getLens(b64){var len2=b64.length;if(len2%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var validLen=b64.indexOf("=");validLen===-1&&(validLen=len2);var placeHoldersLen=validLen===len2?0:4-validLen%4;return[validLen,placeHoldersLen]}function byteLength(b64){var lens=getLens(b64),validLen=lens[0],placeHoldersLen=lens[1];return(validLen+placeHoldersLen)*3/4-placeHoldersLen}function _byteLength(_b64,validLen,placeHoldersLen){return(validLen+placeHoldersLen)*3/4-placeHoldersLen}function toByteArray(b64){var tmp,lens=getLens(b64),validLen=lens[0],placeHoldersLen=lens[1],arr2=new Arr(_byteLength(b64,validLen,placeHoldersLen)),curByte=0,len2=placeHoldersLen>0?validLen-4:validLen,i2;for(i2=0;i2<len2;i2+=4)tmp=revLookup[b64.charCodeAt(i2)]<<18|revLookup[b64.charCodeAt(i2+1)]<<12|revLookup[b64.charCodeAt(i2+2)]<<6|revLookup[b64.charCodeAt(i2+3)],arr2[curByte++]=tmp>>16&255,arr2[curByte++]=tmp>>8&255,arr2[curByte++]=tmp&255;return placeHoldersLen===2&&(tmp=revLookup[b64.charCodeAt(i2)]<<2|revLookup[b64.charCodeAt(i2+1)]>>4,arr2[curByte++]=tmp&255),placeHoldersLen===1&&(tmp=revLookup[b64.charCodeAt(i2)]<<10|revLookup[b64.charCodeAt(i2+1)]<<4|revLookup[b64.charCodeAt(i2+2)]>>2,arr2[curByte++]=tmp>>8&255,arr2[curByte++]=tmp&255),arr2}function tripletToBase64(num){return lookup[num>>18&63]+lookup[num>>12&63]+lookup[num>>6&63]+lookup[num&63]}function encodeChunk(uint8,start,end){for(var tmp,output=[],i2=start;i2<end;i2+=3)tmp=(uint8[i2]<<16&16711680)+(uint8[i2+1]<<8&65280)+(uint8[i2+2]&255),output.push(tripletToBase64(tmp));return output.join("")}function fromByteArray(uint8){for(var tmp,len2=uint8.length,extraBytes=len2%3,parts=[],maxChunkLength=16383,i2=0,len22=len2-extraBytes;i2<len22;i2+=maxChunkLength)parts.push(encodeChunk(uint8,i2,i2+maxChunkLength>len22?len22:i2+maxChunkLength));return extraBytes===1?(tmp=uint8[len2-1],parts.push(lookup[tmp>>2]+lookup[tmp<<4&63]+"==")):extraBytes===2&&(tmp=(uint8[len2-2]<<8)+uint8[len2-1],parts.push(lookup[tmp>>10]+lookup[tmp>>4&63]+lookup[tmp<<2&63]+"=")),parts.join("")}function fromByteArrayUrlSafeNoPadding(uint8){return fromByteArray(uint8).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}var lookup,revLookup,Arr,code,i,len,init_base64=__esm({"../../node_modules/convex/dist/esm/values/base64.js"(){"use strict";lookup=[],revLookup=[],Arr=Uint8Array,code="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(i=0,len=code.length;i<len;++i)lookup[i]=code[i],revLookup[code.charCodeAt(i)]=i;revLookup[45]=62;revLookup[95]=63}});function isSpecial(n){return Number.isNaN(n)||!Number.isFinite(n)||Object.is(n,-0)}function slowBigIntToBase64(value){value<ZERO&&(value-=MIN_INT64+MIN_INT64);let hex=value.toString(16);hex.length%2===1&&(hex="0"+hex);let bytes=new Uint8Array(new ArrayBuffer(8)),i2=0;for(let hexByte of hex.match(/.{2}/g).reverse())bytes.set([parseInt(hexByte,16)],i2++),value>>=EIGHT;return fromByteArray(bytes)}function slowBase64ToBigInt(encoded){let integerBytes=toByteArray(encoded);if(integerBytes.byteLength!==8)throw new Error(`Received ${integerBytes.byteLength} bytes, expected 8 for $integer`);let value=ZERO,power=ZERO;for(let byte of integerBytes)value+=BigInt(byte)*TWOFIFTYSIX**power,power++;return value>MAX_INT64&&(value+=MIN_INT64+MIN_INT64),value}function modernBigIntToBase64(value){if(value<MIN_INT64||MAX_INT64<value)throw new Error(`BigInt ${value} does not fit into a 64-bit signed integer.`);let buffer=new ArrayBuffer(8);return new DataView(buffer).setBigInt64(0,value,!0),fromByteArray(new Uint8Array(buffer))}function modernBase64ToBigInt(encoded){let integerBytes=toByteArray(encoded);if(integerBytes.byteLength!==8)throw new Error(`Received ${integerBytes.byteLength} bytes, expected 8 for $integer`);return new DataView(integerBytes.buffer).getBigInt64(0,!0)}function validateObjectField(k){if(k.length>MAX_IDENTIFIER_LEN)throw new Error(`Field name ${k} exceeds maximum field name length ${MAX_IDENTIFIER_LEN}.`);if(k.startsWith("$"))throw new Error(`Field name ${k} starts with a '$', which is reserved.`);for(let i2=0;i2<k.length;i2+=1){let charCode=k.charCodeAt(i2);if(charCode<32||charCode>=127)throw new Error(`Field name ${k} has invalid character '${k[i2]}': Field names can only contain non-control ASCII characters`)}}function jsonToConvex(value){if(value===null||typeof value=="boolean"||typeof value=="number"||typeof value=="string")return value;if(Array.isArray(value))return value.map(value2=>jsonToConvex(value2));if(typeof value!="object")throw new Error(`Unexpected type of ${value}`);let entries=Object.entries(value);if(entries.length===1){let key=entries[0][0];if(key==="$bytes"){if(typeof value.$bytes!="string")throw new Error(`Malformed $bytes field on ${value}`);return toByteArray(value.$bytes).buffer}if(key==="$integer"){if(typeof value.$integer!="string")throw new Error(`Malformed $integer field on ${value}`);return base64ToBigInt(value.$integer)}if(key==="$float"){if(typeof value.$float!="string")throw new Error(`Malformed $float field on ${value}`);let floatBytes=toByteArray(value.$float);if(floatBytes.byteLength!==8)throw new Error(`Received ${floatBytes.byteLength} bytes, expected 8 for $float`);let float=new DataView(floatBytes.buffer).getFloat64(0,LITTLE_ENDIAN);if(!isSpecial(float))throw new Error(`Float ${float} should be encoded as a number`);return float}if(key==="$commitTs"){if(value.$commitTs!==null)throw new Error(`Malformed $commitTs field on ${value}`);return commitTsPlaceholder}if(key==="$set")throw new Error("Received a Set which is no longer supported as a Convex type.");if(key==="$map")throw new Error("Received a Map which is no longer supported as a Convex type.")}let out={};for(let[k,v2]of Object.entries(value))validateObjectField(k),out[k]=jsonToConvex(v2);return out}function stringifyValueForError(value){let str=JSON.stringify(value,(_key,value2)=>value2===void 0?"undefined":typeof value2=="function"?"[Function]":typeof value2=="symbol"?String(value2):typeof value2=="bigint"?`${value2.toString()}n`:value2);if(str.length>MAX_VALUE_FOR_ERROR_LEN){let rest="[...truncated]",truncateAt=MAX_VALUE_FOR_ERROR_LEN-rest.length,codePoint=str.codePointAt(truncateAt-1);return codePoint!==void 0&&codePoint>65535&&(truncateAt-=1),str.substring(0,truncateAt)+rest}return str}function convexToJsonInternal(value,originalValue,context,includeTopLevelUndefined){if(value===void 0){let contextText=context&&` (present at path ${context} in original object ${stringifyValueForError(originalValue)})`;throw new Error(`undefined is not a valid Convex value${contextText}. To learn about Convex's supported types, see https://docs.convex.dev/using/types.`)}if(value===null)return value;if(typeof value=="bigint"){if(value<MIN_INT64||MAX_INT64<value)throw new Error(`BigInt ${value} does not fit into a 64-bit signed integer.`);return{$integer:bigIntToBase64(value)}}if(typeof value=="number")if(isSpecial(value)){let buffer=new ArrayBuffer(8);return new DataView(buffer).setFloat64(0,value,LITTLE_ENDIAN),{$float:fromByteArray(new Uint8Array(buffer))}}else return value;if(typeof value=="boolean"||typeof value=="string")return value;if(value instanceof ArrayBuffer)return{$bytes:fromByteArray(new Uint8Array(value))};if(value instanceof CommitTsPlaceholder)return{$commitTs:null};if(Array.isArray(value))return value.map((value2,i2)=>convexToJsonInternal(value2,originalValue,context+`[${i2}]`,!1));if(value instanceof Set)throw new Error(errorMessageForUnsupportedType(context,"Set",[...value],originalValue));if(value instanceof Map)throw new Error(errorMessageForUnsupportedType(context,"Map",[...value],originalValue));if(!isSimpleObject(value)){let theType=value?.constructor?.name,typeName=theType?`${theType} `:"";throw new Error(errorMessageForUnsupportedType(context,typeName,value,originalValue))}let out={},entries=Object.entries(value);entries.sort(([k1,_v1],[k2,_v2])=>k1===k2?0:k1<k2?-1:1);for(let[k,v2]of entries)v2!==void 0?(validateObjectField(k),out[k]=convexToJsonInternal(v2,originalValue,context+`.${k}`,!1)):includeTopLevelUndefined&&(validateObjectField(k),out[k]=convexOrUndefinedToJsonInternal(v2,originalValue,context+`.${k}`));return out}function errorMessageForUnsupportedType(context,typeName,value,originalValue){return context?`${typeName}${stringifyValueForError(value)} is not a supported Convex type (present at path ${context} in original object ${stringifyValueForError(originalValue)}). To learn about Convex's supported types, see https://docs.convex.dev/using/types.`:`${typeName}${stringifyValueForError(value)} is not a supported Convex type.`}function convexOrUndefinedToJsonInternal(value,originalValue,context){if(value===void 0)return{$undefined:null};if(originalValue===void 0)throw new Error(`Programming error. Current value is ${stringifyValueForError(value)} but original value is undefined`);return convexToJsonInternal(value,originalValue,context,!1)}function convexToJson(value){return convexToJsonInternal(value,value,"",!1)}var LITTLE_ENDIAN,MIN_INT64,MAX_INT64,ZERO,EIGHT,TWOFIFTYSIX,COMMIT_TS_UNRESOLVED,CommitTsPlaceholder,commitTsPlaceholder,bigIntToBase64,base64ToBigInt,MAX_IDENTIFIER_LEN,MAX_VALUE_FOR_ERROR_LEN,init_value=__esm({"../../node_modules/convex/dist/esm/values/value.js"(){"use strict";init_base64();init_common();LITTLE_ENDIAN=!0,MIN_INT64=BigInt("-9223372036854775808"),MAX_INT64=BigInt("9223372036854775807"),ZERO=BigInt("0"),EIGHT=BigInt("8"),TWOFIFTYSIX=BigInt("256"),COMMIT_TS_UNRESOLVED="This commit timestamp is unresolved: its value is assigned when the mutation commits. Read the document after the mutation completes to get its value.",CommitTsPlaceholder=class{[Symbol.toPrimitive](hint){if(hint==="string")return this.toString();throw new Error(COMMIT_TS_UNRESOLVED)}valueOf(){throw new Error(COMMIT_TS_UNRESOLVED)}toJSON(){throw new Error(COMMIT_TS_UNRESOLVED)}toString(){return"[unresolved commit timestamp]"}},commitTsPlaceholder=new CommitTsPlaceholder;bigIntToBase64=DataView.prototype.setBigInt64?modernBigIntToBase64:slowBigIntToBase64,base64ToBigInt=DataView.prototype.getBigInt64?modernBase64ToBigInt:slowBase64ToBigInt,MAX_IDENTIFIER_LEN=1024;MAX_VALUE_FOR_ERROR_LEN=16384}});var init_validators=__esm({"../../node_modules/convex/dist/esm/values/validators.js"(){"use strict";init_value()}});var init_validator=__esm({"../../node_modules/convex/dist/esm/values/validator.js"(){"use strict";init_validators()}});var __defProp2,__defNormalProp,__publicField,_a,_b,IDENTIFYING_FIELD,ConvexError,init_errors=__esm({"../../node_modules/convex/dist/esm/values/errors.js"(){"use strict";init_value();__defProp2=Object.defineProperty,__defNormalProp=(obj,key,value)=>key in obj?__defProp2(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,__publicField=(obj,key,value)=>__defNormalProp(obj,typeof key!="symbol"?key+"":key,value),IDENTIFYING_FIELD=Symbol.for("ConvexError"),ConvexError=class extends(_b=Error,_a=IDENTIFYING_FIELD,_b){constructor(data){super(typeof data=="string"?data:stringifyValueForError(data)),__publicField(this,"name","ConvexError"),__publicField(this,"data"),__publicField(this,_a,!0),this.data=data}}}});var arr,aBytes,bBytes,init_compare_utf8=__esm({"../../node_modules/convex/dist/esm/values/compare_utf8.js"(){"use strict";arr=()=>Array.from({length:4},()=>0),aBytes=arr(),bBytes=arr()}});var init_compare=__esm({"../../node_modules/convex/dist/esm/values/compare.js"(){"use strict";init_value();init_compare_utf8()}});var init_size=__esm({"../../node_modules/convex/dist/esm/values/size.js"(){"use strict";init_value();init_common()}});var init_values=__esm({"../../node_modules/convex/dist/esm/values/index.js"(){"use strict";init_value();init_validator();init_base64();init_errors();init_compare();init_size()}});function prefix_for_source(source){switch(source){case"query":return"Q";case"mutation":return"M";case"action":return"A";case"any":return"?"}}function instantiateDefaultLogger(options){let logger2=new DefaultLogger(options);return logger2.addLogLineListener((level,...args)=>{switch(level){case"debug":console.debug(...args);break;case"info":console.log(...args);break;case"warn":console.warn(...args);break;case"error":console.error(...args);break;default:console.log(...args)}}),logger2}function instantiateNoopLogger(options){return new DefaultLogger(options)}function logForFunction(logger2,type,source,udfPath,message){let prefix=prefix_for_source(source);if(typeof message=="object"&&(message=`ConvexError ${JSON.stringify(message.errorData,null,2)}`),type==="info"){let match=message.match(/^\[.*?\] /);if(match===null){logger2.error(`[CONVEX ${prefix}(${udfPath})] Could not parse console.log`);return}let level=message.slice(1,match[0].length-2),args=message.slice(match[0].length);logger2.log(`%c[CONVEX ${prefix}(${udfPath})] [${level}]`,INFO_COLOR,args)}else logger2.error(`[CONVEX ${prefix}(${udfPath})] ${message}`)}function logFatalError(logger2,message){let errorMessage=`[CONVEX FATAL ERROR] ${message}`;return logger2.error(errorMessage),new Error(errorMessage)}function createHybridErrorStacktrace(source,udfPath,result){return`[CONVEX ${prefix_for_source(source)}(${udfPath})] ${result.errorMessage}
|
|
6
|
+
Called by client`}function forwardData(result,error2){return error2.data=result.errorData,error2}var __defProp3,__defNormalProp2,__publicField2,INFO_COLOR,DefaultLogger,init_logging=__esm({"../../node_modules/convex/dist/esm/browser/logging.js"(){"use strict";__defProp3=Object.defineProperty,__defNormalProp2=(obj,key,value)=>key in obj?__defProp3(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,__publicField2=(obj,key,value)=>__defNormalProp2(obj,typeof key!="symbol"?key+"":key,value),INFO_COLOR="color:rgb(0, 145, 255)";DefaultLogger=class{constructor(options){__publicField2(this,"_onLogLineFuncs"),__publicField2(this,"_verbose"),this._onLogLineFuncs={},this._verbose=options.verbose}addLogLineListener(func){let id=Math.random().toString(36).substring(2,15);for(let i2=0;i2<10&&this._onLogLineFuncs[id]!==void 0;i2++)id=Math.random().toString(36).substring(2,15);return this._onLogLineFuncs[id]=func,()=>{delete this._onLogLineFuncs[id]}}logVerbose(...args){if(this._verbose)for(let func of Object.values(this._onLogLineFuncs))func("debug",`${new Date().toISOString()}`,...args)}log(...args){for(let func of Object.values(this._onLogLineFuncs))func("info",...args)}warn(...args){for(let func of Object.values(this._onLogLineFuncs))func("warn",...args)}error(...args){for(let func of Object.values(this._onLogLineFuncs))func("error",...args)}}}});function canonicalizeUdfPath(udfPath){let pieces=udfPath.split(":"),moduleName,functionName2;return pieces.length===1?(moduleName=pieces[0],functionName2="default"):(moduleName=pieces.slice(0,pieces.length-1).join(":"),functionName2=pieces[pieces.length-1]),moduleName.endsWith(".js")&&(moduleName=moduleName.slice(0,-3)),`${moduleName}:${functionName2}`}function serializePathAndArgs(udfPath,args){return JSON.stringify({udfPath:canonicalizeUdfPath(udfPath),args:convexToJson(args)})}function serializePaginatedPathAndArgs(udfPath,args,options){let{initialNumItems,id}=options;return JSON.stringify({type:"paginated",udfPath:canonicalizeUdfPath(udfPath),args:convexToJson(args),options:convexToJson({initialNumItems,id})})}function serializedQueryTokenIsPaginated(token){return JSON.parse(token).type==="paginated"}var init_udf_path_utils=__esm({"../../node_modules/convex/dist/esm/browser/sync/udf_path_utils.js"(){"use strict";init_values()}});var __defProp4,__defNormalProp3,__publicField3,LocalSyncState,init_local_state=__esm({"../../node_modules/convex/dist/esm/browser/sync/local_state.js"(){"use strict";init_values();init_udf_path_utils();__defProp4=Object.defineProperty,__defNormalProp3=(obj,key,value)=>key in obj?__defProp4(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,__publicField3=(obj,key,value)=>__defNormalProp3(obj,typeof key!="symbol"?key+"":key,value),LocalSyncState=class{constructor(){__publicField3(this,"nextQueryId"),__publicField3(this,"querySetVersion"),__publicField3(this,"querySet"),__publicField3(this,"queryIdToToken"),__publicField3(this,"identityVersion"),__publicField3(this,"auth"),__publicField3(this,"outstandingQueriesOlderThanRestart"),__publicField3(this,"outstandingAuthOlderThanRestart"),__publicField3(this,"paused"),__publicField3(this,"pendingQuerySetModifications"),this.nextQueryId=0,this.querySetVersion=0,this.identityVersion=0,this.querySet=new Map,this.queryIdToToken=new Map,this.outstandingQueriesOlderThanRestart=new Set,this.outstandingAuthOlderThanRestart=!1,this.paused=!1,this.pendingQuerySetModifications=new Map}hasSyncedPastLastReconnect(){return this.outstandingQueriesOlderThanRestart.size===0&&!this.outstandingAuthOlderThanRestart}markAuthCompletion(){this.outstandingAuthOlderThanRestart=!1}subscribe(udfPath,args,journal,componentPath){let canonicalizedUdfPath=canonicalizeUdfPath(udfPath),queryToken=serializePathAndArgs(canonicalizedUdfPath,args),existingEntry=this.querySet.get(queryToken);if(existingEntry!==void 0)return existingEntry.numSubscribers+=1,{queryToken,modification:null,unsubscribe:()=>this.removeSubscriber(queryToken)};{let queryId=this.nextQueryId++,query={id:queryId,canonicalizedUdfPath,args,numSubscribers:1,journal,componentPath};this.querySet.set(queryToken,query),this.queryIdToToken.set(queryId,queryToken);let baseVersion=this.querySetVersion,newVersion=this.querySetVersion+1,add={type:"Add",queryId,udfPath:canonicalizedUdfPath,args:[convexToJson(args)],journal,componentPath};return this.paused?this.pendingQuerySetModifications.set(queryId,add):this.querySetVersion=newVersion,{queryToken,modification:{type:"ModifyQuerySet",baseVersion,newVersion,modifications:[add]},unsubscribe:()=>this.removeSubscriber(queryToken)}}}transition(transition){for(let modification of transition.modifications)switch(modification.type){case"QueryUpdated":case"QueryFailed":{this.outstandingQueriesOlderThanRestart.delete(modification.queryId);let journal=modification.journal;if(journal!==void 0){let queryToken=this.queryIdToToken.get(modification.queryId);queryToken!==void 0&&(this.querySet.get(queryToken).journal=journal)}break}case"QueryRemoved":{this.outstandingQueriesOlderThanRestart.delete(modification.queryId);break}default:throw new Error(`Invalid modification ${modification.type}`)}}queryId(udfPath,args){let canonicalizedUdfPath=canonicalizeUdfPath(udfPath),queryToken=serializePathAndArgs(canonicalizedUdfPath,args),existingEntry=this.querySet.get(queryToken);return existingEntry!==void 0?existingEntry.id:null}isCurrentOrNewerAuthVersion(version3){return version3>=this.identityVersion}getAuth(){return this.auth}setAuth(value){this.auth={tokenType:"User",value};let baseVersion=this.identityVersion;return this.paused||(this.identityVersion=baseVersion+1),{type:"Authenticate",baseVersion,...this.auth}}setAdminAuth(value,actingAs){let auth2={tokenType:"Admin",value,impersonating:actingAs};this.auth=auth2;let baseVersion=this.identityVersion;return this.paused||(this.identityVersion=baseVersion+1),{type:"Authenticate",baseVersion,...auth2}}clearAuth(){this.auth=void 0,this.markAuthCompletion();let baseVersion=this.identityVersion;return this.paused||(this.identityVersion=baseVersion+1),{type:"Authenticate",tokenType:"None",baseVersion}}hasAuth(){return!!this.auth}isNewAuth(value){return this.auth?.value!==value}queryPath(queryId){let pathAndArgs=this.queryIdToToken.get(queryId);return pathAndArgs?this.querySet.get(pathAndArgs).canonicalizedUdfPath:null}queryArgs(queryId){let pathAndArgs=this.queryIdToToken.get(queryId);return pathAndArgs?this.querySet.get(pathAndArgs).args:null}queryToken(queryId){return this.queryIdToToken.get(queryId)??null}queryJournal(queryToken){return this.querySet.get(queryToken)?.journal}restart(){this.unpause(),this.outstandingQueriesOlderThanRestart.clear();let modifications=[];for(let localQuery of this.querySet.values()){let add={type:"Add",queryId:localQuery.id,udfPath:localQuery.canonicalizedUdfPath,args:[convexToJson(localQuery.args)],journal:localQuery.journal,componentPath:localQuery.componentPath};modifications.push(add),this.outstandingQueriesOlderThanRestart.add(localQuery.id)}this.querySetVersion=1;let querySet={type:"ModifyQuerySet",baseVersion:0,newVersion:1,modifications};if(!this.auth)return this.identityVersion=0,[querySet,void 0];this.outstandingAuthOlderThanRestart=!0;let authenticate={type:"Authenticate",baseVersion:0,...this.auth};return this.identityVersion=1,[querySet,authenticate]}pause(){this.paused=!0}resume(){let querySet=this.pendingQuerySetModifications.size>0?{type:"ModifyQuerySet",baseVersion:this.querySetVersion,newVersion:++this.querySetVersion,modifications:Array.from(this.pendingQuerySetModifications.values())}:void 0,authenticate=this.auth!==void 0?{type:"Authenticate",baseVersion:this.identityVersion++,...this.auth}:void 0;return this.unpause(),[querySet,authenticate]}unpause(){this.paused=!1,this.pendingQuerySetModifications.clear()}removeSubscriber(queryToken){let localQuery=this.querySet.get(queryToken);if(localQuery.numSubscribers>1)return localQuery.numSubscribers-=1,null;{this.querySet.delete(queryToken),this.queryIdToToken.delete(localQuery.id),this.outstandingQueriesOlderThanRestart.delete(localQuery.id);let baseVersion=this.querySetVersion,newVersion=this.querySetVersion+1,remove={type:"Remove",queryId:localQuery.id};return this.paused?this.pendingQuerySetModifications.has(localQuery.id)?this.pendingQuerySetModifications.delete(localQuery.id):this.pendingQuerySetModifications.set(localQuery.id,remove):this.querySetVersion=newVersion,{type:"ModifyQuerySet",baseVersion,newVersion,modifications:[remove]}}}}}});var __defProp5,__defNormalProp4,__publicField4,RequestManager,init_request_manager=__esm({"../../node_modules/convex/dist/esm/browser/sync/request_manager.js"(){"use strict";init_values();init_logging();__defProp5=Object.defineProperty,__defNormalProp4=(obj,key,value)=>key in obj?__defProp5(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,__publicField4=(obj,key,value)=>__defNormalProp4(obj,typeof key!="symbol"?key+"":key,value),RequestManager=class{constructor(logger2,markConnectionStateDirty){this.logger=logger2,this.markConnectionStateDirty=markConnectionStateDirty,__publicField4(this,"inflightRequests"),__publicField4(this,"requestsOlderThanRestart"),__publicField4(this,"inflightMutationsCount",0),__publicField4(this,"inflightActionsCount",0),this.inflightRequests=new Map,this.requestsOlderThanRestart=new Set}request(message,sent){let result=new Promise(resolve4=>{let status=sent?"Requested":"NotSent";this.inflightRequests.set(message.requestId,{message,status:{status,requestedAt:new Date,onResult:resolve4}}),message.type==="Mutation"?this.inflightMutationsCount++:message.type==="Action"&&this.inflightActionsCount++});return this.markConnectionStateDirty(),result}onResponse(response){let requestInfo=this.inflightRequests.get(response.requestId);if(requestInfo===void 0||requestInfo.status.status==="Completed")return null;let udfType=requestInfo.message.type==="Mutation"?"mutation":"action",udfPath=requestInfo.message.udfPath;for(let line of response.logLines)logForFunction(this.logger,"info",udfType,udfPath,line);let status=requestInfo.status,result,onResolve;if(response.success)result={success:!0,logLines:response.logLines,value:jsonToConvex(response.result)},onResolve=()=>status.onResult(result);else{let errorMessage=response.result,{errorData}=response;logForFunction(this.logger,"error",udfType,udfPath,errorMessage),result={success:!1,errorMessage,errorData:errorData!==void 0?jsonToConvex(errorData):void 0,logLines:response.logLines},onResolve=()=>status.onResult(result)}return response.type==="ActionResponse"||!response.success?(onResolve(),this.inflightRequests.delete(response.requestId),this.requestsOlderThanRestart.delete(response.requestId),requestInfo.message.type==="Action"?this.inflightActionsCount--:requestInfo.message.type==="Mutation"&&this.inflightMutationsCount--,this.markConnectionStateDirty(),{requestId:response.requestId,result}):(requestInfo.status={status:"Completed",result,ts:response.ts,onResolve},null)}removeCompleted(ts){let completeRequests=new Map;for(let[requestId,requestInfo]of this.inflightRequests.entries()){let status=requestInfo.status;status.status==="Completed"&&status.ts.lessThanOrEqual(ts)&&(status.onResolve(),completeRequests.set(requestId,status.result),requestInfo.message.type==="Mutation"?this.inflightMutationsCount--:requestInfo.message.type==="Action"&&this.inflightActionsCount--,this.inflightRequests.delete(requestId),this.requestsOlderThanRestart.delete(requestId))}return completeRequests.size>0&&this.markConnectionStateDirty(),completeRequests}restart(){this.requestsOlderThanRestart=new Set(this.inflightRequests.keys());let allMessages=[];for(let[requestId,value]of this.inflightRequests){if(value.status.status==="NotSent"){value.status.status="Requested",allMessages.push(value.message);continue}if(value.message.type==="Mutation")allMessages.push(value.message);else if(value.message.type==="Action"){if(this.inflightRequests.delete(requestId),this.requestsOlderThanRestart.delete(requestId),this.inflightActionsCount--,value.status.status==="Completed")throw new Error("Action should never be in 'Completed' state");value.status.onResult({success:!1,errorMessage:"Connection lost while action was in flight",logLines:[]})}}return this.markConnectionStateDirty(),allMessages}resume(){let allMessages=[];for(let[,value]of this.inflightRequests)if(value.status.status==="NotSent"){value.status.status="Requested",allMessages.push(value.message);continue}return allMessages}hasIncompleteRequests(){for(let requestInfo of this.inflightRequests.values())if(requestInfo.status.status==="Requested")return!0;return!1}hasInflightRequests(){return this.inflightRequests.size>0}hasSyncedPastLastReconnect(){return this.requestsOlderThanRestart.size===0}timeOfOldestInflightRequest(){if(this.inflightRequests.size===0)return null;let oldestInflightRequest=Date.now();for(let request of this.inflightRequests.values())request.status.status!=="Completed"&&request.status.requestedAt.getTime()<oldestInflightRequest&&(oldestInflightRequest=request.status.requestedAt.getTime());return new Date(oldestInflightRequest)}inflightMutations(){return this.inflightMutationsCount}inflightActions(){return this.inflightActionsCount}}}});var __defProp6,__defNormalProp5,__publicField5,OptimisticLocalStoreImpl,OptimisticQueryResults,init_optimistic_updates_impl=__esm({"../../node_modules/convex/dist/esm/browser/sync/optimistic_updates_impl.js"(){"use strict";init_api();init_common();init_logging();init_udf_path_utils();init_errors();__defProp6=Object.defineProperty,__defNormalProp5=(obj,key,value)=>key in obj?__defProp6(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,__publicField5=(obj,key,value)=>__defNormalProp5(obj,typeof key!="symbol"?key+"":key,value),OptimisticLocalStoreImpl=class _OptimisticLocalStoreImpl{constructor(queryResults){__publicField5(this,"queryResults"),__publicField5(this,"modifiedQueries"),this.queryResults=queryResults,this.modifiedQueries=[]}getQuery(query,...args){let queryArgs=parseArgs4(args[0]),name=getFunctionName(query),queryResult=this.queryResults.get(serializePathAndArgs(name,queryArgs));if(queryResult!==void 0)return _OptimisticLocalStoreImpl.queryValue(queryResult.result)}getAllQueries(query){let queriesWithName=[],name=getFunctionName(query);for(let queryResult of this.queryResults.values())queryResult.udfPath===canonicalizeUdfPath(name)&&queriesWithName.push({args:queryResult.args,value:_OptimisticLocalStoreImpl.queryValue(queryResult.result)});return queriesWithName}setQuery(queryReference,args,value){let queryArgs=parseArgs4(args),name=getFunctionName(queryReference),queryToken=serializePathAndArgs(name,queryArgs),result;value===void 0?result=void 0:result={success:!0,value,logLines:[]};let query={udfPath:name,args:queryArgs,result};this.queryResults.set(queryToken,query),this.modifiedQueries.push(queryToken)}static queryValue(result){if(result!==void 0)return result.success?result.value:void 0}},OptimisticQueryResults=class{constructor(){__publicField5(this,"queryResults"),__publicField5(this,"optimisticUpdates"),this.queryResults=new Map,this.optimisticUpdates=[]}ingestQueryResultsFromServer(serverQueryResults,optimisticUpdatesToDrop){this.optimisticUpdates=this.optimisticUpdates.filter(updateAndId=>!optimisticUpdatesToDrop.has(updateAndId.mutationId));let oldQueryResults=this.queryResults;this.queryResults=new Map(serverQueryResults);let localStore=new OptimisticLocalStoreImpl(this.queryResults);for(let updateAndId of this.optimisticUpdates)updateAndId.update(localStore);let changedQueries=[];for(let[queryToken,query]of this.queryResults){let oldQuery=oldQueryResults.get(queryToken);(oldQuery===void 0||oldQuery.result!==query.result)&&changedQueries.push(queryToken)}return changedQueries}applyOptimisticUpdate(update2,mutationId){this.optimisticUpdates.push({update:update2,mutationId});let localStore=new OptimisticLocalStoreImpl(this.queryResults);return update2(localStore),localStore.modifiedQueries}rawQueryResult(queryToken){let query=this.queryResults.get(queryToken);if(query!==void 0)return query.result}queryResult(queryToken){let query=this.queryResults.get(queryToken);if(query===void 0)return;let result=query.result;if(result!==void 0){if(result.success)return result.value;throw result.errorData!==void 0?forwardData(result,new ConvexError(createHybridErrorStacktrace("query",query.udfPath,result))):new Error(createHybridErrorStacktrace("query",query.udfPath,result))}}hasQueryResult(queryToken){return this.queryResults.get(queryToken)!==void 0}queryLogs(queryToken){return this.queryResults.get(queryToken)?.result?.logLines}}}});var __defProp7,__defNormalProp6,__publicField6,Long,UZERO,TWO_PWR_16_DBL,TWO_PWR_32_DBL,TWO_PWR_64_DBL,MAX_UNSIGNED_VALUE,init_long=__esm({"../../node_modules/convex/dist/esm/vendor/long.js"(){"use strict";__defProp7=Object.defineProperty,__defNormalProp6=(obj,key,value)=>key in obj?__defProp7(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,__publicField6=(obj,key,value)=>__defNormalProp6(obj,typeof key!="symbol"?key+"":key,value),Long=class _Long{constructor(low,high){__publicField6(this,"low"),__publicField6(this,"high"),__publicField6(this,"__isUnsignedLong__"),this.low=low|0,this.high=high|0,this.__isUnsignedLong__=!0}static isLong(obj){return(obj&&obj.__isUnsignedLong__)===!0}static fromBytesLE(bytes){return new _Long(bytes[0]|bytes[1]<<8|bytes[2]<<16|bytes[3]<<24,bytes[4]|bytes[5]<<8|bytes[6]<<16|bytes[7]<<24)}toBytesLE(){let hi=this.high,lo=this.low;return[lo&255,lo>>>8&255,lo>>>16&255,lo>>>24,hi&255,hi>>>8&255,hi>>>16&255,hi>>>24]}static fromNumber(value){return isNaN(value)||value<0?UZERO:value>=TWO_PWR_64_DBL?MAX_UNSIGNED_VALUE:new _Long(value%TWO_PWR_32_DBL|0,value/TWO_PWR_32_DBL|0)}toString(){return(BigInt(this.high)*BigInt(TWO_PWR_32_DBL)+BigInt(this.low)).toString()}equals(other){return _Long.isLong(other)||(other=_Long.fromValue(other)),this.high>>>31===1&&other.high>>>31===1?!1:this.high===other.high&&this.low===other.low}notEquals(other){return!this.equals(other)}comp(other){return _Long.isLong(other)||(other=_Long.fromValue(other)),this.equals(other)?0:other.high>>>0>this.high>>>0||other.high===this.high&&other.low>>>0>this.low>>>0?-1:1}lessThanOrEqual(other){return this.comp(other)<=0}static fromValue(val){return typeof val=="number"?_Long.fromNumber(val):new _Long(val.low,val.high)}},UZERO=new Long(0,0),TWO_PWR_16_DBL=65536,TWO_PWR_32_DBL=TWO_PWR_16_DBL*TWO_PWR_16_DBL,TWO_PWR_64_DBL=TWO_PWR_32_DBL*TWO_PWR_32_DBL,MAX_UNSIGNED_VALUE=new Long(-1,-1)}});var __defProp8,__defNormalProp7,__publicField7,RemoteQuerySet,init_remote_query_set=__esm({"../../node_modules/convex/dist/esm/browser/sync/remote_query_set.js"(){"use strict";init_values();init_long();init_logging();__defProp8=Object.defineProperty,__defNormalProp7=(obj,key,value)=>key in obj?__defProp8(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,__publicField7=(obj,key,value)=>__defNormalProp7(obj,typeof key!="symbol"?key+"":key,value),RemoteQuerySet=class{constructor(queryPath,logger2){__publicField7(this,"version"),__publicField7(this,"remoteQuerySet"),__publicField7(this,"queryPath"),__publicField7(this,"logger"),this.version={querySet:0,ts:Long.fromNumber(0),identity:0},this.remoteQuerySet=new Map,this.queryPath=queryPath,this.logger=logger2}transition(transition){let start=transition.startVersion;if(this.version.querySet!==start.querySet||this.version.ts.notEquals(start.ts)||this.version.identity!==start.identity)throw new Error(`Invalid start version: ${start.ts.toString()}:${start.querySet}:${start.identity}, transitioning from ${this.version.ts.toString()}:${this.version.querySet}:${this.version.identity}`);for(let modification of transition.modifications)switch(modification.type){case"QueryUpdated":{let queryPath=this.queryPath(modification.queryId);if(queryPath)for(let line of modification.logLines)logForFunction(this.logger,"info","query",queryPath,line);let value=jsonToConvex(modification.value??null);this.remoteQuerySet.set(modification.queryId,{success:!0,value,logLines:modification.logLines});break}case"QueryFailed":{let queryPath=this.queryPath(modification.queryId);if(queryPath)for(let line of modification.logLines)logForFunction(this.logger,"info","query",queryPath,line);let{errorData}=modification;this.remoteQuerySet.set(modification.queryId,{success:!1,errorMessage:modification.errorMessage,errorData:errorData!==void 0?jsonToConvex(errorData):void 0,logLines:modification.logLines});break}case"QueryRemoved":{this.remoteQuerySet.delete(modification.queryId);break}default:throw new Error(`Invalid modification ${modification.type}`)}this.version=transition.endVersion}remoteQueryResults(){return this.remoteQuerySet}timestamp(){return this.version.ts}}}});function u64ToLong(encoded){let integerBytes=base64_exports.toByteArray(encoded);return Long.fromBytesLE(Array.from(integerBytes))}function longToU64(raw){let integerBytes=new Uint8Array(raw.toBytesLE());return base64_exports.fromByteArray(integerBytes)}function parseServerMessage(encoded){switch(encoded.type){case"FatalError":case"AuthError":case"ActionResponse":case"TransitionChunk":case"Ping":return{...encoded};case"MutationResponse":return encoded.success?{...encoded,ts:u64ToLong(encoded.ts)}:{...encoded};case"Transition":return{...encoded,startVersion:{...encoded.startVersion,ts:u64ToLong(encoded.startVersion.ts)},endVersion:{...encoded.endVersion,ts:u64ToLong(encoded.endVersion.ts)}};default:}}function encodeClientMessage(message){switch(message.type){case"Authenticate":case"ModifyQuerySet":case"Mutation":case"Action":case"Event":return{...message};case"Connect":return message.maxObservedTimestamp!==void 0?{...message,maxObservedTimestamp:longToU64(message.maxObservedTimestamp)}:{...message,maxObservedTimestamp:void 0};default:}}var init_protocol=__esm({"../../node_modules/convex/dist/esm/browser/sync/protocol.js"(){"use strict";init_values();init_long()}});function monotonicMillis(){return typeof performance>"u"||!performance.now?Date.now():((firstTime===void 0||firstPerformanceNow===void 0)&&(firstTime=Date.now(),firstPerformanceNow=performance.now()),Math.round(firstTime+performance.now()-firstPerformanceNow))}function prettyNow(){return`t=${Math.round((monotonicMillis()-firstTime)/100)/10}s`}function classifyDisconnectError(s){if(s===void 0)return"Unknown";for(let prefix of Object.keys(serverDisconnectErrors))if(s.startsWith(prefix))return prefix;return"Unknown"}var __defProp9,__defNormalProp8,__publicField8,CLOSE_NORMAL,CLOSE_GOING_AWAY,CLOSE_NO_STATUS,CLOSE_NOT_FOUND,firstTime,firstPerformanceNow,serverDisconnectErrors,WebSocketManager,init_web_socket_manager=__esm({"../../node_modules/convex/dist/esm/browser/sync/web_socket_manager.js"(){"use strict";init_protocol();__defProp9=Object.defineProperty,__defNormalProp8=(obj,key,value)=>key in obj?__defProp9(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,__publicField8=(obj,key,value)=>__defNormalProp8(obj,typeof key!="symbol"?key+"":key,value),CLOSE_NORMAL=1e3,CLOSE_GOING_AWAY=1001,CLOSE_NO_STATUS=1005,CLOSE_NOT_FOUND=4040;serverDisconnectErrors={InternalServerError:{timeout:1e3},SubscriptionsWorkerFullError:{timeout:3e3},TooManyConcurrentRequests:{timeout:3e3},CommitterFullError:{timeout:3e3},AwsTooManyRequestsException:{timeout:3e3},ExecuteFullError:{timeout:3e3},SystemTimeoutError:{timeout:3e3},ExpiredInQueue:{timeout:3e3},VectorIndexesUnavailable:{timeout:1e3},SearchIndexesUnavailable:{timeout:1e3},TableSummariesUnavailable:{timeout:1e3},VectorIndexTooLarge:{timeout:3e3},TextIndexTooLarge:{timeout:3e3},TooManyWritesInTimePeriod:{timeout:3e3}};WebSocketManager=class{constructor(uri,callbacks,webSocketConstructor,logger2,markConnectionStateDirty,debug){this.markConnectionStateDirty=markConnectionStateDirty,this.debug=debug,__publicField8(this,"socket"),__publicField8(this,"connectionCount"),__publicField8(this,"_hasEverConnected",!1),__publicField8(this,"lastCloseReason"),__publicField8(this,"transitionChunkBuffer",null),__publicField8(this,"defaultInitialBackoff"),__publicField8(this,"maxBackoff"),__publicField8(this,"retries"),__publicField8(this,"serverInactivityThreshold"),__publicField8(this,"reconnectDueToServerInactivityTimeout"),__publicField8(this,"scheduledReconnect",null),__publicField8(this,"networkOnlineHandler",null),__publicField8(this,"pendingNetworkRecoveryInfo",null),__publicField8(this,"uri"),__publicField8(this,"onOpen"),__publicField8(this,"onResume"),__publicField8(this,"onMessage"),__publicField8(this,"webSocketConstructor"),__publicField8(this,"logger"),__publicField8(this,"onServerDisconnectError"),this.webSocketConstructor=webSocketConstructor,this.socket={state:"disconnected"},this.connectionCount=0,this.lastCloseReason="InitialConnect",this.defaultInitialBackoff=1e3,this.maxBackoff=16e3,this.retries=0,this.serverInactivityThreshold=6e4,this.reconnectDueToServerInactivityTimeout=null,this.uri=uri,this.onOpen=callbacks.onOpen,this.onResume=callbacks.onResume,this.onMessage=callbacks.onMessage,this.onServerDisconnectError=callbacks.onServerDisconnectError,this.logger=logger2,this.setupNetworkListener(),this.connect()}setSocketState(state){this.socket=state,this._logVerbose(`socket state changed: ${this.socket.state}, paused: ${"paused"in this.socket?this.socket.paused:void 0}`),this.markConnectionStateDirty()}setupNetworkListener(){typeof window>"u"||typeof window.addEventListener!="function"||this.networkOnlineHandler===null&&(this.networkOnlineHandler=()=>{this._logVerbose("network online event detected"),this.tryReconnectImmediately()},window.addEventListener("online",this.networkOnlineHandler),this._logVerbose("network online event listener registered"))}cleanupNetworkListener(){this.networkOnlineHandler&&typeof window<"u"&&typeof window.removeEventListener=="function"&&(window.removeEventListener("online",this.networkOnlineHandler),this.networkOnlineHandler=null,this._logVerbose("network online event listener removed"))}assembleTransition(chunk){if(chunk.partNumber<0||chunk.partNumber>=chunk.totalParts||chunk.totalParts===0||this.transitionChunkBuffer&&(this.transitionChunkBuffer.totalParts!==chunk.totalParts||this.transitionChunkBuffer.transitionId!==chunk.transitionId))throw this.transitionChunkBuffer=null,new Error("Invalid TransitionChunk");if(this.transitionChunkBuffer===null&&(this.transitionChunkBuffer={chunks:[],totalParts:chunk.totalParts,transitionId:chunk.transitionId}),chunk.partNumber!==this.transitionChunkBuffer.chunks.length){let expectedLength=this.transitionChunkBuffer.chunks.length;throw this.transitionChunkBuffer=null,new Error(`TransitionChunk received out of order: expected part ${expectedLength}, got ${chunk.partNumber}`)}if(this.transitionChunkBuffer.chunks.push(chunk.chunk),this.transitionChunkBuffer.chunks.length===chunk.totalParts){let fullJson=this.transitionChunkBuffer.chunks.join("");this.transitionChunkBuffer=null;let transition=parseServerMessage(JSON.parse(fullJson));if(transition.type!=="Transition")throw new Error(`Expected Transition, got ${transition.type} after assembling chunks`);return transition}return null}connect(){if(this.socket.state==="terminated")return;if(this.socket.state!=="disconnected"&&this.socket.state!=="stopped")throw new Error("Didn't start connection from disconnected state: "+this.socket.state);let ws=new this.webSocketConstructor(this.uri);this._logVerbose("constructed WebSocket"),this.setSocketState({state:"connecting",ws,paused:"no"}),this.resetServerInactivityTimeout(),ws.onopen=()=>{if(this.logger.logVerbose("begin ws.onopen"),this.socket.state!=="connecting")throw new Error("onopen called with socket not in connecting state");if(this.setSocketState({state:"ready",ws,paused:this.socket.paused==="yes"?"uninitialized":"no"}),this.resetServerInactivityTimeout(),this.socket.paused==="no"&&(this._hasEverConnected=!0,this.onOpen({connectionCount:this.connectionCount,lastCloseReason:this.lastCloseReason,clientTs:monotonicMillis()})),this.lastCloseReason!=="InitialConnect"&&(this.lastCloseReason?this.logger.log("WebSocket reconnected at",prettyNow(),"after disconnect due to",this.lastCloseReason):this.logger.log("WebSocket reconnected at",prettyNow())),this.connectionCount+=1,this.lastCloseReason=null,this.pendingNetworkRecoveryInfo!==null){let{timeSavedMs}=this.pendingNetworkRecoveryInfo;this.pendingNetworkRecoveryInfo=null,this.sendMessage({type:"Event",eventType:"NetworkRecoveryReconnect",event:{timeSavedMs}}),this.logger.log(`Network recovery reconnect saved ~${Math.round(timeSavedMs/1e3)}s of waiting`)}},ws.onerror=error2=>{this.transitionChunkBuffer=null;let message=error2.message;message&&this.logger.log(`WebSocket error message: ${message}`)},ws.onmessage=message=>{this.resetServerInactivityTimeout();let messageLength=message.data.length,serverMessage=parseServerMessage(JSON.parse(message.data));if(this._logVerbose(`received ws message with type ${serverMessage.type}`),serverMessage.type==="Ping")return;if(serverMessage.type==="TransitionChunk"){let transition=this.assembleTransition(serverMessage);if(!transition)return;serverMessage=transition,this._logVerbose(`assembled full ws message of type ${serverMessage.type}`)}this.transitionChunkBuffer!==null&&(this.transitionChunkBuffer=null,this.logger.log(`Received unexpected ${serverMessage.type} while buffering TransitionChunks`)),serverMessage.type==="Transition"&&this.reportLargeTransition({messageLength,transition:serverMessage}),this.onMessage(serverMessage).hasSyncedPastLastReconnect&&(this.retries=0,this.markConnectionStateDirty())},ws.onclose=event=>{if(this._logVerbose("begin ws.onclose"),this.transitionChunkBuffer=null,this.lastCloseReason===null&&(this.lastCloseReason=event.reason||`closed with code ${event.code}`),event.code!==CLOSE_NORMAL&&event.code!==CLOSE_GOING_AWAY&&event.code!==CLOSE_NO_STATUS&&event.code!==CLOSE_NOT_FOUND){let msg=`WebSocket closed with code ${event.code}`;event.reason&&(msg+=`: ${event.reason}`),this.logger.log(msg),this.onServerDisconnectError&&event.reason&&this.onServerDisconnectError(msg)}let reason=classifyDisconnectError(event.reason);this.scheduleReconnect(reason)}}socketState(){return this.socket.state}sendMessage(message){let messageForLog={type:message.type,...message.type==="Authenticate"&&message.tokenType==="User"?{value:`...${message.value.slice(-7)}`}:{}};if(this.socket.state==="ready"&&this.socket.paused==="no"){let encodedMessage=encodeClientMessage(message),request=JSON.stringify(encodedMessage),sent=!1;try{this.socket.ws.send(request),sent=!0}catch(error2){this.logger.log(`Failed to send message on WebSocket, reconnecting: ${error2}`),this.closeAndReconnect("FailedToSendMessage")}return this._logVerbose(`${sent?"sent":"failed to send"} message with type ${message.type}: ${JSON.stringify(messageForLog)}`),!0}return this._logVerbose(`message not sent (socket state: ${this.socket.state}, paused: ${"paused"in this.socket?this.socket.paused:void 0}): ${JSON.stringify(messageForLog)}`),!1}resetServerInactivityTimeout(){this.socket.state!=="terminated"&&(this.reconnectDueToServerInactivityTimeout!==null&&(clearTimeout(this.reconnectDueToServerInactivityTimeout),this.reconnectDueToServerInactivityTimeout=null),this.reconnectDueToServerInactivityTimeout=setTimeout(()=>{this.closeAndReconnect("InactiveServer")},this.serverInactivityThreshold))}scheduleReconnect(reason){this.scheduledReconnect&&(clearTimeout(this.scheduledReconnect.timeout),this.scheduledReconnect=null),this.socket={state:"disconnected"};let backoff=this.nextBackoff(reason);this.markConnectionStateDirty(),this.logger.log(`Attempting reconnect in ${Math.round(backoff)}ms`);let scheduledAt=monotonicMillis(),timeoutId=setTimeout(()=>{this.scheduledReconnect?.timeout===timeoutId&&(this.scheduledReconnect=null,this.connect())},backoff);this.scheduledReconnect={timeout:timeoutId,scheduledAt,backoffMs:backoff}}closeAndReconnect(closeReason){switch(this._logVerbose(`begin closeAndReconnect with reason ${closeReason}`),this.socket.state){case"disconnected":case"terminated":case"stopped":return;case"connecting":case"ready":{this.lastCloseReason=closeReason,this.close(),this.scheduleReconnect("client");return}default:this.socket}}close(){switch(this.transitionChunkBuffer=null,this.socket.state){case"disconnected":case"terminated":case"stopped":return Promise.resolve();case"connecting":{let ws=this.socket.ws;return ws.onmessage=_message=>{this._logVerbose("Ignoring message received after close")},new Promise(r=>{ws.onclose=()=>{this._logVerbose("Closed after connecting"),r()},ws.onopen=()=>{this._logVerbose("Opened after connecting"),ws.close()}})}case"ready":{this._logVerbose("ws.close called");let ws=this.socket.ws;ws.onmessage=_message=>{this._logVerbose("Ignoring message received after close")};let result=new Promise(r=>{ws.onclose=()=>{r()}});return ws.close(),result}default:return this.socket,Promise.resolve()}}terminate(){switch(this.reconnectDueToServerInactivityTimeout&&clearTimeout(this.reconnectDueToServerInactivityTimeout),this.scheduledReconnect&&(clearTimeout(this.scheduledReconnect.timeout),this.scheduledReconnect=null),this.cleanupNetworkListener(),this.socket.state){case"terminated":case"stopped":case"disconnected":case"connecting":case"ready":{let result=this.close();return this.setSocketState({state:"terminated"}),result}default:throw this.socket,new Error(`Invalid websocket state: ${this.socket.state}`)}}stop(){switch(this.socket.state){case"terminated":return Promise.resolve();case"connecting":case"stopped":case"disconnected":case"ready":{this.cleanupNetworkListener();let result=this.close();return this.socket={state:"stopped"},result}default:return this.socket,Promise.resolve()}}tryRestart(){switch(this.socket.state){case"stopped":break;case"terminated":case"connecting":case"ready":case"disconnected":this.logger.logVerbose("Restart called without stopping first");return;default:this.socket}this.setupNetworkListener(),this.connect()}pause(){switch(this.socket.state){case"disconnected":case"stopped":case"terminated":return;case"connecting":case"ready":{this.socket={...this.socket,paused:"yes"};return}default:{this.socket;return}}}tryReconnectImmediately(){if(this._logVerbose("tryReconnectImmediately called"),this.socket.state!=="disconnected"){this._logVerbose(`tryReconnectImmediately called but socket state is ${this.socket.state}, no action taken`);return}let timeSavedMs=null;if(this.scheduledReconnect){let elapsed=monotonicMillis()-this.scheduledReconnect.scheduledAt;timeSavedMs=Math.max(0,this.scheduledReconnect.backoffMs-elapsed),this._logVerbose(`would have waited ${Math.round(timeSavedMs)}ms more (backoff was ${Math.round(this.scheduledReconnect.backoffMs)}ms, elapsed ${Math.round(elapsed)}ms)`),clearTimeout(this.scheduledReconnect.timeout),this.scheduledReconnect=null,this._logVerbose("canceled scheduled reconnect")}this.logger.log("Network recovery detected, reconnecting immediately"),this.pendingNetworkRecoveryInfo=timeSavedMs!==null?{timeSavedMs}:null,this.connect()}resume(){switch(this.socket.state){case"connecting":this.socket={...this.socket,paused:"no"};return;case"ready":this.socket.paused==="uninitialized"?(this.socket={...this.socket,paused:"no"},this._hasEverConnected=!0,this.onOpen({connectionCount:this.connectionCount,lastCloseReason:this.lastCloseReason,clientTs:monotonicMillis()})):this.socket.paused==="yes"&&(this.socket={...this.socket,paused:"no"},this.onResume());return;case"terminated":case"stopped":case"disconnected":return;default:this.socket}this.connect()}connectionState(){return{isConnected:this.socket.state==="ready",hasEverConnected:this._hasEverConnected,connectionCount:this.connectionCount,connectionRetries:this.retries}}_logVerbose(message){this.logger.logVerbose(message)}nextBackoff(reason){let baseBackoff=(reason==="client"?100:reason==="Unknown"?this.defaultInitialBackoff:serverDisconnectErrors[reason].timeout)*Math.pow(2,this.retries);this.retries+=1;let actualBackoff=Math.min(baseBackoff,this.maxBackoff),jitter=actualBackoff*(Math.random()-.5);return actualBackoff+jitter}reportLargeTransition({transition,messageLength}){if(transition.clientClockSkew===void 0||transition.serverTs===void 0)return;let transitionTransitTime=monotonicMillis()-transition.clientClockSkew-transition.serverTs/1e6,prettyTransitionTime=`${Math.round(transitionTransitTime)}ms`,prettyMessageMB=`${Math.round(messageLength/1e4)/100}MB`,bytesPerSecond=messageLength/(transitionTransitTime/1e3),prettyBytesPerSecond=`${Math.round(bytesPerSecond/1e4)/100}MB per second`;this._logVerbose(`received ${prettyMessageMB} transition in ${prettyTransitionTime} at ${prettyBytesPerSecond}`),messageLength>2e7?this.logger.log(`received query results totaling more that 20MB (${prettyMessageMB}) which will take a long time to download on slower connections`):transitionTransitTime>2e4&&this.logger.log(`received query results totaling ${prettyMessageMB} which took more than 20s to arrive (${prettyTransitionTime})`),this.debug&&this.sendMessage({type:"Event",eventType:"ClientReceivedTransition",event:{transitionTransitTime,messageLength}})}}}});function newSessionId(){return uuidv4()}function uuidv4(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,c=>{let r=Math.random()*16|0;return(c==="x"?r:r&3|8).toString(16)})}var init_session=__esm({"../../node_modules/convex/dist/esm/browser/sync/session.js"(){"use strict"}});function b64DecodeUnicode(str){return decodeURIComponent(atob(str).replace(/(.)/g,(_m,p)=>{let code2=p.charCodeAt(0).toString(16).toUpperCase();return code2.length<2&&(code2="0"+code2),"%"+code2}))}function base64UrlDecode(str){let output=str.replace(/-/g,"+").replace(/_/g,"/");switch(output.length%4){case 0:break;case 2:output+="==";break;case 3:output+="=";break;default:throw new Error("base64 string is not of the correct length")}try{return b64DecodeUnicode(output)}catch{return atob(output)}}function jwtDecode(token,options){if(typeof token!="string")throw new InvalidTokenError("Invalid token specified: must be a string");options||(options={});let pos=options.header===!0?0:1,part=token.split(".")[pos];if(typeof part!="string")throw new InvalidTokenError(`Invalid token specified: missing part #${pos+1}`);let decoded;try{decoded=base64UrlDecode(part)}catch(e){throw new InvalidTokenError(`Invalid token specified: invalid base64 for part #${pos+1} (${e.message})`)}try{return JSON.parse(decoded)}catch(e){throw new InvalidTokenError(`Invalid token specified: invalid json for part #${pos+1} (${e.message})`)}}var InvalidTokenError,init_jwt_decode=__esm({"../../node_modules/convex/dist/esm/vendor/jwt-decode/index.js"(){"use strict";InvalidTokenError=class extends Error{};InvalidTokenError.prototype.name="InvalidTokenError"}});var __defProp10,__defNormalProp9,__publicField9,MAXIMUM_REFRESH_DELAY,MAX_TOKEN_CONFIRMATION_ATTEMPTS,AuthenticationManager,init_authentication_manager=__esm({"../../node_modules/convex/dist/esm/browser/sync/authentication_manager.js"(){"use strict";init_jwt_decode();__defProp10=Object.defineProperty,__defNormalProp9=(obj,key,value)=>key in obj?__defProp10(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,__publicField9=(obj,key,value)=>__defNormalProp9(obj,typeof key!="symbol"?key+"":key,value),MAXIMUM_REFRESH_DELAY=480*60*60*1e3,MAX_TOKEN_CONFIRMATION_ATTEMPTS=2,AuthenticationManager=class{constructor(syncState,callbacks,config2){__publicField9(this,"authState",{state:"noAuth"}),__publicField9(this,"configVersion",0),__publicField9(this,"syncState"),__publicField9(this,"authenticate"),__publicField9(this,"stopSocket"),__publicField9(this,"tryRestartSocket"),__publicField9(this,"pauseSocket"),__publicField9(this,"resumeSocket"),__publicField9(this,"clearAuth"),__publicField9(this,"logger"),__publicField9(this,"refreshTokenLeewaySeconds"),__publicField9(this,"initialAuthTokenReuse"),__publicField9(this,"lastRefreshChange"),__publicField9(this,"tokenConfirmationAttempts",0),this.syncState=syncState,this.authenticate=callbacks.authenticate,this.stopSocket=callbacks.stopSocket,this.tryRestartSocket=callbacks.tryRestartSocket,this.pauseSocket=callbacks.pauseSocket,this.resumeSocket=callbacks.resumeSocket,this.clearAuth=callbacks.clearAuth,this.logger=config2.logger,this.refreshTokenLeewaySeconds=config2.refreshTokenLeewaySeconds,this.initialAuthTokenReuse=config2.initialAuthTokenReuse,this.lastRefreshChange=!1}notifyRefreshChange(isRefreshing){this.authState.state!=="noAuth"&&this.authState.state!=="initialRefetch"&&this.authState.config.onRefreshChange&&this.lastRefreshChange!==isRefreshing&&(this.lastRefreshChange=isRefreshing,this.authState.config.onRefreshChange(isRefreshing))}async setConfig(fetchToken2,onChange,onRefreshChange){this.resetAuthState(),this._logVerbose("pausing WS for auth token fetch"),this.pauseSocket();let token=await this.fetchTokenAndGuardAgainstRace(fetchToken2,{forceRefreshToken:!1});if(token.isFromOutdatedConfig)return;let config2={fetchToken:fetchToken2,onAuthChange:onChange,onRefreshChange};token.value?(this.setAuthState({state:"waitingForServerConfirmationOfCachedToken",config:config2,hasRetried:!1}),this.authenticate(token.value)):(this.setAuthState({state:"initialRefetch",config:config2}),await this.refetchToken()),this._logVerbose("resuming WS after auth token fetch"),this.resumeSocket()}onTransition(serverMessage){if(this.syncState.isCurrentOrNewerAuthVersion(serverMessage.endVersion.identity)&&!(serverMessage.endVersion.identity<=serverMessage.startVersion.identity)){if(this._logVerbose(`auth state is ${this.authState.state} when handling transition`),this.syncState.markAuthCompletion(),this.authState.state==="waitingForServerConfirmationOfCachedToken"){this._logVerbose("server confirmed auth token is valid");let cachedToken=this.syncState.getAuth()?.value;this.initialAuthTokenReuse&&cachedToken?this.scheduleTokenRefetch(cachedToken,serverMessage.clientClockSkew):this.refetchToken(),this.authState.config.onAuthChange(!0);return}this.authState.state==="waitingForServerConfirmationOfFreshToken"&&(this._logVerbose("server confirmed new auth token is valid"),this.notifyRefreshChange(!1),this.scheduleTokenRefetch(this.authState.token),this.tokenConfirmationAttempts=0,this.authState.hadAuth||this.authState.config.onAuthChange(!0))}}onAuthError(serverMessage){if(serverMessage.authUpdateAttempted===!1&&(this.authState.state==="waitingForServerConfirmationOfFreshToken"||this.authState.state==="waitingForServerConfirmationOfCachedToken")){this._logVerbose("ignoring non-auth token expired error");return}let{baseVersion}=serverMessage;if(!this.syncState.isCurrentOrNewerAuthVersion(baseVersion+1)){this._logVerbose("ignoring auth error for previous auth attempt");return}this.tryToReauthenticate(serverMessage)}async tryToReauthenticate(serverMessage){if(this._logVerbose(`attempting to reauthenticate: ${serverMessage.error}`),this.authState.state==="noAuth"||this.authState.state==="waitingForServerConfirmationOfFreshToken"&&this.tokenConfirmationAttempts>=MAX_TOKEN_CONFIRMATION_ATTEMPTS){this.logger.error(`Failed to authenticate: "${serverMessage.error}", check your server auth config`),this.syncState.hasAuth()&&this.syncState.clearAuth(),this.authState.state!=="noAuth"&&this.setAndReportAuthFailed(this.authState.config.onAuthChange);return}if(this.authState.state==="waitingForServerConfirmationOfFreshToken"&&(this.tokenConfirmationAttempts++,this._logVerbose(`retrying reauthentication, ${MAX_TOKEN_CONFIRMATION_ATTEMPTS-this.tokenConfirmationAttempts} attempts remaining`)),this.notifyRefreshChange(!0),await this.stopSocket(),this.authState.state==="noAuth")return;let token=await this.fetchTokenAndGuardAgainstRace(this.authState.config.fetchToken,{forceRefreshToken:!0});token.isFromOutdatedConfig||(token.value&&this.syncState.isNewAuth(token.value)?(this.authenticate(token.value),this.setAuthState({state:"waitingForServerConfirmationOfFreshToken",config:this.authState.config,token:token.value,hadAuth:this.authState.state==="notRefetching"||this.authState.state==="waitingForScheduledRefetch"})):(this._logVerbose("reauthentication failed, could not fetch a new token"),this.syncState.hasAuth()&&this.syncState.clearAuth(),this.setAndReportAuthFailed(this.authState.config.onAuthChange)),this.tryRestartSocket())}async refetchToken(){if(this.authState.state==="noAuth")return;this._logVerbose("refetching auth token");let token=await this.fetchTokenAndGuardAgainstRace(this.authState.config.fetchToken,{forceRefreshToken:!0});token.isFromOutdatedConfig||(token.value?this.syncState.isNewAuth(token.value)?(this.setAuthState({state:"waitingForServerConfirmationOfFreshToken",hadAuth:this.syncState.hasAuth(),token:token.value,config:this.authState.config}),this.authenticate(token.value)):this.setAuthState({state:"notRefetching",config:this.authState.config}):(this._logVerbose("refetching token failed"),this.syncState.hasAuth()&&this.clearAuth(),this.setAndReportAuthFailed(this.authState.config.onAuthChange)),this._logVerbose("restarting WS after auth token fetch (if currently stopped)"),this.tryRestartSocket())}scheduleTokenRefetch(token,clientClockSkewMs){if(this.authState.state==="noAuth")return;let decodedToken=this.decodeToken(token);if(!decodedToken){this.logger.error("Auth token is not a valid JWT, cannot refetch the token");return}let{iat,exp}=decodedToken;if(!iat||!exp){this.logger.error("Auth token does not have required fields, cannot refetch the token");return}let fullLifetimeSeconds=exp-iat;if(fullLifetimeSeconds<=2){this.logger.error("Auth token does not live long enough, cannot refetch the token");return}let tokenValiditySeconds;if(clientClockSkewMs!==void 0){let estimatedServerNowSeconds=(Date.now()-clientClockSkewMs)/1e3;tokenValiditySeconds=exp-estimatedServerNowSeconds,tokenValiditySeconds<=0&&(tokenValiditySeconds=0)}else tokenValiditySeconds=fullLifetimeSeconds;let delay=Math.min(MAXIMUM_REFRESH_DELAY,(tokenValiditySeconds-this.refreshTokenLeewaySeconds)*1e3);delay<=0&&(this.logger.warn(`Refetching auth token immediately, configured leeway ${this.refreshTokenLeewaySeconds}s is larger than the token's lifetime ${tokenValiditySeconds}s`),delay=0);let refetchTokenTimeoutId=setTimeout(()=>{this._logVerbose("running scheduled token refetch"),this.refetchToken()},delay);this.setAuthState({state:"waitingForScheduledRefetch",refetchTokenTimeoutId,config:this.authState.config}),this._logVerbose(`scheduled preemptive auth token refetching in ${delay}ms`)}async fetchTokenAndGuardAgainstRace(fetchToken2,fetchArgs){let originalConfigVersion=++this.configVersion;this._logVerbose(`fetching token with config version ${originalConfigVersion}`);let token=await fetchToken2(fetchArgs);return this.configVersion!==originalConfigVersion?(this._logVerbose(`stale config version, expected ${originalConfigVersion}, got ${this.configVersion}`),{isFromOutdatedConfig:!0}):{isFromOutdatedConfig:!1,value:token}}stop(){this.resetAuthState(),this.configVersion++,this._logVerbose(`config version bumped to ${this.configVersion}`)}setAndReportAuthFailed(onAuthChange){onAuthChange(!1),this.resetAuthState()}resetAuthState(){this.notifyRefreshChange(!1),this.setAuthState({state:"noAuth"})}setAuthState(newAuth){let authStateForLog=newAuth.state==="waitingForServerConfirmationOfFreshToken"?{hadAuth:newAuth.hadAuth,state:newAuth.state,token:`...${newAuth.token.slice(-7)}`}:{state:newAuth.state};switch(this._logVerbose(`setting auth state to ${JSON.stringify(authStateForLog)}`),newAuth.state){case"waitingForScheduledRefetch":case"notRefetching":case"noAuth":this.tokenConfirmationAttempts=0;break;case"waitingForServerConfirmationOfFreshToken":case"waitingForServerConfirmationOfCachedToken":case"initialRefetch":break;default:}this.authState.state==="waitingForScheduledRefetch"&&clearTimeout(this.authState.refetchTokenTimeoutId),this.authState=newAuth}decodeToken(token){try{return jwtDecode(token)}catch(e){return this._logVerbose(`Error decoding token: ${e instanceof Error?e.message:"Unknown error"}`),null}}_logVerbose(message){this.logger.logVerbose(`${message} [v${this.configVersion}]`)}}}});function mark(name,sessionId){let detail={sessionId};typeof performance>"u"||!performance.mark||performance.mark(name,{detail})}function performanceMarkToJson(mark2){let name=mark2.name.slice(6);return name=name.charAt(0).toLowerCase()+name.slice(1),{name,startTime:mark2.startTime}}function getMarksReport(sessionId){if(typeof performance>"u"||!performance.getEntriesByName)return[];let allMarks=[];for(let name of markNames){let marks=performance.getEntriesByName(name).filter(entry=>entry.entryType==="mark").filter(mark2=>mark2.detail.sessionId===sessionId);allMarks.push(...marks)}return allMarks.map(performanceMarkToJson)}var markNames,init_metrics=__esm({"../../node_modules/convex/dist/esm/browser/sync/metrics.js"(){"use strict";markNames=["convexClientConstructed","convexWebSocketOpen","convexFirstMessageReceived"]}});var __defProp11,__defNormalProp10,__publicField10,BaseConvexClient,init_client=__esm({"../../node_modules/convex/dist/esm/browser/sync/client.js"(){"use strict";init_esm();init_values();init_logging();init_local_state();init_request_manager();init_optimistic_updates_impl();init_remote_query_set();init_udf_path_utils();init_web_socket_manager();init_session();init_authentication_manager();init_metrics();init_common();init_errors();init_jwt_decode();__defProp11=Object.defineProperty,__defNormalProp10=(obj,key,value)=>key in obj?__defProp11(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,__publicField10=(obj,key,value)=>__defNormalProp10(obj,typeof key!="symbol"?key+"":key,value),BaseConvexClient=class{constructor(address,onTransition,options){if(__publicField10(this,"address"),__publicField10(this,"state"),__publicField10(this,"requestManager"),__publicField10(this,"webSocketManager"),__publicField10(this,"authenticationManager"),__publicField10(this,"remoteQuerySet"),__publicField10(this,"optimisticQueryResults"),__publicField10(this,"_transitionHandlerCounter",0),__publicField10(this,"_nextRequestId"),__publicField10(this,"_onTransitionFns",new Map),__publicField10(this,"_sessionId"),__publicField10(this,"firstMessageReceived",!1),__publicField10(this,"debug"),__publicField10(this,"logger"),__publicField10(this,"maxObservedTimestamp"),__publicField10(this,"connectionStateSubscribers",new Map),__publicField10(this,"nextConnectionStateSubscriberId",0),__publicField10(this,"_lastPublishedConnectionState"),__publicField10(this,"markConnectionStateDirty",()=>{Promise.resolve().then(()=>{let curConnectionState=this.connectionState();if(JSON.stringify(curConnectionState)!==JSON.stringify(this._lastPublishedConnectionState)){this._lastPublishedConnectionState=curConnectionState;for(let cb of this.connectionStateSubscribers.values())cb(curConnectionState)}})}),__publicField10(this,"mark",name=>{this.debug&&mark(name,this.sessionId)}),typeof address=="object")throw new Error("Passing a ClientConfig object is no longer supported. Pass the URL of the Convex deployment as a string directly.");options?.skipConvexDeploymentUrlCheck!==!0&&validateDeploymentUrl(address),options={...options};let authRefreshTokenLeewaySeconds=options.authRefreshTokenLeewaySeconds??10,webSocketConstructor=options.webSocketConstructor;if(!webSocketConstructor&&typeof WebSocket>"u")throw new Error("No WebSocket global variable defined! To use Convex in an environment without WebSocket try the HTTP client: https://docs.convex.dev/api/classes/browser.ConvexHttpClient");webSocketConstructor=webSocketConstructor||WebSocket,this.debug=options.reportDebugInfoToConvex??!1,this.address=address,this.logger=options.logger===!1?instantiateNoopLogger({verbose:options.verbose??!1}):options.logger!==!0&&options.logger?options.logger:instantiateDefaultLogger({verbose:options.verbose??!1});let i2=address.search("://");if(i2===-1)throw new Error("Provided address was not an absolute URL.");let origin=address.substring(i2+3),protocol=address.substring(0,i2),wsProtocol;if(protocol==="http")wsProtocol="ws";else if(protocol==="https")wsProtocol="wss";else throw new Error(`Unknown parent protocol ${protocol}`);let wsUri=`${wsProtocol}://${origin}/api/${version}/sync`;this.state=new LocalSyncState,this.remoteQuerySet=new RemoteQuerySet(queryId=>this.state.queryPath(queryId),this.logger),this.requestManager=new RequestManager(this.logger,this.markConnectionStateDirty);let pauseSocket=()=>{this.webSocketManager.pause(),this.state.pause()};this.authenticationManager=new AuthenticationManager(this.state,{authenticate:token=>{let message=this.state.setAuth(token);return this.webSocketManager.sendMessage(message),message.baseVersion},stopSocket:()=>this.webSocketManager.stop(),tryRestartSocket:()=>this.webSocketManager.tryRestart(),pauseSocket,resumeSocket:()=>this.webSocketManager.resume(),clearAuth:()=>{this.clearAuth()}},{logger:this.logger,refreshTokenLeewaySeconds:authRefreshTokenLeewaySeconds,initialAuthTokenReuse:options.initialAuthTokenReuse??!1}),this.optimisticQueryResults=new OptimisticQueryResults,this.addOnTransitionHandler(transition=>{onTransition(transition.queries.map(q=>q.token))}),this._nextRequestId=0,this._sessionId=newSessionId();let{unsavedChangesWarning}=options;if(typeof window>"u"||typeof window.addEventListener>"u"){if(unsavedChangesWarning===!0)throw new Error("unsavedChangesWarning requested, but window.addEventListener not found! Remove {unsavedChangesWarning: true} from Convex client options.")}else unsavedChangesWarning!==!1&&window.addEventListener("beforeunload",e=>{if(this.requestManager.hasIncompleteRequests()){e.preventDefault();let confirmationMessage="Are you sure you want to leave? Your changes may not be saved.";return(e||window.event).returnValue=confirmationMessage,confirmationMessage}});this.webSocketManager=new WebSocketManager(wsUri,{onOpen:reconnectMetadata=>{this.mark("convexWebSocketOpen"),this.webSocketManager.sendMessage({...reconnectMetadata,type:"Connect",sessionId:this._sessionId,maxObservedTimestamp:this.maxObservedTimestamp}),this.remoteQuerySet=new RemoteQuerySet(queryId=>this.state.queryPath(queryId),this.logger);let[querySetModification,authModification]=this.state.restart();authModification&&this.webSocketManager.sendMessage(authModification),this.webSocketManager.sendMessage(querySetModification);for(let message of this.requestManager.restart())this.webSocketManager.sendMessage(message)},onResume:()=>{let[querySetModification,authModification]=this.state.resume();authModification&&this.webSocketManager.sendMessage(authModification),querySetModification&&this.webSocketManager.sendMessage(querySetModification);for(let message of this.requestManager.resume())this.webSocketManager.sendMessage(message)},onMessage:serverMessage=>{switch(this.firstMessageReceived||(this.firstMessageReceived=!0,this.mark("convexFirstMessageReceived"),this.reportMarks()),serverMessage.type){case"Transition":{this.observedTimestamp(serverMessage.endVersion.ts),this.authenticationManager.onTransition(serverMessage),this.remoteQuerySet.transition(serverMessage),this.state.transition(serverMessage);let completedRequests=this.requestManager.removeCompleted(this.remoteQuerySet.timestamp());this.notifyOnQueryResultChanges(completedRequests);break}case"MutationResponse":{serverMessage.success&&this.observedTimestamp(serverMessage.ts);let completedMutationInfo=this.requestManager.onResponse(serverMessage);completedMutationInfo!==null&&this.notifyOnQueryResultChanges(new Map([[completedMutationInfo.requestId,completedMutationInfo.result]]));break}case"ActionResponse":{this.requestManager.onResponse(serverMessage);break}case"AuthError":{this.authenticationManager.onAuthError(serverMessage);break}case"FatalError":{let error2=logFatalError(this.logger,serverMessage.error);throw this.webSocketManager.terminate(),error2}default:}return{hasSyncedPastLastReconnect:this.hasSyncedPastLastReconnect()}},onServerDisconnectError:options.onServerDisconnectError},webSocketConstructor,this.logger,this.markConnectionStateDirty,this.debug),this.mark("convexClientConstructed"),options.expectAuth&&pauseSocket()}hasSyncedPastLastReconnect(){return this.requestManager.hasSyncedPastLastReconnect()&&this.state.hasSyncedPastLastReconnect()}observedTimestamp(observedTs){(this.maxObservedTimestamp===void 0||this.maxObservedTimestamp.lessThanOrEqual(observedTs))&&(this.maxObservedTimestamp=observedTs)}getMaxObservedTimestamp(){return this.maxObservedTimestamp}notifyOnQueryResultChanges(completedRequests){let remoteQueryResults=this.remoteQuerySet.remoteQueryResults(),queryTokenToValue=new Map;for(let[queryId,result]of remoteQueryResults){let queryToken=this.state.queryToken(queryId);if(queryToken!==null){let query={result,udfPath:this.state.queryPath(queryId),args:this.state.queryArgs(queryId)};queryTokenToValue.set(queryToken,query)}}let changedQueryTokens=this.optimisticQueryResults.ingestQueryResultsFromServer(queryTokenToValue,new Set(completedRequests.keys()));this.handleTransition({queries:changedQueryTokens.map(token=>{let optimisticResult=this.optimisticQueryResults.rawQueryResult(token);return{token,modification:{kind:"Updated",result:optimisticResult}}}),reflectedMutations:Array.from(completedRequests).map(([requestId,result])=>({requestId,result})),timestamp:this.remoteQuerySet.timestamp()})}handleTransition(transition){for(let fn of this._onTransitionFns.values())fn(transition)}addOnTransitionHandler(fn){let id=this._transitionHandlerCounter++;return this._onTransitionFns.set(id,fn),()=>this._onTransitionFns.delete(id)}getCurrentAuthClaims(){let authToken=this.state.getAuth(),decoded={};if(authToken&&authToken.tokenType==="User")try{decoded=authToken?jwtDecode(authToken.value):{}}catch{decoded={}}else return;return{token:authToken.value,decoded}}setAuth(fetchToken2,onChange,onRefreshChange){this.authenticationManager.setConfig(fetchToken2,onChange,onRefreshChange)}hasAuth(){return this.state.hasAuth()}setAdminAuth(value,fakeUserIdentity){let message=this.state.setAdminAuth(value,fakeUserIdentity);this.webSocketManager.sendMessage(message)}clearAuth(){let message=this.state.clearAuth();this.webSocketManager.sendMessage(message)}subscribe(name,args,options){let argsObject=parseArgs4(args),{modification,queryToken,unsubscribe}=this.state.subscribe(name,argsObject,options?.journal,options?.componentPath);return modification!==null&&this.webSocketManager.sendMessage(modification),{queryToken,unsubscribe:()=>{let modification2=unsubscribe();modification2&&this.webSocketManager.sendMessage(modification2)}}}localQueryResult(udfPath,args){let argsObject=parseArgs4(args),queryToken=serializePathAndArgs(udfPath,argsObject);return this.optimisticQueryResults.queryResult(queryToken)}localQueryResultByToken(queryToken){return this.optimisticQueryResults.queryResult(queryToken)}hasLocalQueryResultByToken(queryToken){return this.optimisticQueryResults.hasQueryResult(queryToken)}localQueryLogs(udfPath,args){let argsObject=parseArgs4(args),queryToken=serializePathAndArgs(udfPath,argsObject);return this.optimisticQueryResults.queryLogs(queryToken)}queryJournal(name,args){let argsObject=parseArgs4(args),queryToken=serializePathAndArgs(name,argsObject);return this.state.queryJournal(queryToken)}connectionState(){let wsConnectionState=this.webSocketManager.connectionState();return{hasInflightRequests:this.requestManager.hasInflightRequests(),isWebSocketConnected:wsConnectionState.isConnected,hasEverConnected:wsConnectionState.hasEverConnected,connectionCount:wsConnectionState.connectionCount,connectionRetries:wsConnectionState.connectionRetries,timeOfOldestInflightRequest:this.requestManager.timeOfOldestInflightRequest(),inflightMutations:this.requestManager.inflightMutations(),inflightActions:this.requestManager.inflightActions()}}subscribeToConnectionState(cb){let id=this.nextConnectionStateSubscriberId++;return this.connectionStateSubscribers.set(id,cb),()=>{this.connectionStateSubscribers.delete(id)}}async mutation(name,args,options){let result=await this.mutationInternal(name,args,options);if(!result.success)throw result.errorData!==void 0?forwardData(result,new ConvexError(createHybridErrorStacktrace("mutation",name,result))):new Error(createHybridErrorStacktrace("mutation",name,result));return result.value}async mutationInternal(udfPath,args,options,componentPath){let{mutationPromise}=this.enqueueMutation(udfPath,args,options,componentPath);return mutationPromise}enqueueMutation(udfPath,args,options,componentPath){let mutationArgs=parseArgs4(args);this.tryReportLongDisconnect();let requestId=this.nextRequestId;if(this._nextRequestId++,options!==void 0){let optimisticUpdate=options.optimisticUpdate;if(optimisticUpdate!==void 0){let wrappedUpdate=localQueryStore=>{optimisticUpdate(localQueryStore,mutationArgs)instanceof Promise&&this.logger.warn("Optimistic update handler returned a Promise. Optimistic updates should be synchronous.")},changedQueries=this.optimisticQueryResults.applyOptimisticUpdate(wrappedUpdate,requestId).map(token=>{let localResult=this.localQueryResultByToken(token);return{token,modification:{kind:"Updated",result:localResult===void 0?void 0:{success:!0,value:localResult,logLines:[]}}}});this.handleTransition({queries:changedQueries,reflectedMutations:[],timestamp:this.remoteQuerySet.timestamp()})}}let message={type:"Mutation",requestId,udfPath,componentPath,args:[convexToJson(mutationArgs)]},mightBeSent=this.webSocketManager.sendMessage(message),mutationPromise=this.requestManager.request(message,mightBeSent);return{requestId,mutationPromise}}async action(name,args){let result=await this.actionInternal(name,args);if(!result.success)throw result.errorData!==void 0?forwardData(result,new ConvexError(createHybridErrorStacktrace("action",name,result))):new Error(createHybridErrorStacktrace("action",name,result));return result.value}async actionInternal(udfPath,args,componentPath){let actionArgs=parseArgs4(args),requestId=this.nextRequestId;this._nextRequestId++,this.tryReportLongDisconnect();let message={type:"Action",requestId,udfPath,componentPath,args:[convexToJson(actionArgs)]},mightBeSent=this.webSocketManager.sendMessage(message);return this.requestManager.request(message,mightBeSent)}async close(){return this.authenticationManager.stop(),this.webSocketManager.terminate()}get url(){return this.address}get nextRequestId(){return this._nextRequestId}get sessionId(){return this._sessionId}reportMarks(){if(this.debug){let report=getMarksReport(this.sessionId);this.webSocketManager.sendMessage({type:"Event",eventType:"ClientConnect",event:report})}}tryReportLongDisconnect(){if(!this.debug)return;let timeOfOldestRequest=this.connectionState().timeOfOldestInflightRequest;if(timeOfOldestRequest===null||Date.now()-timeOfOldestRequest.getTime()<=60*1e3)return;let endpoint=`${this.address}/api/debug_event`;fetch(endpoint,{method:"POST",headers:{"Content-Type":"application/json","Convex-Client":`npm-${version}`},body:JSON.stringify({event:"LongWebsocketDisconnect"})}).then(response=>{response.ok||this.logger.warn("Analytics request failed with response:",response.body)}).catch(error2=>{this.logger.warn("Analytics response failed with error:",error2)})}}}});function asPaginationResult(value){if(typeof value!="object"||value===null||!Array.isArray(value.page)||typeof value.isDone!="boolean"||typeof value.continueCursor!="string")throw new Error(`Not a valid paginated query result: ${value?.toString()}`);return value}var init_pagination=__esm({"../../node_modules/convex/dist/esm/browser/sync/pagination.js"(){"use strict"}});var __defProp12,__defNormalProp11,__publicField11,PaginatedQueryClient,init_paginated_query_client=__esm({"../../node_modules/convex/dist/esm/browser/sync/paginated_query_client.js"(){"use strict";init_udf_path_utils();init_pagination();init_long();__defProp12=Object.defineProperty,__defNormalProp11=(obj,key,value)=>key in obj?__defProp12(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,__publicField11=(obj,key,value)=>__defNormalProp11(obj,typeof key!="symbol"?key+"":key,value),PaginatedQueryClient=class{constructor(client,onTransition){this.client=client,this.onTransition=onTransition,__publicField11(this,"paginatedQuerySet",new Map),__publicField11(this,"lastTransitionTs"),this.lastTransitionTs=Long.fromNumber(0),this.client.addOnTransitionHandler(transition=>this.onBaseTransition(transition))}subscribe(name,args,options){let canonicalizedUdfPath=canonicalizeUdfPath(name),token=serializePaginatedPathAndArgs(canonicalizedUdfPath,args,options),unsubscribe=()=>this.removePaginatedQuerySubscriber(token),existingEntry=this.paginatedQuerySet.get(token);return existingEntry?(existingEntry.numSubscribers+=1,{paginatedQueryToken:token,unsubscribe}):(this.paginatedQuerySet.set(token,{token,canonicalizedUdfPath,args,numSubscribers:1,options:{initialNumItems:options.initialNumItems},nextPageKey:0,pageKeys:[],pageKeyToQuery:new Map,ongoingSplits:new Map,skip:!1,id:options.id}),this.addPageToPaginatedQuery(token,null,options.initialNumItems),{paginatedQueryToken:token,unsubscribe})}localQueryResult(name,args,options){let canonicalizedUdfPath=canonicalizeUdfPath(name),token=serializePaginatedPathAndArgs(canonicalizedUdfPath,args,options);return this.localQueryResultByToken(token)}localQueryResultByToken(token){let paginatedQuery=this.paginatedQuerySet.get(token);if(!paginatedQuery)return;let activePages=this.activePageQueryTokens(paginatedQuery);if(activePages.length===0)return{results:[],status:"LoadingFirstPage",loadMore:numItems=>this.loadMoreOfPaginatedQuery(token,numItems)};let allResults=[],hasUndefined=!1,isDone=!1;for(let pageToken of activePages){let result=this.client.localQueryResultByToken(pageToken);if(result===void 0){hasUndefined=!0,isDone=!1;continue}let paginationResult=asPaginationResult(result);allResults=allResults.concat(paginationResult.page),isDone=!!paginationResult.isDone}let status;return hasUndefined?status=allResults.length===0?"LoadingFirstPage":"LoadingMore":isDone?status="Exhausted":status="CanLoadMore",{results:allResults,status,loadMore:numItems=>this.loadMoreOfPaginatedQuery(token,numItems)}}onBaseTransition(transition){let changedBaseTokens=transition.queries.map(q=>q.token),changed=this.queriesContainingTokens(changedBaseTokens),paginatedQueries=[];changed.length>0&&(this.processPaginatedQuerySplits(changed,token=>this.client.localQueryResultByToken(token)),paginatedQueries=changed.map(token=>({token,modification:{kind:"Updated",result:this.localQueryResultByToken(token)}})));let extendedTransition={...transition,paginatedQueries};this.onTransition(extendedTransition)}loadMoreOfPaginatedQuery(token,numItems){this.mustGetPaginatedQuery(token);let lastPageToken=this.queryTokenForLastPageOfPaginatedQuery(token),lastPageResult=this.client.localQueryResultByToken(lastPageToken);if(!lastPageResult)return!1;let paginationResult=asPaginationResult(lastPageResult);if(paginationResult.isDone)return!1;this.addPageToPaginatedQuery(token,paginationResult.continueCursor,numItems);let loadMoreTransition={timestamp:this.lastTransitionTs,reflectedMutations:[],queries:[],paginatedQueries:[{token,modification:{kind:"Updated",result:this.localQueryResultByToken(token)}}]};return this.onTransition(loadMoreTransition),!0}queriesContainingTokens(queryTokens){if(queryTokens.length===0)return[];let changed=[],queryTokenSet=new Set(queryTokens);for(let[paginatedToken,paginatedQuery]of this.paginatedQuerySet)for(let pageToken of this.allQueryTokens(paginatedQuery))if(queryTokenSet.has(pageToken)){changed.push(paginatedToken);break}return changed}processPaginatedQuerySplits(changed,getResult){for(let paginatedQueryToken of changed){let paginatedQuery=this.mustGetPaginatedQuery(paginatedQueryToken),{ongoingSplits,pageKeyToQuery,pageKeys}=paginatedQuery;for(let[pageKey,[splitKey1,splitKey2]]of ongoingSplits)getResult(pageKeyToQuery.get(splitKey1).queryToken)!==void 0&&getResult(pageKeyToQuery.get(splitKey2).queryToken)!==void 0&&this.completePaginatedQuerySplit(paginatedQuery,pageKey,splitKey1,splitKey2);for(let pageKey of pageKeys){if(ongoingSplits.has(pageKey))continue;let pageEntry=pageKeyToQuery.get(pageKey);if(!pageEntry)throw new Error(`No page query for active pageKey ${pageKey}`);let pageResult=getResult(pageEntry.queryToken);if(!pageResult)continue;let result=asPaginationResult(pageResult);result.splitCursor&&(result.pageStatus==="SplitRecommended"||result.pageStatus==="SplitRequired"||result.page.length>paginatedQuery.options.initialNumItems*2)&&this.splitPaginatedQueryPage(paginatedQuery,pageKey,pageEntry.cursor,result.splitCursor,result.continueCursor)}}}splitPaginatedQueryPage(paginatedQuery,pageKey,startCursor,splitCursor,continueCursor){let splitKey1=paginatedQuery.nextPageKey++,splitKey2=paginatedQuery.nextPageKey++,paginationOpts={numItems:paginatedQuery.options.initialNumItems,id:paginatedQuery.id},firstSubscription=this.client.subscribe(paginatedQuery.canonicalizedUdfPath,{...paginatedQuery.args,paginationOpts:{...paginationOpts,cursor:startCursor,endCursor:splitCursor}});paginatedQuery.pageKeyToQuery.set(splitKey1,{...firstSubscription,cursor:startCursor});let secondSubscription=this.client.subscribe(paginatedQuery.canonicalizedUdfPath,{...paginatedQuery.args,paginationOpts:{...paginationOpts,cursor:splitCursor,endCursor:continueCursor}});paginatedQuery.pageKeyToQuery.set(splitKey2,{...secondSubscription,cursor:splitCursor}),paginatedQuery.ongoingSplits.set(pageKey,[splitKey1,splitKey2])}addPageToPaginatedQuery(token,continueCursor,numItems){let paginatedQuery=this.mustGetPaginatedQuery(token),pageKey=paginatedQuery.nextPageKey++,paginationOpts={cursor:continueCursor,numItems,id:paginatedQuery.id},pageArgs={...paginatedQuery.args,paginationOpts},subscription=this.client.subscribe(paginatedQuery.canonicalizedUdfPath,pageArgs);return paginatedQuery.pageKeys.push(pageKey),paginatedQuery.pageKeyToQuery.set(pageKey,{...subscription,cursor:continueCursor}),subscription}removePaginatedQuerySubscriber(token){let paginatedQuery=this.paginatedQuerySet.get(token);if(paginatedQuery&&(paginatedQuery.numSubscribers-=1,!(paginatedQuery.numSubscribers>0))){for(let subscription of paginatedQuery.pageKeyToQuery.values())subscription.unsubscribe();this.paginatedQuerySet.delete(token)}}completePaginatedQuerySplit(paginatedQuery,pageKey,splitKey1,splitKey2){let originalQuery=paginatedQuery.pageKeyToQuery.get(pageKey);paginatedQuery.pageKeyToQuery.delete(pageKey);let pageIndex=paginatedQuery.pageKeys.indexOf(pageKey);paginatedQuery.pageKeys.splice(pageIndex,1,splitKey1,splitKey2),paginatedQuery.ongoingSplits.delete(pageKey),originalQuery.unsubscribe()}activePageQueryTokens(paginatedQuery){return paginatedQuery.pageKeys.map(pageKey=>paginatedQuery.pageKeyToQuery.get(pageKey).queryToken)}allQueryTokens(paginatedQuery){return Array.from(paginatedQuery.pageKeyToQuery.values()).map(sub=>sub.queryToken)}queryTokenForLastPageOfPaginatedQuery(token){let paginatedQuery=this.mustGetPaginatedQuery(token),lastPageKey=paginatedQuery.pageKeys[paginatedQuery.pageKeys.length-1];if(lastPageKey===void 0)throw new Error(`No pages for paginated query ${token}`);return paginatedQuery.pageKeyToQuery.get(lastPageKey).queryToken}mustGetPaginatedQuery(token){let paginatedQuery=this.paginatedQuerySet.get(token);if(!paginatedQuery)throw new Error("paginated query no longer exists for token "+token);return paginatedQuery}}}});var __defProp13,__defNormalProp12,__publicField12,defaultWebSocketConstructor,ConvexClient,init_simple_client=__esm({"../../node_modules/convex/dist/esm/browser/simple_client.js"(){"use strict";init_common();init_api();init_client();init_paginated_query_client();init_udf_path_utils();__defProp13=Object.defineProperty,__defNormalProp12=(obj,key,value)=>key in obj?__defProp13(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,__publicField12=(obj,key,value)=>__defNormalProp12(obj,typeof key!="symbol"?key+"":key,value),ConvexClient=class{constructor(address,options={}){__publicField12(this,"listeners"),__publicField12(this,"_client"),__publicField12(this,"_paginatedClient"),__publicField12(this,"callNewListenersWithCurrentValuesTimer"),__publicField12(this,"_closed"),__publicField12(this,"_disabled"),options.skipConvexDeploymentUrlCheck!==!0&&validateDeploymentUrl(address);let{disabled,...baseOptions}=options;this._closed=!1,this._disabled=!!disabled,defaultWebSocketConstructor&&!("webSocketConstructor"in baseOptions)&&typeof WebSocket>"u"&&(baseOptions.webSocketConstructor=defaultWebSocketConstructor),typeof window>"u"&&!("unsavedChangesWarning"in baseOptions)&&(baseOptions.unsavedChangesWarning=!1),this.disabled||(this._client=new BaseConvexClient(address,()=>{},baseOptions),this._paginatedClient=new PaginatedQueryClient(this._client,transition=>this._transition(transition))),this.listeners=new Set}get closed(){return this._closed}get client(){if(this._client)return this._client;throw new Error("ConvexClient is disabled")}get paginatedClient(){if(this._paginatedClient)return this._paginatedClient;throw new Error("ConvexClient is disabled")}get disabled(){return this._disabled}onUpdate(query,args,callback,onError){if(this.disabled)return this.createDisabledUnsubscribe();let{queryToken,unsubscribe}=this.client.subscribe(getFunctionName(query),args),queryInfo={queryToken,callback,onError,unsubscribe,hasEverRun:!1,query,args,paginationOptions:void 0};this.listeners.add(queryInfo),this.queryResultReady(queryToken)&&this.callNewListenersWithCurrentValuesTimer===void 0&&(this.callNewListenersWithCurrentValuesTimer=setTimeout(()=>this.callNewListenersWithCurrentValues(),0));let unsubscribeProps={unsubscribe:()=>{this.closed||(this.listeners.delete(queryInfo),unsubscribe())},getCurrentValue:()=>this.client.localQueryResultByToken(queryToken),getQueryLogs:()=>this.client.localQueryLogs(queryToken)},ret=unsubscribeProps.unsubscribe;return Object.assign(ret,unsubscribeProps),ret}onPaginatedUpdate_experimental(query,args,options,callback,onError){if(this.disabled)return this.createDisabledUnsubscribe();let paginationOptions={initialNumItems:options.initialNumItems,id:-1},{paginatedQueryToken,unsubscribe}=this.paginatedClient.subscribe(getFunctionName(query),args,paginationOptions),queryInfo={queryToken:paginatedQueryToken,callback,onError,unsubscribe,hasEverRun:!1,query,args,paginationOptions};this.listeners.add(queryInfo),this.paginatedClient.localQueryResultByToken(paginatedQueryToken)&&this.callNewListenersWithCurrentValuesTimer===void 0&&(this.callNewListenersWithCurrentValuesTimer=setTimeout(()=>this.callNewListenersWithCurrentValues(),0));let unsubscribeProps={unsubscribe:()=>{this.closed||(this.listeners.delete(queryInfo),unsubscribe())},getCurrentValue:()=>this.paginatedClient.localQueryResult(getFunctionName(query),args,paginationOptions),getQueryLogs:()=>[]},ret=unsubscribeProps.unsubscribe;return Object.assign(ret,unsubscribeProps),ret}callNewListenersWithCurrentValues(){this.callNewListenersWithCurrentValuesTimer=void 0,this._transition({queries:[],paginatedQueries:[]},!0)}queryResultReady(queryToken){return this.client.hasLocalQueryResultByToken(queryToken)}createDisabledUnsubscribe(){let disabledUnsubscribe=(()=>{});return Object.assign(disabledUnsubscribe,{unsubscribe:disabledUnsubscribe,getCurrentValue:()=>{},getQueryLogs:()=>{}}),disabledUnsubscribe}async close(){if(!this.disabled)return this.listeners.clear(),this._closed=!0,this._paginatedClient&&(this._paginatedClient=void 0),this.client.close()}getAuth(){if(!this.disabled)return this.client.getCurrentAuthClaims()}setAuth(fetchToken2,onChange){this.disabled||this.client.setAuth(fetchToken2,onChange??(()=>{}))}setAdminAuth(token,identity){if(this.closed)throw new Error("ConvexClient has already been closed.");this.disabled||this.client.setAdminAuth(token,identity)}_transition({queries,paginatedQueries},callNewListeners=!1){let updatedQueries=[...queries.map(q=>q.token),...paginatedQueries.map(q=>q.token)];for(let queryInfo of this.listeners){let{callback,queryToken,onError,hasEverRun}=queryInfo,isPaginatedQuery=serializedQueryTokenIsPaginated(queryToken),hasResultReady=isPaginatedQuery?!!this.paginatedClient.localQueryResultByToken(queryToken):this.client.hasLocalQueryResultByToken(queryToken);if(updatedQueries.includes(queryToken)||callNewListeners&&!hasEverRun&&hasResultReady){queryInfo.hasEverRun=!0;let newValue;try{isPaginatedQuery?newValue=this.paginatedClient.localQueryResultByToken(queryToken):newValue=this.client.localQueryResultByToken(queryToken)}catch(error2){if(!(error2 instanceof Error))throw error2;onError?onError(error2,"Second argument to onUpdate onError is reserved for later use"):Promise.reject(error2);continue}callback(newValue,"Second argument to onUpdate callback is reserved for later use")}}}async mutation(mutation,args,options){if(this.disabled)throw new Error("ConvexClient is disabled");return await this.client.mutation(getFunctionName(mutation),args,options)}async action(action,args){if(this.disabled)throw new Error("ConvexClient is disabled");return await this.client.action(getFunctionName(action),args)}async query(query,args){if(this.disabled)throw new Error("ConvexClient is disabled");let value=this.client.localQueryResult(getFunctionName(query),args);return value!==void 0?Promise.resolve(value):new Promise((resolve4,reject)=>{let{unsubscribe}=this.onUpdate(query,args,value2=>{unsubscribe(),resolve4(value2)},e=>{unsubscribe(),reject(e)})})}connectionState(){if(this.disabled)throw new Error("ConvexClient is disabled");return this.client.connectionState()}subscribeToConnectionState(cb){return this.disabled?()=>{}:this.client.subscribeToConnectionState(cb)}}}});var require_device_mcp_runner=__commonJS({"../../apps/web/electron/local-tools/device-mcp-runner.js"(exports,module){"use strict";function startDeviceMcpRunner2({registry:registry2,localScope,client,web:web2,scope,log:log2}){let active=new Map,subscriptions=new Map,lifetime=new AbortController,refreshing=!1;async function handle(requestId){if(!(active.has(requestId)||lifetime.signal.aborted)){active.set(requestId,!0);try{let claimed=await client.mutation(web2.claimDeviceMcp,{scope,requestId});if(!claimed||lifetime.signal.aborted)return;let signal=AbortSignal.any([lifetime.signal,AbortSignal.timeout(Math.max(1,claimed.expiresAt-Date.now()))]),sequence=0,lastProgress=0,result;try{result=await registry2.run(localScope,claimed.registrationId,JSON.parse(claimed.operation),{signal,onprogress(progress){Date.now()-lastProgress<250||(lastProgress=Date.now(),client.mutation(web2.reportDeviceMcp,{scope,requestId,event:{seq:++sequence,progress:JSON.stringify({progress:progress.progress,total:progress.total})}}).catch(log2))}})}catch{result={isError:!0,content:[{type:"text",text:"Device MCP call failed. Check the server on the device."}]}}await client.mutation(web2.reportDeviceMcp,{scope,requestId,event:{result:JSON.stringify(result)}})}catch(error2){log2(error2)}finally{active.delete(requestId)}}}async function listTools(entry){let cursor,tools=[];do{let page=await registry2.run(localScope,entry.registrationId,{method:"tools/list",cursor},{signal:lifetime.signal});if(tools.push(...page.tools.map(t=>({name:t.name,description:t.description??"",schema:t.inputSchema}))),cursor=page.nextCursor,tools.length>100||cursor&&!page.tools.length)throw new Error("Device MCP catalog exceeds limit.")}while(cursor);return tools}async function refreshServer(entry){if(lifetime.signal.aborted)return;let subscription=subscriptions.get(entry.registrationId),serverId=subscription?.id??await client.mutation("token"in scope?web2.machineRegisterMcpServer:web2.studioRegisterDeviceMcpServer,{...scope,...entry});if(subscription){await client.mutation(web2.deviceMcpHeartbeat,{scope,serverId});try{let tools2=await listTools(entry),catalog2=JSON.stringify(tools2);if(catalog2===subscription.catalog)return;await client.mutation(web2.publishDeviceMcpCatalog,{scope,serverId,tools:tools2}),subscription.catalog=catalog2}catch(error2){log2(error2)}return}let tools=await listTools(entry),catalog=JSON.stringify(tools);if(await client.mutation(web2.publishDeviceMcpCatalog,{scope,serverId,tools}),lifetime.signal.aborted)return;let off=client.onUpdate(web2.deviceMcpPending,{scope,serverId},ids=>{for(let id of ids)handle(id)},log2);subscriptions.set(entry.registrationId,{id:serverId,off,catalog}),await client.mutation(web2.deviceMcpHeartbeat,{scope,serverId})}async function refresh(){if(!(refreshing||lifetime.signal.aborted)){refreshing=!0;try{let entries=await registry2.list(localScope);await Promise.all(entries.map(entry=>refreshServer(entry).catch(log2)))}catch(error2){log2(error2)}finally{refreshing=!1}}}refresh();let timer=setInterval(refresh,3e4);return()=>{lifetime.abort(),clearInterval(timer);for(let{off}of subscriptions.values())off()}}module.exports={startDeviceMcpRunner:startDeviceMcpRunner2}}});var require_device_mcp_fetch=__commonJS({"../../apps/web/electron/local-tools/device-mcp-fetch.js"(exports,module){"use strict";function deviceMcpFetch(endpoint,signal){let allowed=new URL(endpoint);if(!["http:","https:"].includes(allowed.protocol)||allowed.username||allowed.password||allowed.hash)throw new Error("Choose an HTTP or HTTPS MCP endpoint without embedded credentials or a fragment.");let received=0;return async(input,init)=>{let request=new Request(input,init);if(request.url!==allowed.href)throw new Error("MCP request left the configured device endpoint.");let response=await fetch(request,{redirect:"error",credentials:"omit",signal:AbortSignal.any([signal,request.signal])});if(!response.body)return response;let body=response.body.pipeThrough(new TransformStream({transform(chunk,controller){if(received+=chunk.byteLength,received>512*1024)throw new Error("Device MCP response exceeds 512 KiB.");controller.enqueue(chunk)}}));return new Response(body,{status:response.status,statusText:response.statusText,headers:response.headers})}}module.exports={deviceMcpFetch}}});var util_exports={};__export(util_exports,{BIGINT_FORMAT_RANGES:()=>BIGINT_FORMAT_RANGES,CONSTANT_CATCH:()=>CONSTANT_CATCH,Class:()=>Class,NUMBER_FORMAT_RANGES:()=>NUMBER_FORMAT_RANGES,aborted:()=>aborted,allowsEval:()=>allowsEval,assert:()=>assert,assertEqual:()=>assertEqual,assertIs:()=>assertIs,assertNever:()=>assertNever,assertNotEqual:()=>assertNotEqual,assignProp:()=>assignProp,attachSchema:()=>attachSchema,base64ToUint8Array:()=>base64ToUint8Array,base64urlToUint8Array:()=>base64urlToUint8Array,cached:()=>cached,captureStackTrace:()=>captureStackTrace,cleanEnum:()=>cleanEnum,cleanRegex:()=>cleanRegex,clone:()=>clone,cloneDef:()=>cloneDef,codePointLength:()=>codePointLength,constantCatch:()=>constantCatch,createTransparentProxy:()=>createTransparentProxy,defineLazy:()=>defineLazy,defineLazyInternal:()=>defineLazyInternal,derived:()=>derived,esc:()=>esc,escapeRegex:()=>escapeRegex,explicitlyAborted:()=>explicitlyAborted,extend:()=>extend,finalizeIssue:()=>finalizeIssue,floatSafeRemainder:()=>floatSafeRemainder,getElementAtPath:()=>getElementAtPath,getEnumValues:()=>getEnumValues,getLengthableOrigin:()=>getLengthableOrigin,getParsedType:()=>getParsedType,getSizableOrigin:()=>getSizableOrigin,hexToUint8Array:()=>hexToUint8Array,hide:()=>hide,installLazyProp:()=>installLazyProp,isObject:()=>isObject,isPlainObject:()=>isPlainObject,issue:()=>issue,joinValues:()=>joinValues,jsonStringifyReplacer:()=>jsonStringifyReplacer,members:()=>members,merge:()=>merge,mergeDefs:()=>mergeDefs,normalizeParams:()=>normalizeParams,nullish:()=>nullish,numKeys:()=>numKeys,objectClone:()=>objectClone,omit:()=>omit,optionalKeys:()=>optionalKeys,own:()=>own,parsedType:()=>parsedType,partial:()=>partial,pick:()=>pick,prefixIssues:()=>prefixIssues,primitiveTypes:()=>primitiveTypes,promiseAllObject:()=>promiseAllObject,propertyKeyTypes:()=>propertyKeyTypes,randomString:()=>randomString,rawShape:()=>rawShape,required:()=>required,safeExtend:()=>safeExtend,shallowClone:()=>shallowClone,sizeCaps:()=>sizeCaps,slugify:()=>slugify,stringifyPrimitive:()=>stringifyPrimitive,toZod:()=>toZod,uint8ArrayToBase64:()=>uint8ArrayToBase64,uint8ArrayToBase64url:()=>uint8ArrayToBase64url,uint8ArrayToHex:()=>uint8ArrayToHex,unwrapMessage:()=>unwrapMessage});function assertEqual(val){return val}function assertNotEqual(val){return val}function toZod(){return schema=>schema}function assertIs(_arg){}function assertNever(_x){throw new Error("Unexpected value in exhaustive check")}function assert(_){}function getEnumValues(entries){let numericValues=Object.values(entries).filter(v2=>typeof v2=="number");return Object.entries(entries).filter(([k,_])=>numericValues.indexOf(+k)===-1).map(([_,v2])=>v2)}function joinValues(array2,separator="|"){return array2.map(val=>stringifyPrimitive(val)).join(separator)}function jsonStringifyReplacer(_,value){return typeof value=="bigint"?value.toString():value}function cached(getter){return new Cached(getter)}function nullish(input){return input==null}function cleanRegex(source){let start=source.startsWith("^")?1:0,end=source.endsWith("$")?source.length-1:source.length;return source.slice(start,end)}function floatSafeRemainder(val,step){let ratio=val/step,roundedRatio=Math.round(ratio),tolerance=4*Number.EPSILON*Math.max(Math.abs(ratio),1);return Math.abs(ratio-roundedRatio)<tolerance?0:ratio-roundedRatio}function defineLazy(object3,key,getter){let value;Object.defineProperty(object3,key,{get(){if(value!==EVALUATING)return value===void 0&&(value=EVALUATING,value=getter()),value},set(v2){Object.defineProperty(object3,key,{value:v2})},configurable:!0})}function objectClone(obj){return Object.create(Object.getPrototypeOf(obj),Object.getOwnPropertyDescriptors(obj))}function assignProp(target,prop,value){Object.defineProperty(target,prop,{value,writable:!0,enumerable:!0,configurable:!0})}function rawShape(def){let desc=Object.getOwnPropertyDescriptor(def,"shape");return desc?.get?desc.get.raw:desc?.value}function sourceShape(schema){return rawShape(schema._zod.def)??schema._zod.def.shape}function deferProp(target,key,getter){Object.defineProperty(target,key,{get(){let value=getter();return assignProp(this,key,value),value},enumerable:!0,configurable:!0})}function putProp(target,key,value){key in target?assignProp(target,key,value):target[key]=value}function mirrorShape(target,source,keys,wrap){let raw=sourceShape(source);for(let key of keys){let desc=Object.getOwnPropertyDescriptor(raw,key);desc.enumerable&&(desc.get?deferProp(target,key,()=>{let value=source._zod.def.shape[key];return wrap?wrap(value,key):value}):putProp(target,key,wrap?wrap(desc.value,key):desc.value))}}function mirrorProps(target,source){for(let key of Reflect.ownKeys(source)){let desc=Object.getOwnPropertyDescriptor(source,key);desc.enumerable&&(desc.get?deferProp(target,key,()=>source[key]):putProp(target,key,desc.value))}}function mergeDefs(...defs){let mergedDescriptors={};for(let def of defs){let descriptors=Object.getOwnPropertyDescriptors(def);Object.assign(mergedDescriptors,descriptors)}return Object.defineProperties({},mergedDescriptors)}function cloneDef(schema){return mergeDefs(schema._zod.def)}function getElementAtPath(obj,path){return path?path.reduce((acc,key)=>acc?.[key],obj):obj}function promiseAllObject(promisesObj){let keys=Object.keys(promisesObj),promises=keys.map(key=>promisesObj[key]);return Promise.all(promises).then(results=>{let resolvedObj={};for(let i2=0;i2<keys.length;i2++)resolvedObj[keys[i2]]=results[i2];return resolvedObj})}function randomString(length=10){let chars="abcdefghijklmnopqrstuvwxyz",str="";for(let i2=0;i2<length;i2++)str+=chars[Math.floor(Math.random()*chars.length)];return str}function esc(str){return JSON.stringify(str)}function slugify(input){return input.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}function isObject(data){return typeof data=="object"&&data!==null&&!Array.isArray(data)}function isPlainObject(o){if(isObject(o)===!1)return!1;let ctor=o.constructor;if(ctor===void 0||typeof ctor!="function")return!0;let prot=ctor.prototype;return!(isObject(prot)===!1||Object.prototype.hasOwnProperty.call(prot,"isPrototypeOf")===!1)}function shallowClone(o){return isPlainObject(o)?{...o}:Array.isArray(o)?[...o]:o instanceof Map?new Map(o):o instanceof Set?new Set(o):o}function numKeys(data){let keyCount=0;for(let key in data)Object.prototype.hasOwnProperty.call(data,key)&&keyCount++;return keyCount}function escapeRegex(str){return str.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function clone(inst,def,params){let cl=new inst._zod.constr(def??inst._zod.def);return(!def||params?.parent)&&(cl._zod.parent=inst),cl}function normalizeParams(_params){let params=_params;if(!params)return{};if(typeof params=="string")return{error:()=>params};if(params?.message!==void 0){if(params?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");params.error=params.message}return delete params.message,typeof params.error=="string"?{...params,error:()=>params.error}:params}function createTransparentProxy(getter){let target;return new Proxy({},{get(_,prop,receiver){return target??(target=getter()),Reflect.get(target,prop,receiver)},set(_,prop,value,receiver){return target??(target=getter()),Reflect.set(target,prop,value,receiver)},has(_,prop){return target??(target=getter()),Reflect.has(target,prop)},deleteProperty(_,prop){return target??(target=getter()),Reflect.deleteProperty(target,prop)},ownKeys(_){return target??(target=getter()),Reflect.ownKeys(target)},getOwnPropertyDescriptor(_,prop){return target??(target=getter()),Reflect.getOwnPropertyDescriptor(target,prop)},defineProperty(_,prop,descriptor){return target??(target=getter()),Reflect.defineProperty(target,prop,descriptor)}})}function stringifyPrimitive(value){return typeof value=="bigint"?value.toString()+"n":typeof value=="string"?`"${value}"`:`${value}`}function optionalKeys(shape){return Object.keys(shape).filter(k=>shape[k]._zod.optin!==void 0&&shape[k]._zod.optout==="optional")}function pick(schema,mask){let currDef=schema._zod.def,checks=currDef.checks;if(checks&&checks.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");let newShape={};return mirrorShape(newShape,schema,maskedKeys(schema,mask)),clone(schema,mergeDefs(currDef,{shape:newShape,checks:[]}))}function maskedKeys(schema,mask){let raw=sourceShape(schema),keys=[];for(let key of Reflect.ownKeys(mask)){if(!Object.getOwnPropertyDescriptor(raw,key)?.enumerable)throw new Error(`Unrecognized key: "${String(key)}"`);mask[key]&&keys.push(key)}return keys}function omit(schema,mask){let currDef=schema._zod.def,checks=currDef.checks;if(checks&&checks.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");let omitted=new Set(maskedKeys(schema,mask)),newShape={};return mirrorShape(newShape,schema,Reflect.ownKeys(sourceShape(schema)).filter(key=>!omitted.has(key))),clone(schema,mergeDefs(currDef,{shape:newShape,checks:[]}))}function extend(schema,shape){if(!isPlainObject(shape))throw new Error("Invalid input to extend: expected a plain object");let checks=schema._zod.def.checks;if(checks&&checks.length>0){let existingShape=sourceShape(schema);for(let key of Reflect.ownKeys(shape))if(Object.getOwnPropertyDescriptor(existingShape,key)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return clone(schema,mergeDefs(schema._zod.def,{shape:extended(schema,shape)}))}function extended(schema,shape){let newShape={};return mirrorShape(newShape,schema,Reflect.ownKeys(sourceShape(schema))),mirrorProps(newShape,shape),newShape}function safeExtend(schema,shape){if(!isPlainObject(shape))throw new Error("Invalid input to safeExtend: expected a plain object");return clone(schema,mergeDefs(schema._zod.def,{shape:extended(schema,shape)}))}function merge(a,b){if(!b?._zod?.def)throw new Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`.");if(a._zod.def.checks?.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let newShape={};mirrorShape(newShape,a,Reflect.ownKeys(sourceShape(a))),mirrorShape(newShape,b,Reflect.ownKeys(sourceShape(b)));let def=mergeDefs(a._zod.def,{shape:newShape,get catchall(){return b._zod.def.catchall},checks:b._zod.def.checks??[]});return clone(a,def)}function partial(Class2,schema,mask,name="partial"){let checks=schema._zod.def.checks;if(checks&&checks.length>0)throw new Error(`.${name}() cannot be used on object schemas containing refinements`);let selected=mask?new Set(maskedKeys(schema,mask)):void 0,newShape={};return mirrorShape(newShape,schema,Reflect.ownKeys(sourceShape(schema)),Class2&&((value,key)=>selected&&!selected.has(key)?value:new Class2({type:"optional",innerType:value}))),clone(schema,mergeDefs(schema._zod.def,{shape:newShape,checks:[]}))}function required(Class2,schema,mask){let selected=mask?new Set(maskedKeys(schema,mask)):void 0,newShape={};return mirrorShape(newShape,schema,Reflect.ownKeys(sourceShape(schema)),(value,key)=>selected&&!selected.has(key)?value:new Class2({type:"nonoptional",innerType:value})),clone(schema,mergeDefs(schema._zod.def,{shape:newShape}))}function aborted(x,startIndex=0){if(x.aborted===!0)return!0;for(let i2=startIndex;i2<x.issues.length;i2++)if(x.issues[i2]?.continue!==!0)return!0;return!1}function explicitlyAborted(x,startIndex=0){if(x.aborted===!0)return!0;for(let i2=startIndex;i2<x.issues.length;i2++)if(x.issues[i2]?.continue===!1)return!0;return!1}function prefixIssues(path,issues){return issues.map(iss=>{var _a4;return(_a4=iss).path??(_a4.path=[]),iss.path.unshift(path),iss})}function unwrapMessage(message){return typeof message=="string"?message:message?.message}function sizeCaps(defChecks){let caps=[];for(let ch of defChecks??[]){let d=ch._zod.def;if(!/_(length|size)$|_equals$/.test(d.check))break;let max=d.maximum??d.length??d.size;max>=0&&caps.push([max,ch])}return caps}function attachSchema(issues,start,inst){var _a4;for(let i2=start;i2<issues.length;i2++)(_a4=issues[i2]).schema??(_a4.schema=inst)}function finalizeIssue(iss,ctx,config2){var _a4;let traits=iss.inst?._zod?.traits;traits?.has("$ZodType")&&(traits.has("$ZodCheck")?(_a4=iss).schema??(_a4.schema=iss.inst):iss.schema=iss.inst);let schemaError=iss.schema!==iss.inst?iss.schema?._zod.def?.error:void 0,message=iss.message?iss.message:unwrapMessage(iss.inst?._zod.def?.error?.(iss))??unwrapMessage(schemaError?.(iss))??unwrapMessage(ctx?.error?.(iss))??unwrapMessage(config2.customError?.(iss))??unwrapMessage(config2.localeError?.(iss))??"Invalid input",full={};for(let k of Object.keys(iss))k==="inst"||k==="schema"||k==="continue"||k==="input"||k==="__proto__"||(full[k]=iss[k]);return full.path??(full.path=[]),full.message=message,ctx?.reportInput&&(full.input=iss.input),full}function getSizableOrigin(input){return input instanceof Set?"set":input instanceof Map?"map":input instanceof File?"file":"unknown"}function codePointLength(str){let units=str.length;if(!highSurrogate.test(str))return units;let count=units;for(let i2=0;i2<units-1;i2++)(str.charCodeAt(i2)&64512)===55296&&(str.charCodeAt(i2+1)&64512)===56320&&(count--,i2++);return count}function getLengthableOrigin(input){return Array.isArray(input)?"array":typeof input=="string"?"string":"unknown"}function parsedType(data){let t=typeof data;switch(t){case"number":return Number.isNaN(data)?"nan":"number";case"object":{if(data===null)return"null";if(Array.isArray(data))return"array";let obj=data;if(obj&&Object.getPrototypeOf(obj)!==Object.prototype&&"constructor"in obj&&obj.constructor)return obj.constructor.name}}return t}function issue(...args){let[iss,input,inst]=args;return typeof iss=="string"?{message:iss,code:"custom",input,inst}:{...iss}}function cleanEnum(obj){return Object.entries(obj).filter(([k,_])=>Number.isNaN(Number.parseInt(k,10))).map(el=>el[1])}function base64ToUint8Array(base642){let binaryString=atob(base642),bytes=new Uint8Array(binaryString.length);for(let i2=0;i2<binaryString.length;i2++)bytes[i2]=binaryString.charCodeAt(i2);return bytes}function uint8ArrayToBase64(bytes){let binaryString="";for(let i2=0;i2<bytes.length;i2++)binaryString+=String.fromCharCode(bytes[i2]);return btoa(binaryString)}function base64urlToUint8Array(base64url2){let base642=base64url2.replace(/-/g,"+").replace(/_/g,"/"),padding="=".repeat((4-base642.length%4)%4);return base64ToUint8Array(base642+padding)}function uint8ArrayToBase64url(bytes){return uint8ArrayToBase64(bytes).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function hexToUint8Array(hex){let cleanHex=hex.replace(/^0x/,"");if(cleanHex.length%2!==0)throw new Error("Invalid hex string length");let bytes=new Uint8Array(cleanHex.length/2);for(let i2=0;i2<cleanHex.length;i2+=2)bytes[i2/2]=Number.parseInt(cleanHex.slice(i2,i2+2),16);return bytes}function uint8ArrayToHex(bytes){return Array.from(bytes).map(b=>b.toString(16).padStart(2,"0")).join("")}function members(proto,table){for(let key in table){let desc=Object.getOwnPropertyDescriptor(table,key);desc.get?Object.defineProperty(proto,key,{...desc,enumerable:!1}):defineBound(proto,key,desc.value)}}function own(inst,key,value,enumerable=!0){return Object.defineProperty(inst,key,{configurable:!0,writable:!0,enumerable,value}),value}function hide(inst,key,value){return own(inst,key,value,!1)}function derived(computes,table){for(let key in computes){let compute=computes[key];Object.defineProperty(table,key,{configurable:!0,enumerable:!0,get(){return own(this,key,compute(this))},set(value){own(this,key,value)}})}return table}function defineBound(proto,key,fn){Object.defineProperty(proto,key,{configurable:!0,get(){return this==null?fn:own(this,key,fn.bind(this))},set(value){own(this,key,value)}})}function claim(inst,sentinel){let proto=Object.getPrototypeOf(inst);return sentinel in proto?void 0:proto}function defineLazyInternal(inst,key,compute){let proto=Object.getPrototypeOf(inst._zod);if(key in proto&&installing!==inst._zod){installing=void 0;return}installing=inst._zod,Object.defineProperty(proto,key,{configurable:!0,get(){Object.defineProperty(this,key,breaker);let outer=broke;broke=!1;try{let value=compute(this);return broke?delete this[key]:Object.defineProperty(this,key,{configurable:!0,writable:!0,value}),broke=broke||outer,value}catch(err){throw delete this[key],broke=broke||outer,err}},set(value){Object.defineProperty(this,key,{configurable:!0,writable:!0,value})}})}function installLazyProp(inst,key,make,enumerable){let proto=claim(inst,key);proto&&Object.defineProperty(proto,key,{configurable:!0,get(){let desc={configurable:!0,writable:!0,enumerable,value:void 0};return Object.defineProperty(this,key,desc),desc.value=make(this),Object.defineProperty(this,key,desc),desc.value},set(value){Object.defineProperty(this,key,{configurable:!0,writable:!0,enumerable,value})}})}function constantCatch(value){let fn=()=>value;return fn[CONSTANT_CATCH]=!0,fn}var Cached,EVALUATING,captureStackTrace,allowsEval,getParsedType,propertyKeyTypes,primitiveTypes,NUMBER_FORMAT_RANGES,BIGINT_FORMAT_RANGES,highSurrogate,Class,installing,broke,breaker,CONSTANT_CATCH,init_util=__esm({"../../node_modules/zod/v4/core/util.js"(){init_core();Cached=class{constructor(getter){this._getter=getter,this._value=void 0}get value(){let getter=this._getter;return getter!==void 0&&(this._value=getter(),this._getter=void 0),this._value}};EVALUATING=Symbol("evaluating");captureStackTrace="captureStackTrace"in Error?Error.captureStackTrace:(..._args)=>{};allowsEval=cached(()=>{if(globalConfig.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let F=Function;return new F(""),!0}catch{return!1}});getParsedType=data=>{let t=typeof data;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(data)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(data)?"array":data===null?"null":data.then&&typeof data.then=="function"&&data.catch&&typeof data.catch=="function"?"promise":typeof Map<"u"&&data instanceof Map?"map":typeof Set<"u"&&data instanceof Set?"set":typeof Date<"u"&&data instanceof Date?"date":typeof File<"u"&&data instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${t}`)}},propertyKeyTypes=new Set(["string","number","symbol"]),primitiveTypes=new Set(["string","number","bigint","boolean","symbol","undefined"]);NUMBER_FORMAT_RANGES={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},BIGINT_FORMAT_RANGES={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};highSurrogate=/[\uD800-\uDBFF]/;Class=class{constructor(..._args){}};broke=!1,breaker={configurable:!0,get(){broke=!0}};CONSTANT_CATCH="~constantCatch"}});function newError(Definition){let E=_E;if(E){let saved=E.stackTraceLimit;if(typeof saved=="number"){try{E.stackTraceLimit=0}catch{return _E=null,new Definition}try{return new Definition}finally{E.stackTraceLimit=saved}}}return new Definition}function $constructor(name,initializer3,proto,params){let zodProto={};function Internals(def){this.def=def,this.constr=_,this.traits=new Set}Internals.prototype=zodProto;let protoMembers=proto,initialized=protoMembers&&new WeakSet;function init(inst,def){if(inst._zod){if(inst._zod.traits.has(name))return}else{_zodDesc.value=new Internals(def);try{Object.defineProperty(inst,"_zod",_zodDesc)}finally{_zodDesc.value=void 0}}if(inst._zod.traits.add(name),initializer3(inst,def),initialized){let own2=Object.getPrototypeOf(inst),ctorProto=inst._zod.constr.prototype,up=own2;for(;up&&up!==ctorProto;)up=Object.getPrototypeOf(up);let target=up??own2;initialized.has(target)||(initialized.add(target),members(target,protoMembers))}let proto2=_.prototype;for(let k in proto2)Object.prototype.hasOwnProperty.call(proto2,k)&&(k in inst||(inst[k]=proto2[k].bind(inst)))}let Parent=params?.Parent??Object;class Definition extends Parent{}Object.defineProperty(Definition,"name",{value:name});function _(def){let inst=params?.Parent?newError(Definition):this;init(inst,def);let deferred=inst._zod.deferred;if(deferred){for(let fn of deferred)fn();inst._zod.deferred=void 0}let pp=globalThis.__zod_globalConfig?.postProcessor;return pp&&pp(inst),inst}return Object.defineProperty(_,"init",{value:init}),Object.defineProperty(_,Symbol.hasInstance,{value:inst=>params?.Parent&&inst instanceof params.Parent?!0:inst?._zod?.traits?.has(name)}),Object.defineProperty(_,"name",{value:name}),_}function config(newConfig){return newConfig&&Object.assign(globalConfig,newConfig),globalConfig}var _a2,NEVER,_zodDesc,_E,$ZodAsyncError,$ZodEncodeError,globalConfig,init_core=__esm({"../../node_modules/zod/v4/core/core.js"(){init_util();NEVER=Object.freeze({status:"aborted"}),_zodDesc={value:void 0,enumerable:!1},_E="captureStackTrace"in Error?Error:null;$ZodAsyncError=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},$ZodEncodeError=class extends Error{constructor(name){super(`Encountered unidirectional transform during encode: ${name}`),this.name="ZodEncodeError"}};(_a2=globalThis).__zod_globalConfig??(_a2.__zod_globalConfig={});globalConfig=globalThis.__zod_globalConfig}});function _getMessage(){let internals=this._zod;return internals.message??(internals.message=JSON.stringify(internals.def,jsonStringifyReplacer,2)),internals.message}function _setMessage(value){this._zod.message=value}function node(obj,key,make){return Object.prototype.hasOwnProperty.call(obj,key)||(key==="__proto__"?Object.defineProperty(obj,key,{value:make(),writable:!0,enumerable:!0,configurable:!0}):obj[key]=make()),obj[key]}function flattenError(error2,mapper=issue2=>issue2.message){let fieldErrors={},formErrors=[];for(let sub of error2.issues)sub.path.length>0?node(fieldErrors,sub.path[0],()=>[]).push(mapper(sub)):formErrors.push(mapper(sub));return{formErrors,fieldErrors}}function formatError(error2,mapper=issue2=>issue2.message){let fieldErrors={_errors:[]},processError=(error3,path=[])=>{for(let issue2 of error3.issues)if(issue2.code==="invalid_union"&&issue2.errors.length)issue2.errors.map(issues=>processError({issues},[...path,...issue2.path]));else if(issue2.code==="invalid_key")processError({issues:issue2.issues},[...path,...issue2.path]);else if(issue2.code==="invalid_element")processError({issues:issue2.issues},[...path,...issue2.path]);else{let fullpath=[...path,...issue2.path];if(fullpath.length===0)fieldErrors._errors.push(mapper(issue2));else{let curr=fieldErrors,i2=0;for(;i2<fullpath.length;){let el=fullpath[i2],terminal2=i2===fullpath.length-1;if(el==="_errors"){terminal2&&curr._errors.push(mapper(issue2)),i2++;continue}Object.prototype.hasOwnProperty.call(curr,el)||Object.defineProperty(curr,el,{value:{_errors:[]},enumerable:!0,writable:!0,configurable:!0});let node2=curr[el];terminal2&&node2._errors.push(mapper(issue2)),curr=node2,i2++}}}};return processError(error2),fieldErrors}var _messageDesc,_issuesDesc,_installedToString,initializer,$ZodError,$ZodRealError,init_errors2=__esm({"../../node_modules/zod/v4/core/errors.js"(){init_core();init_util();_messageDesc={get:_getMessage,set:_setMessage,enumerable:!0,configurable:!0},_issuesDesc={value:void 0,enumerable:!1},_installedToString=new WeakSet([Object.prototype,Error.prototype]),initializer=(inst,def)=>{inst.name="$ZodError",_issuesDesc.value=def,Object.defineProperty(inst,"issues",_issuesDesc),_issuesDesc.value=void 0,Object.defineProperty(inst,"message",_messageDesc);let proto=Object.getPrototypeOf(inst);_installedToString.has(proto)||(_installedToString.add(proto),Object.defineProperty(proto,"toString",{configurable:!0,enumerable:!1,get(){let value=()=>this.message;return Object.defineProperty(this,"toString",{value,configurable:!0,writable:!0}),value},set(value){Object.defineProperty(this,"toString",{value,configurable:!0,writable:!0})}}))},$ZodError=$constructor("$ZodError",initializer),$ZodRealError=$constructor("$ZodError",initializer,void 0,{Parent:Error})}});function finalizeParams(callee,params){return{callee:params?.callee??callee,Err:params?.Err}}function failure(Err,issues,ctx){let error2;return{success:!1,get error(){return error2||(error2=new Err(issues.map(iss=>finalizeIssue(iss,ctx,config()))),issues=void 0,ctx=void 0),error2},set error(e){error2=e,issues=void 0,ctx=void 0}}}function validateFallback(schema,value,_ctx){let ctx=_ctx?{..._ctx,async:!1,abortEarly:!0}:{async:!1,abortEarly:!0},fallbackRun=schema._zod.bag.fallbackRun,result;if(fallbackRun?(ctx[COMPILE_FALLBACK]=!0,result=fallbackRun({value,issues:[]},ctx)):result=schema._zod.run({value,issues:[]},ctx),result instanceof Promise)throw new $ZodAsyncError;return result.issues.length===0}var _parse,_parseAsync,_safeParse,safeParse,_safeParseAsync,COMPILE_INVALID,COMPILE_FALLBACK,validate,validateAsync,_encode,_decode,_encodeAsync,_decodeAsync,_safeEncode,_safeDecode,_safeEncodeAsync,_safeDecodeAsync,init_parse=__esm({"../../node_modules/zod/v4/core/parse.js"(){init_core();init_errors2();init_util();_parse=_Err=>{let fn=(schema,value,_ctx,_params)=>{let ctx=_ctx?{..._ctx,async:!1}:{async:!1},result=schema._zod.run({value,issues:[]},ctx);if(result instanceof Promise)throw new $ZodAsyncError;if(result.issues.length){let e=new(_params?.Err??_Err)(result.issues.map(iss=>finalizeIssue(iss,ctx,config())));throw captureStackTrace(e,_params?.callee??fn),e}return result.value};return fn},_parseAsync=_Err=>{let fn=async(schema,value,_ctx,params)=>{let ctx=_ctx?{..._ctx,async:!0}:{async:!0},result=schema._zod.run({value,issues:[]},ctx);if(result instanceof Promise&&(result=await result),result.issues.length){let e=new(params?.Err??_Err)(result.issues.map(iss=>finalizeIssue(iss,ctx,config())));throw captureStackTrace(e,params?.callee??fn),e}return result.value};return fn},_safeParse=_Err=>(schema,value,_ctx)=>{let ctx=_ctx?{..._ctx,async:!1}:{async:!1},result=schema._zod.run({value,issues:[]},ctx);if(result instanceof Promise)throw new $ZodAsyncError;return result.issues.length?failure(_Err,result.issues,ctx):{success:!0,data:result.value}},safeParse=_safeParse($ZodRealError);_safeParseAsync=_Err=>async(schema,value,_ctx)=>{let ctx=_ctx?{..._ctx,async:!0}:{async:!0},result=schema._zod.run({value,issues:[]},ctx);return result instanceof Promise&&(result=await result),result.issues.length?failure(_Err,result.issues,ctx):{success:!0,data:result.value}},COMPILE_INVALID=Symbol.for("zod.compile.invalid"),COMPILE_FALLBACK=Symbol.for("zod.compile.fallback"),validate=((schema,value,_ctx)=>{let validator=schema._zod.bag.validator;if(validator!==void 0){if(validator(value)!==COMPILE_INVALID)return!0;if(validator.definite===!0&&_ctx===void 0)return!1}return validateFallback(schema,value,_ctx)});validateAsync=async(schema,value,_ctx)=>{let ctx=_ctx?{..._ctx,async:!0,abortEarly:!0}:{async:!0,abortEarly:!0},result=schema._zod.run({value,issues:[]},ctx);return result instanceof Promise&&(result=await result),result.issues.length===0},_encode=_Err=>{let parse4=_parse(_Err),fn=(schema,value,_ctx,_params)=>{let ctx=_ctx?{..._ctx,direction:"backward"}:{direction:"backward"};return parse4(schema,value,ctx,finalizeParams(fn,_params))};return fn},_decode=_Err=>{let parse4=_parse(_Err),fn=(schema,value,_ctx,_params)=>parse4(schema,value,_ctx,finalizeParams(fn,_params));return fn},_encodeAsync=_Err=>{let parseAsync3=_parseAsync(_Err),fn=async(schema,value,_ctx,_params)=>{let ctx=_ctx?{..._ctx,direction:"backward"}:{direction:"backward"};return await parseAsync3(schema,value,ctx,finalizeParams(fn,_params))};return fn},_decodeAsync=_Err=>{let parseAsync3=_parseAsync(_Err),fn=async(schema,value,_ctx,_params)=>await parseAsync3(schema,value,_ctx,finalizeParams(fn,_params));return fn},_safeEncode=_Err=>(schema,value,_ctx)=>{let ctx=_ctx?{..._ctx,direction:"backward"}:{direction:"backward"};return _safeParse(_Err)(schema,value,ctx)},_safeDecode=_Err=>(schema,value,_ctx)=>_safeParse(_Err)(schema,value,_ctx),_safeEncodeAsync=_Err=>async(schema,value,_ctx)=>{let ctx=_ctx?{..._ctx,direction:"backward"}:{direction:"backward"};return _safeParseAsync(_Err)(schema,value,ctx)},_safeDecodeAsync=_Err=>async(schema,value,_ctx)=>_safeParseAsync(_Err)(schema,value,_ctx)}});function nanoidOfLength(length){return new RegExp(`^[a-zA-Z0-9_-]{${length}}$`)}function emoji(){return new RegExp(_emoji,"u")}function anchor(source){return new RegExp(`^${source}$`)}function timeSource(args){let hhmm="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof args.precision=="number"?args.precision===-1?`${hhmm}`:args.precision===0?`${hhmm}:[0-5]\\d`:`${hhmm}:[0-5]\\d\\.\\d{${args.precision}}`:args.seconds?`${hhmm}:[0-5]\\d(?:\\.\\d+)?`:`${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`}function time(args){return new RegExp(`^${timeSource(args)}$`)}function datetime(args){let opts=["Z"];args.offset&&opts.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let qualified=`${timeSource({precision:args.precision,seconds:!0})}(?:${opts.join("|")})`,timeRegex=args.local?`${qualified}|${timeSource({precision:args.precision})}`:qualified;return new RegExp(`^${dateSource}T(?:${timeRegex})$`)}var cuid,cuid2,ulid,xid,ksuid,nanoid,duration,guid,uuid,email,_emoji,ipv4,ipv6,cidrv4,cidrv6,base64,base64url,httpProtocol,e164,dateSource,date,anyString,bigint,integer,number,boolean,_null,lowercase,uppercase,init_regexes=__esm({"../../node_modules/zod/v4/core/regexes.js"(){cuid=/^[cC][0-9a-z]{6,}$/,cuid2=/^[0-9a-z]+$/,ulid=/^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/,xid=/^[0-9a-vA-V]{20}$/,ksuid=/^[A-Za-z0-9]{27}$/,nanoid=/^[a-zA-Z0-9_-]{21}$/;duration=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,guid=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,uuid=version3=>version3?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version3}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,email=/^(?:[A-Za-z0-9_'+\-]+\.)*[A-Za-z0-9_'+\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,_emoji="^(?=[\\s\\S]*[\\p{Extended_Pictographic}\\p{Regional_Indicator}\\u20E3])[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$";ipv4=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv6=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,cidrv4=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,cidrv6=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,base64url=/^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/,httpProtocol=/^https?$/,e164=/^\+[1-9]\d{6,14}$/,dateSource="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))";date=anchor(dateSource);anyString=/^[\s\S]{0,}$/,bigint=/^-?\d+n?$/,integer=/^-?\d+$/,number=/^-?\d+(?:\.\d+)?$/,boolean=/^(?:true|false)$/i,_null=/^null$/i,lowercase=/^[^A-Z]*$/,uppercase=/^[^a-z]*$/}});var $ZodCheck,_whenHasLength,numericOriginMap,$ZodCheckLessThan,$ZodCheckGreaterThan,$ZodCheckMultipleOf,$ZodCheckNumberFormat,$ZodCheckMaxLength,$ZodCheckMinLength,$ZodCheckLengthEquals,$ZodCheckStringFormat,$ZodCheckRegex,$ZodCheckLowerCase,$ZodCheckUpperCase,$ZodCheckIncludes,$ZodCheckStartsWith,$ZodCheckEndsWith,$ZodCheckOverwrite,init_checks=__esm({"../../node_modules/zod/v4/core/checks.js"(){init_core();init_regexes();init_util();$ZodCheck=$constructor("$ZodCheck",(inst,def)=>{var _a4;inst._zod??(inst._zod={}),inst._zod.def=def,(_a4=inst._zod).onattach??(_a4.onattach=[])}),_whenHasLength=payload=>{let val=payload.value;return!nullish(val)&&val.length!==void 0},numericOriginMap={number:"number",bigint:"bigint",object:"date"},$ZodCheckLessThan=$constructor("$ZodCheckLessThan",(inst,def)=>{$ZodCheck.init(inst,def);let origin=numericOriginMap[typeof def.value];inst._zod.check=payload=>{(def.inclusive?payload.value<=def.value:payload.value<def.value)||payload.issues.push({origin:numericOriginMap[typeof payload.value]??origin,code:"too_big",maximum:typeof def.value=="object"?def.value.getTime():def.value,input:payload.value,inclusive:def.inclusive,inst,continue:!def.abort})}}),$ZodCheckGreaterThan=$constructor("$ZodCheckGreaterThan",(inst,def)=>{$ZodCheck.init(inst,def);let origin=numericOriginMap[typeof def.value];inst._zod.check=payload=>{(def.inclusive?payload.value>=def.value:payload.value>def.value)||payload.issues.push({origin:numericOriginMap[typeof payload.value]??origin,code:"too_small",minimum:typeof def.value=="object"?def.value.getTime():def.value,input:payload.value,inclusive:def.inclusive,inst,continue:!def.abort})}}),$ZodCheckMultipleOf=$constructor("$ZodCheckMultipleOf",(inst,def)=>{$ZodCheck.init(inst,def),inst._zod.check=payload=>{if(typeof payload.value!=typeof def.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof payload.value=="bigint"?def.value!==BigInt(0)&&payload.value%def.value===BigInt(0):floatSafeRemainder(payload.value,def.value)===0)||payload.issues.push({origin:typeof payload.value,code:"not_multiple_of",divisor:def.value,input:payload.value,inst,continue:!def.abort})}}),$ZodCheckNumberFormat=$constructor("$ZodCheckNumberFormat",(inst,def)=>{$ZodCheck.init(inst,def),def.format=def.format||"float64";let isInt=def.format?.includes("int"),origin=isInt?"int":"number",[minimum,maximum]=NUMBER_FORMAT_RANGES[def.format];inst._zod.check=payload=>{let input=payload.value;if(isInt){if(!Number.isInteger(input)){payload.issues.push({expected:origin,format:def.format,code:"invalid_type",continue:!1,input,inst});return}if(!Number.isSafeInteger(input)){input>0?payload.issues.push({input,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst,origin,inclusive:!0,continue:!def.abort}):payload.issues.push({input,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst,origin,inclusive:!0,continue:!def.abort});return}}input<minimum&&payload.issues.push({origin:"number",input,code:"too_small",minimum,inclusive:!0,inst,continue:!def.abort}),input>maximum&&payload.issues.push({origin:"number",input,code:"too_big",maximum,inclusive:!0,inst,continue:!def.abort})}}),$ZodCheckMaxLength=$constructor("$ZodCheckMaxLength",(inst,def)=>{var _a4;$ZodCheck.init(inst,def),(_a4=inst._zod.def).when??(_a4.when=_whenHasLength),inst._zod.check=payload=>{let input=payload.value,units=input.length;if((typeof input=="string"&&units>def.maximum?codePointLength(input):units)<=def.maximum)return;let origin=getLengthableOrigin(input);payload.issues.push({origin,code:"too_big",maximum:def.maximum,inclusive:!0,input,inst,continue:!def.abort})}}),$ZodCheckMinLength=$constructor("$ZodCheckMinLength",(inst,def)=>{var _a4;$ZodCheck.init(inst,def),(_a4=inst._zod.def).when??(_a4.when=_whenHasLength),inst._zod.check=payload=>{let input=payload.value,units=input.length;if((typeof input=="string"&&units>=def.minimum&&units<def.minimum*2?codePointLength(input):units)>=def.minimum)return;let origin=getLengthableOrigin(input);payload.issues.push({origin,code:"too_small",minimum:def.minimum,inclusive:!0,input,inst,continue:!def.abort})}}),$ZodCheckLengthEquals=$constructor("$ZodCheckLengthEquals",(inst,def)=>{var _a4;$ZodCheck.init(inst,def),(_a4=inst._zod.def).when??(_a4.when=_whenHasLength),inst._zod.check=payload=>{let input=payload.value,units=input.length,length=typeof input=="string"&&units>=def.length&&units<=def.length*2?codePointLength(input):units;if(length===def.length)return;let origin=getLengthableOrigin(input),tooBig=length>def.length;payload.issues.push({origin,...tooBig?{code:"too_big",maximum:def.length}:{code:"too_small",minimum:def.length},inclusive:!0,exact:!0,input:payload.value,inst,continue:!def.abort})}}),$ZodCheckStringFormat=$constructor("$ZodCheckStringFormat",(inst,def)=>{var _a4,_b2;$ZodCheck.init(inst,def),def.pattern?(_a4=inst._zod).check??(_a4.check=payload=>{def.pattern.lastIndex=0,!def.pattern.test(payload.value)&&payload.issues.push({origin:"string",code:"invalid_format",format:def.format,input:payload.value,...def.pattern?{pattern:def.pattern.toString()}:{},inst,continue:!def.abort})}):(_b2=inst._zod).check??(_b2.check=()=>{})}),$ZodCheckRegex=$constructor("$ZodCheckRegex",(inst,def)=>{$ZodCheckStringFormat.init(inst,def),inst._zod.check=payload=>{def.pattern.lastIndex=0,!def.pattern.test(payload.value)&&payload.issues.push({origin:"string",code:"invalid_format",format:"regex",input:payload.value,pattern:def.pattern.toString(),inst,continue:!def.abort})}}),$ZodCheckLowerCase=$constructor("$ZodCheckLowerCase",(inst,def)=>{def.pattern??(def.pattern=lowercase),$ZodCheckStringFormat.init(inst,def)}),$ZodCheckUpperCase=$constructor("$ZodCheckUpperCase",(inst,def)=>{def.pattern??(def.pattern=uppercase),$ZodCheckStringFormat.init(inst,def)}),$ZodCheckIncludes=$constructor("$ZodCheckIncludes",(inst,def)=>{$ZodCheck.init(inst,def);let escapedRegex=escapeRegex(def.includes),pattern=new RegExp(typeof def.position=="number"?`^.{${def.position},}${escapedRegex}`:escapedRegex);def.pattern=pattern,inst._zod.check=payload=>{payload.value.includes(def.includes,def.position)||payload.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:def.includes,input:payload.value,inst,continue:!def.abort})}}),$ZodCheckStartsWith=$constructor("$ZodCheckStartsWith",(inst,def)=>{$ZodCheck.init(inst,def);let pattern=new RegExp(`^${escapeRegex(def.prefix)}.*`);def.pattern??(def.pattern=pattern),inst._zod.check=payload=>{payload.value.startsWith(def.prefix)||payload.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:def.prefix,input:payload.value,inst,continue:!def.abort})}}),$ZodCheckEndsWith=$constructor("$ZodCheckEndsWith",(inst,def)=>{$ZodCheck.init(inst,def);let pattern=new RegExp(`.*${escapeRegex(def.suffix)}$`);def.pattern??(def.pattern=pattern),inst._zod.check=payload=>{payload.value.endsWith(def.suffix)||payload.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:def.suffix,input:payload.value,inst,continue:!def.abort})}}),$ZodCheckOverwrite=$constructor("$ZodCheckOverwrite",(inst,def)=>{$ZodCheck.init(inst,def),inst._zod.check=payload=>{payload.value=def.tx(payload.value)}})}});var Doc,init_doc=__esm({"../../node_modules/zod/v4/core/doc.js"(){Doc=class{constructor(args=[],closed={}){this.content=[],this.indent=0,this.args=args,this.closed=closed}indented(fn){this.indent+=1;try{fn(this)}finally{this.indent-=1}}write(arg){if(typeof arg=="function"){arg(this,{execution:"sync"}),arg(this,{execution:"async"});return}let lines=arg.split(`
|
|
7
7
|
`).filter(x=>x),minIndent=Math.min(...lines.map(x=>x.length-x.trimStart().length)),dedented=lines.map(x=>x.slice(minIndent)).map(x=>" ".repeat(this.indent*2)+x);for(let line of dedented)this.content.push(line)}compile(){let F=Function,content=this?.content??[""];return new F(...Object.keys(this.closed),`return function (${this.args.join(", ")}) {
|
|
8
8
|
${content.join(`
|
|
9
9
|
`)}
|
|
10
|
-
};`)(...Object.values(this.closed))}}}});var version2,init_versions=__esm({"../../node_modules/zod/v4/core/versions.js"(){version2={major:4,minor:6,patch:7}}});async function validateAsync2(inst,value){let ctx={async:!0};return toStandardResult(await inst._zod.run({value,issues:[]},ctx),ctx)}function standardProps(inst){return{validate:value=>{let ctx={async:!1};try{let r=inst._zod.run({value,issues:[]},ctx);if(!(r instanceof Promise))return toStandardResult(r,ctx)}catch{}return validateAsync2(inst,value)},vendor:"zod",version:1}}function canParseURL(input){try{return typeof URL<"u"&&typeof URL.canParse=="function"?URL.canParse(input):(new URL(input),!0)}catch{return!1}}function validateURL(trimmed,def){return!("normalize"in def)&&!("hostname"in def)&&!("protocol"in def)?canParseURL(trimmed)||URL_UNPARSEABLE:parseURLObject(trimmed,def)}function parseURLObject(trimmed,def){if(!def.normalize&&def.protocol?.source===httpProtocol.source&&!/^https?:\/\//i.test(trimmed))return URL_BAD_FORMAT;try{if(typeof URL<"u"){let URLStatic=URL;if(typeof URLStatic.parse=="function")return URLStatic.parse(trimmed)??URL_UNPARSEABLE}return new URL(trimmed)}catch{return URL_UNPARSEABLE}}function stripTabAndNewline(value){return value.replace(asciiTabOrNewline,"")}function urlHostnameOk(url2,hostname2){return hostname2.lastIndex=0,hostname2.test(url2.hostname)}function urlProtocolOk(url2,protocol){return protocol.lastIndex=0,protocol.test(url2.protocol.endsWith(":")?url2.protocol.slice(0,-1):url2.protocol)}function isValidIPv6(value){return ipv6Alphabet.test(value)?canParseURL(`http://[${value}]`):!1}function isValidCIDRv6(value){let parts=value.split("/");if(parts.length!==2)return!1;let[address,prefix]=parts;if(!prefix)return!1;let prefixNum=Number(prefix);return`${prefixNum}`!==prefix||prefixNum<0||prefixNum>128?!1:isValidIPv6(address)}function isValidBase64(data){if(data==="")return!0;if(/\s/.test(data)||data.length%4!==0)return!1;try{return atob(data),!0}catch{return!1}}function isValidBase64URL(data){if(!base64urlCharset.test(data))return!1;let base642=data.replace(/[-_]/g,c=>c==="-"?"+":"/"),padded=base642.padEnd(Math.ceil(base642.length/4)*4,"=");return isValidBase64(padded)}function isValidJWT(token,algorithm=null){try{let tokensParts=token.split(".");if(tokensParts.length!==3)return!1;let[header]=tokensParts;if(!header)return!1;let parsedHeader=JSON.parse(atob(header));return!("typ"in parsedHeader&&parsedHeader?.typ!=="JWT"||!parsedHeader.alg||algorithm&&(!("alg"in parsedHeader)||parsedHeader.alg!==algorithm))}catch{return!1}}function capSize(inst,size){let caps=sizeCaps(inst._zod.def.checks);if(!caps.length)return;let cap=Math.min(...caps.map(c=>c[0])),parse4=inst._zod.parse;inst._zod.parse=(payload,ctx)=>{let n=size(payload.value);if(n>cap&&!ctx?.skipChecks&&ctx?.direction!=="backward"){for(let[max,ch]of sizeCaps(inst._zod.def.checks))if(n>max&&ch._zod.def.when(payload)){let start=payload.issues.length;return ch._zod.check(payload),payload.issues[start].continue=!1,attachSchema(payload.issues,start,inst),payload}}return parse4(payload,ctx)}}function handleArrayResult(result,final,index){result.issues.length&&final.issues.push(...prefixIssues(index,result.issues)),final.value[index]=result.value}function handlePropertyResult(result,final,key,input,optin,optout){let isPresent=key in input,isOptionalOut=optout==="optional";if(!(!isPresent&&isOptionalOut&&optin==="optional")){if(result.issues.length){if(optin!==void 0&&isOptionalOut&&!isPresent)return;final.issues.push(...prefixIssues(key,result.issues))}if(!isPresent&&optin===void 0){result.issues.length||final.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[key]});return}result.value===void 0?(isPresent||optin==="defaulted"&&!isOptionalOut)&&(final.value[key]=void 0):final.value[key]=result.value}}function normalizeDef(def){let keys=Object.keys(def.shape),ownSymbols=Object.getOwnPropertySymbols(def.shape),symbolKeys=ownSymbols.length?ownSymbols:NO_SYMBOL_KEYS,allKeys=symbolKeys.length?[...keys,...symbolKeys]:keys;for(let k of allKeys)if(!def.shape?.[k]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${String(k)}": expected a Zod schema`);let okeys=optionalKeys(def.shape);return{...def,allKeys,symbolKeys,keySet:new Set(keys),numKeys:keys.length,optionalKeys:new Set(okeys)}}function handleCatchall(proms,input,payload,ctx,def,inst,abortEarly){let unrecognized=[],keySet=def.keySet,_catchall=def.catchall._zod,t=_catchall.def.type,optin=_catchall.optin,optout=_catchall.optout,seen=0;for(let key in input){if(abortEarly&&payload.issues.length!==seen){if(aborted(payload,seen))break;seen=payload.issues.length}if(keySet.has(key))continue;if(key==="__proto__"){t==="never"&&unrecognized.push(key);continue}if(t==="never"){unrecognized.push(key);continue}let r=_catchall.run({value:input[key],issues:[]},ctx);r instanceof Promise?proms.push(r.then(r2=>handlePropertyResult(r2,payload,key,input,optin,optout))):handlePropertyResult(r,payload,key,input,optin,optout)}return unrecognized.length&&payload.issues.push({code:"unrecognized_keys",keys:unrecognized,input,inst,continue:!0}),proms.length?Promise.all(proms).then(()=>payload):payload}function handleUnionResults(results,final,inst,ctx){for(let result of results)if(result.issues.length===0)return final.value=result.value,final;let nonaborted=results.filter(r=>!aborted(r));return nonaborted.length===1?(final.value=nonaborted[0].value,nonaborted[0]):(final.issues.push({code:"invalid_union",input:final.value,inst,errors:results.map(result=>result.issues.map(iss=>finalizeIssue(iss,ctx,config())))}),final)}function discriminatorMap(def){let map=new Map;for(let option of def.options){let values=option._zod.propValues?.[def.discriminator];if(!values||values.size===0)throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(option)}"`);for(let value of values)if(map.has(value)){if(value!==void 0)throw new Error(`Duplicate discriminator value "${String(value)}"`);map.set(value,null)}else map.set(value,option)}return map}function mergeValues(a,b){if(a===b)return{valid:!0,data:a};if(a instanceof Date&&b instanceof Date&&+a==+b)return{valid:!0,data:a};if(isPlainObject(a)&&isPlainObject(b)){let bKeys=Object.keys(b),sharedKeys=Object.keys(a).filter(key=>bKeys.indexOf(key)!==-1),newObj={...a,...b};Object.prototype.hasOwnProperty.call(newObj,"__proto__")&&delete newObj.__proto__;for(let key of sharedKeys){if(key==="__proto__")continue;let sharedValue=mergeValues(a[key],b[key]);if(!sharedValue.valid)return{valid:!1,mergeErrorPath:[key,...sharedValue.mergeErrorPath]};newObj[key]=sharedValue.data}return{valid:!0,data:newObj}}if(Array.isArray(a)&&Array.isArray(b)){if(a.length!==b.length)return{valid:!1,mergeErrorPath:[]};let newArray=[];for(let index=0;index<a.length;index++){let itemA=a[index],itemB=b[index],sharedValue=mergeValues(itemA,itemB);if(!sharedValue.valid)return{valid:!1,mergeErrorPath:[index,...sharedValue.mergeErrorPath]};newArray.push(sharedValue.data)}return{valid:!0,data:newArray}}return{valid:!1,mergeErrorPath:[]}}function handleIntersectionResults(result,left,right){let unrecKeys=new Map,unrecIssue,keyIssues=new Map,collect=(iss,side)=>{let keys;if(iss.code==="unrecognized_keys"&&!iss.path?.length)unrecIssue??(unrecIssue=iss),keys=iss.keys;else if(iss.code==="invalid_key"&&iss.origin==="record"&&iss.path?.length===1){let k=String(iss.path[0]);keyIssues.has(k)||keyIssues.set(k,iss),keys=[k]}else return!1;for(let k of keys)unrecKeys.has(k)||unrecKeys.set(k,{}),unrecKeys.get(k)[side]=!0;return!0};for(let iss of left.issues)collect(iss,"l")||result.issues.push(iss);for(let iss of right.issues)collect(iss,"r")||result.issues.push(iss);let bothKeys=[...unrecKeys].filter(([,f])=>f.l&&f.r).map(([k])=>k);if(bothKeys.length){let aggregated=unrecIssue?bothKeys.filter(k=>unrecIssue.keys.includes(k)):[];aggregated.length&&result.issues.push({...unrecIssue,keys:aggregated});for(let k of bothKeys)!aggregated.includes(k)&&keyIssues.has(k)&&result.issues.push(keyIssues.get(k))}let merged=mergeValues(left.value,right.value);if(!merged.valid){if(aborted(result))return result;throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(merged.mergeErrorPath)}`)}return result.value=merged.data,result}function handleOptionalResult(payload,result){return payload.value=result.issues.length?void 0:result.value,payload}function handleDefaultResult(payload,def){return payload.value===void 0&&(payload.value=def.defaultValue),payload}function handleNonOptionalResult(payload,inst){return!payload.issues.length&&payload.value===void 0&&payload.issues.push({code:"invalid_type",expected:"nonoptional",input:payload.value,inst}),payload}function handleCatchResult(payload,result,def,ctx){return result.issues.length?(payload.value=def.catchValue({...result,value:payload.value,error:{issues:result.issues.map(iss=>finalizeIssue(iss,ctx,config()))},input:payload.value}),payload):(payload.value=result.value,result.memo&&(payload.memo=!0),payload)}function handlePipeResult(left,next,ctx){return left.issues.some(iss=>iss.code!=="unrecognized_keys")?(left.aborted=!0,left):next._zod.run({value:left.value,issues:left.issues},ctx)}function handleReadonlyResult(payload){return payload.memo||(payload.value=Object.freeze(payload.value)),payload}function handleRefineResult(result,payload,input,inst){if(!result){let _iss={code:"custom",input,inst,path:[...inst._zod.def.path??[]],continue:!inst._zod.def.abort};inst._zod.def.params&&(_iss.params=inst._zod.def.params),payload.issues.push(issue(_iss))}}var $ZodType,toStandardResult,$ZodString,$ZodStringFormat,$ZodGUID,$ZodUUID,$ZodEmail,URL_BAD_FORMAT,URL_UNPARSEABLE,asciiTabOrNewline,$ZodURL,$ZodEmoji,$ZodNanoID,$ZodCUID,$ZodCUID2,$ZodULID,$ZodXID,$ZodKSUID,$ZodISODateTime,$ZodISODate,$ZodISOTime,$ZodISODuration,$ZodIPv4,ipv6Alphabet,$ZodIPv6,$ZodCIDRv4,$ZodCIDRv6,base64Charset,$ZodBase64,base64urlCharset,$ZodBase64URL,$ZodE164,$ZodJWT,$ZodNumber,$ZodNumberFormat,$ZodBoolean,$ZodBigInt,$ZodNull,$ZodAny,$ZodUnknown,$ZodNever,$ZodDate,arraySize,$ZodArray,NO_SYMBOL_KEYS,$ZodObject,$ZodObjectJIT,$ZodUnion,$ZodDiscriminatedUnion,$ZodIntersection,$ZodRecord,$ZodEnum,$ZodLiteral,$ZodTransform,$ZodOptional,$ZodExactOptional,$ZodNullable,$ZodDefault,$ZodPrefault,$ZodNonOptional,$ZodCatch,$ZodPipe,$ZodPreprocess,$ZodReadonly,$ZodCustom,init_schemas=__esm({"../../node_modules/zod/v4/core/schemas.js"(){init_checks();init_core();init_doc();init_regexes();init_util();init_versions();init_util();$ZodType=$constructor("$ZodType",(inst,def)=>{var _a4;inst??(inst={}),inst._zod.def=def,inst._zod.bag=inst._zod.bag||{},inst._zod.version=version2;let defChecks=inst._zod.def.checks,checks=inst._zod.traits.has("$ZodCheck")?[inst,...defChecks??[]]:defChecks?.length?[...defChecks]:[];for(let ch of checks)for(let fn of ch._zod.onattach)fn(inst);if(checks.length===0)(_a4=inst._zod).deferred??(_a4.deferred=[]),inst._zod.deferred?.push(()=>{inst._zod.run=inst._zod.parse});else{let runChecks=(payload,checks2,ctx)=>{if(payload.memo)return payload;let isAborted=aborted(payload),asyncResult;for(let ch of checks2){if(ch._zod.def.when){if(explicitlyAborted(payload)||!ch._zod.def.when(payload))continue}else if(isAborted)continue;let currLen=payload.issues.length,_=ch._zod.check(payload);if(_ instanceof Promise&&ctx?.async===!1)throw new $ZodAsyncError;if(asyncResult||_ instanceof Promise)asyncResult=(asyncResult??Promise.resolve()).then(async()=>{await _,payload.issues.length!==currLen&&(attachSchema(payload.issues,currLen,inst),isAborted||(isAborted=aborted(payload,currLen)))});else{if(payload.issues.length===currLen)continue;attachSchema(payload.issues,currLen,inst),isAborted||(isAborted=aborted(payload,currLen))}}return asyncResult?asyncResult.then(()=>payload):payload},handleCanaryResult=(canary,payload,ctx)=>{if(aborted(canary))return canary.aborted=!0,canary;let checkResult=runChecks(payload,checks,ctx);if(checkResult instanceof Promise){if(ctx.async===!1)throw new $ZodAsyncError;return checkResult.then(checkResult2=>inst._zod.parse(checkResult2,ctx))}return inst._zod.parse(checkResult,ctx)};inst._zod.run=(payload,ctx)=>{if(ctx.skipChecks)return inst._zod.parse(payload,ctx);if(ctx.direction==="backward"){let canary=inst._zod.parse({value:payload.value,issues:[]},{...ctx,skipChecks:!0});return canary instanceof Promise?canary.then(canary2=>handleCanaryResult(canary2,payload,ctx)):handleCanaryResult(canary,payload,ctx)}let result=inst._zod.parse(payload,ctx);if(result instanceof Promise){if(ctx.async===!1)throw new $ZodAsyncError;return result.then(result2=>runChecks(result2,checks,ctx))}return runChecks(result,checks,ctx)}}},{get"~standard"(){return hide(this,"~standard",standardProps(this))},set"~standard"(value){own(this,"~standard",value)}}),toStandardResult=(r,ctx)=>r.issues.length?{issues:r.issues.map(iss=>finalizeIssue(iss,ctx,config()))}:{value:r.value};$ZodString=$constructor("$ZodString",(inst,def)=>{$ZodType.init(inst,def),inst._zod.pattern=def.pattern??anyString,inst._zod.parse=(payload,_)=>{if(def.coerce)try{payload.value=String(payload.value)}catch{}return typeof payload.value=="string"||payload.issues.push({expected:"string",code:"invalid_type",input:payload.value,inst}),payload}}),$ZodStringFormat=$constructor("$ZodStringFormat",(inst,def)=>{$ZodCheckStringFormat.init(inst,def),$ZodString.init(inst,def)}),$ZodGUID=$constructor("$ZodGUID",(inst,def)=>{def.pattern??(def.pattern=guid),$ZodStringFormat.init(inst,def)}),$ZodUUID=$constructor("$ZodUUID",(inst,def)=>{if(def.version){let v2={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[def.version];if(v2===void 0)throw new Error(`Invalid UUID version: "${def.version}"`);def.pattern??(def.pattern=uuid(v2))}else def.pattern??(def.pattern=uuid());$ZodStringFormat.init(inst,def)}),$ZodEmail=$constructor("$ZodEmail",(inst,def)=>{def.pattern??(def.pattern=email),$ZodStringFormat.init(inst,def)}),URL_BAD_FORMAT=1,URL_UNPARSEABLE=2;asciiTabOrNewline=/[\t\n\r]/g;$ZodURL=$constructor("$ZodURL",(inst,def)=>{$ZodStringFormat.init(inst,def),inst._zod.check=payload=>{try{let trimmed=payload.value.trim(),url2=validateURL(trimmed,def);if(url2===URL_BAD_FORMAT){payload.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:payload.value,inst,continue:!def.abort});return}if(url2===URL_UNPARSEABLE){payload.issues.push({code:"invalid_format",format:"url",input:payload.value,inst,continue:!def.abort});return}if(url2===!0){payload.value=stripTabAndNewline(trimmed);return}def.hostname&&!urlHostnameOk(url2,def.hostname)&&payload.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:def.hostname.source,input:payload.value,inst,continue:!def.abort}),def.protocol&&!urlProtocolOk(url2,def.protocol)&&payload.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:def.protocol.source,input:payload.value,inst,continue:!def.abort}),payload.value=def.normalize?url2.href:stripTabAndNewline(trimmed);return}catch{payload.issues.push({code:"invalid_format",format:"url",input:payload.value,inst,continue:!def.abort})}}}),$ZodEmoji=$constructor("$ZodEmoji",(inst,def)=>{def.pattern??(def.pattern=emoji()),$ZodStringFormat.init(inst,def)}),$ZodNanoID=$constructor("$ZodNanoID",(inst,def)=>{if(def.length!==void 0&&(!Number.isInteger(def.length)||def.length<1))throw new Error(`Invalid nanoid length: ${def.length}`);def.pattern??(def.pattern=def.length===void 0?nanoid:nanoidOfLength(def.length)),$ZodStringFormat.init(inst,def)}),$ZodCUID=$constructor("$ZodCUID",(inst,def)=>{def.pattern??(def.pattern=cuid),$ZodStringFormat.init(inst,def)}),$ZodCUID2=$constructor("$ZodCUID2",(inst,def)=>{def.pattern??(def.pattern=cuid2),$ZodStringFormat.init(inst,def)}),$ZodULID=$constructor("$ZodULID",(inst,def)=>{def.pattern??(def.pattern=ulid),$ZodStringFormat.init(inst,def)}),$ZodXID=$constructor("$ZodXID",(inst,def)=>{def.pattern??(def.pattern=xid),$ZodStringFormat.init(inst,def)}),$ZodKSUID=$constructor("$ZodKSUID",(inst,def)=>{def.pattern??(def.pattern=ksuid),$ZodStringFormat.init(inst,def)}),$ZodISODateTime=$constructor("$ZodISODateTime",(inst,def)=>{def.pattern??(def.pattern=datetime(def)),$ZodStringFormat.init(inst,def)}),$ZodISODate=$constructor("$ZodISODate",(inst,def)=>{def.pattern??(def.pattern=date),$ZodStringFormat.init(inst,def)}),$ZodISOTime=$constructor("$ZodISOTime",(inst,def)=>{def.pattern??(def.pattern=time(def)),$ZodStringFormat.init(inst,def)}),$ZodISODuration=$constructor("$ZodISODuration",(inst,def)=>{def.pattern??(def.pattern=duration),$ZodStringFormat.init(inst,def)}),$ZodIPv4=$constructor("$ZodIPv4",(inst,def)=>{def.pattern??(def.pattern=ipv4),$ZodStringFormat.init(inst,def)}),ipv6Alphabet=/^[0-9a-fA-F:.]+$/;$ZodIPv6=$constructor("$ZodIPv6",(inst,def)=>{def.pattern??(def.pattern=ipv6),$ZodStringFormat.init(inst,def),inst._zod.check=payload=>{isValidIPv6(payload.value)||payload.issues.push({code:"invalid_format",format:"ipv6",input:payload.value,inst,continue:!def.abort})}}),$ZodCIDRv4=$constructor("$ZodCIDRv4",(inst,def)=>{def.pattern??(def.pattern=cidrv4),$ZodStringFormat.init(inst,def)});$ZodCIDRv6=$constructor("$ZodCIDRv6",(inst,def)=>{def.pattern??(def.pattern=cidrv6),$ZodStringFormat.init(inst,def),inst._zod.check=payload=>{isValidCIDRv6(payload.value)||payload.issues.push({code:"invalid_format",format:"cidrv6",input:payload.value,inst,continue:!def.abort})}});base64Charset=/^[0-9a-zA-Z+/]*={0,2}$/,$ZodBase64=$constructor("$ZodBase64",(inst,def)=>{def.pattern??(def.pattern=base64Charset),$ZodStringFormat.init(inst,def),inst._zod.check=payload=>{isValidBase64(payload.value)||payload.issues.push({code:"invalid_format",format:"base64",input:payload.value,inst,continue:!def.abort})}}),base64urlCharset=/^[A-Za-z0-9_-]*$/;$ZodBase64URL=$constructor("$ZodBase64URL",(inst,def)=>{def.pattern??(def.pattern=base64urlCharset),$ZodStringFormat.init(inst,def),inst._zod.check=payload=>{isValidBase64URL(payload.value)||payload.issues.push({code:"invalid_format",format:"base64url",input:payload.value,inst,continue:!def.abort})}}),$ZodE164=$constructor("$ZodE164",(inst,def)=>{def.pattern??(def.pattern=e164),$ZodStringFormat.init(inst,def)});$ZodJWT=$constructor("$ZodJWT",(inst,def)=>{$ZodStringFormat.init(inst,def),inst._zod.check=payload=>{isValidJWT(payload.value,def.alg)||payload.issues.push({code:"invalid_format",format:"jwt",input:payload.value,inst,continue:!def.abort})}}),$ZodNumber=$constructor("$ZodNumber",(inst,def)=>{$ZodType.init(inst,def),inst._zod.pattern=number,inst._zod.parse=(payload,_ctx)=>{if(def.coerce)try{payload.value=Number(payload.value)}catch{}let input=payload.value;if(typeof input=="number"&&!Number.isNaN(input)&&Number.isFinite(input))return payload;let received=typeof input=="number"?Number.isNaN(input)?"NaN":Number.isFinite(input)?void 0:String(input):void 0;return payload.issues.push({expected:"number",code:"invalid_type",input,inst,...received?{received}:{}}),payload}}),$ZodNumberFormat=$constructor("$ZodNumberFormat",(inst,def)=>{$ZodCheckNumberFormat.init(inst,def),$ZodNumber.init(inst,def)}),$ZodBoolean=$constructor("$ZodBoolean",(inst,def)=>{$ZodType.init(inst,def),inst._zod.pattern=boolean,inst._zod.parse=(payload,_ctx)=>{if(def.coerce)try{payload.value=!!payload.value}catch{}let input=payload.value;return typeof input=="boolean"||payload.issues.push({expected:"boolean",code:"invalid_type",input,inst}),payload}}),$ZodBigInt=$constructor("$ZodBigInt",(inst,def)=>{$ZodType.init(inst,def),inst._zod.pattern=bigint,inst._zod.parse=(payload,_ctx)=>{if(def.coerce)try{payload.value=BigInt(payload.value)}catch{}return typeof payload.value=="bigint"||payload.issues.push({expected:"bigint",code:"invalid_type",input:payload.value,inst}),payload}}),$ZodNull=$constructor("$ZodNull",(inst,def)=>{$ZodType.init(inst,def),inst._zod.pattern=_null,inst._zod.values=new Set([null]),inst._zod.parse=(payload,_ctx)=>{let input=payload.value;return input===null||payload.issues.push({expected:"null",code:"invalid_type",input,inst}),payload}}),$ZodAny=$constructor("$ZodAny",(inst,def)=>{$ZodType.init(inst,def),inst._zod.parse=payload=>payload}),$ZodUnknown=$constructor("$ZodUnknown",(inst,def)=>{$ZodType.init(inst,def),inst._zod.parse=payload=>payload}),$ZodNever=$constructor("$ZodNever",(inst,def)=>{$ZodType.init(inst,def),inst._zod.parse=(payload,_ctx)=>(payload.issues.push({expected:"never",code:"invalid_type",input:payload.value,inst}),payload)}),$ZodDate=$constructor("$ZodDate",(inst,def)=>{$ZodType.init(inst,def),inst._zod.parse=(payload,_ctx)=>{if(def.coerce)try{payload.value=new Date(payload.value)}catch{}let input=payload.value,isDate=input instanceof Date;return isDate&&!Number.isNaN(input.getTime())||payload.issues.push({expected:"date",code:"invalid_type",input,...isDate?{received:"Invalid Date"}:{},inst}),payload}});arraySize=input=>Array.isArray(input)?input.length:-1;$ZodArray=$constructor("$ZodArray",(inst,def)=>{$ZodType.init(inst,def);let memo2=globalConfig.memoizer;memo2?.attach(inst),inst._zod.parse=(payload,ctx)=>{let input=payload.value;if(!Array.isArray(input))return payload.issues.push({expected:"array",code:"invalid_type",input,inst}),payload;payload.value=memo2?memo2.alloc(inst,payload,Array(input.length),ctx):Array(input.length);let proms=[],abortEarly=ctx?.abortEarly;for(let i2=0;i2<input.length;i2++){let item=input[i2],result=def.element._zod.run({value:item,issues:[]},ctx);if(result instanceof Promise)proms.push(result.then(result2=>handleArrayResult(result2,payload,i2)));else if(handleArrayResult(result,payload,i2),abortEarly&&result.issues.length!==0&&aborted(result))break}return proms.length?Promise.all(proms).then(()=>payload):payload},capSize(inst,arraySize)});NO_SYMBOL_KEYS=[];$ZodObject=$constructor("$ZodObject",(inst,def)=>{$ZodType.init(inst,def);let desc=Object.getOwnPropertyDescriptor(def,"shape"),sh=desc?.get?desc.get.raw:def.shape??{};if(sh){let get=()=>{let newSh={...sh};return Object.defineProperty(def,"shape",{value:newSh}),get.raw=newSh,newSh};get.raw=sh,Object.defineProperty(def,"shape",{get})}let _normalized=cached(()=>normalizeDef(def));defineLazyInternal(inst,"propValues",zod=>{let shape=zod.def.shape,propValues={};for(let key in shape){let field=shape[key]._zod;if(field.values){Object.prototype.hasOwnProperty.call(propValues,key)||assignProp(propValues,key,new Set);for(let v2 of field.values)propValues[key].add(v2);field.optin!==void 0&&propValues[key].add(void 0)}}return propValues});let isObject2=isObject,catchall=def.catchall,value,memo2=globalConfig.memoizer;memo2?.attach(inst),inst._zod.parse=(payload,ctx)=>{value??(value=_normalized.value);let input=payload.value;if(!isObject2(input))return payload.issues.push({expected:"object",code:"invalid_type",input,inst}),payload;payload.value=memo2?memo2.alloc(inst,payload,{},ctx):{};let proms=[],shape=value.shape,abortEarly=ctx?.abortEarly,seen=payload.issues.length;for(let key of value.allKeys){if(abortEarly&&payload.issues.length!==seen){if(aborted(payload,seen))break;seen=payload.issues.length}if(key==="__proto__")continue;let el=shape[key],optin=el._zod.optin,optout=el._zod.optout,r=el._zod.run({value:input[key],issues:[]},ctx);r instanceof Promise?proms.push(r.then(r2=>handlePropertyResult(r2,payload,key,input,optin,optout))):handlePropertyResult(r,payload,key,input,optin,optout)}return catchall?handleCatchall(proms,input,payload,ctx,_normalized.value,inst,abortEarly===!0):proms.length?Promise.all(proms).then(()=>payload):payload}}),$ZodObjectJIT=$constructor("$ZodObjectJIT",(inst,def)=>{$ZodObject.init(inst,def);let superParse=inst._zod.parse,_normalized=cached(()=>normalizeDef(def)),memo2=globalConfig.memoizer,generateFastpass=shape=>{let normalized=_normalized.value,syms=normalized.symbolKeys,doc=new Doc(["payload","ctx"],{shape,inst,memo:memo2,syms}),parseStr=k=>`shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`,prefixStr=(id,k)=>`
|
|
10
|
+
};`)(...Object.values(this.closed))}}}});var version2,init_versions=__esm({"../../node_modules/zod/v4/core/versions.js"(){version2={major:4,minor:6,patch:7}}});async function validateAsync2(inst,value){let ctx={async:!0};return toStandardResult(await inst._zod.run({value,issues:[]},ctx),ctx)}function standardProps(inst){return{validate:value=>{let ctx={async:!1};try{let r=inst._zod.run({value,issues:[]},ctx);if(!(r instanceof Promise))return toStandardResult(r,ctx)}catch{}return validateAsync2(inst,value)},vendor:"zod",version:1}}function canParseURL(input){try{return typeof URL<"u"&&typeof URL.canParse=="function"?URL.canParse(input):(new URL(input),!0)}catch{return!1}}function validateURL(trimmed,def){return!("normalize"in def)&&!("hostname"in def)&&!("protocol"in def)?canParseURL(trimmed)||URL_UNPARSEABLE:parseURLObject(trimmed,def)}function parseURLObject(trimmed,def){if(!def.normalize&&def.protocol?.source===httpProtocol.source&&!/^https?:\/\//i.test(trimmed))return URL_BAD_FORMAT;try{if(typeof URL<"u"){let URLStatic=URL;if(typeof URLStatic.parse=="function")return URLStatic.parse(trimmed)??URL_UNPARSEABLE}return new URL(trimmed)}catch{return URL_UNPARSEABLE}}function stripTabAndNewline(value){return value.replace(asciiTabOrNewline,"")}function urlHostnameOk(url2,hostname3){return hostname3.lastIndex=0,hostname3.test(url2.hostname)}function urlProtocolOk(url2,protocol){return protocol.lastIndex=0,protocol.test(url2.protocol.endsWith(":")?url2.protocol.slice(0,-1):url2.protocol)}function isValidIPv6(value){return ipv6Alphabet.test(value)?canParseURL(`http://[${value}]`):!1}function isValidCIDRv6(value){let parts=value.split("/");if(parts.length!==2)return!1;let[address,prefix]=parts;if(!prefix)return!1;let prefixNum=Number(prefix);return`${prefixNum}`!==prefix||prefixNum<0||prefixNum>128?!1:isValidIPv6(address)}function isValidBase64(data){if(data==="")return!0;if(/\s/.test(data)||data.length%4!==0)return!1;try{return atob(data),!0}catch{return!1}}function isValidBase64URL(data){if(!base64urlCharset.test(data))return!1;let base642=data.replace(/[-_]/g,c=>c==="-"?"+":"/"),padded=base642.padEnd(Math.ceil(base642.length/4)*4,"=");return isValidBase64(padded)}function isValidJWT(token,algorithm=null){try{let tokensParts=token.split(".");if(tokensParts.length!==3)return!1;let[header]=tokensParts;if(!header)return!1;let parsedHeader=JSON.parse(atob(header));return!("typ"in parsedHeader&&parsedHeader?.typ!=="JWT"||!parsedHeader.alg||algorithm&&(!("alg"in parsedHeader)||parsedHeader.alg!==algorithm))}catch{return!1}}function capSize(inst,size){let caps=sizeCaps(inst._zod.def.checks);if(!caps.length)return;let cap=Math.min(...caps.map(c=>c[0])),parse4=inst._zod.parse;inst._zod.parse=(payload,ctx)=>{let n=size(payload.value);if(n>cap&&!ctx?.skipChecks&&ctx?.direction!=="backward"){for(let[max,ch]of sizeCaps(inst._zod.def.checks))if(n>max&&ch._zod.def.when(payload)){let start=payload.issues.length;return ch._zod.check(payload),payload.issues[start].continue=!1,attachSchema(payload.issues,start,inst),payload}}return parse4(payload,ctx)}}function handleArrayResult(result,final,index){result.issues.length&&final.issues.push(...prefixIssues(index,result.issues)),final.value[index]=result.value}function handlePropertyResult(result,final,key,input,optin,optout){let isPresent=key in input,isOptionalOut=optout==="optional";if(!(!isPresent&&isOptionalOut&&optin==="optional")){if(result.issues.length){if(optin!==void 0&&isOptionalOut&&!isPresent)return;final.issues.push(...prefixIssues(key,result.issues))}if(!isPresent&&optin===void 0){result.issues.length||final.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[key]});return}result.value===void 0?(isPresent||optin==="defaulted"&&!isOptionalOut)&&(final.value[key]=void 0):final.value[key]=result.value}}function normalizeDef(def){let keys=Object.keys(def.shape),ownSymbols=Object.getOwnPropertySymbols(def.shape),symbolKeys=ownSymbols.length?ownSymbols:NO_SYMBOL_KEYS,allKeys=symbolKeys.length?[...keys,...symbolKeys]:keys;for(let k of allKeys)if(!def.shape?.[k]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${String(k)}": expected a Zod schema`);let okeys=optionalKeys(def.shape);return{...def,allKeys,symbolKeys,keySet:new Set(keys),numKeys:keys.length,optionalKeys:new Set(okeys)}}function handleCatchall(proms,input,payload,ctx,def,inst,abortEarly){let unrecognized=[],keySet=def.keySet,_catchall=def.catchall._zod,t=_catchall.def.type,optin=_catchall.optin,optout=_catchall.optout,seen=0;for(let key in input){if(abortEarly&&payload.issues.length!==seen){if(aborted(payload,seen))break;seen=payload.issues.length}if(keySet.has(key))continue;if(key==="__proto__"){t==="never"&&unrecognized.push(key);continue}if(t==="never"){unrecognized.push(key);continue}let r=_catchall.run({value:input[key],issues:[]},ctx);r instanceof Promise?proms.push(r.then(r2=>handlePropertyResult(r2,payload,key,input,optin,optout))):handlePropertyResult(r,payload,key,input,optin,optout)}return unrecognized.length&&payload.issues.push({code:"unrecognized_keys",keys:unrecognized,input,inst,continue:!0}),proms.length?Promise.all(proms).then(()=>payload):payload}function handleUnionResults(results,final,inst,ctx){for(let result of results)if(result.issues.length===0)return final.value=result.value,final;let nonaborted=results.filter(r=>!aborted(r));return nonaborted.length===1?(final.value=nonaborted[0].value,nonaborted[0]):(final.issues.push({code:"invalid_union",input:final.value,inst,errors:results.map(result=>result.issues.map(iss=>finalizeIssue(iss,ctx,config())))}),final)}function discriminatorMap(def){let map=new Map;for(let option of def.options){let values=option._zod.propValues?.[def.discriminator];if(!values||values.size===0)throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(option)}"`);for(let value of values)if(map.has(value)){if(value!==void 0)throw new Error(`Duplicate discriminator value "${String(value)}"`);map.set(value,null)}else map.set(value,option)}return map}function mergeValues(a,b){if(a===b)return{valid:!0,data:a};if(a instanceof Date&&b instanceof Date&&+a==+b)return{valid:!0,data:a};if(isPlainObject(a)&&isPlainObject(b)){let bKeys=Object.keys(b),sharedKeys=Object.keys(a).filter(key=>bKeys.indexOf(key)!==-1),newObj={...a,...b};Object.prototype.hasOwnProperty.call(newObj,"__proto__")&&delete newObj.__proto__;for(let key of sharedKeys){if(key==="__proto__")continue;let sharedValue=mergeValues(a[key],b[key]);if(!sharedValue.valid)return{valid:!1,mergeErrorPath:[key,...sharedValue.mergeErrorPath]};newObj[key]=sharedValue.data}return{valid:!0,data:newObj}}if(Array.isArray(a)&&Array.isArray(b)){if(a.length!==b.length)return{valid:!1,mergeErrorPath:[]};let newArray=[];for(let index=0;index<a.length;index++){let itemA=a[index],itemB=b[index],sharedValue=mergeValues(itemA,itemB);if(!sharedValue.valid)return{valid:!1,mergeErrorPath:[index,...sharedValue.mergeErrorPath]};newArray.push(sharedValue.data)}return{valid:!0,data:newArray}}return{valid:!1,mergeErrorPath:[]}}function handleIntersectionResults(result,left,right){let unrecKeys=new Map,unrecIssue,keyIssues=new Map,collect=(iss,side)=>{let keys;if(iss.code==="unrecognized_keys"&&!iss.path?.length)unrecIssue??(unrecIssue=iss),keys=iss.keys;else if(iss.code==="invalid_key"&&iss.origin==="record"&&iss.path?.length===1){let k=String(iss.path[0]);keyIssues.has(k)||keyIssues.set(k,iss),keys=[k]}else return!1;for(let k of keys)unrecKeys.has(k)||unrecKeys.set(k,{}),unrecKeys.get(k)[side]=!0;return!0};for(let iss of left.issues)collect(iss,"l")||result.issues.push(iss);for(let iss of right.issues)collect(iss,"r")||result.issues.push(iss);let bothKeys=[...unrecKeys].filter(([,f])=>f.l&&f.r).map(([k])=>k);if(bothKeys.length){let aggregated=unrecIssue?bothKeys.filter(k=>unrecIssue.keys.includes(k)):[];aggregated.length&&result.issues.push({...unrecIssue,keys:aggregated});for(let k of bothKeys)!aggregated.includes(k)&&keyIssues.has(k)&&result.issues.push(keyIssues.get(k))}let merged=mergeValues(left.value,right.value);if(!merged.valid){if(aborted(result))return result;throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(merged.mergeErrorPath)}`)}return result.value=merged.data,result}function handleOptionalResult(payload,result){return payload.value=result.issues.length?void 0:result.value,payload}function handleDefaultResult(payload,def){return payload.value===void 0&&(payload.value=def.defaultValue),payload}function handleNonOptionalResult(payload,inst){return!payload.issues.length&&payload.value===void 0&&payload.issues.push({code:"invalid_type",expected:"nonoptional",input:payload.value,inst}),payload}function handleCatchResult(payload,result,def,ctx){return result.issues.length?(payload.value=def.catchValue({...result,value:payload.value,error:{issues:result.issues.map(iss=>finalizeIssue(iss,ctx,config()))},input:payload.value}),payload):(payload.value=result.value,result.memo&&(payload.memo=!0),payload)}function handlePipeResult(left,next,ctx){return left.issues.some(iss=>iss.code!=="unrecognized_keys")?(left.aborted=!0,left):next._zod.run({value:left.value,issues:left.issues},ctx)}function handleReadonlyResult(payload){return payload.memo||(payload.value=Object.freeze(payload.value)),payload}function handleRefineResult(result,payload,input,inst){if(!result){let _iss={code:"custom",input,inst,path:[...inst._zod.def.path??[]],continue:!inst._zod.def.abort};inst._zod.def.params&&(_iss.params=inst._zod.def.params),payload.issues.push(issue(_iss))}}var $ZodType,toStandardResult,$ZodString,$ZodStringFormat,$ZodGUID,$ZodUUID,$ZodEmail,URL_BAD_FORMAT,URL_UNPARSEABLE,asciiTabOrNewline,$ZodURL,$ZodEmoji,$ZodNanoID,$ZodCUID,$ZodCUID2,$ZodULID,$ZodXID,$ZodKSUID,$ZodISODateTime,$ZodISODate,$ZodISOTime,$ZodISODuration,$ZodIPv4,ipv6Alphabet,$ZodIPv6,$ZodCIDRv4,$ZodCIDRv6,base64Charset,$ZodBase64,base64urlCharset,$ZodBase64URL,$ZodE164,$ZodJWT,$ZodNumber,$ZodNumberFormat,$ZodBoolean,$ZodBigInt,$ZodNull,$ZodAny,$ZodUnknown,$ZodNever,$ZodDate,arraySize,$ZodArray,NO_SYMBOL_KEYS,$ZodObject,$ZodObjectJIT,$ZodUnion,$ZodDiscriminatedUnion,$ZodIntersection,$ZodRecord,$ZodEnum,$ZodLiteral,$ZodTransform,$ZodOptional,$ZodExactOptional,$ZodNullable,$ZodDefault,$ZodPrefault,$ZodNonOptional,$ZodCatch,$ZodPipe,$ZodPreprocess,$ZodReadonly,$ZodCustom,init_schemas=__esm({"../../node_modules/zod/v4/core/schemas.js"(){init_checks();init_core();init_doc();init_regexes();init_util();init_versions();init_util();$ZodType=$constructor("$ZodType",(inst,def)=>{var _a4;inst??(inst={}),inst._zod.def=def,inst._zod.bag=inst._zod.bag||{},inst._zod.version=version2;let defChecks=inst._zod.def.checks,checks=inst._zod.traits.has("$ZodCheck")?[inst,...defChecks??[]]:defChecks?.length?[...defChecks]:[];for(let ch of checks)for(let fn of ch._zod.onattach)fn(inst);if(checks.length===0)(_a4=inst._zod).deferred??(_a4.deferred=[]),inst._zod.deferred?.push(()=>{inst._zod.run=inst._zod.parse});else{let runChecks=(payload,checks2,ctx)=>{if(payload.memo)return payload;let isAborted=aborted(payload),asyncResult;for(let ch of checks2){if(ch._zod.def.when){if(explicitlyAborted(payload)||!ch._zod.def.when(payload))continue}else if(isAborted)continue;let currLen=payload.issues.length,_=ch._zod.check(payload);if(_ instanceof Promise&&ctx?.async===!1)throw new $ZodAsyncError;if(asyncResult||_ instanceof Promise)asyncResult=(asyncResult??Promise.resolve()).then(async()=>{await _,payload.issues.length!==currLen&&(attachSchema(payload.issues,currLen,inst),isAborted||(isAborted=aborted(payload,currLen)))});else{if(payload.issues.length===currLen)continue;attachSchema(payload.issues,currLen,inst),isAborted||(isAborted=aborted(payload,currLen))}}return asyncResult?asyncResult.then(()=>payload):payload},handleCanaryResult=(canary,payload,ctx)=>{if(aborted(canary))return canary.aborted=!0,canary;let checkResult=runChecks(payload,checks,ctx);if(checkResult instanceof Promise){if(ctx.async===!1)throw new $ZodAsyncError;return checkResult.then(checkResult2=>inst._zod.parse(checkResult2,ctx))}return inst._zod.parse(checkResult,ctx)};inst._zod.run=(payload,ctx)=>{if(ctx.skipChecks)return inst._zod.parse(payload,ctx);if(ctx.direction==="backward"){let canary=inst._zod.parse({value:payload.value,issues:[]},{...ctx,skipChecks:!0});return canary instanceof Promise?canary.then(canary2=>handleCanaryResult(canary2,payload,ctx)):handleCanaryResult(canary,payload,ctx)}let result=inst._zod.parse(payload,ctx);if(result instanceof Promise){if(ctx.async===!1)throw new $ZodAsyncError;return result.then(result2=>runChecks(result2,checks,ctx))}return runChecks(result,checks,ctx)}}},{get"~standard"(){return hide(this,"~standard",standardProps(this))},set"~standard"(value){own(this,"~standard",value)}}),toStandardResult=(r,ctx)=>r.issues.length?{issues:r.issues.map(iss=>finalizeIssue(iss,ctx,config()))}:{value:r.value};$ZodString=$constructor("$ZodString",(inst,def)=>{$ZodType.init(inst,def),inst._zod.pattern=def.pattern??anyString,inst._zod.parse=(payload,_)=>{if(def.coerce)try{payload.value=String(payload.value)}catch{}return typeof payload.value=="string"||payload.issues.push({expected:"string",code:"invalid_type",input:payload.value,inst}),payload}}),$ZodStringFormat=$constructor("$ZodStringFormat",(inst,def)=>{$ZodCheckStringFormat.init(inst,def),$ZodString.init(inst,def)}),$ZodGUID=$constructor("$ZodGUID",(inst,def)=>{def.pattern??(def.pattern=guid),$ZodStringFormat.init(inst,def)}),$ZodUUID=$constructor("$ZodUUID",(inst,def)=>{if(def.version){let v2={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[def.version];if(v2===void 0)throw new Error(`Invalid UUID version: "${def.version}"`);def.pattern??(def.pattern=uuid(v2))}else def.pattern??(def.pattern=uuid());$ZodStringFormat.init(inst,def)}),$ZodEmail=$constructor("$ZodEmail",(inst,def)=>{def.pattern??(def.pattern=email),$ZodStringFormat.init(inst,def)}),URL_BAD_FORMAT=1,URL_UNPARSEABLE=2;asciiTabOrNewline=/[\t\n\r]/g;$ZodURL=$constructor("$ZodURL",(inst,def)=>{$ZodStringFormat.init(inst,def),inst._zod.check=payload=>{try{let trimmed=payload.value.trim(),url2=validateURL(trimmed,def);if(url2===URL_BAD_FORMAT){payload.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:payload.value,inst,continue:!def.abort});return}if(url2===URL_UNPARSEABLE){payload.issues.push({code:"invalid_format",format:"url",input:payload.value,inst,continue:!def.abort});return}if(url2===!0){payload.value=stripTabAndNewline(trimmed);return}def.hostname&&!urlHostnameOk(url2,def.hostname)&&payload.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:def.hostname.source,input:payload.value,inst,continue:!def.abort}),def.protocol&&!urlProtocolOk(url2,def.protocol)&&payload.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:def.protocol.source,input:payload.value,inst,continue:!def.abort}),payload.value=def.normalize?url2.href:stripTabAndNewline(trimmed);return}catch{payload.issues.push({code:"invalid_format",format:"url",input:payload.value,inst,continue:!def.abort})}}}),$ZodEmoji=$constructor("$ZodEmoji",(inst,def)=>{def.pattern??(def.pattern=emoji()),$ZodStringFormat.init(inst,def)}),$ZodNanoID=$constructor("$ZodNanoID",(inst,def)=>{if(def.length!==void 0&&(!Number.isInteger(def.length)||def.length<1))throw new Error(`Invalid nanoid length: ${def.length}`);def.pattern??(def.pattern=def.length===void 0?nanoid:nanoidOfLength(def.length)),$ZodStringFormat.init(inst,def)}),$ZodCUID=$constructor("$ZodCUID",(inst,def)=>{def.pattern??(def.pattern=cuid),$ZodStringFormat.init(inst,def)}),$ZodCUID2=$constructor("$ZodCUID2",(inst,def)=>{def.pattern??(def.pattern=cuid2),$ZodStringFormat.init(inst,def)}),$ZodULID=$constructor("$ZodULID",(inst,def)=>{def.pattern??(def.pattern=ulid),$ZodStringFormat.init(inst,def)}),$ZodXID=$constructor("$ZodXID",(inst,def)=>{def.pattern??(def.pattern=xid),$ZodStringFormat.init(inst,def)}),$ZodKSUID=$constructor("$ZodKSUID",(inst,def)=>{def.pattern??(def.pattern=ksuid),$ZodStringFormat.init(inst,def)}),$ZodISODateTime=$constructor("$ZodISODateTime",(inst,def)=>{def.pattern??(def.pattern=datetime(def)),$ZodStringFormat.init(inst,def)}),$ZodISODate=$constructor("$ZodISODate",(inst,def)=>{def.pattern??(def.pattern=date),$ZodStringFormat.init(inst,def)}),$ZodISOTime=$constructor("$ZodISOTime",(inst,def)=>{def.pattern??(def.pattern=time(def)),$ZodStringFormat.init(inst,def)}),$ZodISODuration=$constructor("$ZodISODuration",(inst,def)=>{def.pattern??(def.pattern=duration),$ZodStringFormat.init(inst,def)}),$ZodIPv4=$constructor("$ZodIPv4",(inst,def)=>{def.pattern??(def.pattern=ipv4),$ZodStringFormat.init(inst,def)}),ipv6Alphabet=/^[0-9a-fA-F:.]+$/;$ZodIPv6=$constructor("$ZodIPv6",(inst,def)=>{def.pattern??(def.pattern=ipv6),$ZodStringFormat.init(inst,def),inst._zod.check=payload=>{isValidIPv6(payload.value)||payload.issues.push({code:"invalid_format",format:"ipv6",input:payload.value,inst,continue:!def.abort})}}),$ZodCIDRv4=$constructor("$ZodCIDRv4",(inst,def)=>{def.pattern??(def.pattern=cidrv4),$ZodStringFormat.init(inst,def)});$ZodCIDRv6=$constructor("$ZodCIDRv6",(inst,def)=>{def.pattern??(def.pattern=cidrv6),$ZodStringFormat.init(inst,def),inst._zod.check=payload=>{isValidCIDRv6(payload.value)||payload.issues.push({code:"invalid_format",format:"cidrv6",input:payload.value,inst,continue:!def.abort})}});base64Charset=/^[0-9a-zA-Z+/]*={0,2}$/,$ZodBase64=$constructor("$ZodBase64",(inst,def)=>{def.pattern??(def.pattern=base64Charset),$ZodStringFormat.init(inst,def),inst._zod.check=payload=>{isValidBase64(payload.value)||payload.issues.push({code:"invalid_format",format:"base64",input:payload.value,inst,continue:!def.abort})}}),base64urlCharset=/^[A-Za-z0-9_-]*$/;$ZodBase64URL=$constructor("$ZodBase64URL",(inst,def)=>{def.pattern??(def.pattern=base64urlCharset),$ZodStringFormat.init(inst,def),inst._zod.check=payload=>{isValidBase64URL(payload.value)||payload.issues.push({code:"invalid_format",format:"base64url",input:payload.value,inst,continue:!def.abort})}}),$ZodE164=$constructor("$ZodE164",(inst,def)=>{def.pattern??(def.pattern=e164),$ZodStringFormat.init(inst,def)});$ZodJWT=$constructor("$ZodJWT",(inst,def)=>{$ZodStringFormat.init(inst,def),inst._zod.check=payload=>{isValidJWT(payload.value,def.alg)||payload.issues.push({code:"invalid_format",format:"jwt",input:payload.value,inst,continue:!def.abort})}}),$ZodNumber=$constructor("$ZodNumber",(inst,def)=>{$ZodType.init(inst,def),inst._zod.pattern=number,inst._zod.parse=(payload,_ctx)=>{if(def.coerce)try{payload.value=Number(payload.value)}catch{}let input=payload.value;if(typeof input=="number"&&!Number.isNaN(input)&&Number.isFinite(input))return payload;let received=typeof input=="number"?Number.isNaN(input)?"NaN":Number.isFinite(input)?void 0:String(input):void 0;return payload.issues.push({expected:"number",code:"invalid_type",input,inst,...received?{received}:{}}),payload}}),$ZodNumberFormat=$constructor("$ZodNumberFormat",(inst,def)=>{$ZodCheckNumberFormat.init(inst,def),$ZodNumber.init(inst,def)}),$ZodBoolean=$constructor("$ZodBoolean",(inst,def)=>{$ZodType.init(inst,def),inst._zod.pattern=boolean,inst._zod.parse=(payload,_ctx)=>{if(def.coerce)try{payload.value=!!payload.value}catch{}let input=payload.value;return typeof input=="boolean"||payload.issues.push({expected:"boolean",code:"invalid_type",input,inst}),payload}}),$ZodBigInt=$constructor("$ZodBigInt",(inst,def)=>{$ZodType.init(inst,def),inst._zod.pattern=bigint,inst._zod.parse=(payload,_ctx)=>{if(def.coerce)try{payload.value=BigInt(payload.value)}catch{}return typeof payload.value=="bigint"||payload.issues.push({expected:"bigint",code:"invalid_type",input:payload.value,inst}),payload}}),$ZodNull=$constructor("$ZodNull",(inst,def)=>{$ZodType.init(inst,def),inst._zod.pattern=_null,inst._zod.values=new Set([null]),inst._zod.parse=(payload,_ctx)=>{let input=payload.value;return input===null||payload.issues.push({expected:"null",code:"invalid_type",input,inst}),payload}}),$ZodAny=$constructor("$ZodAny",(inst,def)=>{$ZodType.init(inst,def),inst._zod.parse=payload=>payload}),$ZodUnknown=$constructor("$ZodUnknown",(inst,def)=>{$ZodType.init(inst,def),inst._zod.parse=payload=>payload}),$ZodNever=$constructor("$ZodNever",(inst,def)=>{$ZodType.init(inst,def),inst._zod.parse=(payload,_ctx)=>(payload.issues.push({expected:"never",code:"invalid_type",input:payload.value,inst}),payload)}),$ZodDate=$constructor("$ZodDate",(inst,def)=>{$ZodType.init(inst,def),inst._zod.parse=(payload,_ctx)=>{if(def.coerce)try{payload.value=new Date(payload.value)}catch{}let input=payload.value,isDate=input instanceof Date;return isDate&&!Number.isNaN(input.getTime())||payload.issues.push({expected:"date",code:"invalid_type",input,...isDate?{received:"Invalid Date"}:{},inst}),payload}});arraySize=input=>Array.isArray(input)?input.length:-1;$ZodArray=$constructor("$ZodArray",(inst,def)=>{$ZodType.init(inst,def);let memo2=globalConfig.memoizer;memo2?.attach(inst),inst._zod.parse=(payload,ctx)=>{let input=payload.value;if(!Array.isArray(input))return payload.issues.push({expected:"array",code:"invalid_type",input,inst}),payload;payload.value=memo2?memo2.alloc(inst,payload,Array(input.length),ctx):Array(input.length);let proms=[],abortEarly=ctx?.abortEarly;for(let i2=0;i2<input.length;i2++){let item=input[i2],result=def.element._zod.run({value:item,issues:[]},ctx);if(result instanceof Promise)proms.push(result.then(result2=>handleArrayResult(result2,payload,i2)));else if(handleArrayResult(result,payload,i2),abortEarly&&result.issues.length!==0&&aborted(result))break}return proms.length?Promise.all(proms).then(()=>payload):payload},capSize(inst,arraySize)});NO_SYMBOL_KEYS=[];$ZodObject=$constructor("$ZodObject",(inst,def)=>{$ZodType.init(inst,def);let desc=Object.getOwnPropertyDescriptor(def,"shape"),sh=desc?.get?desc.get.raw:def.shape??{};if(sh){let get=()=>{let newSh={...sh};return Object.defineProperty(def,"shape",{value:newSh}),get.raw=newSh,newSh};get.raw=sh,Object.defineProperty(def,"shape",{get})}let _normalized=cached(()=>normalizeDef(def));defineLazyInternal(inst,"propValues",zod=>{let shape=zod.def.shape,propValues={};for(let key in shape){let field=shape[key]._zod;if(field.values){Object.prototype.hasOwnProperty.call(propValues,key)||assignProp(propValues,key,new Set);for(let v2 of field.values)propValues[key].add(v2);field.optin!==void 0&&propValues[key].add(void 0)}}return propValues});let isObject2=isObject,catchall=def.catchall,value,memo2=globalConfig.memoizer;memo2?.attach(inst),inst._zod.parse=(payload,ctx)=>{value??(value=_normalized.value);let input=payload.value;if(!isObject2(input))return payload.issues.push({expected:"object",code:"invalid_type",input,inst}),payload;payload.value=memo2?memo2.alloc(inst,payload,{},ctx):{};let proms=[],shape=value.shape,abortEarly=ctx?.abortEarly,seen=payload.issues.length;for(let key of value.allKeys){if(abortEarly&&payload.issues.length!==seen){if(aborted(payload,seen))break;seen=payload.issues.length}if(key==="__proto__")continue;let el=shape[key],optin=el._zod.optin,optout=el._zod.optout,r=el._zod.run({value:input[key],issues:[]},ctx);r instanceof Promise?proms.push(r.then(r2=>handlePropertyResult(r2,payload,key,input,optin,optout))):handlePropertyResult(r,payload,key,input,optin,optout)}return catchall?handleCatchall(proms,input,payload,ctx,_normalized.value,inst,abortEarly===!0):proms.length?Promise.all(proms).then(()=>payload):payload}}),$ZodObjectJIT=$constructor("$ZodObjectJIT",(inst,def)=>{$ZodObject.init(inst,def);let superParse=inst._zod.parse,_normalized=cached(()=>normalizeDef(def)),memo2=globalConfig.memoizer,generateFastpass=shape=>{let normalized=_normalized.value,syms=normalized.symbolKeys,doc=new Doc(["payload","ctx"],{shape,inst,memo:memo2,syms}),parseStr=k=>`shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`,prefixStr=(id,k)=>`
|
|
11
11
|
let ${id}_ab = false;
|
|
12
12
|
for (let i = 0; i < ${id}.issues.length; i++) {
|
|
13
13
|
const iss = ${id}.issues[i];
|
|
@@ -139,9 +139,9 @@ $request = [Console]::In.ReadToEnd() | ConvertFrom-Json
|
|
|
139
139
|
|
|
140
140
|
`):"";return clean(summary)||null}return null}function claudeThoughts(message){let content=message?.type==="assistant"?message.message?.content:null;if(!Array.isArray(content))return[];let usesTools=content.some(block=>block?.type==="tool_use");return content.map(block=>block?.type==="thinking"?clean(block.thinking):block?.type==="text"&&usesTools?clean(block.text):"").filter(Boolean)}var renderThought=thought=>`_Thinking\u2026_
|
|
141
141
|
|
|
142
|
-
${thought}`;function createThoughtReporter({post,remove,log:log2,schedule=setTimeout,cancel=clearTimeout,now=Date.now}){let latest=null,shown=null,messageId=null,lastWrite=0,timer=null,closed=!1,writing=Promise.resolve();function write(){return writing=writing.then(async()=>{if(closed||latest==null||latest===shown)return;let previous=messageId;messageId=null,previous!=null&&await remove(previous),messageId=await post(renderThought(latest)),shown=latest,lastWrite=now()}).catch(error2=>log2.warn("[Local agents] thought update failed",error2)),writing}return{thought(text){if(closed||!text||(latest=text,timer!=null))return;let wait=messageId==null?0:Math.max(0,lastWrite+2e3-now());timer=schedule(()=>{timer=null,write()},wait)},async finish(){if(closed=!0,timer!=null&&cancel(timer),timer=null,await writing,messageId!=null)try{await remove(messageId)}catch(error2){log2.warn("[Local agents] could not remove thoughts",error2)}}}}module.exports={claudeThoughts,codexThought,createThoughtReporter,renderThought}}});var require_usage=__commonJS({"../../apps/web/electron/local-tools/usage.js"(exports,module){"use strict";function count(value){return typeof value=="number"&&Number.isFinite(value)&&value>0?Math.round(value):0}function addClaudeUsage(total,message){let usage=message?.usage;if(usage==null||typeof usage!="object")return total;let cost=message.total_cost_usd;return{inputTokens:(total?.inputTokens??0)+count(usage.input_tokens),cachedInputTokens:(total?.cachedInputTokens??0)+count(usage.cache_read_input_tokens),cacheWriteTokens:(total?.cacheWriteTokens??0)+count(usage.cache_creation_input_tokens),outputTokens:(total?.outputTokens??0)+count(usage.output_tokens),reasoningTokens:null,costUsd:typeof cost=="number"&&Number.isFinite(cost)&&cost>=0?cost:total?.costUsd??null}}function codexUsage(tokenUsage){let total=tokenUsage?.total;if(total==null||typeof total!="object")return null;let cached2=count(total.cachedInputTokens);return{inputTokens:Math.max(0,count(total.inputTokens)-cached2),cachedInputTokens:cached2,cacheWriteTokens:0,outputTokens:count(total.outputTokens),reasoningTokens:count(total.reasoningOutputTokens),costUsd:null}}function nonNegativeCost(value){return typeof value=="number"&&Number.isFinite(value)&&value>=0?value:null}function normalizeClaudeCheckpoint(previous){let saved=previous?.usage;return saved==null?null:{sessionId:typeof previous.sessionId=="string"?previous.sessionId:null,sessionCostUsd:nonNegativeCost(previous.sessionCostUsd),usage:{inputTokens:count(saved.inputTokens),cachedInputTokens:count(saved.cachedInputTokens),cacheWriteTokens:count(saved.cacheWriteTokens),outputTokens:count(saved.outputTokens),reasoningTokens:null,costUsd:nonNegativeCost(saved.costUsd)}}}function resolvePriorSessionCost(normalized,sessionId,baseline){return normalized?.sessionId===sessionId?normalized?.sessionCostUsd??0:sessionId!=null&&baseline?.sessionId===sessionId?nonNegativeCost(baseline?.usage?.costUsd)??0:0}function checkpointClaudeUsage(previous,current,sessionId,baseline=null){let normalized=normalizeClaudeCheckpoint(previous);if(current==null)return normalized;let before=normalized?.usage,sameSession=normalized?.sessionId===sessionId,priorSessionCost=resolvePriorSessionCost(normalized,sessionId,baseline);return{sessionId,sessionCostUsd:current.costUsd??(sameSession?normalized?.sessionCostUsd??null:null),usage:{inputTokens:(before?.inputTokens??0)+current.inputTokens,cachedInputTokens:(before?.cachedInputTokens??0)+current.cachedInputTokens,cacheWriteTokens:(before?.cacheWriteTokens??0)+current.cacheWriteTokens,outputTokens:(before?.outputTokens??0)+current.outputTokens,reasoningTokens:null,costUsd:current.costUsd==null?before?.costUsd??null:(before?.costUsd??0)+Math.max(0,current.costUsd-priorSessionCost)}}}function subtractUsageBaseline(usage,sessionId,baseline=null){if(usage==null||typeof usage!="object")return null;if(sessionId==null||baseline?.sessionId!==sessionId||baseline?.usage==null)return usage;let base=baseline.usage,baseCost=typeof base.costUsd=="number"&&Number.isFinite(base.costUsd)&&base.costUsd>=0?base.costUsd:0;return{inputTokens:Math.max(0,count(usage.inputTokens)-count(base.inputTokens)),cachedInputTokens:Math.max(0,count(usage.cachedInputTokens)-count(base.cachedInputTokens)),cacheWriteTokens:Math.max(0,count(usage.cacheWriteTokens)-count(base.cacheWriteTokens)),outputTokens:Math.max(0,count(usage.outputTokens)-count(base.outputTokens)),reasoningTokens:usage.reasoningTokens==null?null:Math.max(0,count(usage.reasoningTokens)-count(base.reasoningTokens)),costUsd:typeof usage.costUsd=="number"&&Number.isFinite(usage.costUsd)&&usage.costUsd>=0?Math.max(0,usage.costUsd-baseCost):null}}module.exports={addClaudeUsage,codexUsage,checkpointClaudeUsage,subtractUsageBaseline}}});var require_last_error_line=__commonJS({"../../apps/web/electron/local-tools/last-error-line.js"(exports,module){"use strict";var{stripVTControlCharacters}=__require("node:util"),MAX_LINE_LENGTH=240,LOCATION_ONLY=/^(in|at) `[^`]+`\.?$/,MAX_BUFFER_LENGTH=8e3,SECRET_PATTERNS=[/\b(?:sk|ghp|gho|ghs|xox[abp]|pk)[-_][A-Za-z0-9_-]{8,}/g,/\bBearer\s+[A-Za-z0-9._~+/=-]{8,}/gi,/\b(token|key|secret|password)=\S+/gi];function clean(line){let text=stripVTControlCharacters(line).trim();for(let pattern of SECRET_PATTERNS)text=text.replace(pattern,"[redacted]");return text.length>MAX_LINE_LENGTH?`${text.slice(0,MAX_LINE_LENGTH-1)}\u2026`:text}function createLastErrorLine(){let buffer="";return{push(chunk){buffer=`${buffer}${String(chunk)}`.slice(-MAX_BUFFER_LENGTH)},read(){let lines=buffer.split(/\r?\n/).map(line=>stripVTControlCharacters(line).trim()).filter(Boolean),last=lines.at(-1);if(last==null)return null;let before=lines.at(-2);return clean(LOCATION_ONLY.test(last)&&before!=null?`${before} ${last}`:last)}}}function exitMessage(tool,status,lastLine){let exited=`${tool} exited (${status})`,line=lastLine.read();return line==null?exited:`${exited}: ${line}`}module.exports={createLastErrorLine,exitMessage}}});var require_toolchain=__commonJS({"../../apps/web/electron/local-tools/toolchain.js"(exports,module){"use strict";var fs=__require("fs"),os=__require("os"),path=__require("path");function commandFileNames(name,{platform=process.platform,env=process.env}={}){return platform!=="win32"||path.extname(name)!==""?[name]:(env.PATHEXT||".COM;.EXE;.BAT;.CMD").split(";").filter(extension=>extension.startsWith(".")).map(extension=>`${name}${extension.toLowerCase()}`)}function isRunnableFile(candidate){try{return fs.accessSync(candidate,fs.constants.X_OK),fs.statSync(candidate).isFile()}catch{return!1}}function findCommand2(name,searchPath=process.env.PATH??"",skip=null,options={}){let names=commandFileNames(name,options),resolvedSkip=skip!=null?path.resolve(skip):null,seenDirs=new Set;for(let dir of searchPath.split(path.delimiter)){if(!dir)continue;let resolvedDir=path.resolve(dir);if(!(resolvedDir===resolvedSkip||seenDirs.has(resolvedDir))){seenDirs.add(resolvedDir);for(let fileName of names){let candidate=path.join(dir,fileName);if(isRunnableFile(candidate))return candidate}}}return null}var TOOLCHAIN_COMMANDS=["node","pnpm","npm","npx","corepack","git","gh","aws","gcloud","kubectl","terraform","python3","python","uv","go","cargo","rustup"];function toolchainInstallRoots(home,env){let dataHome=env.XDG_DATA_HOME||path.join(home,".local","share"),stateHome=env.XDG_STATE_HOME||path.join(home,".local","state");return[env.FNM_DIR,env.FNM_MULTISHELL_PATH?path.dirname(env.FNM_MULTISHELL_PATH):null,env.NVM_DIR,env.VOLTA_HOME,env.ASDF_DATA_DIR,env.MISE_DATA_DIR,env.BUN_INSTALL,env.PNPM_HOME,env.RUSTUP_HOME,env.GOROOT,env.GOPATH,env.CLOUDSDK_ROOT_DIR,path.join(dataHome,"fnm"),path.join(stateHome,"fnm_multishells"),path.join(dataHome,"mise"),path.join(dataHome,"pnpm"),path.join(dataHome,"uv","python"),path.join(home,".fnm"),path.join(home,".nvm"),path.join(home,".volta"),path.join(home,".asdf"),path.join(home,".bun"),path.join(home,".rustup"),path.join(home,"go"),path.join(home,"google-cloud-sdk"),path.join(home,"Library","pnpm"),"/opt/homebrew","/usr/local","/opt/local","/nix"].filter(p=>typeof p=="string"&&path.isAbsolute(p))}function isWithin(child,parent){let relative2=path.relative(parent,child);return relative2===""||!relative2.startsWith("..")&&!path.isAbsolute(relative2)}function realPathOf(p){try{return fs.realpathSync(p)}catch{return null}}function toolchainRoots(searchPath,{home=os.homedir(),env=process.env,skip=null}={}){let realPathCache=new Map,cachedRealPath=p=>{if(realPathCache.has(p))return realPathCache.get(p);let real=realPathOf(p);return realPathCache.set(p,real),real},installs=toolchainInstallRoots(home,env).flatMap(root=>{let real=cachedRealPath(root);return real!=null&&real!==root?[root,real]:[root]}),sortedInstalls=[...new Set(installs)].sort((a,b)=>b.length-a.length),rootOf=p=>sortedInstalls.find(root=>isWithin(p,root))??path.dirname(p),roots=new Set,visitedDirs=new Set,foundRust=!1;for(let name of TOOLCHAIN_COMMANDS){let found=findCommand2(name,searchPath,skip);if(found==null)continue;(name==="cargo"||name==="rustup")&&(foundRust=!0);let seen=[found],current=found;for(let hop=0;hop<40;hop+=1){let target;try{target=fs.readlinkSync(current)}catch{break}current=path.resolve(path.dirname(current),target),seen.push(current)}for(let dir=path.dirname(found);dir!==path.dirname(dir)&&!visitedDirs.has(dir);dir=path.dirname(dir)){visitedDirs.add(dir);let real2=cachedRealPath(dir);real2!=null&&real2!==dir&&seen.push(real2)}let real=cachedRealPath(found);real!=null&&seen.push(real);for(let p of seen)roots.add(rootOf(p))}if(foundRust){let rustup=env.RUSTUP_HOME||path.join(home,".rustup"),realRustup=cachedRealPath(rustup);realRustup!=null&&(roots.add(rustup),realRustup!==rustup&&roots.add(realRustup))}let uvPython=path.join(env.XDG_DATA_HOME||path.join(home,".local","share"),"uv","python");cachedRealPath(uvPython)!=null&&roots.add(uvPython);let corepack=env.COREPACK_HOME||path.join(env.XDG_CACHE_HOME||path.join(home,".cache"),"node","corepack");cachedRealPath(corepack)!=null&&roots.add(corepack);let aws=path.join(home,".aws");return cachedRealPath(aws)!=null&&roots.add(aws),[...roots]}function listDir(dir){try{return fs.readdirSync(dir)}catch{return[]}}function openableToolchainRoots(roots,closed,home,readdir4=listDir){let open3=[],visit=(root,depth)=>{if(!closed.some(p=>isWithin(root,p))){if(!closed.some(p=>isWithin(p,root))){open3.push(root);return}if(depth<3&&isWithin(root,home)&&root!==home)for(let entry of readdir4(root))visit(path.join(root,entry),depth+1)}};for(let root of new Set(roots))path.isAbsolute(root)&&!isWithin(home,root)&&visit(root,0);return[...new Set(open3)]}module.exports={commandFileNames,findCommand:findCommand2,openableToolchainRoots,toolchainRoots}}});var require_windows=__commonJS({"../../apps/web/electron/local-tools/windows.js"(exports,module){"use strict";var childProcess=__require("child_process"),{createHash:createHash6}=__require("crypto"),fs=__require("fs"),os=__require("os"),path=__require("path"),{findCommand:findCommand2}=require_toolchain();function windowsEnv(env){let out={},searchPath;for(let[key,value]of Object.entries(env))key.toUpperCase()==="PATH"?searchPath??=value:out[key]=value;return searchPath!=null&&(out.PATH=searchPath),out}var NPM_SCRIPT_TARGET=/"%(?:~dp0|dp0%)\\?([^"%]+\.[cm]?js)"/i;function resolveWindowsCommand(name,env,{readFile:readFile7=file=>fs.readFileSync(file,"utf8"),exists=fs.existsSync}={}){let searchPath=env.PATH??"",found=findCommand2(name,searchPath,null,{platform:"win32",env});if(found==null)return null;let extension=path.extname(found).toLowerCase();if(extension===".exe"||extension===".com")return{file:found,args:[]};if(extension!==".cmd"&&extension!==".bat")return null;let script;try{script=NPM_SCRIPT_TARGET.exec(readFile7(found))?.[1]}catch{return null}if(script==null)return null;let dir=path.dirname(found),besideNode=path.join(dir,"node.exe"),node2=exists(besideNode)?besideNode:findCommand2("node",searchPath,null,{platform:"win32",env});return node2==null?null:{file:node2,args:[path.join(dir,script)]}}function windowsSpawn(spawn5){return(command,args=[],options={})=>{let resolved=!path.isAbsolute(command)&&!/[\\/]/.test(command)?resolveWindowsCommand(command,windowsEnv(options.env??process.env)):null,spawnOptions={...options,windowsHide:!0};return resolved==null?spawn5(command,args,spawnOptions):spawn5(resolved.file,[...resolved.args,...args],spawnOptions)}}function windowsAccountGuardSegment(env=process.env,username=os.userInfo().username){let owner=(env.USERDOMAIN?`${env.USERDOMAIN}\\${username}`:username).toLowerCase();return`user-${createHash6("sha256").update(owner).digest("hex").slice(0,16)}`}function windowsGuardRoot(env=process.env,{username=os.userInfo().username}={}){return path.win32.join(env.ProgramData||"C:\\ProgramData","Ando","task-git",windowsAccountGuardSegment(env,username))}function windowsFallbackGuardRoot(env=process.env,{username=os.userInfo().username}={}){return path.win32.join(env.ProgramData||"C:\\ProgramData",`Ando-task-git-${windowsAccountGuardSegment(env,username)}`)}function lockWindowsToken(tokenFile,{run:run2=childProcess.spawnSync,env=process.env,username=os.userInfo().username,remove=fs.rmSync}={}){let owner=env.USERDOMAIN?`${env.USERDOMAIN}\\${username}`:username,icacls=path.win32.join(env.SystemRoot||"C:\\Windows","System32","icacls.exe");return run2(icacls,[tokenFile,"/inheritance:r","/grant:r",`${owner}:F`,"*S-1-5-18:F","CodexSandboxUsers:R"],{encoding:"utf8",timeout:1e4,windowsHide:!0})?.status===0?!0:(remove(tokenFile,{force:!0}),!1)}function letSandboxReadGuard(dir,{run:run2=childProcess.spawnSync,env=process.env}={}){let icacls=path.win32.join(env.SystemRoot||"C:\\Windows","System32","icacls.exe");return run2(icacls,[dir,"/grant","CodexSandboxUsers:(OI)(CI)RX","/T"],{encoding:"utf8",timeout:1e4,windowsHide:!0})?.status===0}var LEGACY_WINDOWS_GUARD_MAX_AGE_MS=1440*6e4,WINDOWS_LOCK_GUARD_ROOT_SCRIPT=["$ErrorActionPreference = 'Stop'","$root = $env:ANDO_GUARD_DIR","$parentCount = [int]$env:ANDO_GUARD_PARENT_COUNT","$maxAgeMs = [double]$env:ANDO_LEGACY_GUARD_MAX_AGE_MS","$me = [Security.Principal.WindowsIdentity]::GetCurrent().User","$sys = New-Object Security.Principal.SecurityIdentifier 'S-1-5-18'","$admins = New-Object Security.Principal.SecurityIdentifier 'S-1-5-32-544'","$trusted = @($me.Value, $sys.Value, $admins.Value)","$parent1 = Split-Path -Parent $root","$parents = @($parent1)","if ($parentCount -ge 2) {"," $parent2 = Split-Path -Parent $parent1"," if ($parent2 -and $parent2 -ne $parent1) { $parents = @($parent2, $parent1) }","}","foreach ($p in @($parents + @($root))) {"," $item = Get-Item -LiteralPath $p -Force"," if (-not $item.PSIsContainer -or ($item.Attributes -band [IO.FileAttributes]::ReparsePoint)) {",' [Console]::Error.WriteLine("reparse or non-directory: $p")'," exit 2"," }","}","$danger = [int]([Security.AccessControl.FileSystemRights]::DeleteSubdirectoriesAndFiles -bor [Security.AccessControl.FileSystemRights]::Delete -bor [Security.AccessControl.FileSystemRights]::TakeOwnership -bor [Security.AccessControl.FileSystemRights]::ChangePermissions) -bor 0x10000000","foreach ($parent in $parents) {"," $pacl = Get-Acl -LiteralPath $parent"," $pOwner = $pacl.GetOwner([Security.Principal.SecurityIdentifier]).Value"," if ($trusted -notcontains $pOwner) {",' [Console]::Error.WriteLine("untrusted parent owner on ${parent}: $pOwner")'," exit 5"," }"," foreach ($rule in $pacl.GetAccessRules($true, $true, [Security.Principal.SecurityIdentifier])) {"," if ($rule.AccessControlType -ne [Security.AccessControl.AccessControlType]::Allow) { continue }"," $sid = $rule.IdentityReference.Value"," if ($trusted -contains $sid -or $sid -eq 'S-1-3-0') { continue }"," if (([int]$rule.FileSystemRights -band $danger) -ne 0) {",' [Console]::Error.WriteLine("unsafe parent ACL on $parent for $sid ($($rule.FileSystemRights))")'," exit 3"," }"," }","}","$acl = Get-Acl -LiteralPath $root","$ownerSid = $acl.GetOwner([Security.Principal.SecurityIdentifier]).Value","if ($trusted -notcontains $ownerSid) {",' [Console]::Error.WriteLine("untrusted root owner: $ownerSid")'," exit 4","}","$acl.SetAccessRuleProtection($true, $false)","foreach ($existing in @($acl.GetAccessRules($true, $true, [Security.Principal.SecurityIdentifier]))) {"," [void]$acl.RemoveAccessRuleSpecific($existing)","}","$inh = [Security.AccessControl.InheritanceFlags]'ContainerInherit,ObjectInherit'","$prop = [Security.AccessControl.PropagationFlags]::None","$allow = [Security.AccessControl.AccessControlType]::Allow","$full = [Security.AccessControl.FileSystemRights]::FullControl","foreach ($sid in @($me, $sys, $admins)) {"," $acl.AddAccessRule((New-Object Security.AccessControl.FileSystemAccessRule($sid, $full, $inh, $prop, $allow)))","}","Set-Acl -LiteralPath $root -AclObject $acl","if ($parentCount -ge 2) {"," try {"," $cmdLines = @(Get-CimInstance Win32_Process -ErrorAction Stop | ForEach-Object { $_.CommandLine } | Where-Object { $_ })"," $hasLegacyConnector = ($cmdLines | Where-Object { $_ -match 'ando-machine|@ando/machine|machine-connector' }).Count -gt 0"," if (-not $hasLegacyConnector) {"," $cutoff = [DateTime]::UtcNow.AddMilliseconds(-$maxAgeMs)"," foreach ($child in Get-ChildItem -LiteralPath $parent1 -Force -ErrorAction SilentlyContinue) {"," if (-not $child.PSIsContainer -or ($child.Attributes -band [IO.FileAttributes]::ReparsePoint)) { continue }"," if ($child.Name -notmatch '^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$') { continue }"," if ($child.LastWriteTimeUtc -gt $cutoff) { continue }"," if (($cmdLines | Where-Object { $_.IndexOf($child.Name, [StringComparison]::OrdinalIgnoreCase) -ge 0 }).Count -gt 0) { continue }"," try {"," $cacl = Get-Acl -LiteralPath $child.FullName"," if ($cacl.GetOwner([Security.Principal.SecurityIdentifier]).Value -ne $ownerSid) { continue }"," $skipChild = $false"," foreach ($desc in Get-ChildItem -LiteralPath $child.FullName -Recurse -Force -ErrorAction SilentlyContinue) {"," if (($desc.Attributes -band [IO.FileAttributes]::ReparsePoint) -or ($desc.LastWriteTimeUtc -gt $cutoff)) {"," $skipChild = $true"," break"," }"," }"," if (-not $skipChild) { [IO.Directory]::Delete($child.FullName, $true) }"," } catch {}"," }"," }"," } catch {}","}"].join(`
|
|
142
|
+
${thought}`;function createThoughtReporter({post,remove,log:log2,schedule=setTimeout,cancel=clearTimeout,now=Date.now}){let latest=null,shown=null,messageId=null,lastWrite=0,timer=null,closed=!1,writing=Promise.resolve();function write(){return writing=writing.then(async()=>{if(closed||latest==null||latest===shown)return;let previous=messageId;messageId=null,previous!=null&&await remove(previous),messageId=await post(renderThought(latest)),shown=latest,lastWrite=now()}).catch(error2=>log2.warn("[Local agents] thought update failed",error2)),writing}return{thought(text){if(closed||!text||(latest=text,timer!=null))return;let wait=messageId==null?0:Math.max(0,lastWrite+2e3-now());timer=schedule(()=>{timer=null,write()},wait)},async finish(){if(closed=!0,timer!=null&&cancel(timer),timer=null,await writing,messageId!=null)try{await remove(messageId)}catch(error2){log2.warn("[Local agents] could not remove thoughts",error2)}}}}module.exports={claudeThoughts,codexThought,createThoughtReporter,renderThought}}});var require_usage=__commonJS({"../../apps/web/electron/local-tools/usage.js"(exports,module){"use strict";function count(value){return typeof value=="number"&&Number.isFinite(value)&&value>0?Math.round(value):0}function addClaudeUsage(total,message){let usage=message?.usage;if(usage==null||typeof usage!="object")return total;let cost=message.total_cost_usd;return{inputTokens:(total?.inputTokens??0)+count(usage.input_tokens),cachedInputTokens:(total?.cachedInputTokens??0)+count(usage.cache_read_input_tokens),cacheWriteTokens:(total?.cacheWriteTokens??0)+count(usage.cache_creation_input_tokens),outputTokens:(total?.outputTokens??0)+count(usage.output_tokens),reasoningTokens:null,costUsd:typeof cost=="number"&&Number.isFinite(cost)&&cost>=0?cost:total?.costUsd??null}}function codexUsage(tokenUsage){let total=tokenUsage?.total;if(total==null||typeof total!="object")return null;let cached2=count(total.cachedInputTokens);return{inputTokens:Math.max(0,count(total.inputTokens)-cached2),cachedInputTokens:cached2,cacheWriteTokens:0,outputTokens:count(total.outputTokens),reasoningTokens:count(total.reasoningOutputTokens),costUsd:null}}function nonNegativeCost(value){return typeof value=="number"&&Number.isFinite(value)&&value>=0?value:null}function normalizeClaudeCheckpoint(previous){let saved=previous?.usage;return saved==null?null:{sessionId:typeof previous.sessionId=="string"?previous.sessionId:null,sessionCostUsd:nonNegativeCost(previous.sessionCostUsd),usage:{inputTokens:count(saved.inputTokens),cachedInputTokens:count(saved.cachedInputTokens),cacheWriteTokens:count(saved.cacheWriteTokens),outputTokens:count(saved.outputTokens),reasoningTokens:null,costUsd:nonNegativeCost(saved.costUsd)}}}function resolvePriorSessionCost(normalized,sessionId,baseline){return normalized?.sessionId===sessionId?normalized?.sessionCostUsd??0:sessionId!=null&&baseline?.sessionId===sessionId?nonNegativeCost(baseline?.usage?.costUsd)??0:0}function checkpointClaudeUsage(previous,current,sessionId,baseline=null){let normalized=normalizeClaudeCheckpoint(previous);if(current==null)return normalized;let before=normalized?.usage,sameSession=normalized?.sessionId===sessionId,priorSessionCost=resolvePriorSessionCost(normalized,sessionId,baseline);return{sessionId,sessionCostUsd:current.costUsd??(sameSession?normalized?.sessionCostUsd??null:null),usage:{inputTokens:(before?.inputTokens??0)+current.inputTokens,cachedInputTokens:(before?.cachedInputTokens??0)+current.cachedInputTokens,cacheWriteTokens:(before?.cacheWriteTokens??0)+current.cacheWriteTokens,outputTokens:(before?.outputTokens??0)+current.outputTokens,reasoningTokens:null,costUsd:current.costUsd==null?before?.costUsd??null:(before?.costUsd??0)+Math.max(0,current.costUsd-priorSessionCost)}}}function subtractUsageBaseline(usage,sessionId,baseline=null){if(usage==null||typeof usage!="object")return null;if(sessionId==null||baseline?.sessionId!==sessionId||baseline?.usage==null)return usage;let base=baseline.usage,baseCost=typeof base.costUsd=="number"&&Number.isFinite(base.costUsd)&&base.costUsd>=0?base.costUsd:0;return{inputTokens:Math.max(0,count(usage.inputTokens)-count(base.inputTokens)),cachedInputTokens:Math.max(0,count(usage.cachedInputTokens)-count(base.cachedInputTokens)),cacheWriteTokens:Math.max(0,count(usage.cacheWriteTokens)-count(base.cacheWriteTokens)),outputTokens:Math.max(0,count(usage.outputTokens)-count(base.outputTokens)),reasoningTokens:usage.reasoningTokens==null?null:Math.max(0,count(usage.reasoningTokens)-count(base.reasoningTokens)),costUsd:typeof usage.costUsd=="number"&&Number.isFinite(usage.costUsd)&&usage.costUsd>=0?Math.max(0,usage.costUsd-baseCost):null}}module.exports={addClaudeUsage,codexUsage,checkpointClaudeUsage,subtractUsageBaseline}}});var require_last_error_line=__commonJS({"../../apps/web/electron/local-tools/last-error-line.js"(exports,module){"use strict";var{stripVTControlCharacters}=__require("node:util"),MAX_LINE_LENGTH=240,LOCATION_ONLY=/^(in|at) `[^`]+`\.?$/,MAX_BUFFER_LENGTH=8e3,SECRET_PATTERNS=[/\b(?:sk|ghp|gho|ghs|xox[abp]|pk)[-_][A-Za-z0-9_-]{8,}/g,/\bBearer\s+[A-Za-z0-9._~+/=-]{8,}/gi,/\b(token|key|secret|password)=\S+/gi];function clean(line){let text=stripVTControlCharacters(line).trim();for(let pattern of SECRET_PATTERNS)text=text.replace(pattern,"[redacted]");return text.length>MAX_LINE_LENGTH?`${text.slice(0,MAX_LINE_LENGTH-1)}\u2026`:text}function createLastErrorLine(){let buffer="";return{push(chunk){buffer=`${buffer}${String(chunk)}`.slice(-MAX_BUFFER_LENGTH)},read(){let lines=buffer.split(/\r?\n/).map(line=>stripVTControlCharacters(line).trim()).filter(Boolean),last=lines.at(-1);if(last==null)return null;let before=lines.at(-2);return clean(LOCATION_ONLY.test(last)&&before!=null?`${before} ${last}`:last)}}}function exitMessage(tool,status,lastLine){let exited=`${tool} exited (${status})`,line=lastLine.read();return line==null?exited:`${exited}: ${line}`}module.exports={createLastErrorLine,exitMessage}}});var require_toolchain=__commonJS({"../../apps/web/electron/local-tools/toolchain.js"(exports,module){"use strict";var fs=__require("fs"),os=__require("os"),path=__require("path");function commandFileNames(name,{platform=process.platform,env=process.env}={}){return platform!=="win32"||path.extname(name)!==""?[name]:(env.PATHEXT||".COM;.EXE;.BAT;.CMD").split(";").filter(extension=>extension.startsWith(".")).map(extension=>`${name}${extension.toLowerCase()}`)}function isRunnableFile(candidate){try{return fs.accessSync(candidate,fs.constants.X_OK),fs.statSync(candidate).isFile()}catch{return!1}}function findCommand2(name,searchPath=process.env.PATH??"",skip=null,options={}){let names=commandFileNames(name,options),resolvedSkip=skip!=null?path.resolve(skip):null,seenDirs=new Set;for(let dir of searchPath.split(path.delimiter)){if(!dir)continue;let resolvedDir=path.resolve(dir);if(!(resolvedDir===resolvedSkip||seenDirs.has(resolvedDir))){seenDirs.add(resolvedDir);for(let fileName of names){let candidate=path.join(dir,fileName);if(isRunnableFile(candidate))return candidate}}}return null}var TOOLCHAIN_COMMANDS=["node","pnpm","npm","npx","corepack","git","gh","aws","gcloud","kubectl","terraform","python3","python","uv","go","cargo","rustup"];function toolchainInstallRoots(home,env){let dataHome=env.XDG_DATA_HOME||path.join(home,".local","share"),stateHome=env.XDG_STATE_HOME||path.join(home,".local","state");return[env.FNM_DIR,env.FNM_MULTISHELL_PATH?path.dirname(env.FNM_MULTISHELL_PATH):null,env.NVM_DIR,env.VOLTA_HOME,env.ASDF_DATA_DIR,env.MISE_DATA_DIR,env.BUN_INSTALL,env.PNPM_HOME,env.RUSTUP_HOME,env.GOROOT,env.GOPATH,env.CLOUDSDK_ROOT_DIR,path.join(dataHome,"fnm"),path.join(stateHome,"fnm_multishells"),path.join(dataHome,"mise"),path.join(dataHome,"pnpm"),path.join(dataHome,"uv","python"),path.join(home,".fnm"),path.join(home,".nvm"),path.join(home,".volta"),path.join(home,".asdf"),path.join(home,".bun"),path.join(home,".rustup"),path.join(home,"go"),path.join(home,"google-cloud-sdk"),path.join(home,"Library","pnpm"),"/opt/homebrew","/usr/local","/opt/local","/nix"].filter(p=>typeof p=="string"&&path.isAbsolute(p))}function isWithin(child,parent){let relative2=path.relative(parent,child);return relative2===""||!relative2.startsWith("..")&&!path.isAbsolute(relative2)}function realPathOf(p){try{return fs.realpathSync(p)}catch{return null}}function toolchainRoots(searchPath,{home=os.homedir(),env=process.env,skip=null}={}){let realPathCache=new Map,cachedRealPath=p=>{if(realPathCache.has(p))return realPathCache.get(p);let real=realPathOf(p);return realPathCache.set(p,real),real},installs=toolchainInstallRoots(home,env).flatMap(root=>{let real=cachedRealPath(root);return real!=null&&real!==root?[root,real]:[root]}),sortedInstalls=[...new Set(installs)].sort((a,b)=>b.length-a.length),rootOf=p=>sortedInstalls.find(root=>isWithin(p,root))??path.dirname(p),roots=new Set,visitedDirs=new Set,foundRust=!1;for(let name of TOOLCHAIN_COMMANDS){let found=findCommand2(name,searchPath,skip);if(found==null)continue;(name==="cargo"||name==="rustup")&&(foundRust=!0);let seen=[found],current=found;for(let hop=0;hop<40;hop+=1){let target;try{target=fs.readlinkSync(current)}catch{break}current=path.resolve(path.dirname(current),target),seen.push(current)}for(let dir=path.dirname(found);dir!==path.dirname(dir)&&!visitedDirs.has(dir);dir=path.dirname(dir)){visitedDirs.add(dir);let real2=cachedRealPath(dir);real2!=null&&real2!==dir&&seen.push(real2)}let real=cachedRealPath(found);real!=null&&seen.push(real);for(let p of seen)roots.add(rootOf(p))}if(foundRust){let rustup=env.RUSTUP_HOME||path.join(home,".rustup"),realRustup=cachedRealPath(rustup);realRustup!=null&&(roots.add(rustup),realRustup!==rustup&&roots.add(realRustup))}let uvPython=path.join(env.XDG_DATA_HOME||path.join(home,".local","share"),"uv","python");cachedRealPath(uvPython)!=null&&roots.add(uvPython);let corepack=env.COREPACK_HOME||path.join(env.XDG_CACHE_HOME||path.join(home,".cache"),"node","corepack");cachedRealPath(corepack)!=null&&roots.add(corepack);let aws=path.join(home,".aws");return cachedRealPath(aws)!=null&&roots.add(aws),[...roots]}function listDir(dir){try{return fs.readdirSync(dir)}catch{return[]}}function openableToolchainRoots(roots,closed,home,readdir4=listDir){let open3=[],visit=(root,depth)=>{if(!closed.some(p=>isWithin(root,p))){if(!closed.some(p=>isWithin(p,root))){open3.push(root);return}if(depth<3&&isWithin(root,home)&&root!==home)for(let entry of readdir4(root))visit(path.join(root,entry),depth+1)}};for(let root of new Set(roots))path.isAbsolute(root)&&!isWithin(home,root)&&visit(root,0);return[...new Set(open3)]}module.exports={commandFileNames,findCommand:findCommand2,openableToolchainRoots,toolchainRoots}}});var require_windows=__commonJS({"../../apps/web/electron/local-tools/windows.js"(exports,module){"use strict";var childProcess=__require("child_process"),{createHash:createHash6}=__require("crypto"),fs=__require("fs"),os=__require("os"),path=__require("path"),{findCommand:findCommand2}=require_toolchain();function windowsEnv(env){let out={},searchPath;for(let[key,value]of Object.entries(env))key.toUpperCase()==="PATH"?searchPath??=value:out[key]=value;return searchPath!=null&&(out.PATH=searchPath),out}var NPM_SCRIPT_TARGET=/"%(?:~dp0|dp0%)\\?([^"%]+\.[cm]?js)"/i;function resolveWindowsCommand(name,env,{readFile:readFile7=file=>fs.readFileSync(file,"utf8"),exists=fs.existsSync}={}){let searchPath=env.PATH??"",found=findCommand2(name,searchPath,null,{platform:"win32",env});if(found==null)return null;let extension=path.extname(found).toLowerCase();if(extension===".exe"||extension===".com")return{file:found,args:[]};if(extension!==".cmd"&&extension!==".bat")return null;let script;try{script=NPM_SCRIPT_TARGET.exec(readFile7(found))?.[1]}catch{return null}if(script==null)return null;let dir=path.dirname(found),besideNode=path.join(dir,"node.exe"),node2=exists(besideNode)?besideNode:findCommand2("node",searchPath,null,{platform:"win32",env});return node2==null?null:{file:node2,args:[path.join(dir,script)]}}function windowsSpawn(spawn6){return(command,args=[],options={})=>{let resolved=!path.isAbsolute(command)&&!/[\\/]/.test(command)?resolveWindowsCommand(command,windowsEnv(options.env??process.env)):null,spawnOptions={...options,windowsHide:!0};return resolved==null?spawn6(command,args,spawnOptions):spawn6(resolved.file,[...resolved.args,...args],spawnOptions)}}function windowsAccountGuardSegment(env=process.env,username=os.userInfo().username){let owner=(env.USERDOMAIN?`${env.USERDOMAIN}\\${username}`:username).toLowerCase();return`user-${createHash6("sha256").update(owner).digest("hex").slice(0,16)}`}function windowsGuardRoot(env=process.env,{username=os.userInfo().username}={}){return path.win32.join(env.ProgramData||"C:\\ProgramData","Ando","task-git",windowsAccountGuardSegment(env,username))}function windowsFallbackGuardRoot(env=process.env,{username=os.userInfo().username}={}){return path.win32.join(env.ProgramData||"C:\\ProgramData",`Ando-task-git-${windowsAccountGuardSegment(env,username)}`)}function lockWindowsToken(tokenFile,{run:run2=childProcess.spawnSync,env=process.env,username=os.userInfo().username,remove=fs.rmSync}={}){let owner=env.USERDOMAIN?`${env.USERDOMAIN}\\${username}`:username,icacls=path.win32.join(env.SystemRoot||"C:\\Windows","System32","icacls.exe");return run2(icacls,[tokenFile,"/inheritance:r","/grant:r",`${owner}:F`,"*S-1-5-18:F","CodexSandboxUsers:R"],{encoding:"utf8",timeout:1e4,windowsHide:!0})?.status===0?!0:(remove(tokenFile,{force:!0}),!1)}function letSandboxReadGuard(dir,{run:run2=childProcess.spawnSync,env=process.env}={}){let icacls=path.win32.join(env.SystemRoot||"C:\\Windows","System32","icacls.exe");return run2(icacls,[dir,"/grant","CodexSandboxUsers:(OI)(CI)RX","/T"],{encoding:"utf8",timeout:1e4,windowsHide:!0})?.status===0}var LEGACY_WINDOWS_GUARD_MAX_AGE_MS=1440*6e4,WINDOWS_LOCK_GUARD_ROOT_SCRIPT=["$ErrorActionPreference = 'Stop'","$root = $env:ANDO_GUARD_DIR","$parentCount = [int]$env:ANDO_GUARD_PARENT_COUNT","$maxAgeMs = [double]$env:ANDO_LEGACY_GUARD_MAX_AGE_MS","$me = [Security.Principal.WindowsIdentity]::GetCurrent().User","$sys = New-Object Security.Principal.SecurityIdentifier 'S-1-5-18'","$admins = New-Object Security.Principal.SecurityIdentifier 'S-1-5-32-544'","$trusted = @($me.Value, $sys.Value, $admins.Value)","$parent1 = Split-Path -Parent $root","$parents = @($parent1)","if ($parentCount -ge 2) {"," $parent2 = Split-Path -Parent $parent1"," if ($parent2 -and $parent2 -ne $parent1) { $parents = @($parent2, $parent1) }","}","foreach ($p in @($parents + @($root))) {"," $item = Get-Item -LiteralPath $p -Force"," if (-not $item.PSIsContainer -or ($item.Attributes -band [IO.FileAttributes]::ReparsePoint)) {",' [Console]::Error.WriteLine("reparse or non-directory: $p")'," exit 2"," }","}","$danger = [int]([Security.AccessControl.FileSystemRights]::DeleteSubdirectoriesAndFiles -bor [Security.AccessControl.FileSystemRights]::Delete -bor [Security.AccessControl.FileSystemRights]::TakeOwnership -bor [Security.AccessControl.FileSystemRights]::ChangePermissions) -bor 0x10000000","foreach ($parent in $parents) {"," $pacl = Get-Acl -LiteralPath $parent"," $pOwner = $pacl.GetOwner([Security.Principal.SecurityIdentifier]).Value"," if ($trusted -notcontains $pOwner) {",' [Console]::Error.WriteLine("untrusted parent owner on ${parent}: $pOwner")'," exit 5"," }"," foreach ($rule in $pacl.GetAccessRules($true, $true, [Security.Principal.SecurityIdentifier])) {"," if ($rule.AccessControlType -ne [Security.AccessControl.AccessControlType]::Allow) { continue }"," $sid = $rule.IdentityReference.Value"," if ($trusted -contains $sid -or $sid -eq 'S-1-3-0') { continue }"," if (([int]$rule.FileSystemRights -band $danger) -ne 0) {",' [Console]::Error.WriteLine("unsafe parent ACL on $parent for $sid ($($rule.FileSystemRights))")'," exit 3"," }"," }","}","$acl = Get-Acl -LiteralPath $root","$ownerSid = $acl.GetOwner([Security.Principal.SecurityIdentifier]).Value","if ($trusted -notcontains $ownerSid) {",' [Console]::Error.WriteLine("untrusted root owner: $ownerSid")'," exit 4","}","$acl.SetAccessRuleProtection($true, $false)","foreach ($existing in @($acl.GetAccessRules($true, $true, [Security.Principal.SecurityIdentifier]))) {"," [void]$acl.RemoveAccessRuleSpecific($existing)","}","$inh = [Security.AccessControl.InheritanceFlags]'ContainerInherit,ObjectInherit'","$prop = [Security.AccessControl.PropagationFlags]::None","$allow = [Security.AccessControl.AccessControlType]::Allow","$full = [Security.AccessControl.FileSystemRights]::FullControl","foreach ($sid in @($me, $sys, $admins)) {"," $acl.AddAccessRule((New-Object Security.AccessControl.FileSystemAccessRule($sid, $full, $inh, $prop, $allow)))","}","Set-Acl -LiteralPath $root -AclObject $acl","if ($parentCount -ge 2) {"," try {"," $cmdLines = @(Get-CimInstance Win32_Process -ErrorAction Stop | ForEach-Object { $_.CommandLine } | Where-Object { $_ })"," $hasLegacyConnector = ($cmdLines | Where-Object { $_ -match 'ando-machine|@ando/machine|machine-connector' }).Count -gt 0"," if (-not $hasLegacyConnector) {"," $cutoff = [DateTime]::UtcNow.AddMilliseconds(-$maxAgeMs)"," foreach ($child in Get-ChildItem -LiteralPath $parent1 -Force -ErrorAction SilentlyContinue) {"," if (-not $child.PSIsContainer -or ($child.Attributes -band [IO.FileAttributes]::ReparsePoint)) { continue }"," if ($child.Name -notmatch '^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$') { continue }"," if ($child.LastWriteTimeUtc -gt $cutoff) { continue }"," if (($cmdLines | Where-Object { $_.IndexOf($child.Name, [StringComparison]::OrdinalIgnoreCase) -ge 0 }).Count -gt 0) { continue }"," try {"," $cacl = Get-Acl -LiteralPath $child.FullName"," if ($cacl.GetOwner([Security.Principal.SecurityIdentifier]).Value -ne $ownerSid) { continue }"," $skipChild = $false"," foreach ($desc in Get-ChildItem -LiteralPath $child.FullName -Recurse -Force -ErrorAction SilentlyContinue) {"," if (($desc.Attributes -band [IO.FileAttributes]::ReparsePoint) -or ($desc.LastWriteTimeUtc -gt $cutoff)) {"," $skipChild = $true"," break"," }"," }"," if (-not $skipChild) { [IO.Directory]::Delete($child.FullName, $true) }"," } catch {}"," }"," }"," } catch {}","}"].join(`
|
|
143
143
|
`),WINDOWS_LOCK_GUARD_ROOT_ENCODED=Buffer.from(WINDOWS_LOCK_GUARD_ROOT_SCRIPT,"utf16le").toString("base64");function lockWindowsGuardRoot(root,{run:run2=childProcess.spawnSync,env=process.env,mkdirSync:mkdirSync3=fs.mkdirSync,lstatSync=fs.lstatSync,legacyMaxAgeMs=LEGACY_WINDOWS_GUARD_MAX_AGE_MS,log:log2=null}={}){let parentCount;try{let ops=/^(?:[A-Za-z]:[\\/]|\\\\[^\\])/.test(root)?path.win32:path,isFallbackRoot=/^Ando-task-git-user-[0-9a-f]{16}$/i.test(ops.basename(root));parentCount=isFallbackRoot?1:2;let parent1=ops.dirname(root),dirsToCheck=isFallbackRoot?[parent1,root]:[ops.dirname(parent1),parent1,root];mkdirSync3(dirsToCheck[0],{recursive:!0});for(let dir of dirsToCheck){mkdirSync3(dir,{recursive:!0});let stat2=lstatSync(dir);if(!stat2.isDirectory()||stat2.isSymbolicLink())return!1}}catch{return!1}let powershell=path.win32.join(env.SystemRoot||"C:\\Windows","System32","WindowsPowerShell","v1.0","powershell.exe"),result=run2(powershell,["-NoProfile","-NonInteractive","-EncodedCommand",WINDOWS_LOCK_GUARD_ROOT_ENCODED],{env:{...env,ANDO_GUARD_DIR:root,ANDO_GUARD_PARENT_COUNT:String(parentCount),ANDO_LEGACY_GUARD_MAX_AGE_MS:String(legacyMaxAgeMs)},encoding:"utf8",timeout:15e3,windowsHide:!0});return result?.status===0?!0:(log2?.warn?.("[Local tools] failed to lock Windows guard root",{root,status:result?.status??null,stderr:typeof result?.stderr=="string"?result.stderr.trim():""}),!1)}module.exports={letSandboxReadGuard,lockWindowsGuardRoot,lockWindowsToken,resolveWindowsCommand,windowsEnv,windowsFallbackGuardRoot,windowsGuardRoot,windowsSpawn}}});var require_command_env=__commonJS({"../../apps/web/electron/local-tools/command-env.js"(exports,module){"use strict";var fs=__require("fs"),{execFile:execFile3}=__require("child_process"),os=__require("os"),path=__require("path"),{windowsEnv}=require_windows(),isInside=(entry,folder)=>entry===folder||entry.startsWith(`${folder}${path.sep}`);function trustedPath2(value,folders=[]){return value.split(path.delimiter).filter(entry=>path.isAbsolute(entry)&&!/[\\/]node_modules[\\/]\.bin[\\/]?$/.test(entry)&&!/[\\/]node-gyp-bin[\\/]?$/.test(entry)&&!folders.some(folder=>isInside(path.resolve(entry),path.resolve(folder)))).join(path.delimiter)}function wellKnownCommandFolders(home){return[path.join(home,".local","bin"),path.join(home,".claude","local"),"/opt/homebrew/bin","/usr/local/bin",path.join(home,".bun","bin"),path.join(home,".volta","bin"),path.join(home,".npm-global","bin"),path.join(home,"Library","pnpm")]}function withFolders(value,folders,isFolder){let entries=value.split(path.delimiter).filter(Boolean);for(let folder of folders)!entries.includes(folder)&&isFolder(folder)&&entries.push(folder);return entries.join(path.delimiter)}var isDirectory=folder=>{try{return fs.statSync(folder).isDirectory()}catch{return!1}},PATH_MARKER="__ANDO_LOGIN_PATH__";function readCommandEnv({spawnSync:spawnSync6,env,platform=process.platform,home=os.homedir(),isFolder=isDirectory}){if(platform==="win32"){let normalized=windowsEnv(env);return{env:{...normalized,PATH:trustedPath2(normalized.PATH??"")},fromLoginShell:!0}}let shell=env.SHELL||"/bin/zsh",result=spawnSync6(shell,["-ilc",`printf "%s%s" "${PATH_MARKER}" "$PATH"`],{encoding:"utf8",timeout:5e3,cwd:home,env:{...env,PATH:trustedPath2(env.PATH??"")}});return commandEnvFromResult({env,home,isFolder},result)}function commandEnvFromResult({env,home,isFolder},result){let output=typeof result?.stdout=="string"?result.stdout:"",marked=output.lastIndexOf(PATH_MARKER),loginPath=result?.status===0&&marked!==-1?output.slice(marked+PATH_MARKER.length).trim():"",searchPath=withFolders(loginPath||(env.PATH??""),wellKnownCommandFolders(home),isFolder);return{env:{...env,PATH:trustedPath2(searchPath)},fromLoginShell:loginPath!==""}}var executeLoginShell=(shell,args,options,callback)=>{execFile3(shell,args,options,callback)};async function readCommandEnvAsync({env,platform=process.platform,home=os.homedir(),isFolder=isDirectory,execute=executeLoginShell}){if(platform==="win32")return readCommandEnv({env,platform});let result=await new Promise(resolve4=>{execute(env.SHELL||"/bin/zsh",["-ilc",`printf "%s%s" "${PATH_MARKER}" "$PATH"`],{encoding:"utf8",timeout:5e3,cwd:home,env:{...env,PATH:trustedPath2(env.PATH??"")}},(error2,stdout)=>resolve4({status:error2==null?0:1,stdout}))});return commandEnvFromResult({env,home,isFolder},result)}var VARIABLES_MARKER="__ANDO_LOGIN_VARIABLES__";async function readLoginShellVariables({env,platform=process.platform,home=os.homedir(),execute=executeLoginShell}){if(platform==="win32")return{...env};let output=await new Promise(resolve4=>{execute(env.SHELL||"/bin/zsh",["-ilc",`printf "%s" "${VARIABLES_MARKER}"; env -0`],{encoding:"utf8",timeout:5e3,cwd:home,maxBuffer:4*1024*1024,env:{...env,PATH:trustedPath2(env.PATH??"")}},(error2,stdout)=>resolve4(error2==null&&typeof stdout=="string"?stdout:""))}),marked=output.lastIndexOf(VARIABLES_MARKER);if(marked===-1)return{...env};let variables={};for(let entry of output.slice(marked+VARIABLES_MARKER.length).split("\0")){let equals=entry.indexOf("=");equals>0&&(variables[entry.slice(0,equals)]=entry.slice(equals+1))}return{...env,...variables}}function resolveCommandEnv(options){return readCommandEnv(options).env}function readFallbackCommandEnv({env,platform=process.platform,home=os.homedir(),isFolder=isDirectory}){if(platform==="win32"){let normalized=windowsEnv(env);return{...normalized,PATH:trustedPath2(normalized.PATH??"")}}return commandEnvFromResult({env,home,isFolder},{status:1,stdout:""}).env}var COMMAND_ENV_RETRY_MS=6e4;function createCommandEnvReader({read,refresh,readFallback=null,onFallback=()=>{},now=Date.now,retryMs=COMMAND_ENV_RETRY_MS}){let settled=null,fallback=null,inflightFallback=null,fallbackAt=0,pending=null,getInflightFallback=()=>(inflightFallback==null&&typeof readFallback=="function"&&(inflightFallback=readFallback()),inflightFallback),accept=answer=>(answer.fromLoginShell?settled=answer.env:(fallback==null&&onFallback(),fallback=answer.env),fallbackAt=now(),settled??fallback),startAsyncRefresh=()=>(settled!=null||pending!=null||typeof refresh!="function"||(fallbackAt=now(),pending=Promise.resolve().then(refresh).then(accept).catch(()=>{fallback==null&&typeof readFallback=="function"&&(onFallback(),fallback=getInflightFallback()),fallbackAt=now()}).finally(()=>{pending=null})),pending),reader=()=>settled??(fallback==null?pending!=null&&typeof readFallback=="function"?getInflightFallback():accept(read()):(pending==null&&now()-fallbackAt>=retryMs&&startAsyncRefresh(),fallback));return reader.prefetch=()=>{startAsyncRefresh()},reader.ready=()=>settled??(pending!=null?pending.then(()=>reader()):reader()),reader}function startFailure(tool,command,error2){if(error2?.code!=="ENOENT")return error2;let failure2=new Error(`Couldn't find \`${command}\` on this computer. Ando looks for ${tool} on the PATH your login shell sets. Check that \`${command}\` runs in a terminal, then quit and reopen Ando.`);return failure2.code="ENOENT",failure2.cause=error2,failure2}module.exports={COMMAND_ENV_RETRY_MS,createCommandEnvReader,readCommandEnv,readCommandEnvAsync,readFallbackCommandEnv,readLoginShellVariables,resolveCommandEnv,startFailure,trustedPath:trustedPath2,wellKnownCommandFolders}}});var require_claude_background=__commonJS({"../../apps/web/electron/local-tools/claude-background.js"(exports,module){"use strict";var ENDED=new Set(["completed","failed","killed"]);function createBackgroundWork(){let live=new Set,ambient=new Set;function note(message){if(!(message?.type!=="system"||typeof message.subtype!="string"))switch(message.subtype){case"background_tasks_changed":{if(!Array.isArray(message.tasks))return;live.clear();for(let task of message.tasks)typeof task?.task_id=="string"&&(task.ambient===!0?ambient.add(task.task_id):live.add(task.task_id));return}case"task_started":{if(typeof message.task_id!="string")return;if(message.ambient===!0){ambient.add(message.task_id);return}message.is_backgrounded===!0&&live.add(message.task_id);return}case"task_updated":{if(typeof message.task_id!="string")return;if(ENDED.has(message.patch?.status)){live.delete(message.task_id);return}message.patch?.is_backgrounded===!0&&!ambient.has(message.task_id)&&live.add(message.task_id);return}case"task_notification":{typeof message.task_id=="string"&&live.delete(message.task_id);return}default:return}}return{note,outstanding:()=>live.size>0}}function isHeldNotificationResult(message){return message?.origin?.kind==="task-notification"&&message.num_turns===0&&(message.result??"")===""}function isNotificationReplay(message){return message?.origin?.kind==="task-notification"}module.exports={createBackgroundWork,isHeldNotificationResult,isNotificationReplay}}});var require_claude_runtime=__commonJS({"../../apps/web/electron/local-tools/claude-runtime.js"(exports,module){"use strict";var readline=__require("readline"),{claudeThoughts}=require_thoughts(),{addClaudeUsage}=require_usage(),{createLastErrorLine,exitMessage}=require_last_error_line(),{startFailure}=require_command_env(),{createBackgroundWork,isHeldNotificationResult,isNotificationReplay}=require_claude_background();function userMessage(text){return`${JSON.stringify({type:"user",message:{role:"user",content:[{type:"text",text}]}})}
|
|
144
|
-
`}var SESSION_MISSING="session_missing",IDLE_EXIT_MS=15*6e4;function isMissingSession(message){return message.is_error===!0&&message.num_turns===0&&Array.isArray(message.errors)&&message.errors.some(error2=>typeof error2=="string"&&error2.startsWith("No conversation found with session ID"))}function createClaudeRuntime({spawn:
|
|
144
|
+
`}var SESSION_MISSING="session_missing",IDLE_EXIT_MS=15*6e4;function isMissingSession(message){return message.is_error===!0&&message.num_turns===0&&Array.isArray(message.errors)&&message.errors.some(error2=>typeof error2=="string"&&error2.startsWith("No conversation found with session ID"))}function createClaudeRuntime({spawn:spawn6,env,cwd,instructions,permissionArgs=[],effort=null,model=null,onExtraReply=()=>{},onClose=null,idleExitMs=IDLE_EXIT_MS,setTimer=setTimeout,clearTimer=clearTimeout}){let sessions=new Map,closed=!1,stopped=()=>new Error("This agent was stopped");function start(key,sessionId){if(closed)throw stopped();if(sessionId!=null&&(typeof sessionId!="string"||!/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(sessionId)))throw new Error("Invalid session id.");let args=["-p","--input-format","stream-json","--output-format","stream-json","--verbose","--replay-user-messages",...permissionArgs,...effort?["--effort",effort]:[],...model?["--model",model]:[],"--append-system-prompt",instructions,...sessionId?["--resume",sessionId]:[]],child=spawn6("claude",args,{cwd,env,stdio:["pipe","pipe","pipe"]}),lastError=createLastErrorLine();child.stderr?.on("data",chunk=>lastError.push(chunk));let session={child,sessionId,turn:null,ready:!sessionId,written:[],taken:[],replays:!1,background:createBackgroundWork()};sessions.set(key,session),session.idle=()=>{clearTimer(session.idleTimer),session.idleTimer=setTimer(()=>{if(session.turn!=null||session.taken.length>0||session.replays&&session.written.length>0){session.idle();return}sessions.get(key)===session&&sessions.delete(key),child.stdin.end(),child.kill()},idleExitMs),session.idleTimer?.unref?.()};let end=error2=>{clearTimer(session.idleTimer),session.ended=error2,sessions.get(key)===session&&sessions.delete(key),session.turn?.reject(error2),session.turn=null};child.on("error",error2=>end(startFailure("Claude Code","claude",error2))),child.on("close",(code2,signal)=>end(new Error(exitMessage("Claude",signal??code2,lastError)))),child.stdin?.on("error",end),session.end=end;let progress=message=>{session.background.note(message),session.ready||(session.ready=!0,session.turn?.onStarted?.()),typeof message.session_id=="string"&&(session.sessionId=message.session_id),session.turn?.onMessage?.(message);for(let thought of claudeThoughts(message))session.turn?.onThought?.(thought)},answer=(turn,message,reply)=>{if(reply&&turn.replies.push(reply),turn.usage=addClaudeUsage(turn.usage,message),turn.usage!=null&&turn.onUsage?.(turn.usage,session.sessionId),turn.waiting=!message.is_error&&turn.answerSteers&&session.written.some(input=>!input.turn),!turn.waiting){if(turn.awaitBackground&&!message.is_error&&(session.background.outstanding()||isHeldNotificationResult(message))){let interim=turn.replies.join(`
|
|
145
145
|
|
|
146
146
|
`);turn.replies=[],turn.awaiting=!0,interim&&turn.onInterimReply?.(interim);return}(session.turn===turn||!session.replays)&&(session.turn=null),session.turn==null&&session.idle(),message.is_error?turn.reject(new Error(reply||"Claude could not finish")):turn.resolve({sessionId:session.sessionId,reply:turn.replies.join(`
|
|
147
147
|
|
|
@@ -157,9 +157,9 @@ Host: ${target}\r
|
|
|
157
157
|
${auth2}\r
|
|
158
158
|
`);let buf=Buffer.alloc(0),onData=chunk=>{buf=Buffer.concat([buf,chunk]);let idx=buf.indexOf(`\r
|
|
159
159
|
\r
|
|
160
|
-
`);if(idx===-1)return;let head=buf.subarray(0,idx).toString("latin1");if(sock.removeListener("data",onData),!/^HTTP\/1\.[01]\s+200\b/i.test(head))return fail("ECONNREFUSED");finish(buf.subarray(idx+4))};sock.on("data",onData)}),sock}function openProxyTunnel(targetHost,targetPort,cb){let clean=String(targetHost).replace(/^\[|\]$/g,""),host=ipToHost.get(clean)||clean;return proxy.useSocks?openSocks5Tunnel(host,targetPort,cb):openHttpConnectTunnel(host,targetPort,cb)}function parseDnsName(buf,offset){let labels=[],pos=offset,nextPos=0;for(let jumps=0;pos<buf.length&&jumps<16;){let len2=buf[pos];if(len2===0)return{name:labels.join("."),nextPos:nextPos||pos+1};if((len2&192)===192){if(pos+1>=buf.length)return null;nextPos||(nextPos=pos+2),pos=(len2&63)<<8|buf[pos+1],jumps+=1}else{if(pos+1+len2>buf.length)return null;labels.push(buf.subarray(pos+1,pos+1+len2).toString("utf8")),pos+=1+len2}}return null}function recordDnsAnswers(buf){if(buf.length<12)return;let qdcount=buf.readUInt16BE(4),rrcount=buf.readUInt16BE(6)+buf.readUInt16BE(8)+buf.readUInt16BE(10),pos=12,qname="";for(let i2=0;i2<qdcount;i2+=1){let q=parseDnsName(buf,pos);if(!q)return;i2===0&&(qname=q.name),pos=q.nextPos+4}for(let i2=0;i2<rrcount&&pos<buf.length;i2+=1){let owner=parseDnsName(buf,pos);if(!owner||owner.nextPos+10>buf.length)return;let rtype=buf.readUInt16BE(owner.nextPos),rdlen=buf.readUInt16BE(owner.nextPos+8);pos=owner.nextPos+10,rtype===1&&rdlen===4&&pos+4<=buf.length&&ipToHost.set(`${buf[pos]}.${buf[pos+1]}.${buf[pos+2]}.${buf[pos+3]}`,owner.name||qname),pos+=rdlen}}function dnsUpstreams(){let custom2=process.env.ANDO_SANDBOX_DNS_UPSTREAM;if(!custom2)return[{host:"1.1.1.1",port:53},{host:"8.8.8.8",port:53}];let idx=custom2.lastIndexOf(":");return idx>0?[{host:custom2.slice(0,idx),port:Number(custom2.slice(idx+1))||53}]:[{host:custom2,port:53}]}function queryDnsOverTcp(msg,cb){let upstreams=dnsUpstreams(),tryAt=idx=>{if(idx>=upstreams.length)return cb(new Error("DNS proxy forward failed"));let{host,port}=upstreams[idx];openProxyTunnel(host,port,(err,sock,initialRest)=>{if(err||!sock)return tryAt(idx+1);sock.unref();let done=!1,finish=(qErr,ans)=>{done||(done=!0,sock.destroy(),qErr?tryAt(idx+1):cb(null,ans))};sock.setTimeout(8e3,()=>finish(new Error("DNS timeout"))),sock.once("error",finish),sock.once("close",()=>finish(new Error("DNS closed")));let buf=initialRest||Buffer.alloc(0),onData=chunk=>{if(buf=Buffer.concat([buf,chunk]),buf.length<2)return;let len2=buf.readUInt16BE(0);if(buf.length<2+len2)return;let ans=buf.subarray(2,2+len2);recordDnsAnswers(ans),finish(null,ans)};sock.on("data",onData),buf.length>=2&&onData(Buffer.alloc(0)),sock.resume();let framed=Buffer.alloc(2+msg.length);framed.writeUInt16BE(msg.length,0),msg.copy(framed,2),sock.write(framed)})};tryAt(0)}function patchResolverProtos(dnsServerAddr){let customSym=Symbol("ando.customDnsServers"),protos=[dns.Resolver?.prototype,dns.promises?.Resolver?.prototype].filter(Boolean),methods=["resolve","resolve4","resolve6","resolveAny","resolveCaa","resolveCname","resolveMx","resolveNaptr","resolveNs","resolvePtr","resolveSoa","resolveSrv","resolveTxt","reverse"];for(let proto of protos){let origSet=proto.setServers;if(typeof origSet=="function"){proto.setServers=function(...args){return this[customSym]=!0,origSet.apply(this,args)};for(let m of methods){let origM=proto[m];typeof origM=="function"&&(proto[m]=function(...args){if(!this[customSym]){this[customSym]=!0;try{origSet.call(this,[dnsServerAddr])}catch{}}return origM.apply(this,args)})}}}}function pipeSockets(a,b,rest){rest&&rest.length>0&&a.write(rest),a.pipe(b),b.pipe(a),b.resume(),a.on("error",()=>b.destroy()),b.on("error",()=>a.destroy()),a.on("close",()=>b.destroy()),b.on("close",()=>a.destroy())}function startLocalDnsForwarder(){try{let udp=dgram.createSocket("udp4");for(let s of Object.getOwnPropertySymbols(udp))udp[s]?.handle&&(udp[s].handle.lookup=(_a4,cb)=>cb(null,"127.0.0.1"));udp.bind(0,"127.0.0.1"),udp.unref();let dnsPort=udp.address().port;udp.on("message",(msg,rinfo)=>{queryDnsOverTcp(msg,(err,ans)=>{!err&&ans&&udp.send(ans,rinfo.port,rinfo.address)})});let tcpDns=net.createServer(client=>{client.unref();let{host,port}=dnsUpstreams()[0];openProxyTunnel(host,port,(err,proxySock,rest)=>{if(err||!proxySock)return client.destroy();proxySock.unref(),pipeSockets(client,proxySock,rest)})});tcpDns._listen2("127.0.0.1",dnsPort,4),tcpDns.unref();let addr=`127.0.0.1:${dnsPort}`;dns.setServers([addr]),dns.promises?.setServers?.([addr]),patchResolverProtos(addr)}catch{}}function recordLookupResult(
|
|
160
|
+
`);if(idx===-1)return;let head=buf.subarray(0,idx).toString("latin1");if(sock.removeListener("data",onData),!/^HTTP\/1\.[01]\s+200\b/i.test(head))return fail("ECONNREFUSED");finish(buf.subarray(idx+4))};sock.on("data",onData)}),sock}function openProxyTunnel(targetHost,targetPort,cb){let clean=String(targetHost).replace(/^\[|\]$/g,""),host=ipToHost.get(clean)||clean;return proxy.useSocks?openSocks5Tunnel(host,targetPort,cb):openHttpConnectTunnel(host,targetPort,cb)}function parseDnsName(buf,offset){let labels=[],pos=offset,nextPos=0;for(let jumps=0;pos<buf.length&&jumps<16;){let len2=buf[pos];if(len2===0)return{name:labels.join("."),nextPos:nextPos||pos+1};if((len2&192)===192){if(pos+1>=buf.length)return null;nextPos||(nextPos=pos+2),pos=(len2&63)<<8|buf[pos+1],jumps+=1}else{if(pos+1+len2>buf.length)return null;labels.push(buf.subarray(pos+1,pos+1+len2).toString("utf8")),pos+=1+len2}}return null}function recordDnsAnswers(buf){if(buf.length<12)return;let qdcount=buf.readUInt16BE(4),rrcount=buf.readUInt16BE(6)+buf.readUInt16BE(8)+buf.readUInt16BE(10),pos=12,qname="";for(let i2=0;i2<qdcount;i2+=1){let q=parseDnsName(buf,pos);if(!q)return;i2===0&&(qname=q.name),pos=q.nextPos+4}for(let i2=0;i2<rrcount&&pos<buf.length;i2+=1){let owner=parseDnsName(buf,pos);if(!owner||owner.nextPos+10>buf.length)return;let rtype=buf.readUInt16BE(owner.nextPos),rdlen=buf.readUInt16BE(owner.nextPos+8);pos=owner.nextPos+10,rtype===1&&rdlen===4&&pos+4<=buf.length&&ipToHost.set(`${buf[pos]}.${buf[pos+1]}.${buf[pos+2]}.${buf[pos+3]}`,owner.name||qname),pos+=rdlen}}function dnsUpstreams(){let custom2=process.env.ANDO_SANDBOX_DNS_UPSTREAM;if(!custom2)return[{host:"1.1.1.1",port:53},{host:"8.8.8.8",port:53}];let idx=custom2.lastIndexOf(":");return idx>0?[{host:custom2.slice(0,idx),port:Number(custom2.slice(idx+1))||53}]:[{host:custom2,port:53}]}function queryDnsOverTcp(msg,cb){let upstreams=dnsUpstreams(),tryAt=idx=>{if(idx>=upstreams.length)return cb(new Error("DNS proxy forward failed"));let{host,port}=upstreams[idx];openProxyTunnel(host,port,(err,sock,initialRest)=>{if(err||!sock)return tryAt(idx+1);sock.unref();let done=!1,finish=(qErr,ans)=>{done||(done=!0,sock.destroy(),qErr?tryAt(idx+1):cb(null,ans))};sock.setTimeout(8e3,()=>finish(new Error("DNS timeout"))),sock.once("error",finish),sock.once("close",()=>finish(new Error("DNS closed")));let buf=initialRest||Buffer.alloc(0),onData=chunk=>{if(buf=Buffer.concat([buf,chunk]),buf.length<2)return;let len2=buf.readUInt16BE(0);if(buf.length<2+len2)return;let ans=buf.subarray(2,2+len2);recordDnsAnswers(ans),finish(null,ans)};sock.on("data",onData),buf.length>=2&&onData(Buffer.alloc(0)),sock.resume();let framed=Buffer.alloc(2+msg.length);framed.writeUInt16BE(msg.length,0),msg.copy(framed,2),sock.write(framed)})};tryAt(0)}function patchResolverProtos(dnsServerAddr){let customSym=Symbol("ando.customDnsServers"),protos=[dns.Resolver?.prototype,dns.promises?.Resolver?.prototype].filter(Boolean),methods=["resolve","resolve4","resolve6","resolveAny","resolveCaa","resolveCname","resolveMx","resolveNaptr","resolveNs","resolvePtr","resolveSoa","resolveSrv","resolveTxt","reverse"];for(let proto of protos){let origSet=proto.setServers;if(typeof origSet=="function"){proto.setServers=function(...args){return this[customSym]=!0,origSet.apply(this,args)};for(let m of methods){let origM=proto[m];typeof origM=="function"&&(proto[m]=function(...args){if(!this[customSym]){this[customSym]=!0;try{origSet.call(this,[dnsServerAddr])}catch{}}return origM.apply(this,args)})}}}}function pipeSockets(a,b,rest){rest&&rest.length>0&&a.write(rest),a.pipe(b),b.pipe(a),b.resume(),a.on("error",()=>b.destroy()),b.on("error",()=>a.destroy()),a.on("close",()=>b.destroy()),b.on("close",()=>a.destroy())}function startLocalDnsForwarder(){try{let udp=dgram.createSocket("udp4");for(let s of Object.getOwnPropertySymbols(udp))udp[s]?.handle&&(udp[s].handle.lookup=(_a4,cb)=>cb(null,"127.0.0.1"));udp.bind(0,"127.0.0.1"),udp.unref();let dnsPort=udp.address().port;udp.on("message",(msg,rinfo)=>{queryDnsOverTcp(msg,(err,ans)=>{!err&&ans&&udp.send(ans,rinfo.port,rinfo.address)})});let tcpDns=net.createServer(client=>{client.unref();let{host,port}=dnsUpstreams()[0];openProxyTunnel(host,port,(err,proxySock,rest)=>{if(err||!proxySock)return client.destroy();proxySock.unref(),pipeSockets(client,proxySock,rest)})});tcpDns._listen2("127.0.0.1",dnsPort,4),tcpDns.unref();let addr=`127.0.0.1:${dnsPort}`;dns.setServers([addr]),dns.promises?.setServers?.([addr]),patchResolverProtos(addr)}catch{}}function recordLookupResult(hostname3,address){if(Array.isArray(address))for(let item of address)item?.address&&!isLoopbackHost(item.address)&&ipToHost.set(item.address,hostname3);else typeof address=="string"&&!isLoopbackHost(address)&&ipToHost.set(address,hostname3)}function fallbackDnsResolve(hostname3,opts,origErr,cb){let fam=opts.family===6?6:4;(fam===6?dns.resolve6:dns.resolve4).call(dns,hostname3,(resErr,list)=>{if(resErr||!list?.length)return cb(origErr||resErr);for(let ip of list)ipToHost.set(ip,hostname3);return cb(null,opts.all?list.map(ip=>({address:ip,family:fam})):list[0],fam)})}function normalizeConnectCall(args){if(Array.isArray(args[0]))return{options:args[0][0],cb:args[0][1]};if(typeof args[0]=="object"&&args[0]!==null)return{options:args[0],cb:typeof args[1]=="function"?args[1]:null};if(typeof args[0]=="string"&&Number.isNaN(Number(args[0])))return{options:null,cb:null};let options={port:Number(args[0])};return typeof args[1]=="string"?(options.host=args[1],{options,cb:typeof args[2]=="function"?args[2]:null}):{options,cb:typeof args[1]=="function"?args[1]:null}}startLocalDnsForwarder(),dns.lookup=function(hostname3,options,callback){let cb=typeof options=="function"?options:callback,opts=typeof options=="function"?{}:typeof options=="number"?{family:options}:options||{};return!hostname3||isLoopbackHost(hostname3)||net.isIP(hostname3)!==0?origLookup.call(this,hostname3,options,callback):origLookup.call(this,hostname3,opts,(err,address,family)=>{if(!err&&address)return recordLookupResult(hostname3,address),cb(null,address,family);fallbackDnsResolve(hostname3,opts,err,cb)})},dns.promises?.lookup&&(dns.promises.lookup=(hostname3,options)=>new Promise((resolve4,reject)=>{dns.lookup(hostname3,options,(err,address,family)=>err?reject(err):resolve4(Array.isArray(address)?address:{address,family}))})),net.Socket.prototype.connect=function(...args){let{options,cb}=normalizeConnectCall(args);if(!options||options.path||!options.port)return origConnect.apply(this,args);let rawHost=options.host||options.hostname||"localhost";if(isLoopbackHost(rawHost))return origConnect.apply(this,args);if(this._parent?.connecting)return this;let realHost=ipToHost.get(rawHost)||rawHost,targetPort=Number(options.port);this.write!==net.Socket.prototype.write&&(this.write=net.Socket.prototype.write),this.connecting=!0,this._host||(this._host=realHost),typeof this.setServername=="function"&&!this.servername&&!net.isIP(realHost)&&this.setServername(realHost),typeof cb=="function"&&this.once("connect",cb);let tunnelSock=openProxyTunnel(realHost,targetPort,(err,proxySock,rest)=>{if(this.destroyed)return proxySock?.destroy();if(err||!proxySock)return this.connecting=!1,this.destroy(err||new Error(`connect ECONNREFUSED ${realHost}:${targetPort}`));proxySock.unref();let srv=net.createServer({allowHalfOpen:!!options.allowHalfOpen},localClient=>{srv.close(),localClient.unref(),localClient.setNoDelay(!0),pipeSockets(localClient,proxySock,rest)});srv._listen2("127.0.0.1",0,4),srv.unref(),this.once("close",()=>{srv.close(),proxySock.destroy()}),origConnect.call(this,{...options,host:"127.0.0.1",port:srv.address().port,family:4,lookup:void 0,localAddress:void 0,localPort:void 0,autoSelectFamily:!1})});return this.once("close",()=>tunnelSock?.destroy()),this}}var{PYTHON_SITECUSTOMIZE_PY}=require_python_bridge(),NET_BRIDGE_JS=`(${installSandboxNetBridge.toString()})(require);
|
|
161
161
|
`;module.exports={NET_BRIDGE_JS,PYTHON_SITECUSTOMIZE_PY,installSandboxNetBridge}}});var require_shell_quote=__commonJS({"../../apps/web/electron/local-tools/shell-quote.js"(exports,module){"use strict";function shellQuote(value){return`'${String(value).replace(/'/g,"'\\''")}'`}module.exports={shellQuote}}});var require_git_guard=__commonJS({"../../apps/web/electron/local-tools/git-guard.js"(exports,module){"use strict";var fs=__require("fs"),os=__require("os"),path=__require("path"),{NET_BRIDGE_JS,PYTHON_SITECUSTOMIZE_PY}=require_net_bridge(),{shellQuote}=require_shell_quote(),{findCommand:findCommand2}=require_toolchain();function findGit(searchPath=process.env.PATH??"",skip=null){return findCommand2("git",searchPath,skip)??"/usr/bin/git"}function shellPath(p,platform=process.platform){return platform==="win32"?p.replace(/\\/g,"/"):p}function gitShellFor(realGit,exists=fs.existsSync){let dir=path.dirname(realGit);for(let up=0;up<3;up+=1){for(let sh of[path.join(dir,"bin","sh.exe"),path.join(dir,"usr","bin","sh.exe")])if(exists(sh))return sh;dir=path.dirname(dir)}return null}function windowsLauncher(sh,name){return["@echo off","rem Written by Ando for one task: runs its guard's script in Git's sh.",`"${sh.replace(/%/g,"%%")}" "%~dp0${name}" %*`,""].join(`\r
|
|
162
|
-
`)}function repoHooksPath(folder,{git,env=process.env,run:run2}){let home=env.HOME||os.homedir(),bare={HOME:home,PATH:env.PATH??"/usr/bin:/bin",...env.XDG_CONFIG_HOME?{XDG_CONFIG_HOME:env.XDG_CONFIG_HOME}:{},GIT_CONFIG_COUNT:"0",GIT_TERMINAL_PROMPT:"0"},ask2=args=>{let result=run2(git,args,{cwd:folder,env:bare,encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"]});return result?.status===0&&typeof result.stdout=="string"?result.stdout.trim():""},own2=ask2(["config","--get","core.hooksPath"]);if(!own2)return null;if(own2.startsWith("~/")&&(own2=path.join(home,own2.slice(2))),path.isAbsolute(own2))return path.resolve(own2);let top=ask2(["rev-parse","--show-toplevel"]);return top?path.resolve(top,own2):null}function pathsOf(platform){return platform==="win32"?path.win32:path.posix}function gitGuardBin(dir,platform=process.platform){return pathsOf(platform).join(dir,"bin")}function guardedPath(dir,searchPath="",platform=process.platform){let{delimiter}=pathsOf(platform);return[gitGuardBin(dir,platform),...searchPath.split(
|
|
162
|
+
`)}function repoHooksPath(folder,{git,env=process.env,run:run2}){let home=env.HOME||os.homedir(),bare={HOME:home,PATH:env.PATH??"/usr/bin:/bin",...env.XDG_CONFIG_HOME?{XDG_CONFIG_HOME:env.XDG_CONFIG_HOME}:{},GIT_CONFIG_COUNT:"0",GIT_TERMINAL_PROMPT:"0"},ask2=args=>{let result=run2(git,args,{cwd:folder,env:bare,encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"]});return result?.status===0&&typeof result.stdout=="string"?result.stdout.trim():""},own2=ask2(["config","--get","core.hooksPath"]);if(!own2)return null;if(own2.startsWith("~/")&&(own2=path.join(home,own2.slice(2))),path.isAbsolute(own2))return path.resolve(own2);let top=ask2(["rev-parse","--show-toplevel"]);return top?path.resolve(top,own2):null}function pathsOf(platform){return platform==="win32"?path.win32:path.posix}function gitGuardBin(dir,platform=process.platform){return pathsOf(platform).join(dir,"bin")}function guardedPath(dir,searchPath="",platform=process.platform){let{delimiter:delimiter2}=pathsOf(platform);return[gitGuardBin(dir,platform),...searchPath.split(delimiter2).filter(Boolean)].join(delimiter2)}var HOOKLESS_PUSH_COMMANDS=["send-pack","http-push"],PLAIN_GIT_COMMANDS="add|am|apply|blame|branch|cat-file|check-ignore|checkout|cherry-pick|clean|clone|commit|config|describe|diff|fetch|for-each-ref|grep|init|log|ls-files|ls-remote|ls-tree|merge|merge-base|mv|pull|rebase|reflog|remote|reset|restore|rev-list|rev-parse|revert|rm|show|show-ref|stash|status|switch|symbolic-ref|tag|update-index|version|worktree",SIGNING_OFF=[["commit.gpgsign","false"],["tag.gpgsign","false"]];function anyCase(text){return text.replace(/[a-z]/gi,c=>`[${c.toLowerCase()}${c.toUpperCase()}]`)}function gitShim(policy,realGit,entries){let guarded=policy.push==="never"||policy.deploy==="never",refuse=what=>`{ echo "Ando: this computer's owner doesn't let tasks ${what}." >&2; exit 1; }`,offHooks=refuse("skip or replace git's hooks"),shellAlias=refuse("run git aliases that start a shell command"),checks=`
|
|
163
163
|
# A setting that would switch the push hook off, include external config, or hide a push in an alias.
|
|
164
164
|
check_key() {
|
|
165
165
|
case "$1" in ${anyCase("core.hookspath")}*|${anyCase("alias.")}*|${anyCase("include.")}*|${anyCase("includeif.")}*) ${offHooks} ;; esac
|
|
@@ -258,8 +258,8 @@ ${tables}`:preamble||tables}function stringify(obj,{maxDepth=1e3,numbersAsFloat=
|
|
|
258
258
|
`)}module.exports={CLAUDE_OUTWARD_TOOLS,DEFAULT_POLICY,SECRET_PATHS,claudeTaskArgs,closedPaths,linkedPaths,canonicalizableWindowsPaths,mountablePaths,codexTaskArgs,fullAccessRunsHere,policyInstructions,resolvePolicy}}});var require_acp_protocol=__commonJS({"../../apps/web/electron/local-tools/acp-protocol.js"(exports,module){"use strict";var fs=__require("node:fs"),path=__require("node:path"),{resolvePolicy}=require_policy(),STEP_TEXT_LIMIT=280,PUSH_COMMAND_PATTERN=/(?:^|\s|[;&|()])(?:git\s+push\b|gh\s+(?:pr\s+create|repo\s+fork|gist\s+create|release\s+create)\b)/i,MERGE_COMMAND_PATTERN=/(?:^|\s|[;&|()])(?:gh\s+pr\s+merge\b|gh\s+api\b[^\n;|&]*\/pulls\/\d+\/merge\b)/i,DEPLOY_COMMAND_PATTERN=/(?:^|\s|[;&|()])(?:vercel(?:\s+--prod|\s+deploy)\b|netlify\s+deploy\b|fly(?:ctl)?\s+deploy\b|wrangler\s+(?:deploy|publish)\b|railway\s+up\b|kubectl\s+(?:apply|delete|rollout|set|patch)\b|terraform\s+(?:apply|destroy)\b|pulumi\s+(?:up|destroy)\b|helm\s+(?:install|upgrade|uninstall)\b|npm\s+publish\b|pnpm\s+publish\b|cargo\s+publish\b)/i,NETWORK_COMMAND_PATTERN=/(?:^|\s|[;&|()])(?:curl|wget|nc|ncat|netcat|ssh|scp|sftp|rsync)\b/i;function clip(value,max=STEP_TEXT_LIMIT){let text=typeof value=="string"?value.trim().replace(/\s+/g," "):"";return text.length>max?`${text.slice(0,max-1)}\u2026`:text}function shortPath(filePath,folder){if(typeof filePath!="string"||filePath.trim()==="")return"";let relative2=folder?path.relative(folder,filePath):filePath;return relative2&&!relative2.startsWith("..")&&!path.isAbsolute(relative2)?relative2:filePath}function sanitizeAcpSpawnEnv(baseEnv={},extraEnv={}){let clean={};for(let[key,value]of Object.entries(baseEnv))value==null||key.startsWith("ANDO_")||key.startsWith("ELECTRON_")||(clean[key]=String(value));clean.CI="1",clean.GIT_TERMINAL_PROMPT="0",clean.GH_PROMPT_DISABLED="1";for(let[key,value]of Object.entries(extraEnv))value==null?delete clean[key]:clean[key]=String(value);return clean}function isInsideRoot(candidatePath,rootPath){let resolvedCandidate=path.resolve(candidatePath),resolvedRoot=path.resolve(rootPath);if(resolvedCandidate===resolvedRoot)return!0;let rel=path.relative(resolvedRoot,resolvedCandidate);return rel!==""&&!rel.startsWith("..")&&!path.isAbsolute(rel)}var realpathSyncFn=fs.realpathSync.native??fs.realpathSync;function resolveRealOrParentPath(targetPath,depth=0){if(depth>16)return null;let current=path.resolve(targetPath),trailing=[];for(;;)try{let realCurrent=realpathSyncFn(current);return trailing.length===0?realCurrent:path.join(realCurrent,...trailing.reverse())}catch{try{if(fs.lstatSync(current).isSymbolicLink()){let linkTarget=fs.readlinkSync(current),resolvedLink=path.resolve(path.dirname(current),linkTarget),nextTarget=trailing.length===0?resolvedLink:path.join(resolvedLink,...trailing.reverse());return resolveRealOrParentPath(nextTarget,depth+1)}}catch{}let parent=path.dirname(current);if(parent===current)return trailing.length===0?current:path.join(current,...trailing.reverse());trailing.push(path.basename(current)),current=parent}}function extractToolPaths(toolCall,cwd){let found=[],locations=Array.isArray(toolCall?.locations)?toolCall.locations:[];for(let loc of locations)typeof loc?.path=="string"&&loc.path.trim()!==""&&found.push(path.isAbsolute(loc.path)?loc.path:path.resolve(cwd,loc.path));let raw=toolCall?.rawInput??toolCall?.arguments;if(raw&&typeof raw=="object")for(let key of["path","file_path","filePath","target_file","destination","source"]){let val=raw[key];typeof val=="string"&&val.trim()!==""&&found.push(path.isAbsolute(val)?val:path.resolve(cwd,val))}return[...new Set(found)]}function extractToolCommand(toolCall){let raw=toolCall?.rawInput??toolCall?.arguments;if(typeof raw=="string")return raw;if(raw&&typeof raw=="object"){if(typeof raw.command=="string")return raw.command;if(Array.isArray(raw.command))return raw.command.join(" ");if(typeof raw.cmd=="string")return raw.cmd;if(Array.isArray(raw.args)&&typeof raw.program=="string")return[raw.program,...raw.args].join(" ")}return typeof toolCall?.title=="string"?toolCall.title:""}function inferToolKind(toolCall){let explicit=typeof toolCall?.kind=="string"?toolCall.kind.toLowerCase():"";if(explicit)return explicit;let name=String(toolCall?.name||toolCall?.title||"").toLowerCase();return/\b(bash|shell|terminal|exec|command|run)\b/.test(name)?"execute":/\b(write|edit|patch|replace|create|delete|remove|rename|move)\b/.test(name)?"edit":/\b(fetch|http|web|url|browser)\b/.test(name)?"fetch":/\b(grep|glob|search|find|list)\b/.test(name)?"search":/\b(read|view|cat|open)\b/.test(name)?"read":"other"}function isReadOnlyMcpCall(toolCall){let label=String(toolCall?.name||toolCall?.title||"");return/(?:^|__|\/|:|\b)ando(?:__|\/|:|\s+|-)?(ask_wiki|get_ando_guide|get_message|get_miniapp_command|get_miniapp_instance|get_reconnection_instructions|get_skill|get_workspace_overview|list_calls|list_chats|list_connections|list_members|read_call|read_chat|read_file|read_inbox|read_thread|read_wiki_page|search_messages|search_wiki)\b/i.test(label)}function findOptionByIds(options,ids,labelPattern){for(let id of ids){let match=options.find(opt=>opt?.kind===id||opt?.optionId===id);if(match?.optionId)return match.optionId}return options.find(opt=>labelPattern.test(String(opt?.name||opt?.optionId||"")))?.optionId??null}function pickPermissionOption(options,allow){return!Array.isArray(options)||options.length===0?null:allow?findOptionByIds(options,["allow_once","allow-once","allow_always","allow-always"],/\b(allow|approve|yes)\b/i):findOptionByIds(options,["reject_once","reject-once","deny","reject_always","reject-always"],/\b(reject|deny|block|cancel|no)\b/i)}function checkPathBoundaries({paths,kind,cwd,allowedRoots,closed}){let gitInternal=path.join(cwd,".git"),gitHooksLexical=path.join(gitInternal,"hooks"),gitConfigLexical=path.resolve(gitInternal,"config"),gitHooksReal=resolveRealOrParentPath(gitHooksLexical),gitConfigReal=resolveRealOrParentPath(gitConfigLexical),realClosed=closed.map(secretPath=>({lexical:secretPath,real:resolveRealOrParentPath(secretPath)})).filter(Boolean),realAllowedRoots=allowedRoots.map(root=>resolveRealOrParentPath(root)).filter(Boolean),mutatesPath=kind==="edit"||kind==="delete"||kind==="move";for(let candidate of paths){let realCandidate=resolveRealOrParentPath(candidate);if(!realCandidate)return{allowed:!1,reason:"outside_folder"};if(realClosed.some(({lexical,real})=>isInsideRoot(candidate,lexical)||real!=null&&isInsideRoot(realCandidate,real)))return{allowed:!1,reason:"closed_path"};if(mutatesPath&&(isInsideRoot(candidate,gitHooksLexical)||path.resolve(candidate)===gitConfigLexical||gitHooksReal!=null&&isInsideRoot(realCandidate,gitHooksReal)||gitConfigReal!=null&&realCandidate===gitConfigReal))return{allowed:!1,reason:"git_guard_path"};if(!realAllowedRoots.some(root=>isInsideRoot(realCandidate,root)))return{allowed:!1,reason:"outside_folder"}}return null}function checkExecutePolicy(command,effective,fullAccess){return effective.commands!=="allow"?{allowed:!1,reason:"commands_never"}:fullAccess?effective.deploy!=="allow"&&MERGE_COMMAND_PATTERN.test(command)?{allowed:!1,reason:"merge_blocked"}:effective.push!=="allow"&&PUSH_COMMAND_PATTERN.test(command)?{allowed:!1,reason:"push_never"}:effective.deploy!=="allow"&&DEPLOY_COMMAND_PATTERN.test(command)?{allowed:!1,reason:"deploy_never"}:effective.network!=="allow"&&NETWORK_COMMAND_PATTERN.test(command)?{allowed:!1,reason:"network_never"}:{allowed:!0,reason:"commands_allowed"}:{allowed:!1,reason:"unsandboxed_shell_requires_full_access"}}function evaluateAcpPermission(input){let{toolCall,policy,cwd,linked=[],closed=[],platform=process.platform}=input||{},effective=resolvePolicy(policy,{platform}),fullAccess=effective.full_access==="allow",kind=inferToolKind(toolCall);if(!fullAccess){let pathBlock=checkPathBoundaries({paths:extractToolPaths(toolCall,cwd),kind,cwd,allowedRoots:[cwd,...linked].filter(Boolean),closed});if(pathBlock)return pathBlock}return isReadOnlyMcpCall(toolCall)?{allowed:!0,reason:"read_only_ando_mcp"}:kind==="read"||kind==="search"||kind==="think"?{allowed:!0,reason:"read_only"}:kind==="edit"||kind==="delete"||kind==="move"?effective.files==="allow"?{allowed:!0,reason:"files_allowed"}:{allowed:!1,reason:"files_never"}:kind==="fetch"?effective.network==="allow"?{allowed:!0,reason:"network_allowed"}:{allowed:!1,reason:"network_never"}:kind==="execute"?checkExecutePolicy(extractToolCommand(toolCall),effective,fullAccess):fullAccess?{allowed:!0,reason:"other_allowed"}:{allowed:!1,reason:"other_requires_full_access"}}function stepTargetText(rawField,fallback){return clip((typeof rawField=="string"?rawField:"")||fallback)}function formatFileStep(verb,tool,primaryFile,title){let target=primaryFile||title;return target?{text:primaryFile?`${verb} ${primaryFile}`:title,tool,target}:null}function formatPrefixedStep(prefix,tool,rawField,fallback){let target=stepTargetText(rawField,fallback);return target?{text:target.startsWith(prefix.split(" ")[0])?target:`${prefix} ${target}`,tool,target}:null}function readUpdateRawObject(update2){let raw=update2.rawInput??update2.arguments;return raw&&typeof raw=="object"?raw:{}}function acpStepFromUpdate(update2,folder){if(!update2||typeof update2!="object")return null;let kind=inferToolKind(update2),paths=extractToolPaths(update2,folder),primaryFile=paths[0]?shortPath(paths[0],folder):"",title=clip(update2.title||update2.name||""),rawObj=readUpdateRawObject(update2);if(kind==="read")return formatFileStep("Read","read",primaryFile,title);if(kind==="edit"||kind==="delete"||kind==="move")return formatFileStep("Edited","edit",primaryFile,title);if(kind==="execute"){let command=clip(extractToolCommand(update2));return formatFileStep("Ran","bash",command,title)}return kind==="search"?formatPrefixedStep("Searched for","search",rawObj.pattern||rawObj.query,primaryFile||title):kind==="fetch"?formatPrefixedStep("Looked up","web",rawObj.url||rawObj.query,title):title?kind==="think"?{text:title}:{text:title.startsWith("Used ")?title:`Used ${title}`}:null}function readTokenCount(rawUsage,keys){for(let key of keys)if(rawUsage[key]!==void 0&&rawUsage[key]!==null)return Number(rawUsage[key]);return 0}function readOptionalMetric(rawValue){let num=Number(rawValue);return rawValue!=null&&Number.isFinite(num)?num:null}function parseAcpUsage(rawUsage){if(!rawUsage||typeof rawUsage!="object")return null;let inputTokens=readTokenCount(rawUsage,["inputTokens","input_tokens","promptTokens"]),outputTokens=readTokenCount(rawUsage,["outputTokens","output_tokens","completionTokens"]),cachedInputTokens=readTokenCount(rawUsage,["cachedReadTokens","cachedInputTokens","cached_input_tokens"]),cacheWriteTokens=readTokenCount(rawUsage,["cachedWriteTokens","cacheWriteTokens","cache_creation_input_tokens"]);return!Number.isFinite(inputTokens)||!Number.isFinite(outputTokens)||inputTokens===0&&outputTokens===0&&cachedInputTokens===0?null:{inputTokens,cachedInputTokens:Number.isFinite(cachedInputTokens)?cachedInputTokens:0,cacheWriteTokens:Number.isFinite(cacheWriteTokens)?cacheWriteTokens:0,outputTokens,reasoningTokens:readOptionalMetric(rawUsage.thoughtTokens??rawUsage.reasoningTokens??rawUsage.reasoning_tokens),costUsd:readOptionalMetric(rawUsage.costUsd??rawUsage.cost_usd??rawUsage.cost?.amount)}}function extractUpdateChunkText(update2){return typeof update2?.content?.text=="string"?update2.content.text:typeof update2?.text=="string"?update2.text:""}function applyToolUpdateToRun(run2,update2){let commentary=clip(run2.currentSegment);commentary&&update2.sessionUpdate==="tool_call"&&(run2.currentSegment="",run2.onStep?.({text:commentary}));let callId=update2.toolCallId||update2.id||null,merged=callId&&run2.toolCalls.has(callId)?{...run2.toolCalls.get(callId),...update2}:{...update2};callId&&run2.toolCalls.set(callId,merged);let stepEntry=acpStepFromUpdate(merged,run2.StepFolder);if(!stepEntry)return;let signature=`${callId||""}:${stepEntry.tool||""}:${stepEntry.text}`;run2.emittedSteps.has(signature)||(run2.emittedSteps.add(signature),run2.onStep?.(stepEntry))}function applySessionUpdateToRun(run2,update2){let kind=update2.sessionUpdate;if(kind==="agent_message_chunk"){let chunk=extractUpdateChunkText(update2);chunk&&(run2.currentSegment+=chunk,run2.replyChunks.push(chunk));return}if(kind==="agent_thought_chunk"){let trimmed=extractUpdateChunkText(update2).trim();trimmed&&run2.onThought?.(trimmed);return}if(kind==="tool_call"||kind==="tool_call_update"){applyToolUpdateToRun(run2,update2);return}if(kind==="usage_update"||update2.usage){let parsed=parseAcpUsage(update2.usage??update2);parsed&&(run2.usage=parsed,run2.onUsage?.(parsed,run2.sessionId))}}module.exports={acpStepFromUpdate,applySessionUpdateToRun,evaluateAcpPermission,parseAcpUsage,pickPermissionOption,sanitizeAcpSpawnEnv}}});var require_mcp_proxy=__commonJS({"../../apps/web/electron/local-tools/mcp-proxy.js"(exports,module){"use strict";var crypto3=__require("node:crypto"),fs=__require("node:fs"),http=__require("node:http"),os=__require("node:os"),path=__require("node:path"),{findCommand:findCommand2}=require_toolchain(),{isAndoPostingTool}=require_outward_tools(),{readAntigravityServers,readGeminiServers,readOpenCodeServers}=require_servers(),DEFAULT_ANDO_MCP_URL="https://mcp.ando.so/mcp",MAX_BODY_BYTES=4*1024*1024,READ_ONLY_ANDO_TOOLS=new Set(["ask_wiki","get_ando_guide","get_message","get_miniapp_command","get_miniapp_instance","get_reconnection_instructions","get_skill","get_workspace_overview","list_calls","list_chats","list_connections","list_members","read_call","read_chat","read_file","read_inbox","read_thread","read_wiki_page","search_messages","search_wiki"]),WRITE_ANDO_TOOLS=new Set(["add_chat_members","connect_app_account","create_channel","delete_message","propose_agent_environment","publish_miniapp","publish_page","react_to_message","remove_chat_members","run_miniapp_action","save_message_draft","save_wiki_page","send_message","share_page","update_channel","update_inbox","upload_file"]),STDIO_HTTP_BRIDGE_SCRIPT=['const url = process.argv[1]; let sessionId = null; let buffer = ""; let chain = Promise.resolve();','function emitJsonLine(text) { const t = text.trim(); if (!t) return; try { process.stdout.write(JSON.stringify(JSON.parse(t)) + "\\n"); } catch {} }',"async function forward(line) {"," const trimmed = line.trim(); if (!trimmed) return;"," let parsed; try { parsed = JSON.parse(trimmed); } catch { return; }",' const headers = { "content-type": "application/json", accept: "application/json, text/event-stream" };',' if (sessionId) headers["mcp-session-id"] = sessionId;'," try {",' const res = await fetch(url, { method: "POST", headers, body: JSON.stringify(parsed) });',' const nextSession = res.headers.get("mcp-session-id"); if (nextSession) sessionId = nextSession;'," if (res.status === 202 || res.status === 204) return;",' const contentType = res.headers.get("content-type") || ""; const body = await res.text();',' if (contentType.includes("text/event-stream")) {'," for (const block of body.split(/\\r?\\n\\r?\\n/)) {",' const data = block.split(/\\r?\\n/).filter((l) => l.startsWith("data:")).map((l) => l.slice(5).trimStart()).join("\\n");'," if (data) emitJsonLine(data);"," }"," return;"," }"," if (!res.ok && parsed && parsed.id !== undefined) {"," let errBody = null; try { errBody = JSON.parse(body); } catch {}",' if (errBody && errBody.jsonrpc === "2.0") { emitJsonLine(body); return; }',' process.stdout.write(JSON.stringify({ jsonrpc: "2.0", id: parsed.id, error: { code: -32000, message: body || ("HTTP " + res.status) } }) + "\\n");'," return;"," }"," emitJsonLine(body);"," } catch (err) {"," if (parsed && parsed.id !== undefined) {",' process.stdout.write(JSON.stringify({ jsonrpc: "2.0", id: parsed.id, error: { code: -32000, message: err && err.message ? err.message : String(err) } }) + "\\n");'," }"," }","}",'process.stdin.setEncoding("utf8");','process.stdin.on("data", (chunk) => { buffer += chunk; let nl; while ((nl = buffer.indexOf("\\n")) >= 0) { const line = buffer.slice(0, nl); buffer = buffer.slice(nl + 1); chain = chain.then(() => forward(line)); } });','process.stdin.on("end", () => { if (buffer.trim()) chain = chain.then(() => forward(buffer)); });'].join(`
|
|
259
259
|
`);function deriveMcpUrlFromApiUrl(rawApiUrl){if(typeof rawApiUrl!="string"||rawApiUrl.trim()==="")return null;try{let parsed=new URL(rawApiUrl.trim());return parsed.protocol!=="https:"&&parsed.protocol!=="http:"?null:(parsed.hostname.startsWith("api.")&&(parsed.hostname=`mcp.${parsed.hostname.slice(4)}`),parsed.pathname="/mcp",parsed.search="",parsed.hash="",parsed.toString())}catch{return null}}function normalizeUpstreamMcpUrl(rawUrl){if(typeof rawUrl!="string"||rawUrl.trim()==="")return null;try{let parsed=new URL(rawUrl.trim());return parsed.protocol!=="https:"&&parsed.protocol!=="http:"?null:parsed.hostname.startsWith("api.")||/^\/v\d+(?:\/|$)/.test(parsed.pathname)?deriveMcpUrlFromApiUrl(rawUrl):((parsed.pathname==="/"||parsed.pathname==="")&&(parsed.pathname="/mcp"),parsed.toString())}catch{return null}}function resolveStdioNodeLaunch({nodeCommand=null,electronRunAsNode=null,env=process.env,isElectron=!!process.versions?.electron}={}){if(typeof nodeCommand=="string"&&nodeCommand.trim()!=="")return{command:nodeCommand,env:electronRunAsNode===!0?[{name:"ELECTRON_RUN_AS_NODE",value:"1"}]:[]};if(!isElectron)return{command:process.execPath,env:[]};let systemNode=findCommand2("node",env?.PATH??process.env.PATH);return systemNode?{command:systemNode,env:[]}:{command:process.execPath,env:[{name:"ELECTRON_RUN_AS_NODE",value:"1"}]}}function extractBearerFromHeaders(headers){if(!headers||typeof headers!="object")return null;for(let[key,value]of Object.entries(headers))if(key.toLowerCase()==="authorization"&&typeof value=="string"){let match=value.trim().match(/^Bearer\s+(.+)$/i);if(match?.[1]?.trim())return match[1].trim()}return null}function readConfiguredToolAndoEntry(provider,home,env){let readers=provider==="antigravity-cli"?[()=>readAntigravityServers(home)]:provider==="gemini-cli"?[()=>readGeminiServers(home)]:provider==="opencode"?[()=>readOpenCodeServers(home,env)]:[()=>readAntigravityServers(home),()=>readGeminiServers(home),()=>readOpenCodeServers(home,env)];for(let readTable of readers)try{let table=readTable(),entry=table&&typeof table=="object"?table.ando:null;if(entry&&typeof entry=="object"&&entry.enabled!==!1&&entry.disabled!==!0)return entry}catch{}return null}function readWorkspaceIdFromObject(obj){if(!obj||typeof obj!="object")return null;let unpacked=obj.data&&typeof obj.data=="object"?obj.data:obj,candidate=unpacked?.principal?.workspace_id??unpacked?.identity?.workspace_id??unpacked?.workspace?.id??unpacked?.workspace_id;return typeof candidate=="string"&&candidate.trim()!==""?candidate.trim():null}function readWorkspaceIdFromResult(result){if(!result||typeof result!="object")return null;let direct=readWorkspaceIdFromObject(result.structuredContent);if(direct)return direct;if(!Array.isArray(result.content))return null;for(let block of result.content)if(typeof block?.text=="string")try{let wsId=readWorkspaceIdFromObject(JSON.parse(block.text));if(wsId)return wsId}catch{}return null}function extractWorkspaceIdFromMcpPayload(payloadText){if(typeof payloadText!="string"||payloadText.trim()==="")return null;let candidates=[],trimmed=payloadText.trim();if(trimmed.startsWith("{")||trimmed.startsWith("["))try{candidates.push(JSON.parse(trimmed))}catch{}for(let line of payloadText.split(/\r?\n/))if(line.startsWith("data:"))try{candidates.push(JSON.parse(line.slice(5).trim()))}catch{}for(let msg of candidates){let item=Array.isArray(msg)?msg[0]:msg,wsId=readWorkspaceIdFromResult(item?.result);if(wsId)return wsId}return null}async function probeUpstreamWorkspaceId(targetUrl,token,fetchImpl){let baseHeaders={authorization:`Bearer ${token}`,"content-type":"application/json",accept:"application/json, text/event-stream"},sessionId;try{let initRes=await fetchImpl(targetUrl,{method:"POST",headers:baseHeaders,body:JSON.stringify({jsonrpc:"2.0",id:"ando-ws-init",method:"initialize",params:{protocolVersion:"2025-03-26",capabilities:{},clientInfo:{name:"ando-local-mcp-proxy",version:"1.0.0"}}})});if(!initRes.ok)return null;sessionId=initRes.headers.get("mcp-session-id"),await initRes.arrayBuffer()}catch{return null}let callHeaders=sessionId?{...baseHeaders,"mcp-session-id":sessionId}:baseHeaders;for(let toolName of["get_workspace_overview","get_current_principal"])try{let res=await fetchImpl(targetUrl,{method:"POST",headers:callHeaders,body:JSON.stringify({jsonrpc:"2.0",id:`ando-ws-${toolName}`,method:"tools/call",params:{name:toolName,arguments:{}}})});if(!res.ok)continue;let bodyText=Buffer.from(await res.arrayBuffer()).toString("utf8"),wsId=extractWorkspaceIdFromMcpPayload(bodyText);if(wsId)return wsId}catch{}return null}function nonEmptyTrimmed(value){return typeof value=="string"&&value.trim()!==""?value.trim():null}function resolveHostAndoMcpConfig({env=process.env,home=os.homedir(),provider=null,upstreamUrl=null,getToken=null,allowAmbientCliCredentials=!1,expectedWorkspaceId=null}={}){let configDir=env.XDG_CONFIG_HOME?.trim()||path.join(home,".config"),cliConfigFile=path.join(configDir,"ando","cli.json"),expectedWs=nonEmptyTrimmed(expectedWorkspaceId),workspaceMatches=candidateWs=>{let candidate=nonEmptyTrimmed(candidateWs);return!expectedWs||!candidate||candidate===expectedWs},readCliConfig=()=>{if(allowAmbientCliCredentials!==!0)return null;try{let parsed=JSON.parse(fs.readFileSync(cliConfigFile,"utf8"));return!parsed||typeof parsed!="object"||!workspaceMatches(parsed.workspaceId)?null:parsed}catch{return null}},resolveAmbientUrl=()=>{if(workspaceMatches(env.ANDO_WORKSPACE_ID)){let envUrl=normalizeUpstreamMcpUrl(env.ANDO_MCP_URL)||deriveMcpUrlFromApiUrl(env.ANDO_API_URL);if(envUrl)return envUrl}let cfg=readCliConfig(),cliUrl=normalizeUpstreamMcpUrl(cfg?.mcpUrl||cfg?.url)||deriveMcpUrlFromApiUrl(cfg?.apiUrl);if(cliUrl)return cliUrl;let toolEntry=readConfiguredToolAndoEntry(provider,home,env),toolUrl=normalizeUpstreamMcpUrl(toolEntry?.url??toolEntry?.httpUrl??toolEntry?.serverUrl);return toolUrl||(workspaceMatches(env.ANDO_WORKSPACE_ID)&&nonEmptyTrimmed(env.ANDO_API_KEY)!=null||!!cfg?.apiKey||extractBearerFromHeaders(toolEntry?.headers)!=null?DEFAULT_ANDO_MCP_URL:null)};return{resolveUrl:()=>{let explicit=normalizeUpstreamMcpUrl(upstreamUrl);if(explicit)return explicit;if(allowAmbientCliCredentials===!0){let ambient=resolveAmbientUrl();if(ambient)return ambient}return typeof getToken=="function"?normalizeUpstreamMcpUrl(env.ANDO_MCP_URL)||deriveMcpUrlFromApiUrl(env.ANDO_API_URL)||DEFAULT_ANDO_MCP_URL:null},resolveToken:async()=>{if(typeof getToken=="function"){let direct=nonEmptyTrimmed(await getToken());if(direct)return direct}if(allowAmbientCliCredentials!==!0)return null;if(workspaceMatches(env.ANDO_WORKSPACE_ID)){let envKey=nonEmptyTrimmed(env.ANDO_API_KEY);if(envKey)return envKey}let cfg=readCliConfig(),cliToken=nonEmptyTrimmed(cfg?.apiKey||cfg?.accessToken||cfg?.token);if(cliToken)return cliToken;let toolEntry=readConfiguredToolAndoEntry(provider,home,env);return extractBearerFromHeaders(toolEntry?.headers)||nonEmptyTrimmed(toolEntry?.env?.ANDO_API_KEY??toolEntry?.environment?.ANDO_API_KEY)}}}function isToolAllowedByPolicy(toolName,{policy,allowWriteTools,allowedTools,allowPosting=!1}){if(typeof toolName!="string"||toolName.trim()==="")return!1;let bare=toolName.replace(/^mcp__ando__|^ando[.:/]/,"");return allowPosting!==!0&&isAndoPostingTool(bare)?!1:allowedTools instanceof Set?allowedTools.has(bare)||allowedTools.has(toolName):policy?.full_access==="allow"||allowWriteTools===!0||READ_ONLY_ANDO_TOOLS.has(bare)?!0:(WRITE_ANDO_TOOLS.has(bare),policy?.network==="allow")}function checkJsonRpcMessagePolicy(msg,policyContext){if(!msg||typeof msg!="object"||msg.method!=="tools/call")return null;let toolName=msg.params?.name;return isToolAllowedByPolicy(toolName,policyContext)?null:{jsonrpc:"2.0",id:msg.id??null,error:{code:-32001,message:`Ando task policy blocks MCP tool "${String(toolName??"unknown")}" in this session.`}}}function readRequestBody(req){return new Promise((resolve4,reject)=>{let chunks=[],total=0;req.on("data",chunk=>{if(total+=chunk.length,total>MAX_BODY_BYTES){reject(Object.assign(new Error("Request body too large."),{statusCode:413})),req.destroy();return}chunks.push(chunk)}),req.on("end",()=>resolve4(Buffer.concat(chunks))),req.on("error",reject)})}function sendJson(res,status,payload){res.writeHead(status,{"content-type":"application/json"}),res.end(JSON.stringify(payload))}function validatePostPayload(bodyBuffer,policyContext){if(bodyBuffer.length===0)return null;let parsed;try{parsed=JSON.parse(bodyBuffer.toString("utf8"))}catch{return{status:400,payload:{jsonrpc:"2.0",id:null,error:{code:-32700,message:"Parse error"}}}}let items=Array.isArray(parsed)?parsed:[parsed];for(let item of items){let denied=checkJsonRpcMessagePolicy(item,policyContext);if(denied)return{status:200,payload:denied}}return null}function buildUpstreamHeaders(req,token){let headers={authorization:`Bearer ${token}`,accept:req.headers.accept||"application/json, text/event-stream"};return req.headers["content-type"]&&(headers["content-type"]=req.headers["content-type"]),req.headers["mcp-session-id"]&&(headers["mcp-session-id"]=String(req.headers["mcp-session-id"])),req.headers["mcp-protocol-version"]&&(headers["mcp-protocol-version"]=String(req.headers["mcp-protocol-version"])),headers}async function forwardUpstreamRequest({req,res,targetUrl,token,bodyBuffer,fetchImpl}){try{let upstream=await fetchImpl(targetUrl,{method:req.method,headers:buildUpstreamHeaders(req,token),body:req.method==="POST"?bodyBuffer:void 0}),responseHeaders={},contentType2=upstream.headers.get("content-type");contentType2&&(responseHeaders["content-type"]=contentType2);let sessionId=upstream.headers.get("mcp-session-id");sessionId&&(responseHeaders["mcp-session-id"]=sessionId);let payload=Buffer.from(await upstream.arrayBuffer());res.writeHead(upstream.status,responseHeaders),res.end(payload)}catch(error2){sendJson(res,502,{jsonrpc:"2.0",id:null,error:{code:-32003,message:`Ando MCP proxy upstream error: ${error2?.message||String(error2)}`}})}}async function createLocalMcpProxy(options={}){let{upstreamUrl=null,getToken=null,allowAmbientCliCredentials=!1,expectedWorkspaceId=null,provider=null,env=process.env,home=os.homedir(),policy=null,allowWriteTools=!1,allowedTools=null,allowPosting=!1,serverName="ando",nodeCommand=null,electronRunAsNode=null,isElectron=!!process.versions?.electron,fetchImpl=globalThis.fetch}=options||{},expectedWs=nonEmptyTrimmed(expectedWorkspaceId),{resolveUrl,resolveToken}=resolveHostAndoMcpConfig({env,home,provider,upstreamUrl,getToken,allowAmbientCliCredentials,expectedWorkspaceId:expectedWs}),stdioLaunch=resolveStdioNodeLaunch({nodeCommand,electronRunAsNode,env,isElectron}),initialUrl=resolveUrl(),initialToken=await resolveToken();if(!initialUrl||!initialToken||typeof fetchImpl!="function")return null;let verifiedTokens=new Map,verifyTokenWorkspace=(targetUrl,token)=>{if(!expectedWs)return Promise.resolve(!0);let cacheKey=`${targetUrl}\0${token}`,pending=verifiedTokens.get(cacheKey);return pending||(pending=probeUpstreamWorkspaceId(targetUrl,token,fetchImpl).then(actualWs=>actualWs===expectedWs),verifiedTokens.set(cacheKey,pending)),pending};if(!await verifyTokenWorkspace(initialUrl,initialToken))return null;let expectedPath=`/mcp/${crypto3.randomBytes(24).toString("hex")}`,allowedSet=Array.isArray(allowedTools)?new Set(allowedTools):allowedTools,policyContext={policy,allowWriteTools,allowedTools:allowedSet,allowPosting},sockets=new Set,server=http.createServer(async(req,res)=>{if(new URL(req.url||"/","http://127.0.0.1").pathname!==expectedPath)return sendJson(res,404,{error:"Not found"});if(req.method!=="POST"&&req.method!=="GET"&&req.method!=="DELETE")return sendJson(res,405,{error:"Method not allowed"});let bodyBuffer=Buffer.alloc(0);if(req.method==="POST"){try{bodyBuffer=await readRequestBody(req)}catch(error2){return sendJson(res,error2?.statusCode||400,{error:error2?.message||"Invalid request body"})}let rejected=validatePostPayload(bodyBuffer,policyContext);if(rejected)return sendJson(res,rejected.status,rejected.payload)}let targetUrl=resolveUrl(),token=await resolveToken();return!targetUrl||!token?sendJson(res,503,{jsonrpc:"2.0",id:null,error:{code:-32002,message:"Ando MCP credentials are unavailable."}}):await verifyTokenWorkspace(targetUrl,token)?forwardUpstreamRequest({req,res,targetUrl,token,bodyBuffer,fetchImpl}):sendJson(res,403,{jsonrpc:"2.0",id:null,error:{code:-32004,message:"Ando MCP credentials do not belong to this task's workspace."}})});server.on("connection",socket=>{sockets.add(socket),socket.on("close",()=>sockets.delete(socket))}),await new Promise((resolve4,reject)=>{server.once("error",reject),server.listen(0,"127.0.0.1",()=>{server.removeListener("error",reject),resolve4()})});let address=server.address(),port=typeof address=="object"&&address?address.port:0,proxyUrl=`http://127.0.0.1:${port}${expectedPath}`,closed=!1;return{url:proxyUrl,port,serverName,mcpServerForCapabilities(agentCapabilities){return agentCapabilities?.mcpCapabilities?.http===!0?{type:"http",name:serverName,url:proxyUrl,headers:[]}:{name:serverName,command:stdioLaunch.command,args:["-e",STDIO_HTTP_BRIDGE_SCRIPT,proxyUrl],env:stdioLaunch.env}},async close(){if(!closed){closed=!0;for(let socket of sockets)socket.destroy();sockets.clear(),await new Promise(resolve4=>server.close(()=>resolve4()))}}}}module.exports={READ_ONLY_ANDO_TOOLS,STDIO_HTTP_BRIDGE_SCRIPT,WRITE_ANDO_TOOLS,createLocalMcpProxy,deriveMcpUrlFromApiUrl,isToolAllowedByPolicy,normalizeUpstreamMcpUrl,resolveHostAndoMcpConfig,resolveStdioNodeLaunch}}});var require_acp_runtime=__commonJS({"../../apps/web/electron/local-tools/acp-runtime.js"(exports,module){"use strict";var os=__require("node:os"),readline=__require("node:readline"),{acpStepFromUpdate,applySessionUpdateToRun,evaluateAcpPermission,parseAcpUsage,pickPermissionOption,sanitizeAcpSpawnEnv}=require_acp_protocol(),{createLastErrorLine,exitMessage}=require_last_error_line(),{createLocalMcpProxy}=require_mcp_proxy(),{closedPaths,linkedPaths}=require_policy(),IDLE_EXIT_MS=15*6e4;function formatSteerMessage(texts){return texts.join(`
|
|
260
260
|
|
|
261
|
-
`)}function safeCloseChildProcess(child){try{child.stdin?.end()}catch{}try{child.kill()}catch{}}function createAcpRuntime(options){let{spawn:
|
|
262
|
-
`),!0)}function teardownProcess(error2){clearTimer(idleTimer),idleTimer=null;let current=proc;proc=null;for(let[,pending]of pendingRequests)pending.reject(error2);pendingRequests.clear();for(let cancelPermission of pendingPermissions)cancelPermission();pendingPermissions.clear(),current?.child&&safeCloseChildProcess(current.child)}async function resolveCustomPermissionHook({id,params,toolCall,options:permOptions,decision,child}){let settled=!1,cancelHook=()=>{settled||(settled=!0,pendingPermissions.delete(cancelHook),sendRaw({jsonrpc:"2.0",id,result:{outcome:{outcome:"cancelled"}}},child))};pendingPermissions.add(cancelHook);try{let override=await onPermissionRequest({sessionId:params?.sessionId??null,toolCall,options:permOptions,policyDecision:decision});return settled?{handled:!0,allowed:!1}:(settled=!0,pendingPermissions.delete(cancelHook),override&&typeof override=="object"&&override.outcome?(sendRaw({jsonrpc:"2.0",id,result:override},child),{handled:!0,allowed:!1}):{handled:!1,allowed:typeof override=="boolean"?override:decision.allowed})}catch{return settled?{handled:!0,allowed:!1}:(settled=!0,pendingPermissions.delete(cancelHook),{handled:!1,allowed:!1})}}async function handleIncomingRequest(message,child){let{id,method,params}=message;if(method!=="session/request_permission"){sendRaw({jsonrpc:"2.0",id,error:{code:-32601,message:`Unsupported client method: ${String(method)}`}},child);return}if(closed){sendRaw({jsonrpc:"2.0",id,result:{outcome:{outcome:"cancelled"}}},child);return}let toolCall=params?.toolCall??{},permOptions=Array.isArray(params?.options)?params.options:[],activeRun=[...activeRuns.values()].find(r=>r.sessionId===params?.sessionId)??[...activeRuns.values()][0]??null,decision=evaluateAcpPermission({toolCall,policy,cwd:activeRun?.projectFolder||cwd,linked,closed:closedSecretPaths,platform}),allowed=decision.allowed;if(allowed&&typeof onPermissionRequest=="function"){let hookResult=await resolveCustomPermissionHook({id,params,toolCall,options:permOptions,decision,child});if(hookResult.handled)return;allowed=hookResult.allowed}let optionId=pickPermissionOption(permOptions,allowed);sendRaw({jsonrpc:"2.0",id,result:optionId?{outcome:{outcome:"selected",optionId}}:{outcome:{outcome:"cancelled"}}},child)}function handleSessionUpdate(params){let update2=params?.update;if(!update2||typeof update2!="object")return;let sessionId=params?.sessionId,run2=sessionId&&[...activeRuns.values()].find(entry=>entry.sessionId===sessionId)||(activeRuns.size===1?[...activeRuns.values()][0]:null);!run2||run2.suppressUpdates||applySessionUpdateToRun(run2,update2)}function handleJsonRpcLine(line,child){let trimmed=line.trim();if(!trimmed)return;let message;try{message=JSON.parse(trimmed)}catch{return}if(message.id!==void 0&&typeof message.method=="string"){handleIncomingRequest(message,child);return}if(message.id!==void 0){let pending=pendingRequests.get(message.id);if(!pending)return;if(pendingRequests.delete(message.id),message.error){let err=new Error(message.error.message||`${toolLabel} RPC error`);err.code=message.error.code,pending.reject(err)}else pending.resolve(message.result);return}message.method==="session/update"&&handleSessionUpdate(message.params)}async function ensureMcpProxyReady(){if(closed)throw stoppedError();if(!(mcpProxy||ownedMcpProxy||mcpProxyOptions===!1)){if(startingMcpProxy){if(await startingMcpProxy,closed)throw stoppedError();return}startingMcpProxy=createLocalMcpProxy({env,home,policy,...mcpProxyOptions&&typeof mcpProxyOptions=="object"?mcpProxyOptions:{}});try{let created=await startingMcpProxy;if(closed)throw created&&await created.close().catch(()=>{}),stoppedError();ownedMcpProxy=created}finally{startingMcpProxy=null}}}async function ensureProcess(spawnCwd){if(closed)throw stoppedError();if(proc?.ready)return proc;if(proc?.starting)return proc.starting;let child=
|
|
261
|
+
`)}function safeCloseChildProcess(child){try{child.stdin?.end()}catch{}try{child.kill()}catch{}}function createAcpRuntime(options){let{spawn:spawn6,command="gemini",args=["--acp"],toolLabel="ACP agent",env=process.env,extraEnv={},cwd,instructions="",policy=null,mcpServers=[],mcpProxy=null,mcpProxyOptions=!1,home=os.homedir(),platform=process.platform,onPermissionRequest=null,idleExitMs=IDLE_EXIT_MS,setTimer=setTimeout,clearTimer=clearTimeout}=options||{},proc=null,closed=!1,idleTimer=null,nextId=1,agentCapabilities=null,ownedMcpProxy=null,startingMcpProxy=null,pendingRequests=new Map,pendingPermissions=new Set,activeRuns=new Map,linked=cwd?linkedPaths(cwd).linked:[],closedSecretPaths=cwd?closedPaths(cwd,{home,linked,platform}):[];function stoppedError(){return new Error("This agent was stopped")}function armIdleTimer(){clearTimer(idleTimer),idleTimer=setTimer(()=>{if(activeRuns.size>0){armIdleTimer();return}teardownProcess(new Error(`${toolLabel} idle timeout`))},idleExitMs),idleTimer?.unref?.()}function sendRaw(payload,child=proc?.child){return!child?.stdin||child.stdin.destroyed?!1:(child.stdin.write(`${JSON.stringify(payload)}
|
|
262
|
+
`),!0)}function teardownProcess(error2){clearTimer(idleTimer),idleTimer=null;let current=proc;proc=null;for(let[,pending]of pendingRequests)pending.reject(error2);pendingRequests.clear();for(let cancelPermission of pendingPermissions)cancelPermission();pendingPermissions.clear(),current?.child&&safeCloseChildProcess(current.child)}async function resolveCustomPermissionHook({id,params,toolCall,options:permOptions,decision,child}){let settled=!1,cancelHook=()=>{settled||(settled=!0,pendingPermissions.delete(cancelHook),sendRaw({jsonrpc:"2.0",id,result:{outcome:{outcome:"cancelled"}}},child))};pendingPermissions.add(cancelHook);try{let override=await onPermissionRequest({sessionId:params?.sessionId??null,toolCall,options:permOptions,policyDecision:decision});return settled?{handled:!0,allowed:!1}:(settled=!0,pendingPermissions.delete(cancelHook),override&&typeof override=="object"&&override.outcome?(sendRaw({jsonrpc:"2.0",id,result:override},child),{handled:!0,allowed:!1}):{handled:!1,allowed:typeof override=="boolean"?override:decision.allowed})}catch{return settled?{handled:!0,allowed:!1}:(settled=!0,pendingPermissions.delete(cancelHook),{handled:!1,allowed:!1})}}async function handleIncomingRequest(message,child){let{id,method,params}=message;if(method!=="session/request_permission"){sendRaw({jsonrpc:"2.0",id,error:{code:-32601,message:`Unsupported client method: ${String(method)}`}},child);return}if(closed){sendRaw({jsonrpc:"2.0",id,result:{outcome:{outcome:"cancelled"}}},child);return}let toolCall=params?.toolCall??{},permOptions=Array.isArray(params?.options)?params.options:[],activeRun=[...activeRuns.values()].find(r=>r.sessionId===params?.sessionId)??[...activeRuns.values()][0]??null,decision=evaluateAcpPermission({toolCall,policy,cwd:activeRun?.projectFolder||cwd,linked,closed:closedSecretPaths,platform}),allowed=decision.allowed;if(allowed&&typeof onPermissionRequest=="function"){let hookResult=await resolveCustomPermissionHook({id,params,toolCall,options:permOptions,decision,child});if(hookResult.handled)return;allowed=hookResult.allowed}let optionId=pickPermissionOption(permOptions,allowed);sendRaw({jsonrpc:"2.0",id,result:optionId?{outcome:{outcome:"selected",optionId}}:{outcome:{outcome:"cancelled"}}},child)}function handleSessionUpdate(params){let update2=params?.update;if(!update2||typeof update2!="object")return;let sessionId=params?.sessionId,run2=sessionId&&[...activeRuns.values()].find(entry=>entry.sessionId===sessionId)||(activeRuns.size===1?[...activeRuns.values()][0]:null);!run2||run2.suppressUpdates||applySessionUpdateToRun(run2,update2)}function handleJsonRpcLine(line,child){let trimmed=line.trim();if(!trimmed)return;let message;try{message=JSON.parse(trimmed)}catch{return}if(message.id!==void 0&&typeof message.method=="string"){handleIncomingRequest(message,child);return}if(message.id!==void 0){let pending=pendingRequests.get(message.id);if(!pending)return;if(pendingRequests.delete(message.id),message.error){let err=new Error(message.error.message||`${toolLabel} RPC error`);err.code=message.error.code,pending.reject(err)}else pending.resolve(message.result);return}message.method==="session/update"&&handleSessionUpdate(message.params)}async function ensureMcpProxyReady(){if(closed)throw stoppedError();if(!(mcpProxy||ownedMcpProxy||mcpProxyOptions===!1)){if(startingMcpProxy){if(await startingMcpProxy,closed)throw stoppedError();return}startingMcpProxy=createLocalMcpProxy({env,home,policy,...mcpProxyOptions&&typeof mcpProxyOptions=="object"?mcpProxyOptions:{}});try{let created=await startingMcpProxy;if(closed)throw created&&await created.close().catch(()=>{}),stoppedError();ownedMcpProxy=created}finally{startingMcpProxy=null}}}async function ensureProcess(spawnCwd){if(closed)throw stoppedError();if(proc?.ready)return proc;if(proc?.starting)return proc.starting;let child=spawn6(command,args,{cwd:spawnCwd||cwd,env:sanitizeAcpSpawnEnv(env,extraEnv),stdio:["pipe","pipe","pipe"]}),lastError=createLastErrorLine();child.stderr?.on("data",chunk=>lastError.push(chunk));let instance={child,ready:!1,starting:null};proc=instance;let onExit=error2=>{if(proc===instance)teardownProcess(error2);else{for(let[,pending]of pendingRequests)pending.reject(error2);pendingRequests.clear()}for(let[,run2]of activeRuns)run2.abort?.(error2)};return child.on("error",onExit),child.on("close",(code2,signal)=>onExit(new Error(exitMessage(toolLabel,signal??code2,lastError)))),child.stdin?.on("error",onExit),readline.createInterface({input:child.stdout}).on("line",line=>handleJsonRpcLine(line,child)),instance.starting=(async()=>(await ensureMcpProxyReady(),agentCapabilities=(await rpcCall("initialize",{protocolVersion:1,clientCapabilities:{},clientInfo:{name:"ando-local-tools",version:"1.0.0"}},child))?.agentCapabilities??{},instance.ready=!0,instance.starting=null,instance))(),instance.starting}function rpcCall(method,params,targetChild=proc?.child){return new Promise((resolve4,reject)=>{if(closed){reject(stoppedError());return}let id=nextId++;pendingRequests.set(id,{resolve:resolve4,reject}),sendRaw({jsonrpc:"2.0",id,method,params},targetChild)||(pendingRequests.delete(id),reject(new Error(`${toolLabel} stdin is closed`)))})}function buildSessionMcpServers(){let activeProxy=mcpProxy||ownedMcpProxy,list=[],seenNames=new Set;if(activeProxy&&typeof activeProxy.mcpServerForCapabilities=="function"){let descriptor=activeProxy.mcpServerForCapabilities(agentCapabilities);descriptor&&typeof descriptor=="object"&&(list.push(descriptor),descriptor.name&&seenNames.add(descriptor.name))}if(Array.isArray(mcpServers))for(let server of mcpServers)server&&typeof server=="object"&&server.name&&!seenNames.has(server.name)&&(seenNames.add(server.name),list.push(server));return list}async function openOrLoadSession({sessionId,sessionCwd}){let sessionMcpServers=buildSessionMcpServers();if(sessionId&&agentCapabilities?.loadSession===!0)try{return{sessionId:(await rpcCall("session/load",{sessionId,cwd:sessionCwd,mcpServers:sessionMcpServers}))?.sessionId||sessionId,loadedExisting:!0}}catch{}let created=await rpcCall("session/new",{cwd:sessionCwd,mcpServers:sessionMcpServers});if(!created?.sessionId||typeof created.sessionId!="string")throw new Error(`${toolLabel} did not return a sessionId from session/new`);return{sessionId:created.sessionId,loadedExisting:!1}}return{async runTurn(turnOptions){let{key,sessionId=null,text,newSessionText,projectFolder,onStarted,onSession,onStep,onThought,onUsage,answerSteers=!1}=turnOptions||{};if(clearTimer(idleTimer),closed)throw stoppedError();let effectiveCwd=cwd||projectFolder,runState={key,sessionId:sessionId||null,projectFolder:effectiveCwd,StepFolder:effectiveCwd,suppressUpdates:!!sessionId,replyChunks:[],currentSegment:"",toolCalls:new Map,emittedSteps:new Set,queuedSteers:[],usage:null,onStep,onThought,onUsage,abort:null};activeRuns.set(key,runState);try{if(await ensureProcess(effectiveCwd),closed)throw stoppedError();let opened=await openOrLoadSession({sessionId,sessionCwd:effectiveCwd});runState.sessionId=opened.sessionId,runState.suppressUpdates=!1,runState.replyChunks=[],runState.currentSegment="",onStarted?.(),onSession?.(opened.sessionId);let initialText=text;sessionId&&!opened.loadedExisting&&typeof newSessionText=="function"&&(initialText=await newSessionText());let promptBody=instructions?`<ando_task_instructions>
|
|
263
263
|
${instructions}
|
|
264
264
|
</ando_task_instructions>
|
|
265
265
|
|
|
@@ -269,7 +269,7 @@ ${initialText}`:initialText,executePrompt=async messageText=>{runState.replyChun
|
|
|
269
269
|
Ando ran this with ${which}, the \`codex\` command on this computer's PATH. It may be older than the Codex app's own copy, and older versions can't use newer models. Update it (\`npm i -g @openai/codex@latest\` or \`brew upgrade codex\`), check with \`codex --version\`, then quit and reopen Ando.`}function unansweredSteersText(steers){return["These messages arrived as you finished, and may not have reached you:",...steers.map(steer=>steer.text),"Act on them, then reply with what you did about them."].join(`
|
|
270
270
|
|
|
271
271
|
`)}function noteItem(turn,item,completed){if(item?.type==="userMessage")for(let steer of turn.steers)steer.id===item.clientId&&(steer.taken=!0);if(!completed)return;let thought=codexThought(item);if(thought&&turn.onThought?.(thought),item?.type==="agentMessage"&&typeof item.text=="string"){item.phase==="final_answer"?turn.final.push(item.text):turn.last=item.text;for(let steer of turn.steers)steer.taken&&(steer.answered=!0)}}function withResumedInstructions(instructions,text){return instructions?["<ando_task_instructions>","Ando's instructions for this run. They replace the task instructions this session started with: where those differ (the run id in a file name, whether you may post in Ando, the folder), follow these.","",instructions,"</ando_task_instructions>","",text].join(`
|
|
272
|
-
`):text}var EXIT_CLOSE_GRACE_MS=500,METADATA_TIMEOUT_MS=5e3;function createCodexRuntime({spawn:
|
|
272
|
+
`):text}var EXIT_CLOSE_GRACE_MS=500,METADATA_TIMEOUT_MS=5e3;function createCodexRuntime({spawn:spawn6,env,cwd,instructions,log:log2,sandbox=null,serverArgs=[],windowsSandbox=!1,onWindowsSandboxReady=()=>{},effort=null,model=null}){let server=null,closed=!1,stopped=()=>new Error("This agent was stopped");function startServer(){let args=["app-server","--listen","stdio://"];args.push(...serverArgs);let child=spawn6("codex",args,{cwd,env,stdio:["pipe","pipe","pipe"]}),lastError=createLastErrorLine();child.stderr?.on("data",chunk=>lastError.push(chunk));let state={child,nextId:0,pending:new Map,turns:new Map,threadsByKey:new Map,loadedThreads:new Set,usageByThread:new Map,ready:null,windowsSetup:null,version:null},fail=error2=>{state.windowsSetup?.reject(error2);for(let request2 of state.pending.values())request2.reject(error2);for(let turn of state.turns.values())turn.reject(error2);state.pending.clear(),state.turns.clear(),server===state&&(server=null)};child.on("error",error2=>fail(startFailure("Codex","codex",error2))),child.stdin?.on("error",error2=>fail(error2));let failExited=(code2,signal)=>fail(new Error(exitMessage("Codex",signal??code2,lastError)));return child.on("close",failExited),child.on("exit",(code2,signal)=>{setTimeout(()=>failExited(code2,signal),EXIT_CLOSE_GRACE_MS).unref?.()}),readline.createInterface({input:child.stdout}).on("line",line=>handleLine(state,line)),state.ready=request(state,"initialize",{clientInfo:{name:"ando-desktop",title:"Ando",version:"1"},capabilities:{experimentalApi:!0}}).then(result=>(state.version=codexVersion(result?.userAgent),write(state,{method:"initialized"}))).then(async()=>{windowsSandbox&&(await ensureWindowsSandbox(state),onWindowsSandboxReady())}),state}async function ensureWindowsSandbox(state){let readiness;try{readiness=await request(state,"windowsSandbox/readiness",void 0)}catch(error2){throw new Error(`Update Codex to run tasks on Windows: ${error2.message}`,{cause:error2})}if(readiness?.status==="ready")return;let completed=new Promise((resolve4,reject)=>{state.windowsSetup={resolve:resolve4,reject}});completed.catch(()=>{});let result;try{result=(await request(state,"windowsSandbox/setupStart",{mode:"elevated",cwd}))?.started===!1?{success:!1,error:null}:await completed}finally{state.windowsSetup=null}if(!result?.success)throw new Error(`Codex's Windows sandbox isn't set up${result?.error?` (${result.error})`:""}. Approve Windows' prompt to set it up, then try again.`)}function write(state,message){let stdin=state.child.stdin;if(stdin==null||stdin.destroyed||!stdin.writable)throw new Error("Codex isn't running");stdin.write(`${JSON.stringify(message)}
|
|
273
273
|
`)}function request(state,method,params,timeoutMs=null){state.nextId+=1;let id=state.nextId,timer;return new Promise((resolve4,reject)=>{state.pending.set(id,{method,resolve:resolve4,reject}),timeoutMs!=null&&(timer=setTimeout(()=>{state.pending.delete(id),reject(new Error(`${method} timed out`))},timeoutMs));try{write(state,{id,method,params})}catch(error2){state.pending.delete(id),reject(error2)}}).finally(()=>clearTimeout(timer))}function handleLine(state,line){let message;try{message=JSON.parse(line)}catch{return}if(message.id!=null&&message.method==null){let pending=state.pending.get(message.id);if(!pending)return;state.pending.delete(message.id),message.error?pending.reject(new Error(message.error.message||`${pending.method} failed`)):pending.resolve(message.result);return}if(message.id!=null){log2.warn("[Local agents] declined Codex request",message.method);try{write(state,{id:message.id,error:{code:-32601,message:"Not supported by Ando desktop"}})}catch{}return}let params=message.params??{};if(message.method==="windowsSandbox/setupCompleted"){state.windowsSetup?.resolve(params);return}if(message.method==="thread/tokenUsage/updated"){let usage=codexUsage(params.tokenUsage);usage!=null&&typeof params.threadId=="string"&&state.usageByThread.set(params.threadId,usage);return}let turn=state.turns.get(params.threadId);turn&&(message.method==="turn/started"&¶ms.turn?.id?turn.turnId??=params.turn.id:message.method==="item/started"||message.method==="item/completed"?noteItem(turn,params.item,message.method==="item/completed"):message.method==="turn/completed"&&completeTurn(state,params.threadId,turn,params.turn))}function completeTurn(state,threadId,turn,result){if(state.turns.delete(threadId),result?.status==="failed"){turn.reject(new Error(turnFailureMessage(result?.error?.message||"Turn failed",state.version)));return}turn.replies.push(turn.final.join(`
|
|
274
274
|
|
|
275
275
|
`)||turn.last||"");let unanswered=turn.answerSteers?turn.steers.filter(steer=>!steer.answered):[];for(let steer of unanswered)steer.handedOn=!0;if(unanswered.length>0){startTurn(state,threadId,turn,unansweredSteersText(unanswered)).catch(turn.reject);return}turn.resolve(turn.replies.filter(Boolean).join(`
|
|
@@ -277,14 +277,14 @@ Ando ran this with ${which}, the \`codex\` command on this computer's PATH. It m
|
|
|
277
277
|
`))}async function startTurn(state,threadId,turn,text){Object.assign(turn,{final:[],last:"",turnId:null,steers:[]}),state.turns.set(threadId,turn);try{let response=await request(state,"turn/start",{threadId,input:[{type:"text",text,text_elements:[]}],...effort?{effort}:{},...model?{model}:{}});turn.turnId??=response?.turn?.id??null}catch(error2){throw state.turns.get(threadId)===turn&&state.turns.delete(threadId),error2}}async function taskProject(state,projectFolder){if(!projectFolder)return null;let deadline=Date.now()+METADATA_TIMEOUT_MS;try{return await resolveCodexProject((method,params)=>{let remaining=deadline-Date.now();if(remaining<=0)throw new Error("Codex project lookup timed out");return request(state,method,params,remaining)},projectFolder)}catch(error2){return log2.warn("[Local agents] could not resolve Codex task project",error2),null}}async function updateTaskIdentity(state,threadId,projectId,title){if(projectId)try{await request(state,"thread/metadata/update",{threadId,projectId},METADATA_TIMEOUT_MS)}catch(error2){log2.warn("[Local agents] could not associate Codex task with its project",error2)}if(title)try{await request(state,"thread/name/set",{threadId,name:title},METADATA_TIMEOUT_MS)}catch(error2){log2.warn("[Local agents] could not name Codex task",error2)}}async function openThread(state,sessionId,projectFolder){if(sessionId&&state.loadedThreads.has(sessionId))return{threadId:sessionId,resumed:!0,reinstruct:!1};let projectId=await taskProject(state,projectFolder),shared={cwd,approvalPolicy:"never",...sandbox==null?{}:{sandbox},developerInstructions:instructions},resumed=!1;if(sessionId)try{await request(state,"thread/resume",{...shared,threadId:sessionId}),resumed=!0}catch(error2){log2.warn("[Local agents] could not resume Codex thread",error2)}if(resumed)return await updateTaskIdentity(state,sessionId,projectId,null),state.loadedThreads.add(sessionId),{threadId:sessionId,resumed:!0,reinstruct:!0};let threadId=(await request(state,"thread/start",{...shared,...projectId?{projectId}:{}}))?.thread?.id;if(typeof threadId!="string")throw new Error("Codex returned no thread");return state.loadedThreads.add(threadId),{threadId,resumed:!1,reinstruct:!1}}return{async runTurn({key,sessionId,text,newSessionText,projectFolder,title,onThought,onStarted,onSession,answerSteers=!1}){if(closed)throw stopped();server??=startServer();let state=server;await state.ready;let{threadId,resumed,reinstruct}=await openThread(state,sessionId,projectFolder);onSession?.(threadId),!resumed&&projectFolder&&await updateTaskIdentity(state,threadId,null,codexTaskTitle(title,text));let message=resumed||!newSessionText?text:await newSessionText(),input=reinstruct?withResumedInstructions(instructions,message):message;if(closed)throw stopped();state.threadsByKey.set(key,threadId);let turn={onThought,answerSteers,replies:[]},reply=new Promise((resolve4,reject)=>{Object.assign(turn,{resolve:resolve4,reject})});await startTurn(state,threadId,turn,input),onStarted?.();let answered=await reply,usage=state.usageByThread.get(threadId);return{sessionId:threadId,reply:answered,...usage==null?{}:{usage}}},async steer({key,text}){let state=server,threadId=state?.threadsByKey.get(key),turn=threadId&&state.turns.get(threadId);if(!turn?.turnId)return!1;let steers=turn.answerSteers?turn.steers:null,steer={id:randomUUID3(),text,taken:!1,answered:!1,handedOn:!1};steers?.push(steer);try{return await request(state,"turn/steer",{threadId,input:[{type:"text",text,text_elements:[]}],expectedTurnId:turn.turnId,...steers==null?{}:{clientUserMessageId:steer.id}}),!0}catch(error2){if(steer.handedOn)return!0;if(steers?.splice(steers.indexOf(steer),1),/no active turn|expected.*turn|turn.*mismatch/i.test(error2.message))return!1;throw error2}},close(){closed=!0,server?.child.kill(),server=null}}}module.exports={codexVersion,createCodexRuntime,turnFailureMessage}}});var require_credentials=__commonJS({"../../apps/web/electron/local-tools/credentials.js"(exports,module){"use strict";var childProcess=__require("child_process"),fs=__require("fs"),os=__require("os"),path=__require("path"),{commandFileNames}=require_toolchain(),KNOWN_GITS=["/usr/bin/git","/usr/local/bin/git","/opt/homebrew/bin/git","/opt/local/bin/git","/Library/Developer/CommandLineTools/usr/bin/git"],SIGN_IN_PROGRAMS=["/usr/bin/security"];function realPathOf(p){try{return fs.realpathSync(p)}catch{return null}}function isExecutable(p){try{return fs.accessSync(p,fs.constants.X_OK),fs.statSync(p).isFile()}catch{return!1}}function listDir(dir){try{return fs.readdirSync(dir)}catch{return[]}}function findAll(name,searchPath="",options={}){let names=commandFileNames(name,options),dirs=[...new Set(searchPath.split(path.delimiter).filter(dir=>path.isAbsolute(dir)))];return[...new Set(dirs.flatMap(dir=>names.map(fileName=>path.join(dir,fileName))).filter(isExecutable))]}function shellWords(line,home){let words=[],word=null,quote=null;for(let index=0;index<line.length;index+=1){let char=line[index];if(quote==="'"){char==="'"?quote=null:word+=char;continue}if(quote==='"'){char==='"'?quote=null:char==="\\"&&index+1<line.length&&'"\\$`'.includes(line[index+1])?word+=line[++index]:word+=char;continue}if(/\s/.test(char)){word!=null&&words.push(word),word=null;continue}word??="",char==="'"||char==='"'?quote=char:char==="\\"&&index+1<line.length?word+=line[++index]:char==="~"&&word===""&&(index+1===line.length||line[index+1]==="/")?word+=home:word+=char}return word!=null&&words.push(word),words}function parseHelper(value,home){let shell=value.startsWith("!"),words=shellWords(shell?value.slice(1):value,home);if(words.length===0)return null;let expand=word=>word==="~"||word.startsWith("~/")?path.join(home,word.slice(1)):word,paths=words.slice(1).map(word=>expand(word.replace(/^--?[A-Za-z-]+=/,""))).filter(word=>path.isAbsolute(word)),program=words[0];return path.isAbsolute(program)?{program,paths}:{program:shell?program:`git-credential-${program}`,paths}}function readGit(git,{env,folder,run:run2}){let bare={HOME:env.HOME??os.homedir(),PATH:env.PATH??"/usr/bin:/bin",...env.XDG_CONFIG_HOME?{XDG_CONFIG_HOME:env.XDG_CONFIG_HOME}:{},...env.DEVELOPER_DIR?{DEVELOPER_DIR:env.DEVELOPER_DIR}:{},GIT_TERMINAL_PROMPT:"0"},ask2=(args,cwd)=>{let result=run2(git,args,{cwd,env:bare,encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"]});return result?.status===0&&typeof result.stdout=="string"?result.stdout:""},execPath=ask2(["--exec-path"],"/").trim(),helpers=new Set;for(let cwd of folder==null?["/"]:["/",folder])for(let line of ask2(["config","--get-regexp","^credential\\..*helper$"],cwd).split(`
|
|
278
278
|
`)){let value=line.replace(/^\S+\s?/,"").trim();value&&helpers.add(value)}return{execPath:path.isAbsolute(execPath)?execPath:null,helpers:[...helpers]}}function developerGitOf({env,platform,run:run2}){if(platform!=="darwin")return null;let dir=env.DEVELOPER_DIR||String(run2("/usr/bin/xcode-select",["-p"],{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"]})?.stdout??"").trim();return path.isAbsolute(dir)?path.join(dir,"usr","bin","git"):null}function gitsOnComputer({gits,searchPath,known,developerGit,realPath=realPathOf}){let byReal=new Map;for(let git of[...gits,...findAll("git",searchPath),...known,...developerGit==null?[]:[developerGit]]){if(!isExecutable(git))continue;let real=realPath(git)??git;byReal.has(real)||byReal.set(real,git)}let developerRuns=developerGit!=null&&isExecutable(developerGit);return{binaries:new Set(byReal.keys()),toRun:[...byReal.values()].filter(git=>!(developerRuns&&git==="/usr/bin/git"))}}function pushCredentialPaths({env=process.env,home=env.HOME||os.homedir(),folder=null,gits=[],known=KNOWN_GITS,programs=SIGN_IN_PROGRAMS,platform=process.platform,run:run2=childProcess.spawnSync}={}){let realPathCache=new Map,cachedRealPath=p=>{if(realPathCache.has(p))return realPathCache.get(p);let real=realPathOf(p);return realPathCache.set(p,real),real},searchPath=env.PATH??"",pathDirs=[...new Set(searchPath.split(path.delimiter).filter(dir=>path.isAbsolute(dir)))],developerGit=developerGitOf({env,platform,run:run2}),{binaries,toRun}=gitsOnComputer({gits,searchPath,known,developerGit,realPath:cachedRealPath}),closed=new Set,close=p=>{let real=cachedRealPath(p);real==null||binaries.has(real)||(closed.add(p),closed.add(real))},read=toRun.map(git=>readGit(git,{env,folder,run:run2})),helperDirs=[...new Set(read.map(({execPath})=>execPath).filter(dir=>dir!=null))],searchDirs=[...new Set([...helperDirs,...pathDirs])];for(let dir of searchDirs)for(let entry of listDir(dir))entry.startsWith("git-credential-")&&close(path.join(dir,entry));for(let value of new Set(read.flatMap(({helpers})=>helpers))){let helper=parseHelper(value,home);if(helper!=null){for(let p of helper.paths)closed.add(p);if(path.isAbsolute(helper.program))close(helper.program);else for(let dir of searchDirs)close(path.join(dir,helper.program))}}closed.add(path.join(env.XDG_CACHE_HOME||path.join(home,".cache"),"git","credential")),closed.add(path.join(home,".git-credential-cache"));for(let gh of findAll("gh",searchPath))close(gh);for(let program of programs)isExecutable(program)&&close(program);return[...closed].sort()}function ownerGithubToken({env=process.env,gh=findAll("gh",env.PATH??"")[0]??null,execFile:execFile3=childProcess.execFile}={}){return gh==null?Promise.resolve(null):new Promise(resolve4=>{execFile3(gh,["auth","token","--hostname","github.com"],{env:{...env,GH_PROMPT_DISABLED:"1"},encoding:"utf8",timeout:5e3},(error2,stdout)=>{let token=error2==null&&typeof stdout=="string"?stdout.trim():"";resolve4(/^\S+$/.test(token)?token:null)})})}module.exports={findAll,ownerGithubToken,parseHelper,pushCredentialPaths}}});var require_task_env=__commonJS({"../../apps/web/electron/local-tools/task-env.js"(exports,module){"use strict";var HOSTING_TOKEN_ENV=/^(GH|GITHUB|GH_ENTERPRISE|GITHUB_ENTERPRISE|GITLAB|GL|CI_JOB|BITBUCKET|GITEA|FORGEJO)(_[A-Z0-9]+)*_(TOKEN|PAT)$/,PUSH_SIGN_IN_ENV=/^(GIT_ASKPASS|SSH_ASKPASS|SUDO_ASKPASS|SSH_AUTH_SOCK)$/,TASK_ENV_NAMES=new Set(["PATH","HOME","USER","LOGNAME","SHELL","TMPDIR","TMP","TEMP","PWD","SHLVL","LANG","LANGUAGE","TERM","TERM_PROGRAM","COLORTERM","TZ","EDITOR","VISUAL","PAGER","DISPLAY","__CF_USER_TEXT_ENCODING","HTTP_PROXY","HTTPS_PROXY","ALL_PROXY","NO_PROXY","http_proxy","https_proxy","all_proxy","no_proxy","NODE_EXTRA_CA_CERTS","SSL_CERT_FILE","SSL_CERT_DIR","REQUESTS_CA_BUNDLE","CURL_CA_BUNDLE","JAVA_HOME","GOPATH","GOROOT","CARGO_HOME","RUSTUP_HOME","PNPM_HOME","BUN_INSTALL","DENO_INSTALL","VIRTUAL_ENV","ANDROID_HOME","ANDROID_SDK_ROOT","AWS_PROFILE","AWS_DEFAULT_PROFILE","AWS_REGION","AWS_DEFAULT_REGION","AWS_SDK_LOAD_CONFIG","AWS_CONFIG_FILE","AWS_STS_REGIONAL_ENDPOINTS","CLOUDSDK_CORE_PROJECT","CLOUDSDK_COMPUTE_REGION","CLOUDSDK_COMPUTE_ZONE","CLOUDSDK_ROOT_DIR","GOOGLE_GENAI_USE_VERTEXAI","GOOGLE_CLOUD_PROJECT","GOOGLE_CLOUD_LOCATION"]),WINDOWS_ENV_NAMES=new Set(["SYSTEMROOT","SYSTEMDRIVE","WINDIR","COMSPEC","PATHEXT","PSMODULEPATH","OS","USERPROFILE","HOMEDRIVE","HOMEPATH","USERNAME","USERDOMAIN","COMPUTERNAME","APPDATA","LOCALAPPDATA","PROGRAMDATA","ALLUSERSPROFILE","PUBLIC","PROGRAMFILES","PROGRAMFILES(X86)","PROGRAMW6432","COMMONPROGRAMFILES","COMMONPROGRAMFILES(X86)","COMMONPROGRAMW6432","PROCESSOR_ARCHITECTURE","PROCESSOR_IDENTIFIER","NUMBER_OF_PROCESSORS"]),TASK_ENV_PREFIXES=["LC_","XDG_","NVM_","FNM_","VOLTA_","ASDF_","MISE_","PYENV_","RBENV_","NODENV_","COREPACK_","HOMEBREW_","CONDA_","GIT_","npm_config_"],TOOL_LOGIN_ENV=/^(ANTHROPIC|CLAUDE|OPENAI|CODEX|GEMINI|OPENCODE|GOOSE)_/,SECRET_NAME=/(TOKEN|SECRET|PASSW|API_?KEY|PRIVATE_?KEY|CREDENTIAL|_AUTH($|_))/i;function passedToTask(key,{pushNever,deployNever}){return key==="CLAUDECODE"||key.startsWith("CLAUDE_CODE_")?!1:HOSTING_TOKEN_ENV.test(key)?!deployNever:PUSH_SIGN_IN_ENV.test(key)?!pushNever:TOOL_LOGIN_ENV.test(key)?!0:SECRET_NAME.test(key)?!1:TASK_ENV_NAMES.has(key)||WINDOWS_ENV_NAMES.has(key.toUpperCase())||TASK_ENV_PREFIXES.some(prefix=>key.startsWith(prefix))}function taskEnv(env,policy=null,{claudeAiConnectors=!1}={}){let pushNever=policy?.push==="never",deployNever=pushNever||policy?.deploy==="never",out={};for(let[key,value]of Object.entries(env))value==null||!passedToTask(key,{pushNever,deployNever})||(out[key]=value);return claudeAiConnectors||(out.ENABLE_CLAUDEAI_MCP_SERVERS="false"),pushNever&&(out.GIT_TERMINAL_PROMPT="0",out.GCM_INTERACTIVE="never"),out}module.exports={taskEnv}}});var require_task_setup=__commonJS({"../../apps/web/electron/local-tools/task-setup.js"(exports,module){"use strict";var{createHash:createHash6,randomUUID:randomUUID3}=__require("crypto"),fs=__require("fs"),os=__require("os"),path=__require("path"),{projectNotLoadedNotice,reviewClaudeProject}=require_claude_project(),{DESKTOP_ENTRYPOINT,ownerSkillsNotice,prepareOwnerSkills}=require_claude_desktop_parity(),{pushCredentialPaths}=require_credentials(),{findGit,gitGuardEnv,githubSignIn,guardedPath,ownedGuardRoot,repoHooksPath,writeGitGuard}=require_git_guard(),{claudeTaskArgs,linkedPaths}=require_policy(),{CLAUDE_AI_CONNECTORS,codexHome,projectMcpServerNames,readClaudeAiConnectors,readClaudeServers}=require_servers(),{taskEnv}=require_task_env(),{findCommand:findCommand2,toolchainRoots}=require_toolchain();function prepareTaskGuard({dir,cwd,policy,githubToken=null,ownerEnv,run:run2,platform=process.platform,lockSecret}){let realGit=findGit(ownerEnv.PATH),hooksDir=writeGitGuard(dir,policy,{realGit,realGh:findCommand2("gh",ownerEnv.PATH),githubToken,platform,lockSecret}),{linkedRepos}=linkedPaths(cwd,{home:ownerEnv.HOME||os.homedir(),codexDir:codexHome(ownerEnv),configHome:ownerEnv.XDG_CONFIG_HOME,platform}),linkedRepoHooks=linkedRepos.map(linkedDir=>repoHooksPath(linkedDir,{git:realGit,env:ownerEnv,run:run2})).filter(p=>p!=null);return{hooksDir,repoHooks:repoHooksPath(cwd,{git:realGit,env:ownerEnv,run:run2}),linkedRepoHooks,github:githubToken!=null&&policy.push!=="never"&&fs.existsSync(githubSignIn(hooksDir,platform).token),credentialPaths:policy.push==="never"?pushCredentialPaths({env:ownerEnv,folder:cwd,gits:[realGit],run:run2,platform}):[]}}function guardedTaskEnv(ownerEnv,policy,guard,platform=process.platform,options={}){return{...taskEnv(ownerEnv,policy,options),...gitGuardEnv(guard.hooksDir,policy,{github:guard.github,platform}),PATH:guardedPath(guard.hooksDir,ownerEnv.PATH,platform)}}function claudeAiConnectorsFor(servers,{cwd,home,log:log2=null}){if(!servers.includes(CLAUDE_AI_CONNECTORS))return null;let deniedServers=projectMcpServerNames(cwd);return deniedServers==null?(log2?.warn?.(`[Local tools] left claude.ai connectors out: a .mcp.json in or above ${cwd} couldn't be read`),null):{connectors:readClaudeAiConnectors(home),deniedServers}}var LINUX_GIT_SENTINELS=new Map([["commondir",`.
|
|
279
279
|
`],["config.worktree",""]]),SENTINEL_LOCK_STALE_MS=5e3,SENTINEL_LOCK_ATTEMPTS=100,SENTINEL_LOCK_WAIT_MS=15,SENTINEL_SLEEP_BUF=new Int32Array(new SharedArrayBuffer(4));function isPidAlive(pid){if(!Number.isInteger(pid)||pid<=0)return!1;try{return process.kill(pid,0),!0}catch(error2){return error2?.code==="EPERM"}}function withSentinelLock(leaseDir,fn){let lockDir=path.join(leaseDir,".lock");for(let attempt=0;attempt<SENTINEL_LOCK_ATTEMPTS;attempt+=1){try{fs.mkdirSync(leaseDir,{recursive:!0,mode:448}),fs.mkdirSync(lockDir,{mode:448})}catch(error2){if(error2?.code==="ENOENT")continue;if(error2?.code==="EEXIST"){try{if(Date.now()-fs.statSync(lockDir).mtimeMs>SENTINEL_LOCK_STALE_MS){fs.rmdirSync(lockDir);continue}}catch{}Atomics.wait(SENTINEL_SLEEP_BUF,0,0,SENTINEL_LOCK_WAIT_MS);continue}return null}try{return fn()}finally{try{fs.rmdirSync(lockDir)}catch{}}}return null}function pruneSentinelLeases(leaseDir){let entries;try{entries=fs.readdirSync(leaseDir)}catch{return{hadAny:!1,active:0}}let hadAny=!1,active=0;for(let entry of entries){let match=/^(\d+)-[0-9a-f-]+\.lease$/i.exec(entry);if(match)if(hadAny=!0,isPidAlive(Number(match[1])))active+=1;else try{fs.unlinkSync(path.join(leaseDir,entry))}catch{}}return{hadAny,active}}function isExactSentinelFile(filePath,content){try{let info=fs.lstatSync(filePath);return info.isFile()&&!info.isSymbolicLink()&&fs.readFileSync(filePath,"utf8")===content}catch{return!1}}function pinLinuxGitMetadataSentinels(metadataPaths,{platform=process.platform,leaseRoot=null}={}){if(platform!=="linux"||!Array.isArray(metadataPaths)||metadataPaths.length===0)return()=>{};let verifiedLeaseRoot;try{verifiedLeaseRoot=ownedGuardRoot(leaseRoot??path.join(os.tmpdir(),"ando-task-git",".sentinels"),{platform})}catch{return()=>{}}let held=new Map;for(let candidate of metadataPaths){if(typeof candidate!="string"||candidate.length===0)continue;let base=path.basename(candidate),content=LINUX_GIT_SENTINELS.get(base);if(content==null)continue;let dir=path.dirname(candidate),dirInfo;try{dirInfo=fs.lstatSync(dir)}catch{continue}if(!dirInfo.isDirectory()||dirInfo.isSymbolicLink()||!fs.existsSync(path.join(dir,"HEAD"))&&!fs.existsSync(path.join(dir,"config")))continue;let realDir;try{realDir=fs.realpathSync(dir)}catch{continue}let key=path.join(realDir,base);if(held.has(key))continue;let leaseDir=path.join(verifiedLeaseRoot,createHash6("sha256").update(key).digest("hex")),leaseFile=withSentinelLock(leaseDir,()=>{let{hadAny}=pruneSentinelLeases(leaseDir),owns=!1;try{fs.writeFileSync(key,content,{flag:"wx",mode:420}),owns=!0}catch(error2){error2?.code==="EEXIST"&&hadAny&&isExactSentinelFile(key,content)&&(owns=!0)}if(!owns)return null;let file=path.join(leaseDir,`${process.pid}-${randomUUID3()}.lease`);return fs.writeFileSync(file,"",{flag:"wx",mode:384}),file});typeof leaseFile=="string"&&held.set(key,{content,leaseDir,leaseFile})}if(held.size===0)return()=>{};let cleaned=!1;return()=>{if(!cleaned){cleaned=!0;for(let[key,{content,leaseDir,leaseFile}]of held){withSentinelLock(leaseDir,()=>{try{fs.unlinkSync(leaseFile)}catch{}let{active}=pruneSentinelLeases(leaseDir);if(!(active>0)&&isExactSentinelFile(key,content))try{fs.unlinkSync(key)}catch{}});try{fs.rmdirSync(leaseDir)}catch{}}}}}function claudeTaskLaunch({policy,cwd,servers,guard,ownerEnv,extraClosed=[],home=os.homedir(),projectHooks=!1,postAsOwner=!1,platform=process.platform,log:log2=null}){let own2=readClaudeServers(home),picked=Object.fromEntries(servers.filter(name=>name in own2).map(name=>[name,own2[name]])),claudeAi=claudeAiConnectorsFor(servers,{cwd,home,log:log2}),codexDir=codexHome(ownerEnv),configHome=ownerEnv.XDG_CONFIG_HOME,{linked,linkedDirs,linkedGitMetadata,linkedSources}=linkedPaths(cwd,{home,codexDir,configHome,platform}),leaseRoot=guard?.hooksDir?path.join(path.dirname(guard.hooksDir),".sentinels"):null,cleanup=policy?.files==="allow"&&policy?.full_access!=="allow"?pinLinuxGitMetadataSentinels(linkedGitMetadata,{platform,leaseRoot}):()=>{};try{let env={...guardedTaskEnv(ownerEnv,policy,guard,platform,{claudeAiConnectors:claudeAi!=null}),CLAUDE_ENV_FILE:path.join(guard.hooksDir,"shell-env.sh"),CLAUDE_CODE_ENTRYPOINT:DESKTOP_ENTRYPOINT},ownerSkills=prepareOwnerSkills({home,hooksDir:guard.hooksDir,log:log2}),project=reviewClaudeProject(cwd,{env,linkedFiles:linked.filter(p=>!linkedDirs.includes(p))});return project.load||log2?.warn?.(`[Local tools] left out ${cwd}'s Claude Code project setup: ${project.reasons.join("; ")}`),{env,cleanup,notice:[project.load?null:projectNotLoadedNotice(project),ownerSkillsNotice(ownerSkills)].filter(line=>line!=null).join(`
|
|
280
|
-
`)||null,permissionArgs:claudeTaskArgs(policy,{servers:picked,claudeAi,home,folder:cwd,hooksDir:guard.hooksDir,repoHooks:guard.repoHooks,linkedRepoHooks:guard.linkedRepoHooks??[],codexDir,configHome,toolchain:toolchainRoots(ownerEnv.PATH??"",{env:ownerEnv,home}),credentialPaths:[...guard.credentialPaths,...extraClosed],linked,linkedDirs,linkedGitMetadata,linkedSources,project,projectHooks,postAsOwner,ownerSkills,platform,log:log2})}}catch(error2){throw cleanup(),error2}}module.exports={claudeTaskLaunch,guardedTaskEnv,pinLinuxGitMetadataSentinels,prepareTaskGuard}}});var require_drivers=__commonJS({"../../apps/web/electron/local-tools/drivers.js"(exports,module){"use strict";var os=__require("node:os"),{createAcpRuntime}=require_acp_runtime(),{createClaudeRuntime}=require_claude_runtime(),{createCodexRuntime}=require_codex_runtime(),{codexTaskArgs,linkedPaths,resolvePolicy}=require_policy(),{isAndoMcpUrl}=require_outward_tools(),{codexHome,listAndoServers,listToolServers,readToolMcpServersForAcp}=require_servers(),{claudeTaskLaunch,guardedTaskEnv}=require_task_setup(),{letSandboxReadGuard}=require_windows(),LOCAL_DRIVER_SPECS=Object.freeze({"claude-code":Object.freeze({provider:"claude-code",kind:"claude-native",displayName:"Claude Code",command:"claude",acpArgs:[]}),codex:Object.freeze({provider:"codex",kind:"codex-native",displayName:"Codex",command:"codex",acpArgs:[]}),"antigravity-cli":Object.freeze({provider:"antigravity-cli",kind:"acp",displayName:"Antigravity CLI",command:"agy",acpArgs:["acp"]}),"gemini-cli":Object.freeze({provider:"gemini-cli",kind:"acp",displayName:"Gemini CLI",command:"gemini",acpArgs:["--acp"]}),opencode:Object.freeze({provider:"opencode",kind:"acp",displayName:"OpenCode",command:"opencode",acpArgs:["acp"]}),goose:Object.freeze({provider:"goose",kind:"acp",displayName:"Goose",command:"goose",acpArgs:["acp"]})}),TOOL_NAMES=Object.freeze(Object.fromEntries(Object.values(LOCAL_DRIVER_SPECS).map(spec=>[spec.provider,spec.displayName]))),TOOL_COMMANDS=Object.freeze(Object.fromEntries(Object.values(LOCAL_DRIVER_SPECS).map(spec=>[spec.provider,spec.command])));function isAcpProvider(provider){return LOCAL_DRIVER_SPECS[provider]?.kind==="acp"}function acpUnsandboxedError(toolName,platform=process.platform){return platform==="darwin"?`${toolName} runs without an OS sandbox, so it cannot take tasks until "Full access" is turned on in Studio > Devices.`:`${toolName} runs without an OS sandbox, so it cannot take tasks on this computer. Use Claude Code or Codex here.`}function parseCommandOverride(rawValue){if(typeof rawValue!="string"||rawValue.trim()==="")return null;let trimmed=rawValue.trim();if(trimmed.startsWith("["))try{let parsed=JSON.parse(trimmed);if(Array.isArray(parsed)&&parsed.length>0&&parsed.every(part=>typeof part=="string"&&part.length>0))return{command:parsed[0],args:parsed.slice(1)}}catch{return null}let parts=trimmed.split(/\s+/).filter(Boolean);return parts.length>0?{command:parts[0],args:parts.slice(1)}:null}function readAcpCommandOverride(provider,ownerEnv={}){let envSuffix=String(provider||"").toUpperCase().replace(/[^A-Z0-9]+/g,"_");return parseCommandOverride(ownerEnv?.[`ANDO_ACP_COMMAND_${envSuffix}`])||parseCommandOverride(ownerEnv?.ANDO_ACP_COMMAND)}function hasAcpLaunchOverride(provider,ownerEnv={}){return readAcpCommandOverride(provider,ownerEnv)!=null}function resolveAcpLaunch(provider,ownerEnv={}){let spec=LOCAL_DRIVER_SPECS[provider],override=readAcpCommandOverride(provider,ownerEnv);return override?{command:override.command,args:override.args,toolLabel:spec?.displayName||String(provider)}:{command:spec?.command||String(provider),args:spec?.acpArgs?[...spec.acpArgs]:["--acp"],toolLabel:spec?.displayName||String(provider)}}function resolveAcpMcpSetup({provider,servers,workspaceId,ownerEnv,home,resolvedPolicy,mcpProxy,mcpProxyOptions,postAsOwner=!1}){let allowAndoMcp=Array.isArray(servers)&&servers.includes("ando"),resolvedProxyOptions=!1;allowAndoMcp&&mcpProxyOptions!==!1&&(mcpProxyOptions&&typeof mcpProxyOptions=="object"?resolvedProxyOptions={env:ownerEnv,home,provider,policy:resolvedPolicy,allowPosting:postAsOwner,...workspaceId?{expectedWorkspaceId:workspaceId}:{},...mcpProxyOptions}:mcpProxy==null&&typeof workspaceId=="string"&&workspaceId.trim()!==""&&(resolvedProxyOptions={env:ownerEnv,home,provider,policy:resolvedPolicy,allowPosting:postAsOwner,allowAmbientCliCredentials:!0,expectedWorkspaceId:workspaceId.trim()}));let staticServers=allowAndoMcp&&(mcpProxy!=null||resolvedProxyOptions!==!1)?servers.filter(name=>name!=="ando"):servers;return{pickedMcpServers:(typeof readToolMcpServersForAcp=="function"?readToolMcpServersForAcp(provider,staticServers,home,ownerEnv):[]).filter(entry=>postAsOwner||!isAndoMcpUrl(entry?.url)),mcpProxy:allowAndoMcp?mcpProxy:null,mcpProxyOptions:resolvedProxyOptions}}function createLocalDriverRuntime(provider,{spawn:
|
|
281
|
-
${notice}`,log:log2,permissionArgs,effort,model,onClose:cleanup})}catch(error2){throw cleanup?.(),error2}}let launch=resolveAcpLaunch(provider,ownerEnv),resolvedPolicy=resolvePolicy(policy,{platform});if(resolvedPolicy.full_access!=="allow")throw new Error(acpUnsandboxedError(launch.toolLabel,platform));let mcpSetup=resolveAcpMcpSetup({provider,servers,workspaceId,ownerEnv,home,resolvedPolicy,mcpProxy,mcpProxyOptions,postAsOwner});return createAcpRuntime({spawn:
|
|
280
|
+
`)||null,permissionArgs:claudeTaskArgs(policy,{servers:picked,claudeAi,home,folder:cwd,hooksDir:guard.hooksDir,repoHooks:guard.repoHooks,linkedRepoHooks:guard.linkedRepoHooks??[],codexDir,configHome,toolchain:toolchainRoots(ownerEnv.PATH??"",{env:ownerEnv,home}),credentialPaths:[...guard.credentialPaths,...extraClosed],linked,linkedDirs,linkedGitMetadata,linkedSources,project,projectHooks,postAsOwner,ownerSkills,platform,log:log2})}}catch(error2){throw cleanup(),error2}}module.exports={claudeTaskLaunch,guardedTaskEnv,pinLinuxGitMetadataSentinels,prepareTaskGuard}}});var require_drivers=__commonJS({"../../apps/web/electron/local-tools/drivers.js"(exports,module){"use strict";var os=__require("node:os"),{createAcpRuntime}=require_acp_runtime(),{createClaudeRuntime}=require_claude_runtime(),{createCodexRuntime}=require_codex_runtime(),{codexTaskArgs,linkedPaths,resolvePolicy}=require_policy(),{isAndoMcpUrl}=require_outward_tools(),{codexHome,listAndoServers,listToolServers,readToolMcpServersForAcp}=require_servers(),{claudeTaskLaunch,guardedTaskEnv}=require_task_setup(),{letSandboxReadGuard}=require_windows(),LOCAL_DRIVER_SPECS=Object.freeze({"claude-code":Object.freeze({provider:"claude-code",kind:"claude-native",displayName:"Claude Code",command:"claude",acpArgs:[]}),codex:Object.freeze({provider:"codex",kind:"codex-native",displayName:"Codex",command:"codex",acpArgs:[]}),"antigravity-cli":Object.freeze({provider:"antigravity-cli",kind:"acp",displayName:"Antigravity CLI",command:"agy",acpArgs:["acp"]}),"gemini-cli":Object.freeze({provider:"gemini-cli",kind:"acp",displayName:"Gemini CLI",command:"gemini",acpArgs:["--acp"]}),opencode:Object.freeze({provider:"opencode",kind:"acp",displayName:"OpenCode",command:"opencode",acpArgs:["acp"]}),goose:Object.freeze({provider:"goose",kind:"acp",displayName:"Goose",command:"goose",acpArgs:["acp"]})}),TOOL_NAMES=Object.freeze(Object.fromEntries(Object.values(LOCAL_DRIVER_SPECS).map(spec=>[spec.provider,spec.displayName]))),TOOL_COMMANDS=Object.freeze(Object.fromEntries(Object.values(LOCAL_DRIVER_SPECS).map(spec=>[spec.provider,spec.command])));function isAcpProvider(provider){return LOCAL_DRIVER_SPECS[provider]?.kind==="acp"}function acpUnsandboxedError(toolName,platform=process.platform){return platform==="darwin"?`${toolName} runs without an OS sandbox, so it cannot take tasks until "Full access" is turned on in Studio > Devices.`:`${toolName} runs without an OS sandbox, so it cannot take tasks on this computer. Use Claude Code or Codex here.`}function parseCommandOverride(rawValue){if(typeof rawValue!="string"||rawValue.trim()==="")return null;let trimmed=rawValue.trim();if(trimmed.startsWith("["))try{let parsed=JSON.parse(trimmed);if(Array.isArray(parsed)&&parsed.length>0&&parsed.every(part=>typeof part=="string"&&part.length>0))return{command:parsed[0],args:parsed.slice(1)}}catch{return null}let parts=trimmed.split(/\s+/).filter(Boolean);return parts.length>0?{command:parts[0],args:parts.slice(1)}:null}function readAcpCommandOverride(provider,ownerEnv={}){let envSuffix=String(provider||"").toUpperCase().replace(/[^A-Z0-9]+/g,"_");return parseCommandOverride(ownerEnv?.[`ANDO_ACP_COMMAND_${envSuffix}`])||parseCommandOverride(ownerEnv?.ANDO_ACP_COMMAND)}function hasAcpLaunchOverride(provider,ownerEnv={}){return readAcpCommandOverride(provider,ownerEnv)!=null}function resolveAcpLaunch(provider,ownerEnv={}){let spec=LOCAL_DRIVER_SPECS[provider],override=readAcpCommandOverride(provider,ownerEnv);return override?{command:override.command,args:override.args,toolLabel:spec?.displayName||String(provider)}:{command:spec?.command||String(provider),args:spec?.acpArgs?[...spec.acpArgs]:["--acp"],toolLabel:spec?.displayName||String(provider)}}function resolveAcpMcpSetup({provider,servers,workspaceId,ownerEnv,home,resolvedPolicy,mcpProxy,mcpProxyOptions,postAsOwner=!1}){let allowAndoMcp=Array.isArray(servers)&&servers.includes("ando"),resolvedProxyOptions=!1;allowAndoMcp&&mcpProxyOptions!==!1&&(mcpProxyOptions&&typeof mcpProxyOptions=="object"?resolvedProxyOptions={env:ownerEnv,home,provider,policy:resolvedPolicy,allowPosting:postAsOwner,...workspaceId?{expectedWorkspaceId:workspaceId}:{},...mcpProxyOptions}:mcpProxy==null&&typeof workspaceId=="string"&&workspaceId.trim()!==""&&(resolvedProxyOptions={env:ownerEnv,home,provider,policy:resolvedPolicy,allowPosting:postAsOwner,allowAmbientCliCredentials:!0,expectedWorkspaceId:workspaceId.trim()}));let staticServers=allowAndoMcp&&(mcpProxy!=null||resolvedProxyOptions!==!1)?servers.filter(name=>name!=="ando"):servers;return{pickedMcpServers:(typeof readToolMcpServersForAcp=="function"?readToolMcpServersForAcp(provider,staticServers,home,ownerEnv):[]).filter(entry=>postAsOwner||!isAndoMcpUrl(entry?.url)),mcpProxy:allowAndoMcp?mcpProxy:null,mcpProxyOptions:resolvedProxyOptions}}function createLocalDriverRuntime(provider,{spawn:spawn6,log:log2=()=>{},cwd,workspaceId=null,instructions,policy,servers=[],guard,ownerEnv,platform=process.platform,letSandboxGuard=letSandboxReadGuard,otherFolders=[],closedToCodex=[],home=os.homedir(),mcpProxy=null,mcpProxyOptions=null,onPermissionRequest=null,projectHooks=!1,postAsOwner=!1,effort=null,model=null}){let spec=LOCAL_DRIVER_SPECS[provider];if(spec?.kind==="codex-native"){let{linked,linkedDirs,linkedGitMetadata,linkedSources}=linkedPaths(cwd,{home,codexDir:codexHome(ownerEnv),configHome:ownerEnv.XDG_CONFIG_HOME,platform});return createCodexRuntime({spawn:spawn6,env:guardedTaskEnv(ownerEnv,policy,guard,platform),cwd,instructions,log:log2,sandbox:null,windowsSandbox:platform==="win32",effort,model,onWindowsSandboxReady:()=>{if(!letSandboxGuard(guard.hooksDir))throw new Error("Ando couldn't let Codex's Windows sandbox read this task's git guard, so it won't run.")},serverArgs:codexTaskArgs(policy,{available:listToolServers("codex",home,ownerEnv),allowed:servers,andoServers:postAsOwner?{}:listAndoServers("codex",home,ownerEnv),hooksDir:guard.hooksDir,repoHooks:guard.repoHooks,linkedRepoHooks:guard.linkedRepoHooks??[],github:guard.github,folder:cwd,codexDir:codexHome(ownerEnv),configHome:ownerEnv.XDG_CONFIG_HOME,credentialPaths:[...guard.credentialPaths,...otherFolders,...closedToCodex],linked,linkedDirs,linkedGitMetadata,linkedSources,log:log2,platform})})}if(spec?.kind==="claude-native"){let{env,permissionArgs,notice,cleanup}=claudeTaskLaunch({policy,cwd,servers,guard,ownerEnv,extraClosed:otherFolders,home,projectHooks,postAsOwner,platform,log:log2});try{return createClaudeRuntime({spawn:spawn6,env,cwd,instructions:notice==null?instructions:`${instructions}
|
|
281
|
+
${notice}`,log:log2,permissionArgs,effort,model,onClose:cleanup})}catch(error2){throw cleanup?.(),error2}}let launch=resolveAcpLaunch(provider,ownerEnv),resolvedPolicy=resolvePolicy(policy,{platform});if(resolvedPolicy.full_access!=="allow")throw new Error(acpUnsandboxedError(launch.toolLabel,platform));let mcpSetup=resolveAcpMcpSetup({provider,servers,workspaceId,ownerEnv,home,resolvedPolicy,mcpProxy,mcpProxyOptions,postAsOwner});return createAcpRuntime({spawn:spawn6,command:launch.command,args:launch.args,toolLabel:launch.toolLabel,env:guardedTaskEnv(ownerEnv,resolvedPolicy,guard,platform),cwd,instructions,policy:resolvedPolicy,mcpServers:mcpSetup.pickedMcpServers,mcpProxy:mcpSetup.mcpProxy,mcpProxyOptions:mcpSetup.mcpProxyOptions,home,platform,onPermissionRequest})}module.exports={LOCAL_DRIVER_SPECS,TOOL_COMMANDS,TOOL_NAMES,acpUnsandboxedError,createLocalDriverRuntime,hasAcpLaunchOverride,isAcpProvider,parseCommandOverride,resolveAcpLaunch,resolveAcpMcpSetup}}});var require_codex_models=__commonJS({"../../apps/web/electron/local-tools/codex-models.js"(exports,module){"use strict";function readCodexModels({spawn:spawn6,env,timeoutMs=1e4}){return new Promise(resolve4=>{let child;try{child=spawn6("codex",["app-server","--listen","stdio://"],{env,stdio:["pipe","pipe","ignore"]})}catch{resolve4(null);return}let settled=!1,buffer="",nextId=2,models=[],finish=models2=>{if(!settled){settled=!0,clearTimeout(timer);try{child.stdin?.end(),child.kill()}catch{}resolve4(models2)}},timer=setTimeout(()=>finish(null),timeoutMs);timer.unref?.();let send2=message=>child.stdin?.write(`${JSON.stringify(message)}
|
|
282
282
|
`);child.on("error",()=>finish(null)),child.on("close",()=>finish(null)),child.stdin?.on("error",()=>finish(null)),child.stdout?.on("data",chunk=>{buffer+=chunk.toString();let newline;for(;(newline=buffer.indexOf(`
|
|
283
283
|
`))>=0;){let line=buffer.slice(0,newline);buffer=buffer.slice(newline+1);let message;try{message=JSON.parse(line)}catch{continue}if(message.id===1)send2({method:"initialized"}),send2({id:nextId,method:"model/list",params:{cursor:null}});else if(message.id===nextId){let data=Array.isArray(message.result?.data)?message.result.data:null;if(data==null){finish(null);continue}for(let model of data)model?.hidden===!0||typeof model?.id!="string"||models.push({id:model.id,name:typeof model.displayName=="string"&&model.displayName?model.displayName:model.id});let cursor=message.result?.nextCursor;typeof cursor=="string"&&cursor!==""&&nextId<11?(nextId+=1,send2({id:nextId,method:"model/list",params:{cursor}})):finish(typeof cursor=="string"&&cursor!==""?null:models)}}}),send2({id:1,method:"initialize",params:{clientInfo:{name:"ando",version:"1"}}})})}module.exports={readCodexModels}}});var require_wsl=__commonJS({"../../apps/web/electron/local-tools/wsl.js"(exports,module){"use strict";var{createHash:createHash6}=__require("crypto"),fs=__require("fs"),path=__require("path"),{CLAUDE_AI_CONNECTORS}=require_servers(),{shellQuote}=require_shell_quote(),WSL_COMMANDS=["claude","node","bwrap","socat","git","gh"],WSL_NODE_MAJOR=18,RUNNER_FILES=["wsl-task.js","command-env.js","outward-tools.js","claude-mcp.js","claude-desktop-parity.js","claude-project.js","task-setup.js","credentials.js","full-access.js","git-guard.js","linked-paths.js","codex-closed-paths.js","net-bridge.js","policy.js","python-bridge.js","servers.js","shell-quote.js","task-env.js","toolchain.js","windows.js"];function runsInWsl(provider,platform){return provider==="claude-code"&&platform==="win32"}function wslExe(env=process.env){return path.win32.join(env.SystemRoot||"C:\\Windows","System32","wsl.exe")}function loginShellArgs(script){return["-e","sh","-c","set -f && IFS= && exec ${SHELL:-/bin/sh} -ilc $1","sh",script]}function defaultWslVersion(listing){let version3=listing.replace(/\0/g,"").split(/\r?\n/).find(row=>row.trim().startsWith("*"))?.trim().split(/\s+/).at(-1);return version3==null||!/^\d+$/.test(version3)?null:Number(version3)}var WSL_SERVER_NAMES=`node -e 'let c;try{c=JSON.parse(fs.readFileSync(os.homedir()+"/.claude.json","utf8"))}catch{}const s=c&&c.mcpServers;const a=c&&Array.isArray(c.claudeAiMcpEverConnected)&&c.claudeAiMcpEverConnected.some(n=>typeof n=="string"&&n.startsWith("claude.ai "));console.log("ando-servers:"+JSON.stringify([...(a?[${JSON.stringify(CLAUDE_AI_CONNECTORS)}]:[]),...(s&&typeof s=="object"?Object.keys(s).sort():[])]))'`;function wslServerNames(lines){let line=lines.find(row=>row.startsWith("ando-servers:"));try{let names=JSON.parse(line?.slice(13)??"[]");return Array.isArray(names)?names.filter(name=>typeof name=="string"):[]}catch{return[]}}async function readWslClaude({run:run2,env=process.env}){let wsl=wslExe(env),listing=await run2(wsl,["--list","--verbose"],{env:{...env,WSL_UTF8:"1"},timeout:1e4});if(listing.status!==0||defaultWslVersion(listing.stdout)!==2)return{ready:!1,missing:["wsl2"],signedIn:null,servers:[]};let lines=(await run2(wsl,loginShellArgs([`for c in ${WSL_COMMANDS.join(" ")}; do command -v "$c" >/dev/null 2>&1 || printf 'ando-missing:%s\\n' "$c"; done`,`command -v node >/dev/null 2>&1 && { node -e 'process.exit(+process.versions.node.split(".")[0] < ${WSL_NODE_MAJOR} ? 1 : 0)' || printf 'ando-missing:node\\n'; }`,`command -v node >/dev/null 2>&1 && ${WSL_SERVER_NAMES}`,"command -v claude >/dev/null 2>&1 && claude --help 2>/dev/null | grep -q -- '--effort' && printf 'ando-effort\\n'","printf 'ando-probed\\n'"].join("; ")),{env,timeout:2e4})).stdout.split(/\r?\n/);if(!lines.includes("ando-probed"))return{ready:!1,missing:["wsl2"],signedIn:null,servers:[]};let missing=[...new Set(lines.filter(line=>line.startsWith("ando-missing:")).map(line=>line.slice(13)))];if(missing.length>0)return{ready:!1,missing,signedIn:null,servers:[]};let answer=(await run2(wsl,loginShellArgs("claude auth status"),{env,timeout:2e4})).stdout.split(/\r?\n/).findLast(line=>line.trim().startsWith("{")),signedIn=null;try{let parsed=JSON.parse(answer??"");typeof parsed?.loggedIn=="boolean"&&(signedIn=parsed.loggedIn)}catch{}return{ready:!0,missing:[],signedIn,servers:wslServerNames(lines),effort:lines.includes("ando-effort")}}var WSL_PROJECTS=['const fs=require("fs"),os=require("os"),path=require("path"),cp=require("child_process");','const win=(p)=>{try{return cp.execFileSync("wslpath",["-w",p],{encoding:"utf8"}).trim()}catch{return null}};',"const home=os.homedir();let projects={};",'try{projects=JSON.parse(fs.readFileSync(home+"/.claude.json","utf8")).projects||{}}catch{}','const at=(f)=>{try{return fs.statSync(home+"/.claude/projects/"+f.replace(/[^A-Za-z0-9]/g,"-")).mtimeMs}catch{return 0}};','const git=(f)=>{try{return fs.statSync(f+"/.git").isDirectory()}catch{return false}};','const list=Object.keys(projects).filter((f)=>f.startsWith("/")&&!f.startsWith("/tmp/")&&git(f))'," .map((f)=>({f,at:at(f)})).sort((a,b)=>b.at-a.at).slice(0,12)"," .map(({f})=>({name:path.posix.basename(f)||f,folder:win(f)})).filter((p)=>p.folder);",'console.log("ando-projects:"+JSON.stringify({home:win(home),projects:list}));'].join("");async function readWslProjects({run:run2,env=process.env}){let none={home:null,projects:[]},line=(await run2(wslExe(env),loginShellArgs(`node -e ${shellQuote(WSL_PROJECTS)}`),{env,timeout:2e4})).stdout.split(/\r?\n/).findLast(row=>row.startsWith("ando-projects:"));if(line==null)return none;try{let parsed=JSON.parse(line.slice(14)),isWindowsPath=value=>typeof value=="string"&&/^(?:[A-Za-z]:\\|\\\\[^\\])/.test(value);return{home:isWindowsPath(parsed?.home)?parsed.home:null,projects:Array.isArray(parsed?.projects)?parsed.projects.filter(entry=>isWindowsPath(entry?.folder)&&typeof entry?.name=="string").map(entry=>({name:entry.name,folder:entry.folder})):[]}}catch{return none}}function toWslPath(windowsPath,{spawnSync:spawnSync6,env=process.env}){let result=spawnSync6(wslExe(env),["-e","wslpath","-u",windowsPath],{encoding:"utf8",timeout:1e4,windowsHide:!0}),linuxPath=result.status===0&&typeof result.stdout=="string"?result.stdout.trim():"";if(!linuxPath.startsWith("/"))throw new Error(`WSL can't reach ${windowsPath}`);return linuxPath}function sendRunnerToWsl({spawnSync:spawnSync6,env=process.env,sourceDir=__dirname,readFile:readFile7=file=>fs.readFileSync(file,"utf8")}){let files=RUNNER_FILES.map(name=>({name,content:readFile7(path.join(sourceDir,name))})),hash=createHash6("sha256");for(let file of files)hash.update(`${file.name}\0${file.content}\0`);let script=["set -e",`dir="$HOME/.cache/ando/wsl-runner/${hash.digest("hex").slice(0,16)}"`,'if [ ! -f "$dir/ready" ]; then',' mkdir -p "$dir.part"',...files.map(file=>` printf '%s' ${shellQuote(Buffer.from(file.content).toString("base64"))} | base64 -d > "$dir.part/${file.name}"`),' touch "$dir.part/ready"',' rm -rf "$dir" && mv "$dir.part" "$dir"',"fi",`printf '%s\\n' "$dir"`,""].join(`
|
|
284
284
|
`),result=spawnSync6(wslExe(env),["-e","sh","-s"],{input:script,encoding:"utf8",timeout:3e4,windowsHide:!0}),dir=result.status===0&&typeof result.stdout=="string"?result.stdout.trim().split(`
|
|
285
285
|
`).at(-1):"";if(!dir?.startsWith("/"))throw new Error("Ando couldn't set up Claude Code's tasks in WSL");return dir}function wslTaskInput(run2){return`${JSON.stringify(run2)}
|
|
286
|
-
`}function wslClaudeSpawn({spawn:
|
|
287
|
-
`)).digest("hex")}function hasNonEmptyFile(file){try{let stat2=fs.statSync(file);return stat2.isFile()&&stat2.size>2}catch{return!1}}function isGeminiSignedIn(env,home){return!!env?.GEMINI_API_KEY?.trim()||env?.GOOGLE_GENAI_USE_VERTEXAI==="true"||hasNonEmptyFile(path.join(home,".gemini","oauth_creds.json"))||hasNonEmptyFile(path.join(home,".gemini","google_accounts.json"))}function isOpenCodeSignedIn(env,home){let dataHome=env?.XDG_DATA_HOME?.trim()||path.join(home,".local","share");return!!env?.OPENCODE_API_KEY?.trim()||!!env?.ANTHROPIC_API_KEY?.trim()||!!env?.OPENAI_API_KEY?.trim()||!!env?.GEMINI_API_KEY?.trim()||hasNonEmptyFile(path.join(dataHome,"opencode","auth.json"))}function isGooseSignedIn(env,home){let configHome=env?.XDG_CONFIG_HOME?.trim()||path.join(home,".config");return!!env?.GOOSE_PROVIDER?.trim()||hasNonEmptyFile(path.join(configHome,"goose","config.yaml"))}async function readSignedIn(provider,{run:run2,env,home=os.homedir()}){if(provider==="claude-code"){let result=await run2("claude",["auth","status"],{env});try{let status=JSON.parse(result.stdout);return typeof status?.loggedIn=="boolean"?status.loggedIn:null}catch{return null}}if(provider==="codex"){let result=await run2("codex",["login","status"],{env});return result.error!=null?null:result.status===0}return provider==="antigravity-cli"?env?.GEMINI_API_KEY?.trim()?!0:null:provider==="gemini-cli"?isGeminiSignedIn(env,home)?!0:null:provider==="opencode"?isOpenCodeSignedIn(env,home)?!0:null:provider==="goose"&&isGooseSignedIn(env,home)?!0:null}async function supportsAcpCli(provider,command,{run:run2,env}){if(provider==="gemini-cli"){let help=await run2(command,["--help"],{env,timeout:5e3});return help.status===0&&/--acp\b/.test(help.stdout)}return provider==="antigravity-cli"||provider==="opencode"||provider==="goose"?(await run2(command,["acp","--help"],{env,timeout:5e3})).status===0:!1}function hasExplicitCommandFile(command,platform,env){for(let candidate of commandFileNames(command,{platform,env}))try{if(fs.accessSync(candidate,fs.constants.X_OK),fs.statSync(candidate).isFile())return candidate}catch{}return null}async function resolveInstalledCommand(command,{run:run2,env,platform}){return path.isAbsolute(command)||command.includes("/")||platform==="win32"&&command.includes("\\")?hasExplicitCommandFile(command,platform,env):platform==="win32"?findCommand2(command,env.PATH??"",null,{platform,env}):(await run2("/usr/bin/which",[command],{env,timeout:5e3})).status===0?command:null}async function installedTools({run:run2,env,platform,wslClaude}){return(await Promise.all(Object.entries(TOOL_COMMANDS).map(async([provider,defaultCommand])=>{if(runsInWsl(provider,platform))return wslClaude?.ready?provider:null;let acp=isAcpProvider(provider),overridden=acp&&hasAcpLaunchOverride(provider,env),command=acp?resolveAcpLaunch(provider,env).command:defaultCommand,resolved=await resolveInstalledCommand(command,{run:run2,env,platform});return resolved==null?null:!acp||overridden||await supportsAcpCli(provider,resolved,{run:run2,env})?provider:null}))).filter(provider=>provider!=null)}function createMachineDescriber({machineFile,platform,spawn:
|
|
286
|
+
`}function wslClaudeSpawn({spawn:spawn6,env=process.env,runnerDir,run:run2}){return(_command,args,options={})=>{let child=spawn6(wslExe(env),["--cd","~",...loginShellArgs(`exec node ${shellQuote(`${runnerDir}/wsl-task.js`)}`)],{stdio:options.stdio,windowsHide:!0});return child.stdin?.write(wslTaskInput({...run2,claudeArgs:args})),child}}module.exports={RUNNER_FILES,WSL_COMMANDS,defaultWslVersion,loginShellArgs,readWslClaude,readWslProjects,runsInWsl,sendRunnerToWsl,toWslPath,wslClaudeSpawn,wslExe,wslTaskInput}}});var require_machine=__commonJS({"../../apps/web/electron/local-tools/machine.js"(exports,module){"use strict";var{createHash:createHash6,randomUUID:randomUUID3}=__require("crypto"),{readCodexModels}=require_codex_models(),fs=__require("fs"),os=__require("os"),path=__require("path"),{TOOL_COMMANDS,hasAcpLaunchOverride,isAcpProvider,resolveAcpLaunch}=require_drivers(),{listToolServers}=require_servers(),{commandFileNames,findCommand:findCommand2}=require_toolchain(),{readWslClaude,runsInWsl}=require_wsl(),UUID=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,DESCRIBE_CACHE_MS=15e3;function readMachineId(file){try{let{id:id2}=JSON.parse(fs.readFileSync(file,"utf8"));if(typeof id2=="string"&&UUID.test(id2))return id2}catch(error2){if(error2.code!=="ENOENT"&&!(error2 instanceof SyntaxError))throw error2}let id=randomUUID3();return fs.mkdirSync(path.dirname(file),{recursive:!0,mode:448}),fs.writeFileSync(file,JSON.stringify({id}),{mode:384}),id}function runCommand(spawn6,command,args,{env,timeout=1e4}={}){return new Promise(resolve4=>{let child;try{child=spawn6(command,args,{env,stdio:["ignore","pipe","ignore"]})}catch(error2){resolve4({status:null,stdout:"",error:error2});return}let stdout="",timedOut=!1,timer=setTimeout(()=>{timedOut=!0,child.kill()},timeout);child.stdout?.setEncoding?.("utf8"),child.stdout?.on("data",chunk=>{stdout+=chunk,stdout.length>64e3&&child.kill()}),child.on("error",error2=>{clearTimeout(timer),resolve4({status:null,stdout,error:error2})}),child.on("close",status=>{clearTimeout(timer),resolve4({status:timedOut?null:status,stdout,error:timedOut?new Error(`${command} timed out`):null})})})}async function readMachineName({platform,run:run2,hostname:hostname3}){if(platform==="darwin"){let result=await run2("/usr/sbin/scutil",["--get","ComputerName"],{timeout:5e3}),name=result.status===0?result.stdout.trim():"";if(name)return name}return hostname3().replace(/\.local$/,"")||"This computer"}async function readHardwareId({platform,run:run2,readFile:readFile7,systemRoot=process.env.SystemRoot||"C:\\Windows"}){if(platform==="win32"){let result=await run2(path.join(systemRoot,"System32","reg.exe"),["query","HKLM\\SOFTWARE\\Microsoft\\Cryptography","/v","MachineGuid"],{timeout:5e3});return/MachineGuid\s+REG_SZ\s+([0-9A-Fa-f-]{36})/.exec(result.stdout)?.[1]?.toLowerCase()??null}if(platform==="darwin"){let result=await run2("/usr/sbin/ioreg",["-rd1","-c","IOPlatformExpertDevice"],{timeout:5e3});return/"IOPlatformUUID"\s*=\s*"([0-9A-Fa-f-]{36})"/.exec(result.stdout)?.[1]?.toLowerCase()??null}for(let file of["/etc/machine-id","/var/lib/dbus/machine-id"])try{let id=readFile7(file).trim();if(/^[0-9a-f]{32}$/i.test(id))return id.toLowerCase()}catch{}return null}async function readMachineKey({platform,run:run2,readFile:readFile7,username,appName}){if(!username)return null;let hardwareId=await readHardwareId({platform,run:run2,readFile:readFile7});return hardwareId==null?null:createHash6("sha256").update(["ando-local-tool-machine",hardwareId,username,appName].join(`
|
|
287
|
+
`)).digest("hex")}function hasNonEmptyFile(file){try{let stat2=fs.statSync(file);return stat2.isFile()&&stat2.size>2}catch{return!1}}function isGeminiSignedIn(env,home){return!!env?.GEMINI_API_KEY?.trim()||env?.GOOGLE_GENAI_USE_VERTEXAI==="true"||hasNonEmptyFile(path.join(home,".gemini","oauth_creds.json"))||hasNonEmptyFile(path.join(home,".gemini","google_accounts.json"))}function isOpenCodeSignedIn(env,home){let dataHome=env?.XDG_DATA_HOME?.trim()||path.join(home,".local","share");return!!env?.OPENCODE_API_KEY?.trim()||!!env?.ANTHROPIC_API_KEY?.trim()||!!env?.OPENAI_API_KEY?.trim()||!!env?.GEMINI_API_KEY?.trim()||hasNonEmptyFile(path.join(dataHome,"opencode","auth.json"))}function isGooseSignedIn(env,home){let configHome=env?.XDG_CONFIG_HOME?.trim()||path.join(home,".config");return!!env?.GOOSE_PROVIDER?.trim()||hasNonEmptyFile(path.join(configHome,"goose","config.yaml"))}async function readSignedIn(provider,{run:run2,env,home=os.homedir()}){if(provider==="claude-code"){let result=await run2("claude",["auth","status"],{env});try{let status=JSON.parse(result.stdout);return typeof status?.loggedIn=="boolean"?status.loggedIn:null}catch{return null}}if(provider==="codex"){let result=await run2("codex",["login","status"],{env});return result.error!=null?null:result.status===0}return provider==="antigravity-cli"?env?.GEMINI_API_KEY?.trim()?!0:null:provider==="gemini-cli"?isGeminiSignedIn(env,home)?!0:null:provider==="opencode"?isOpenCodeSignedIn(env,home)?!0:null:provider==="goose"&&isGooseSignedIn(env,home)?!0:null}async function supportsAcpCli(provider,command,{run:run2,env}){if(provider==="gemini-cli"){let help=await run2(command,["--help"],{env,timeout:5e3});return help.status===0&&/--acp\b/.test(help.stdout)}return provider==="antigravity-cli"||provider==="opencode"||provider==="goose"?(await run2(command,["acp","--help"],{env,timeout:5e3})).status===0:!1}function hasExplicitCommandFile(command,platform,env){for(let candidate of commandFileNames(command,{platform,env}))try{if(fs.accessSync(candidate,fs.constants.X_OK),fs.statSync(candidate).isFile())return candidate}catch{}return null}async function resolveInstalledCommand(command,{run:run2,env,platform}){return path.isAbsolute(command)||command.includes("/")||platform==="win32"&&command.includes("\\")?hasExplicitCommandFile(command,platform,env):platform==="win32"?findCommand2(command,env.PATH??"",null,{platform,env}):(await run2("/usr/bin/which",[command],{env,timeout:5e3})).status===0?command:null}async function installedTools({run:run2,env,platform,wslClaude}){return(await Promise.all(Object.entries(TOOL_COMMANDS).map(async([provider,defaultCommand])=>{if(runsInWsl(provider,platform))return wslClaude?.ready?provider:null;let acp=isAcpProvider(provider),overridden=acp&&hasAcpLaunchOverride(provider,env),command=acp?resolveAcpLaunch(provider,env).command:defaultCommand,resolved=await resolveInstalledCommand(command,{run:run2,env,platform});return resolved==null?null:!acp||overridden||await supportsAcpCli(provider,resolved,{run:run2,env})?provider:null}))).filter(provider=>provider!=null)}function createMachineDescriber({machineFile,platform,spawn:spawn6,hostname:hostname3,env,log:log2,username=()=>"",appName="",readFile:readFile7=file=>fs.readFileSync(file,"utf8"),listServers=listToolServers,listCodexModels=readCodexModels,readWsl=readWslClaude,cacheMs=DESCRIBE_CACHE_MS,now=Date.now}){let run2=(command,args,options={})=>runCommand(spawn6,command,args,options),cached2=null,inFlight=null,generation=0,machineId=null,machineKey=null,confirmedSignedIn=new Map;async function readKey(){if(machineKey!=null)return machineKey;try{machineKey=await readMachineKey({platform,run:run2,readFile:readFile7,username:username(),appName})}catch(error2){log2.warn("[Local tools] could not read this computer's key",error2)}return machineKey}async function describe2(started){let maybeEnv=typeof env.ready=="function"?env.ready():env(),commandEnv=maybeEnv!=null&&typeof maybeEnv.then=="function"?await maybeEnv:maybeEnv,wslClaude=platform==="win32"?await readWsl({run:run2}):null,toolsPromise=installedTools({run:run2,env:commandEnv,platform,wslClaude}),namePromise=readMachineName({platform,run:run2,hostname:hostname3}),keyPromise=readKey(),tools=await toolsPromise,[name,checked,key,codexModels,claudeEffort]=await Promise.all([namePromise,Promise.all(tools.map(provider=>wslClaude!=null&&provider==="claude-code"?wslClaude.signedIn:readSignedIn(provider,{run:run2,env:commandEnv}))),keyPromise,tools.includes("codex")?listCodexModels({spawn:spawn6,env:commandEnv}).catch(()=>null):Promise.resolve(null),tools.includes("claude-code")?wslClaude!=null?Promise.resolve(typeof wslClaude.effort=="boolean"?wslClaude.effort:null):run2("claude",["--help"],{env:commandEnv,timeout:5e3}).then(help=>help.status===0?/--effort\b/.test(help.stdout??""):null,()=>null):Promise.resolve(null)]),current=started===generation,signedIn=tools.map((provider,index)=>(current&&checked[index]!=null&&confirmedSignedIn.set(provider,checked[index]),checked[index]??confirmedSignedIn.get(provider)??null));return{id:machineId??=readMachineId(machineFile),key,name,tools,servers:Object.fromEntries(tools.map(provider=>{try{return wslClaude!=null&&provider==="claude-code"?[provider,wslClaude.servers]:[provider,listServers(provider)]}catch(error2){return log2.warn("[Local tools] could not read a tool's servers",error2),[provider,[]]}})),signedOut:tools.filter((_,index)=>signedIn[index]===!1),...codexModels==null?{}:{models:{codex:codexModels}},effortUnsupported:tools.includes("claude-code")&&claudeEffort!==!0?["claude-code"]:[]}}return{get(){if(cached2!=null&&now()-cached2.at<cacheMs)return Promise.resolve(cached2.value);if(inFlight==null){let started=generation;inFlight=describe2(started).then(value=>(started===generation&&(cached2={at:now(),value}),value)).finally(()=>{started===generation&&(inFlight=null)})}return inFlight},invalidate(){generation+=1,cached2=null,inFlight=null}}}module.exports={TOOL_COMMANDS,UUID,createMachineDescriber,readMachineId,readMachineKey,readMachineName,readSignedIn,runCommand}}});var require_outbox=__commonJS({"../../apps/web/electron/local-tools/outbox.js"(exports,module){"use strict";var fs=__require("fs"),path=__require("path"),MAX_EVENTS=2e3,MAX_BYTES=2*1024*1024,SEQ_RESERVE_STEP=64,ENDING_KINDS=new Set(["done","failed","stopped"]),KEPT_KINDS=new Set(["session",...ENDING_KINDS]);function isEvent(value){return value!=null&&typeof value=="object"&&Number.isSafeInteger(value.seq)&&value.seq>0&&typeof value.runId=="string"&&typeof value.workspaceId=="string"&&typeof value.kind=="string"}var cachedByteSizes=new WeakMap;function size(event){let bytes=cachedByteSizes.get(event);return bytes===void 0&&(bytes=Buffer.byteLength(JSON.stringify(event))+1,cachedByteSizes.set(event,bytes)),bytes}function sumBytes(items){let total=0;for(let i2=0;i2<items.length;i2+=1)total+=size(items[i2]);return total}function readSeq2(file){try{let value=Number(fs.readFileSync(file,"utf8").trim());return Number.isSafeInteger(value)&&value>0?value:0}catch{return 0}}function replaceFile(file,text){let temporary=`${file}.${process.pid}.tmp`;try{fs.writeFileSync(temporary,text,{mode:384}),fs.chmodSync(temporary,384),fs.renameSync(temporary,file)}catch(error2){try{fs.rmSync(temporary,{force:!0})}catch{}throw error2}}function createRunOutbox({file,log:log2,maxEvents=MAX_EVENTS,maxBytes=MAX_BYTES,coalesceMs=0}){let events=[],usageCheckpoints=[],seqFile=`${file.replace(/\.json$/,"")}.seq`,savedSeq=readSeq2(seqFile),lastSeq=savedSeq,dirReady=savedSeq>0,savedOk=!0;try{let saved=JSON.parse(fs.readFileSync(file,"utf8"));dirReady=!0,Array.isArray(saved?.usageCheckpoints)&&(usageCheckpoints=saved.usageCheckpoints.filter(row=>typeof row?.runId=="string"&&typeof row?.workspaceId=="string"&&row?.checkpoint?.usage!=null).slice(-maxEvents)),Array.isArray(saved?.events)&&(events=saved.events.filter(isEvent).sort((a,b)=>a.seq-b.seq)),Number.isSafeInteger(saved?.lastSeq)&&saved.lastSeq>lastSeq&&(lastSeq=saved.lastSeq)}catch(error2){error2?.code!=="ENOENT"&&log2.warn("[Local tools] could not restore run events",error2)}let nextSeq=events.reduce((max,event)=>Math.max(max,event.seq),lastSeq)+1,bytes=sumBytes(events),usageBytes=sumBytes(usageCheckpoints),saveTimer=null,dirty=!1,checkpointBytes=()=>usageCheckpoints.length===0?2:usageBytes+1;function shiftCheckpoint(){let dropped=usageCheckpoints.shift();dropped!==void 0&&(usageBytes-=size(dropped))}function bound(){for(;usageCheckpoints.length>maxEvents;)shiftCheckpoint();for(;usageCheckpoints.length>0&&bytes+checkpointBytes()>maxBytes;)shiftCheckpoint();for(;events.length>1&&(events.length>maxEvents||bytes>maxBytes);){let step=events.findIndex(event=>!KEPT_KINDS.has(String(event.kind))),[dropped]=events.splice(step===-1?0:step,1);bytes-=size(dropped)}for(;usageCheckpoints.length>0&&bytes+checkpointBytes()>maxBytes;)shiftCheckpoint()}function save(){saveTimer!=null&&(clearTimeout(saveTimer),saveTimer=null),dirty=!1;try{dirReady||(fs.mkdirSync(path.dirname(file),{recursive:!0,mode:448}),dirReady=!0);let currentSeq=nextSeq-1;if(currentSeq>savedSeq){let targetSeq=coalesceMs>0?currentSeq+SEQ_RESERVE_STEP:currentSeq;replaceFile(seqFile,`${targetSeq}
|
|
288
288
|
`),savedSeq=targetSeq}replaceFile(file,JSON.stringify({version:1,lastSeq:currentSeq,events,usageCheckpoints})),savedOk=!0}catch(error2){savedOk=!1,dirReady=!1,log2.warn("[Local tools] could not save run events",error2)}}function ensureSeqReserved(seq){if(!(seq<=savedSeq))try{dirReady||(fs.mkdirSync(path.dirname(file),{recursive:!0,mode:448}),dirReady=!0);let targetSeq=coalesceMs>0?seq+SEQ_RESERVE_STEP:seq;replaceFile(seqFile,`${targetSeq}
|
|
289
289
|
`),savedSeq=targetSeq}catch(error2){dirReady=!1,log2.warn("[Local tools] could not reserve run event sequence",error2)}}function scheduleSave(immediate=!1){if(dirty=!0,immediate||coalesceMs<=0){save();return}ensureSeqReserved(nextSeq-1),saveTimer==null&&(saveTimer=setTimeout(()=>(saveTimer=null,dirty&&save(),savedOk),coalesceMs),saveTimer.unref?.())}function filterCheckpointsOut(runId,workspaceId){let kept=[],keptBytes=0;for(let i2=0;i2<usageCheckpoints.length;i2+=1){let row=usageCheckpoints[i2];(row.runId!==runId||row.workspaceId!==workspaceId)&&(kept.push(row),keptBytes+=size(row))}usageCheckpoints=kept,usageBytes=keptBytes}return{push(event){let queued={...event,seq:nextSeq++};return events.push(queued),ENDING_KINDS.has(String(event.kind))&&filterCheckpointsOut(event.runId,event.workspaceId),bytes+=size(queued),bound(),scheduleSave(KEPT_KINDS.has(String(event.kind))),queued},rememberUsage(runId,workspaceId,checkpoint){let existing=usageCheckpoints.find(row2=>row2.runId===runId&&row2.workspaceId===workspaceId);if(savedOk&&existing!=null&&JSON.stringify(existing.checkpoint)===JSON.stringify(checkpoint))return;filterCheckpointsOut(runId,workspaceId);let row={runId,workspaceId,checkpoint};usageCheckpoints.push(row),usageBytes+=size(row),bound(),scheduleSave(!1)},recall(runId,workspaceId){let ended=!1,sessionId=null;for(let event of events)event.runId!==runId||event.workspaceId!==workspaceId||(ENDING_KINDS.has(String(event.kind))&&(ended=!0),event.kind==="session"&&typeof event.sessionId=="string"&&(sessionId=event.sessionId));let usageCheckpoint=usageCheckpoints.find(row=>row.runId===runId&&row.workspaceId===workspaceId)?.checkpoint;return{ended,sessionId,...usageCheckpoint==null?{}:{usageCheckpoint}}},list:()=>[...events],ack(seqs){let acked=new Set(seqs),kept=[],nextBytes=0;for(let i2=0;i2<events.length;i2+=1){let event=events[i2];acked.has(event.seq)||(kept.push(event),nextBytes+=size(event))}kept.length!==events.length&&(events=kept,bytes=nextBytes,scheduleSave(!1))},flush(){return dirty&&save(),savedOk}}}module.exports={createRunOutbox}}});var require_runs=__commonJS({"../../apps/web/electron/local-tools/runs.js"(exports,module){"use strict";var{checkpointClaudeUsage,subtractUsageBaseline}=require_usage(),fs=__require("fs"),path=__require("path"),{linkedPaths,policyInstructions}=require_policy(),{resultFileInstructions}=require_result_files(),STEP_LIMIT=280,TEST_PROMPT="This is a test from Ando that you start and answer. Reply with the single word OK. Do not read or change any files and do not run any commands.",TEST_TIMEOUT_MS=2*6e4,START_TIMEOUT_MS=5*6e4;function clip(value){let text=typeof value=="string"?value.trim().replace(/\s+/g," "):"";return text.length>STEP_LIMIT?`${text.slice(0,STEP_LIMIT-1)}\u2026`:text}function shortPath(value,folder){if(typeof value!="string")return"";let relative2=path.relative(folder,value);return relative2&&!relative2.startsWith("..")?relative2:value}function step(text,tool,target){return tool==null?{text}:{text,tool,target:clip(target)}}function describeToolUse(block,folder){let input=block?.input??{};switch(block?.name){case"Read":{let file=shortPath(input.file_path,folder);return step(`Read ${file}`,"read",file)}case"Edit":case"MultiEdit":case"Write":{let file=shortPath(input.file_path,folder);return step(`Edited ${file}`,"edit",file)}case"Bash":return step(`Ran ${clip(input.command)}`,"bash",input.command);case"Grep":return step(`Searched for ${clip(input.pattern)}`,"search",input.pattern);case"Glob":return step(`Listed ${clip(input.pattern)}`,"search",input.pattern);case"WebFetch":case"WebSearch":return step(`Looked up ${clip(input.url??input.query)}`,"web",input.url??input.query);case"TodoWrite":return null;default:return typeof block?.name=="string"?step(`Used ${block.name}`):null}}function claudeRunSteps(message,folder){let content=message?.type==="assistant"?message.message?.content:null;if(!Array.isArray(content))return[];let usesTools=content.some(block=>block?.type==="tool_use");return content.map(block=>{if(block?.type==="tool_use")return describeToolUse(block,folder);if(block?.type==="text"&&usesTools){let text=clip(block.text);return text?step(text):null}return null}).filter(Boolean)}var SIGNED_OUT=/not logged in|please run \/login|not authenticated|login required/i;function describeFailure(run2,error2){let message=error2?.message??String(error2);return SIGNED_OUT.test(message)?`${run2.toolName??(run2.provider==="codex"?"Codex":"Claude Code")} isn't signed in on this computer. Open its connection for this computer in Ando, sign in there, then start the task again.`:message}function commits(count){return`${count} ${count===1?"commit":"commits"}`}function baseInstructions(base){if(base==null)return[];if(base.kind==="folder"){if(!(base.behind>0))return[];let ref2=base.ref??`origin/${base.branch}`;return[`This folder is ${commits(base.behind)} behind ${ref2} (${base.fetched?"fetched just now":"as of its last fetch; origin couldn't be reached"}), so its files can describe behavior that has since changed. When the task is about how things work now, read ${ref2} rather than the files here, with \`git show ${ref2}:<path>\` or \`git grep <pattern> ${ref2}\`, and say which version you read.`]}if(base.startedFromOrigin===!0)return base.dependenciesChanged===!0?["Dependency files changed between the folder's commit and this one, and the installed dependencies here were copied from the folder: reinstall them before running or testing code."]:[];if(base.reachedOrigin===!1)return base.hasOrigin?["Origin couldn't be reached when this checkout was made, so it may be behind the repository's default branch."]:[];if(!(base.behind>0))return[];let ref=`origin/${base.branch}`;return base.linksChanged===!0?[`This started from the folder's commit, ${commits(base.behind)} behind ${ref}: origin's newer commits add or change symlinks or \`.claude/settings.local.json\`, which could reach folders the owner hasn't opened to tasks. See \`git log HEAD..${ref}\` when current behavior matters.`]:[`The commit this started from has work that isn't on ${ref} yet, and is ${commits(base.behind)} behind it as fetched when the task started. Code merged since then isn't here: see \`git log HEAD..${ref}\` when current behavior matters.`]}function runInstructions(run2){let{linked}=linkedPaths(run2.folder);return[`You are ${run2.toolName} working on a task that ${run2.agentName??"an Ando agent"} started on this computer for its owner, through Ando, their team messenger.`,`Work in ${run2.folder}. Messages that arrive while you work are new context from the task's thread in Ando.`,...run2.checkoutOf==null?[]:[run2.policy?.files==="never"?`This is the task's checkout of ${run2.checkoutOf}; nothing here changes the original folder.`:`This is your own checkout of ${run2.checkoutOf}, on a branch of its own, made from ${run2.base?.startedFromOrigin===!0?`origin's ${run2.base.branch} as fetched when the task started`:"what's committed there"}. Commit your work here. To hand it over, push this branch and open a pull request if you can; nothing here changes the original folder.`],...baseInstructions(run2.base),policyInstructions(run2.policy,run2.folder,{linked}),...run2.returnFiles===!0?[resultFileInstructions(run2)]:[],"Do not start commands in the background or leave work running: wait for every command to finish, however long it takes, before your final message.","When you finish, your final message is reported back to the task as its result: say briefly what you did, what changed, and anything the team should know.",run2.postAsOwner===!0?"This computer's owner asked for you to post in Ando yourself. Your posts there show as them, so post only what the task asks for.":`${run2.agentName??"The agent"} posts your result in the thread. Do not send, reply, react or upload in Ando yourself, even if the task says to send or share something: return it in your result. Anything posted from here shows as this computer's owner.`].join(`
|
|
290
290
|
|
|
@@ -293,10 +293,10 @@ ${notice}`,log:log2,permissionArgs,effort,model,onClose:cleanup})}catch(error2){
|
|
|
293
293
|
`),...outputs.files.length===0?{}:{files:outputs.files},...usage==null?{}:{usage}})}catch(error2){if(closing)return;if(runs.get(run2.runId)?.startTimedOut){let hint=notStartedHint(run2);report(run2,{kind:"failed",sessionId:reportedSession,error:[`${run2.toolName??(run2.provider==="codex"?"Codex":"Claude Code")} didn't start in ${run2.folder} within ${Math.round(startTimeoutMs/6e4)} minutes, so this task was ended.`,hint??"Check that it starts there from a terminal, then start the task again."].join(" ")});return}if(runs.get(run2.runId)?.stopping){report(run2,{kind:"stopped",sessionId:reportedSession,...lastUsage==null?{}:{usage:lastUsage}});return}report(run2,{kind:"failed",sessionId:reportedSession,error:describeFailure(run2,error2)})}finally{clearTimeout(startTimer),runtime.close(),runs.delete(run2.runId)}}return{start(run2,setup={}){if(runs.has(run2.runId))return{status:"running"};if(!exists(run2.folder))return report(run2,{kind:"failed",sessionId:run2.sessionId??null,error:`${run2.folder} isn't on this computer.`}),{status:"failed"};let runtime;try{runtime=createRunRuntime(run2,setup)}catch(error2){return report(run2,{kind:"failed",sessionId:run2.sessionId??null,error:describeFailure(run2,error2)}),{status:"failed"}}return runs.set(run2.runId,{runtime,run:run2}),execute(run2,runtime),{status:"started"}},async test(run2,{timeoutMs=TEST_TIMEOUT_MS}={}){let failed=error2=>({status:"failed",error:describeFailure(run2,error2)});if(!exists(run2.folder))return failed(new Error(`${run2.folder} isn't on this computer.`));let runtime;try{runtime=createRunRuntime(run2)}catch(error2){return failed(error2)}tests.add(runtime);let timer;try{return await Promise.race([runtime.runTurn({key:run2.runId,sessionId:null,text:TEST_PROMPT}),new Promise((_,reject)=>{timer=setTimeout(()=>reject(new Error(`${run2.toolName} didn't answer within ${Math.round(timeoutMs/6e4)} minutes.`)),timeoutMs)})]),{status:"passed"}}catch(error2){return failed(error2)}finally{clearTimeout(timer),tests.delete(runtime),runtime.close()}},async steer({runId,text}){let active=runs.get(runId);return active?active.runtime.steer({key:runId,text}):!1},stop(runId){let active=runs.get(runId);return active==null?!1:(active.stopping=!0,active.runtime.close(),!0)},list:()=>[...runs.keys()],listMeta:()=>[...runs.values()].map(({run:run2})=>({runId:run2.runId,workspaceId:run2.workspaceId,...run2.ownerId==null?{}:{ownerId:run2.ownerId}})),stopAll(){closing=!0;for(let{runtime}of runs.values())runtime.close();for(let runtime of tests)runtime.close();runs.clear()}}}module.exports={START_TIMEOUT_MS,claudeRunSteps,createLocalToolRuns,runInstructions}}});var require_run_request=__commonJS({"../../apps/web/electron/local-tools/run-request.js"(exports,module){"use strict";var fs=__require("fs"),os=__require("os"),path=__require("path"),{TOOL_COMMANDS,TOOL_NAMES,acpUnsandboxedError,isAcpProvider}=require_drivers(),{UUID}=require_machine(),{resolvePolicy}=require_policy(),EFFORTS=new Set(["low","medium","high"]),MODEL_ID=/^[A-Za-z0-9][A-Za-z0-9._:/-]{0,79}$/,LIMITS_DONT_HOLD_ERROR="Codex can't take this task on Linux with network access on: its sandbox lets a task reach local services such as Docker, and run commands outside it. Turn network access off for this machine, or use Claude Code.",SESSION_ID=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;function text(value,limit){return typeof value=="string"&&value.trim()&&value.length<=limit?value:null}function limitsDontHoldReason(run2,platform){return platform==="linux"&&run2.provider==="codex"&&run2.policy.network!=="never"?LIMITS_DONT_HOLD_ERROR:isAcpProvider(run2.provider)&&run2.policy.full_access!=="allow"?acpUnsandboxedError(run2.toolName,platform):null}function parseUsageBaseline(raw){if(raw==null||typeof raw!="object")return null;let num=v2=>typeof v2=="number"&&Number.isFinite(v2)&&v2>=0?v2:0,optNum=v2=>typeof v2=="number"&&Number.isFinite(v2)&&v2>=0?v2:null;return{inputTokens:num(raw.inputTokens),cachedInputTokens:num(raw.cachedInputTokens),cacheWriteTokens:num(raw.cacheWriteTokens),outputTokens:num(raw.outputTokens),reasoningTokens:optNum(raw.reasoningTokens),costUsd:optNum(raw.costUsd)}}function isValidSessionId(value){return typeof value=="string"&&SESSION_ID.test(value)}function holdsHome2(folder,home=os.homedir(),{realpath:realpath2=fs.realpathSync}={}){if(typeof folder!="string"||folder.trim().length===0)return!1;let winStyle=/^(?:[A-Za-z]:[\\/]|\\\\[^\\])/.test(folder)&&/^(?:[A-Za-z]:[\\/]|\\\\[^\\])/.test(home),ops=winStyle?path.win32:path,check2=(candidate,targetHome)=>{let inside=ops.relative(winStyle?candidate.toLowerCase():candidate,winStyle?targetHome.toLowerCase():targetHome);return inside===""||!inside.startsWith("..")&&!ops.isAbsolute(inside)},resolvedFolder=ops.resolve(folder),resolvedHome=ops.resolve(home);if(check2(resolvedFolder,resolvedHome))return!0;let realOr=target=>{try{return realpath2(target)}catch{return target}},realFolder=realOr(resolvedFolder),realHome=realOr(resolvedHome);return realFolder!==resolvedFolder||realHome!==resolvedHome?check2(realFolder,realHome):!1}function parseRunRequest(input,platform=process.platform,home=os.homedir()){let value=input!=null&&typeof input=="object"?input:{};if(typeof value.runId!="string"||!UUID.test(value.runId)||!(value.provider in TOOL_COMMANDS))return null;let workspaceId=text(value.workspaceId,200);if(workspaceId==null)return null;let folder=text(value.folder,1e3),prompt=text(value.prompt,2e4);if(folder==null||!path.isAbsolute(folder)||holdsHome2(folder,home)||prompt==null)return null;let rawSessionId=text(value.sessionId,200);if(rawSessionId!=null&&!isValidSessionId(rawSessionId))return null;let sessionId=rawSessionId,continuedFromRunId=typeof value.continuedFromRunId=="string"&&UUID.test(value.continuedFromRunId)?value.continuedFromRunId:null,rawContinuedSessionId=text(value.continuedSessionId,200);if(rawContinuedSessionId!=null&&!isValidSessionId(rawContinuedSessionId))return null;let continuedSessionId=rawContinuedSessionId??(continuedFromRunId!=null?sessionId:null);return{runId:value.runId,workspaceId,ownerId:text(value.ownerId,200),...value.returnFiles===!0?{returnFiles:!0}:{},...value.postAsOwner===!0?{postAsOwner:!0}:{},provider:value.provider,toolName:TOOL_NAMES[value.provider],folder,prompt,title:text(value.title,200),sessionId,continuedSessionId,continuedFromRunId,continuedUsageBaseline:parseUsageBaseline(value.continuedUsageBaseline),checkoutRunId:typeof value.checkoutRunId=="string"&&UUID.test(value.checkoutRunId)?value.checkoutRunId:null,midTurnRestart:value.midTurnRestart===!0,agentName:text(value.agentName,200),policy:resolvePolicy(value.policy,{platform}),effort:EFFORTS.has(value.effort)?value.effort:null,model:typeof value.model=="string"&&MODEL_ID.test(value.model)?value.model:null,bareCheckout:value.bareCheckout===!0,servers:Array.isArray(value.servers)?value.servers.filter(name=>text(name,200)!=null).slice(0,50):[]}}module.exports={holdsHome:holdsHome2,isValidSessionId,limitsDontHoldReason,parseRunRequest,text}}});var require_sessions=__commonJS({"../../apps/web/electron/local-tools/sessions.js"(exports,module){"use strict";var fs=__require("fs"),os=__require("os"),path=__require("path"),readline=__require("readline"),{codexHome}=require_servers(),SESSION_ID=/^[A-Za-z0-9][A-Za-z0-9._-]{7,127}$/,LIST_LIMIT=30,DEFAULT_TURNS=20,MAX_TURNS=60,MAX_BYTES=6e4,TOOL_OUTPUT_CHARS=600,TEXT_CHARS=6e3,TITLE_CHARS=200,LIST_SCAN_FILES=200,LIST_HEAD_SCAN_FILES=5e3,HEAD_BYTES=64*1024,PROVIDERS=new Set(["claude-code","codex"]);function sessionRoots({home=os.homedir(),env=process.env}={}){return[path.join(home,".claude","projects"),path.join(codexHome(env,home),"sessions")]}function claudeProjectKey(folder){return folder.replace(/[^A-Za-z0-9]/g,"-")}function isInside(folder,file){if(typeof file!="string"||typeof folder!="string")return!1;let relative2=path.relative(folder,file);return relative2===""||!relative2.startsWith("..")&&!path.isAbsolute(relative2)}function folderOf(folders,cwd){return folders.find(folder=>isInside(folder,cwd))??null}function clip(text,limit){let value=typeof text=="string"?text:"";return value.length>limit?`${value.slice(0,limit-1)}\u2026`:value}function mtime(file){try{return fs.statSync(file).mtimeMs}catch{return 0}}function readdir4(dir){try{return fs.readdirSync(dir,{withFileTypes:!0})}catch{return[]}}function toTime(value){if(typeof value=="number"&&Number.isFinite(value))return value>1e12?value:value*1e3;if(typeof value!="string")return null;let time3=Date.parse(value);return Number.isFinite(time3)?time3:null}var SENSITIVE_NAME=/(api[_-]?key|authorization|cookie|credential|jwt|passw(or)?d|passphrase|private[_-]?key|secret|token|signature)/i,HEADER_LINE=/\b(proxy-authorization|authorization|set-cookie|cookie|x-api-key|api-key|x-auth-token|x-csrf-token|x-amz-security-token)(["']?[ \t]{0,8}[:=][ \t]{0,8}["']?)([^\r\n"'`]+)/gi,BEARER=/\b(bearer)(\s+)([A-Za-z0-9\-._~+/]{8,4096}={0,2})(?![A-Za-z0-9\-._~+/=])/gi,JWT=/(?<![A-Za-z0-9_.-])eyJ[A-Za-z0-9_-]{8,4096}\.[A-Za-z0-9_-]{8,16384}\.[A-Za-z0-9_-]{0,4096}(?![A-Za-z0-9_-])/g,URL_PARAMETER=/([?&#;])([A-Za-z0-9_.%-]{1,64})=([^&#\s"'<>`]*)/g,SENSITIVE_PARAMETER=/^(access_token|api[_-]?key|auth|client_secret|code|id_token|key|password|refresh_token|secret|sig|signature|state|token|x-amz-credential|x-amz-security-token|x-amz-signature|x-goog-signature)$/i,KNOWN_TOKENS=[[/(?<![A-Za-z0-9_-])ando_sk_[A-Za-z0-9_-]{16,512}(?![A-Za-z0-9_-])/g,"ando_api_key"],[/(?<![A-Za-z0-9_-])ando_join_[A-Za-z0-9_-]{16,512}(?![A-Za-z0-9_-])/g,"ando_join_token"],[/(?<![A-Za-z0-9_-])(?:ando_)?whsec_[A-Za-z0-9_:+/=-]{16,1024}(?![A-Za-z0-9_:+/=-])/g,"webhook_secret"],[/(?<![A-Za-z0-9_-])sk-(?:ant-|proj-)?[A-Za-z0-9_-]{20,512}(?![A-Za-z0-9_-])/g,"api_key"],[/(?<![A-Za-z0-9_])[sr]k_(?:live|test)_[A-Za-z0-9]{16,512}(?![A-Za-z0-9_])/g,"api_key"],[/(?<![A-Za-z0-9_])(?:github_pat_|gh[oprsu]_)[A-Za-z0-9_]{20,512}(?![A-Za-z0-9_])/g,"github_token"],[/(?<![A-Za-z0-9_-])glpat-[A-Za-z0-9_-]{20,512}(?![A-Za-z0-9_-])/g,"gitlab_token"],[/(?<![A-Za-z0-9-])xox[abprs]-[A-Za-z0-9-]{10,512}(?![A-Za-z0-9-])/g,"slack_token"],[/(?<![A-Za-z0-9._-])ya29\.[A-Za-z0-9._-]{20,4096}(?![A-Za-z0-9._-])/g,"google_token"],[/\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g,"aws_access_key"],[/(?<![A-Za-z0-9_-])npm_[A-Za-z0-9]{30,128}(?![A-Za-z0-9_-])/g,"npm_token"]],ASSIGNMENT=/(["']?)(?<![A-Za-z0-9_.-])([A-Za-z][A-Za-z0-9_.-]{1,63})\1[ \t]{0,8}[:=][ \t]{0,8}(["']?)([^\s"'&,;}<>`\]]{12,})/g,PEM=/-----BEGIN [A-Z0-9 ]{0,40}PRIVATE KEY-----[\s\S]{0,65536}?-----END [A-Z0-9 ]{0,40}PRIVATE KEY-----/g;function marker(kind){return`[redacted:${kind}]`}function looksSecret(value){if(value.length<12||value.startsWith("[redacted:"))return!1;let classes=0;return/[a-z]/.test(value)&&(classes+=1),/[A-Z]/.test(value)&&(classes+=1),/[0-9]/.test(value)&&(classes+=1),/[-_.+/=~]/.test(value)&&(classes+=1),classes>=2}var URL_CREDENTIALS=/\b([a-z][a-z0-9+.-]*:\/\/)[^\s/@:]+(?::[^\s/@]*)?@/gi;function redact2(input){if(typeof input!="string"||input.length<8)return input;let text=input;text.includes("://")&&text.includes("@")&&(text=text.replace(URL_CREDENTIALS,`$1${marker("url_credentials")}@`)),text.includes("-----BEGIN ")&&(text=text.replace(PEM,marker("private_key"))),text=text.replace(HEADER_LINE,(match,name,separator,value)=>/^(?:bearer|basic|digest|token)\s+\S{6,}/i.test(value.trim())||/[^\s=]=[^\s=]/.test(value)||looksSecret(value.trim())?`${name}${separator}${marker(name.toLowerCase())}`:match),text.includes("=")&&(text=text.replace(URL_PARAMETER,(match,lead,name,value)=>value.length>0&&!value.startsWith("[redacted:")&&SENSITIVE_PARAMETER.test(name)?`${lead}${name}=${marker(name.toLowerCase())}`:match)),text=text.replace(BEARER,(match,bearer,space,token)=>looksSecret(token)||token.length>=20?`${bearer}${space}${marker("bearer")}`:match),text.includes("eyJ")&&(text=text.replace(JWT,marker("jwt")));for(let[pattern,kind]of KNOWN_TOKENS)text=text.replace(pattern,marker(kind));return text=text.replace(ASSIGNMENT,(match,quote,name,valueQuote,value)=>SENSITIVE_NAME.test(name)&&looksSecret(value)?`${match.slice(0,match.length-value.length)}${marker(name.toLowerCase())}`:match),text}function blocksText(content,type="text"){return typeof content=="string"?content:Array.isArray(content)?content.filter(block=>block!=null&&typeof block=="object"&&block.type===type&&typeof block.text=="string").map(block=>block.text).join(`
|
|
294
294
|
`):""}function describeCall(name,input){let value=input!=null&&typeof input=="object"?input:{},target=typeof value.command=="string"?value.command:typeof value.file_path=="string"?value.file_path:typeof value.pattern=="string"?value.pattern:typeof value.query=="string"?value.query:typeof value.url=="string"?value.url:typeof input=="string"?input:JSON.stringify(value);return`[${name}] ${clip(redact2(target??""),300)}`}var ATTACHED_CONTEXT=/<(system-reminder|task-notification|ci-monitor-event|side-sessions-event)>[\s\S]*?<\/\1>\s*/g;function strippedPrompt(text){return text.includes("</")?text.replace(ATTACHED_CONTEXT,"").trim():text.trim()}function isInjectedPrompt(text){let trimmed=text.trimStart();return trimmed.startsWith("<")||trimmed.startsWith("# AGENTS.md")||trimmed.startsWith("Base directory for this skill")}function newTranscript(provider,file){return{provider,file,sessionId:null,cwd:null,gitBranch:null,title:null,customTitle:null,startedAt:null,lastAt:null,startedByAndo:!1,turnCount:0,entries:[],maxTurns:null,droppedTurns:0,cwdNow:null,folders:null,turnsElsewhere:0}}function inShared(transcript){let cwd=transcript.cwdNow??transcript.cwd;return transcript.folders==null||cwd==null||folderOf(transcript.folders,cwd)!=null}function forgetOldestTurns(transcript){let starts=[];transcript.entries.forEach((entry,index)=>{entry.role==="user"&&starts.push(index)});let excess=starts.length+1-transcript.maxTurns;excess<=0||(transcript.entries.splice(0,starts[excess]),transcript.droppedTurns+=excess)}function note(transcript,at,role,text,keep){if(!inShared(transcript))return;let clean=clip(redact2(text),TEXT_CHARS);clean.trim()&&keep&&transcript.entries.push({at,role,text:clean,cwd:transcript.cwdNow??transcript.cwd})}function noteTime(transcript,at){at!=null&&(transcript.startedAt??=at,transcript.lastAt=Math.max(transcript.lastAt??at,at))}function notePrompt(transcript,at,text,keep){if(!inShared(transcript)){transcript.turnsElsewhere+=1;return}transcript.turnCount+=1,transcript.title??=clip(redact2(text.split(`
|
|
295
295
|
`)[0]??text),TITLE_CHARS),keep&&transcript.maxTurns!=null&&forgetOldestTurns(transcript),note(transcript,at,"user",text,keep)}function takeClaudeUser(transcript,line,at,keep,toolNames){if(line.isMeta===!0||line.turnCompanion===!0)return;let content=line.message.content;if(Array.isArray(content)&&content.some(block=>block?.type==="tool_result")){for(let block of content){if(block?.type!=="tool_result")continue;let name=toolNames.get(block.tool_use_id)??"tool",output=typeof block.content=="string"?block.content:blocksText(block.content);note(transcript,at,"tool",`${name}: ${clip(redact2(output),TOOL_OUTPUT_CHARS)}`,keep)}return}let text=strippedPrompt(blocksText(content)),starts=typeof line.turnOrigin=="string"||line.origin?.kind!=null;!text||!starts&&isInjectedPrompt(text)||notePrompt(transcript,at,text,keep)}function takeClaudeAssistant(transcript,line,at,keep,toolNames){if(Array.isArray(line.message.content))for(let block of line.message.content)block?.type==="text"?note(transcript,at,"assistant",block.text,keep):block?.type==="tool_use"&&(typeof block.id=="string"&&toolNames.set(block.id,typeof block.name=="string"?block.name:"tool"),note(transcript,at,"assistant",describeCall(block.name??"tool",block.input),keep))}function takeClaudeLine(transcript,line,keep,toolNames){typeof line.cwd=="string"&&(transcript.cwd??=line.cwd,transcript.cwdNow=line.cwd);let shared=inShared(transcript);shared&&typeof line.gitBranch=="string"&&line.gitBranch&&(transcript.gitBranch=line.gitBranch),typeof line.sessionId=="string"&&transcript.sessionId==null&&(transcript.sessionId=line.sessionId);let at=toTime(line.timestamp);if(shared&¬eTime(transcript,at),line.type==="custom-title"&&typeof line.customTitle=="string"){shared&&(transcript.customTitle=clip(redact2(line.customTitle),TITLE_CHARS));return}line.isSidechain===!0||line.message==null||(line.type==="user"?takeClaudeUser(transcript,line,at,keep,toolNames):line.type==="assistant"&&takeClaudeAssistant(transcript,line,at,keep,toolNames))}function codexOutputText(output){return typeof output=="string"?output:Array.isArray(output)?blocksText(output,"input_text")||blocksText(output,"output_text")||blocksText(output):""}function takeCodexMeta(transcript,payload){typeof payload.cwd=="string"&&(transcript.cwd=payload.cwd,transcript.cwdNow=payload.cwd),typeof payload.id=="string"?transcript.sessionId=payload.id:typeof payload.session_id=="string"&&(transcript.sessionId=payload.session_id),typeof payload.git?.branch=="string"&&inShared(transcript)&&(transcript.gitBranch=payload.git.branch);let started=toTime(payload.timestamp);started!=null&&(transcript.startedAt=started),transcript.startedByAndo=payload.originator==="ando-desktop"}function takeCodexItem(transcript,payload,at,keep,toolNames){switch(payload.type){case"message":{let text=blocksText(payload.content,"input_text")||blocksText(payload.content,"output_text")||blocksText(payload.content);payload.role==="user"?text.trim()&&!isInjectedPrompt(text)&¬ePrompt(transcript,at,text,keep):payload.role==="assistant"&¬e(transcript,at,"assistant",text,keep);return}case"function_call":case"custom_tool_call":{let name=typeof payload.name=="string"?payload.name:"tool";typeof payload.call_id=="string"&&toolNames.set(payload.call_id,name),note(transcript,at,"assistant",describeCall(name,payload.arguments??payload.input),keep);return}case"function_call_output":case"custom_tool_call_output":{let name=toolNames.get(payload.call_id)??"tool";note(transcript,at,"tool",`${name}: ${clip(redact2(codexOutputText(payload.output)),TOOL_OUTPUT_CHARS)}`,keep);return}default:return}}function takeCodexLine(transcript,line,keep,toolNames){let at=toTime(line.timestamp),payload=line.payload;payload==null||typeof payload!="object"||(line.type==="session_meta"?takeCodexMeta(transcript,payload):line.type==="turn_context"&&typeof payload.cwd=="string"&&(transcript.cwd??=payload.cwd,transcript.cwdNow=payload.cwd),inShared(transcript)&¬eTime(transcript,at),line.type==="response_item"&&takeCodexItem(transcript,payload,at,keep,toolNames))}async function parseTranscript(provider,file,{keep,maxTurns=null,folders=null}){let transcript=newTranscript(provider,file);transcript.maxTurns=maxTurns,transcript.folders=folders;let toolNames=new Map,take=provider==="codex"?takeCodexLine:takeClaudeLine,stream=fs.createReadStream(file,{encoding:"utf8"});try{for await(let raw of readline.createInterface({input:stream,crlfDelay:1/0})){if(!raw.trim())continue;let line;try{line=JSON.parse(raw)}catch{continue}line==null||typeof line!="object"||take(transcript,line,keep,toolNames)}}finally{stream.destroy()}return transcript.lastAt==null&&(transcript.lastAt=mtime(file)||null),transcript}function readHeadCwd(provider,file){let fd;try{fd=fs.openSync(file,"r");let buffer=Buffer.alloc(HEAD_BYTES),read=fs.readSync(fd,buffer,0,HEAD_BYTES,0),head=buffer.toString("utf8",0,read);for(let raw of head.split(`
|
|
296
|
-
`)){if(!raw.trim())continue;let line;try{line=JSON.parse(raw)}catch{continue}if(provider==="codex"){if(line?.type==="session_meta"&&typeof line.payload?.cwd=="string")return line.payload.cwd}else if(typeof line?.cwd=="string")return line.cwd}return null}catch{return null}finally{fd!=null&&fs.closeSync(fd)}}function claudeProjectDirs(home,folders){let root=path.join(home,".claude","projects"),keys=folders.map(claudeProjectKey);return readdir4(root).filter(entry=>entry.isDirectory()&&keys.some(key=>entry.name===key||entry.name.startsWith(`${key}-`))).map(entry=>path.join(root,entry.name))}function claudeCandidates(home,folders){let files=[];for(let dir of claudeProjectDirs(home,folders))for(let entry of readdir4(dir)){if(!entry.isFile()||!entry.name.endsWith(".jsonl"))continue;let id=entry.name.slice(0,-6);if(!SESSION_ID.test(id))continue;let file=path.join(dir,entry.name);files.push({file,id,mtime:mtime(file)})}return files}function codexCandidates(codexDir){let root=path.join(codexDir,"sessions"),files=[],descending=entries=>entries.filter(e=>e.isDirectory()).sort((a,b)=>b.name.localeCompare(a.name));for(let year of descending(readdir4(root)))for(let month of descending(readdir4(path.join(root,year.name))))for(let day of descending(readdir4(path.join(root,year.name,month.name)))){let dir=path.join(root,year.name,month.name,day.name);for(let entry of readdir4(dir)){let match=entry.isFile()&&/^rollout-.*-([0-9a-f-]{36})\.jsonl$/i.exec(entry.name);if(!match)continue;let file=path.join(dir,entry.name);files.push({file,id:match[1],mtime:mtime(file)})}}return files}function candidates(provider,{home,codexDir,folders}){return(provider==="codex"?codexCandidates(codexDir):claudeCandidates(home,folders)).sort((a,b)=>b.mtime-a.mtime)}function summary(transcript,folder){return{session_id:transcript.sessionId,provider:transcript.provider,folder,...transcript.cwd!=null&&transcript.cwd!==folder?{working_dir:transcript.cwd}:{},git_branch:transcript.gitBranch,title:transcript.customTitle??transcript.title??"(no prompt yet)",started_at:transcript.startedAt==null?null:new Date(transcript.startedAt).toISOString(),last_active_at:transcript.lastAt==null?null:new Date(transcript.lastAt).toISOString(),turn_count:transcript.turnCount,started_by_ando:transcript.startedByAndo}}async function listSessions(input){let home=input.home??os.homedir(),codexDir=codexHome(input.env??process.env,home),limit=Math.min(LIST_LIMIT,Math.max(1,input.limit??LIST_LIMIT)),folders=input.folders,reads=input.budget?.reads??LIST_SCAN_FILES,looks=input.budget?.looks??LIST_HEAD_SCAN_FILES,sessions=[],read=0,looked=0,incomplete=!1;for(let candidate of candidates(input.provider,{home,codexDir,folders})){if(sessions.length>=limit)break;if(read>=reads||looked>=looks){incomplete=!0;break}looked+=1;let folder=folderOf(folders,readHeadCwd(input.provider,candidate.file));if(folder==null)continue;read+=1;let transcript=await parseTranscript(input.provider,candidate.file,{keep:!1,folders});folderOf(folders,transcript.cwd)===folder&&(transcript.sessionId??=candidate.id,sessions.push(summary(transcript,folder)))}return sessions.sort((a,b)=>(b.last_active_at??"").localeCompare(a.last_active_at??"")),{sessions,incomplete}}function groupTurns(entries){let turns=[];for(let entry of entries)(entry.role==="user"||turns.length===0)&&turns.push([]),turns[turns.length-1].push(entry);return turns}async function readSession(input){let home=input.home??os.homedir(),codexDir=codexHome(input.env??process.env,home);if(typeof input.sessionId!="string"||!SESSION_ID.test(input.sessionId))throw new Error("That isn't a session id.");let wanted=input.sessionId.toLowerCase(),candidate=candidates(input.provider,{home,codexDir,folders:input.folders}).find(entry=>entry.id.toLowerCase()===wanted),notFound=new Error("No session with that id in the folders agents may read. list_sessions names the ones there are.");if(candidate==null)throw notFound;let folder=folderOf(input.folders,readHeadCwd(input.provider,candidate.file));if(folder==null)throw notFound;let wantedTurns=Math.min(MAX_TURNS,Math.max(1,input.turns??DEFAULT_TURNS)),transcript=await parseTranscript(input.provider,candidate.file,{keep:!0,maxTurns:wantedTurns,folders:input.folders});if(folderOf(input.folders,transcript.cwd)!==folder)throw notFound;transcript.sessionId??=candidate.id;let turnsElsewhere=transcript.turnsElsewhere,all=groupTurns(transcript.entries),kept=all.slice(-wantedTurns),entries=kept.flat(),truncated=transcript.droppedTurns>0||kept.length<all.length||turnsElsewhere>0,answer=list=>({...summary(transcript,folder),turns_returned:list.filter(entry=>entry.role==="user").length,...turnsElsewhere>0?{turns_elsewhere:turnsElsewhere}:{},truncated,turns:list.map(entry=>({at:entry.at==null?null:new Date(entry.at).toISOString(),role:entry.role,text:entry.text}))}),bytes=list=>Buffer.byteLength(JSON.stringify(answer(list)),"utf8");for(;entries.length>1&&bytes(entries)>MAX_BYTES;)entries=entries.slice(1),truncated=!0;return entries.length===1&&bytes(entries)>MAX_BYTES&&(entries=[{...entries[0],text:clipBytes(entries[0].text,MAX_BYTES-500)}],truncated=!0),answer(entries)}function clipBytes(text,max){let cut=text;for(;Buffer.byteLength(cut,"utf8")>max;)cut=cut.slice(0,Math.max(1,Math.floor(cut.length*max/Buffer.byteLength(cut,"utf8"))-1));return cut===text?text:`${cut.trimEnd()} \u2026`}function absoluteFolders(value){return Array.isArray(value)?value.filter(folder=>typeof folder=="string"&&path.isAbsolute(folder)&&folder.length<=1e3).slice(0,20):[]}async function answerSessionRequest(input,deps2={}){let platform=deps2.platform??process.platform,request=input!=null&&typeof input=="object"?input:{},folders=absoluteFolders(request.folders);if(!PROVIDERS.has(request.provider)||request.kind!=="list"&&request.kind!=="read"||folders.length===0)return{status:"failed",error:"The Ando app couldn't read this request."};if(request.provider==="claude-code"&&platform==="win32")return{status:"failed",error:"Claude Code's sessions on Windows live in WSL, where the Ando app can't read them."};let base={provider:request.provider,folders,home:deps2.home,env:deps2.env};try{let result=request.kind==="list"?await listSessions({...base,limit:typeof request.limit=="number"?request.limit:void 0}).then(({sessions,incomplete})=>incomplete?{sessions,incomplete:!0}:sessions):await readSession({...base,sessionId:request.session_id,turns:typeof request.turns=="number"?request.turns:void 0});return{status:"done",result:JSON.stringify(result)}}catch(error2){return{status:"failed",error:clip(error2?.message??String(error2),400)}}}module.exports={answerSessionRequest,claudeProjectKey,listSessions,readSession,redact:redact2,sessionRoots}}});var require_host=__commonJS({"../../apps/web/electron/local-tools/host.js"(exports,module){"use strict";var{createResultFileStore}=require_result_files(),{randomUUID:randomUUID3}=__require("crypto"),fs=__require("fs"),os=__require("os"),path=__require("path"),{createClaudeRuntime}=require_claude_runtime(),{clearFinishedCheckout,listEndedCheckouts,markTaskEnded,prepareTaskCheckout,sweepTaskCheckouts}=require_checkouts(),{readOriginBase}=require_origin_base(),{createCommandEnvReader,readCommandEnv,readCommandEnvAsync,readFallbackCommandEnv,trustedPath:trustedPath2}=require_command_env(),{createLocalDriverRuntime}=require_drivers(),{ownedGuardRoot}=require_git_guard(),{ownerGithubToken,pushCredentialPaths}=require_credentials(),{createMachineDescriber}=require_machine(),{createRunOutbox}=require_outbox(),{createLocalToolRuns}=require_runs(),{closedPaths}=require_policy(),{holdsHome:holdsHome2,isValidSessionId,limitsDontHoldReason,parseRunRequest,text}=require_run_request(),{codexHome,listToolServers}=require_servers(),{answerSessionRequest}=require_sessions(),{prepareTaskGuard}=require_task_setup(),{findCommand:findCommand2}=require_toolchain(),{lockWindowsGuardRoot,lockWindowsToken,windowsGuardRoot,windowsSpawn}=require_windows(),{runsInWsl,sendRunnerToWsl,toWslPath,wslClaudeSpawn}=require_wsl(),GUARD_GRACE_MS=5*6e4,STALE_GUARD_MS=1440*6e4;function sweepStaleGuards(root,now=Date.now()){let entries;try{entries=fs.readdirSync(root)}catch{return}for(let entry of entries){if(entry===".sentinels")continue;let dir=path.join(root,entry);try{now-fs.statSync(dir).mtimeMs>STALE_GUARD_MS&&fs.rmSync(dir,{recursive:!0,force:!0})}catch{}}}function createTaskRuntime(provider,options){return createLocalDriverRuntime(provider,options)}var CLAUDE_EFFORT_RECHECK_MS=5*6e4;function createClaudeEffortCheck(spawnSync6,now=Date.now){let supported=!1,checkedAt=-1/0;return env=>{if(supported||now()-checkedAt<CLAUDE_EFFORT_RECHECK_MS)return supported;checkedAt=now();let help=spawnSync6("claude",["--help"],{env,encoding:"utf8",timeout:5e3});return supported=help?.status===0&&/--effort\b/.test(help.stdout??""),supported}}function createWslClaudeRuntime({spawn:spawn5,spawnSync:spawnSync6,log:log2,cwd,instructions,runId,policy,servers,githubToken,projectHooks,postAsOwner,effort=null,model=null,guardRoot=null}){let folder=toWslPath(cwd,{spawnSync:spawnSync6}),windowsHome=null;try{windowsHome=toWslPath(os.homedir(),{spawnSync:spawnSync6})}catch{}let windowsGuardRoot2=null;if(typeof guardRoot=="string"&&guardRoot.length>0)try{let parentGuardRoot=path.win32.dirname(guardRoot);windowsGuardRoot2=toWslPath(parentGuardRoot,{spawnSync:spawnSync6})}catch{}return createClaudeRuntime({spawn:wslClaudeSpawn({spawn:spawn5,runnerDir:sendRunnerToWsl({spawnSync:spawnSync6}),run:{runId,folder,windowsHome,windowsGuardRoot:windowsGuardRoot2,policy,servers,githubToken,projectHooks,postAsOwner}}),env:{},cwd,instructions,log:log2,permissionArgs:[],effort,model})}function wslNotStartedHint(run2,platform){return runsInWsl(run2.provider,platform)?/^[A-Za-z]:[\\/]/.test(run2.checkoutOf??run2.folder)?"On Windows, Claude Code runs in WSL, where folders on the Windows drive are slow. Connect a folder in your WSL home instead (under \\\\wsl.localhost), then start the task again.":"On Windows, Claude Code runs in WSL: check that claude starts in this folder from a WSL terminal, then start the task again.":null}function createLocalToolHost2({directory,appName,log:log2,onEvent,platform=process.platform,spawn:spawnProcess,spawnSync:spawnSync6,hostname:hostname2=os.hostname,guardRoot:chosenGuardRoot=platform==="win32"?windowsGuardRoot():path.join(os.tmpdir(),"ando-task-git"),lockToken=lockWindowsToken,lockGuardRoot=root=>lockWindowsGuardRoot(root,{run:spawnSync6,log:log2}),guardGraceMs=GUARD_GRACE_MS,readGithubToken=ownerEnv=>ownerGithubToken({env:ownerEnv,gh:findCommand2("gh",ownerEnv.PATH)}),taskFolders=(()=>[]),inPlaceFolders=(()=>[]),hookFolders=(()=>[]),checkoutRoot=null,mcpProxyOptions:hostMcpProxyOptions=null,ownerCommandEnv:prefetchedCommandEnv=null}){let spawn5=platform==="win32"?windowsSpawn(spawnProcess):spawnProcess,guardRoot=ownedGuardRoot(chosenGuardRoot,{platform,lockWindowsRoot:lockGuardRoot});sweepStaleGuards(guardRoot);let claudeTakesEffort=createClaudeEffortCheck(spawnSync6),ownerCommandEnv=prefetchedCommandEnv??createCommandEnvReader({read:()=>readCommandEnv({spawnSync:spawnSync6,env:process.env,platform}),refresh:()=>readCommandEnvAsync({env:process.env,platform}),readFallback:()=>readFallbackCommandEnv({env:process.env,platform}),onFallback:()=>log2?.warn?.("[Local tools] the login shell didn't report a PATH; using the app's own and the usual install folders")}),applyTaskFolders=current=>{let folders=taskFolders();return folders.length===0?{...current}:{...current,PATH:trustedPath2(current.PATH??"",folders)}},env=()=>applyTaskFolders(ownerCommandEnv());env.ready=()=>{let current=ownerCommandEnv.ready();return current!=null&&typeof current.then=="function"?current.then(applyTaskFolders):applyTaskFolders(current)};let machine=createMachineDescriber({machineFile:path.join(directory,"machine.json"),platform,spawn:spawn5,hostname:hostname2,env,log:log2,username:()=>os.userInfo().username,appName,listServers:provider=>listToolServers(provider,os.homedir(),env())}),outbox=createRunOutbox({file:path.join(directory,"run-events.json"),log:log2,coalesceMs:50}),checkoutByRunId=new Map,runs=null,emit=event=>{if(checkoutRoot!=null&&(event.kind==="done"||event.kind==="failed")){let checkoutId=checkoutByRunId.get(event.runId)??event.runId;checkoutByRunId.delete(event.runId),markTaskEnded(checkoutRoot,checkoutId)}onEvent(outbox.push(event))},activeCheckouts=()=>runs==null?[]:runs.list().map(id=>checkoutByRunId.get(id)??id);checkoutRoot!=null&&sweepTaskCheckouts(checkoutRoot,{active:activeCheckouts});let resultFiles=createResultFileStore(path.join(directory,"result-files"));try{resultFiles.prune(outbox.list().flatMap(event=>event.files??[]))}catch(error2){log2.warn("[Local tools] could not clean up result files",error2)}runs=createLocalToolRuns({collectResultFiles:run2=>resultFiles.collect(run2),log:log2,createRuntime:(provider,{runId,workspaceId=null,cwd,instructions,policy,servers,githubToken=null,projectHooks=!1,postAsOwner=!1,effort=null,model=null})=>{if(runsInWsl(provider,platform))return createWslClaudeRuntime({spawn:spawnProcess,spawnSync:spawnSync6,log:log2,cwd,instructions,guardRoot,runId,policy,servers,githubToken,projectHooks,postAsOwner,effort,model});let ownerEnv=env(),guard=prepareTaskGuard({dir:path.join(guardRoot,runId),cwd,policy,githubToken,ownerEnv,run:spawnSync6,platform,...platform==="win32"?{lockSecret:lockToken}:{}});githubToken!=null&&policy.push!=="never"&&!guard.github&&log2.warn("[Local tools] could not keep the owner's GitHub sign-in to this task; it can't push");let removing=null,removeGuard=()=>{removing??=setTimeout(()=>{try{fs.rmSync(guard.hooksDir,{recursive:!0,force:!0})}catch(error2){log2.warn("[Local tools] could not remove a task's git guard",error2)}},guardGraceMs),removing.unref?.()};try{let extraMcpProxyOptions=typeof hostMcpProxyOptions=="function"?hostMcpProxyOptions({workspaceId,runId,provider}):hostMcpProxyOptions,runtimeMcpProxyOptions=Array.isArray(servers)&&servers.includes("ando")&&workspaceId?{env:ownerEnv,home:os.homedir(),provider,allowAmbientCliCredentials:!0,expectedWorkspaceId:workspaceId,allowPosting:postAsOwner,...extraMcpProxyOptions&&typeof extraMcpProxyOptions=="object"?extraMcpProxyOptions:{}}:!1,runtime=createTaskRuntime(provider,{spawn:spawn5,log:log2,cwd,workspaceId,instructions,policy,servers,guard,ownerEnv,platform,mcpProxyOptions:runtimeMcpProxyOptions,postAsOwner,effort:provider==="claude-code"&&effort!=null&&!claudeTakesEffort(ownerEnv)?null:effort,model,otherFolders:taskFolders().filter(folder=>cwd!==folder&&!cwd.startsWith(`${folder}${path.sep}`)),closedToCodex:checkoutRoot==null?[]:[checkoutRoot],projectHooks});return{...runtime,close(){runtime.close(),removeGuard()}}}catch(error2){throw removeGuard(),error2}},emit,rememberUsage:(run2,checkpoint)=>outbox.rememberUsage(run2.runId,run2.workspaceId,checkpoint),notStartedHint:run2=>wslNotStartedHint(run2,platform)});let starting=new Map,stoppedWhileStarting=new Set;async function placeRun(run2){let limitError=limitsDontHoldReason(run2,platform);if(limitError!=null)return emit({runId:run2.runId,workspaceId:run2.workspaceId,...run2.ownerId==null?{}:{ownerId:run2.ownerId},kind:"failed",sessionId:run2.sessionId??null,error:limitError}),null;let reusingCheckout=checkoutRoot!=null&&run2.checkoutRunId!=null&&run2.checkoutRunId!==run2.runId&&fs.existsSync(path.join(checkoutRoot,run2.checkoutRunId,".git"));if(!fs.existsSync(path.join(run2.folder,".git")))return{};if(checkoutRoot==null||!reusingCheckout&&(run2.policy.files==="never"||inPlaceFolders().includes(run2.folder))){let ownerEnv=env(),folderBase=await readOriginBase({git:findCommand2("git",ownerEnv.PATH)??"git",cwd:run2.folder,env:ownerEnv,spawnSync:spawnSync6,trustRemoteRefs:!0}).catch(()=>null);return folderBase==null?{}:{base:{kind:"folder",branch:folderBase.branch,ref:folderBase.ref.replace(/^refs\/remotes\//u,""),behind:folderBase.behind,fetched:folderBase.fetched}}}try{let ownerEnv=env(),checkoutId=run2.checkoutRunId??run2.runId,checkoutExpired=!1;checkoutId!==run2.runId&&!fs.existsSync(path.join(checkoutRoot,checkoutId,".git"))&&(log2.info?.(`[Local tools] earlier checkout ${checkoutId} is gone; starting a fresh checkout for ${run2.runId}`),checkoutId=run2.runId,checkoutExpired=!0),checkoutByRunId.set(run2.runId,checkoutId);let base=null;return{folder:await prepareTaskCheckout({root:checkoutRoot,folder:run2.folder,runId:checkoutId,git:findCommand2("git",ownerEnv.PATH)??"git",env:ownerEnv,spawnSync:spawnSync6,platform,bare:run2.bareCheckout,onProgress:message=>log2.info?.(message),onBase:found=>{base=found}}),checkoutOf:run2.folder,...base==null?{}:{base},...checkoutExpired?{checkoutExpired:!0}:{}}}catch(error2){return checkoutByRunId.delete(run2.runId),emit({runId:run2.runId,workspaceId:run2.workspaceId,...run2.ownerId==null?{}:{ownerId:run2.ownerId},kind:"failed",sessionId:run2.sessionId??null,error:`Couldn't set up a checkout of ${run2.folder}: ${error2.message}`}),null}}async function startRun(input){let run2=parseRunRequest(input,platform);if(run2==null)return{status:"invalid"};let pending=starting.get(run2.runId);if(pending!=null)return await pending;if(outbox.recall(run2.runId,run2.workspaceId).ended)return{status:"finished"};let start=(async()=>{let maybeEnv=env.ready(),readyEnv=maybeEnv!=null&&typeof maybeEnv.then=="function"?await maybeEnv:maybeEnv,githubToken=run2.policy.push==="never"?null:await readGithubToken(readyEnv),saved=outbox.recall(run2.runId,run2.workspaceId);if(saved.ended)return{status:"finished"};let endStopped=()=>(emit({runId:run2.runId,workspaceId:run2.workspaceId,...run2.ownerId==null?{}:{ownerId:run2.ownerId},kind:"stopped",sessionId:run2.sessionId??saved.sessionId??null,...saved.usageCheckpoint?.usage==null?{}:{usage:saved.usageCheckpoint.usage}}),{status:"finished"});if(stoppedWhileStarting.has(run2.runId))return endStopped();let place=await placeRun(run2);if(place==null)return{status:"finished"};if(stoppedWhileStarting.has(run2.runId))return endStopped();let freshCheckout=place.checkoutExpired===!0,{checkoutExpired:_expired,...placement}=place,placed={...run2,...placement,...freshCheckout?{sessionId:null,continuedSessionId:null,continuedFromRunId:null,continuedUsageBaseline:null,checkoutRunId:run2.runId,midTurnRestart:!1}:{sessionId:saved.sessionId??run2.sessionId,midTurnRestart:run2.midTurnRestart||saved.sessionId!=null},usageCheckpoint:saved.usageCheckpoint},projectHooks=hookFolders().includes(run2.folder);if(!run2.returnFiles)return runs.start(placed,{githubToken,projectHooks});let prepared;try{let ownerEnv=env(),denied=closedPaths(placed.folder,{codexDir:codexHome(ownerEnv),configHome:ownerEnv.XDG_CONFIG_HOME,platform,extra:[directory,guardRoot,...taskFolders().filter(folder=>placed.folder!==folder&&!placed.folder.startsWith(`${folder}${path.sep}`)),...run2.policy.push==="never"?pushCredentialPaths({env:ownerEnv,folder:placed.folder,run:spawnSync6,platform}):[]]});prepared=resultFiles.prepare(placed,denied)}catch(error2){return emit({runId:placed.runId,workspaceId:placed.workspaceId,...placed.ownerId==null?{}:{ownerId:placed.ownerId},kind:"failed",sessionId:placed.sessionId??null,error:`Couldn't prepare file returns from ${placed.folder}: ${error2.message}`}),{status:"failed"}}return runs.start(prepared,{githubToken,projectHooks})})();starting.set(run2.runId,start);try{return await start}finally{starting.delete(run2.runId),stoppedWhileStarting.delete(run2.runId)}}let testing=new Map;async function testTool(input){let run2=parseRunRequest({...input!=null&&typeof input=="object"?input:{},runId:randomUUID3(),prompt:"test"},platform);if(run2==null)return{status:"failed",error:"The Ando app couldn't read this test."};let limitError=limitsDontHoldReason(run2,platform);if(limitError!=null)return{status:"failed",error:limitError};let key=JSON.stringify([run2.workspaceId,run2.provider,run2.folder,run2.policy,[...run2.servers].sort()]),pending=testing.get(key);if(pending!=null)return await pending;let test=runs.test(run2).finally(()=>testing.delete(key));return testing.set(key,test),await test}function steerRun(input){let runId=typeof input?.runId=="string"?input.runId:null,message=text(input?.text,2e4);return runId==null||message==null?!1:runs.steer({runId,text:message})}function stopRun(input){if(typeof input?.runId!="string")return!1;let stopped=runs.stop(input.runId);return starting.has(input.runId)?(stoppedWhileStarting.add(input.runId),!0):stopped}return{machine,env,spawn:spawn5,startRun,testTool,steerRun,stopRun,readSessions:input=>answerSessionRequest(input,{env:env(),platform}),runState:()=>({active:runs.list(),activeRuns:runs.listMeta(),events:outbox.list()}),readRunFile:({seq,slot,workspaceId,ownerId})=>{let event=outbox.list().find(entry=>entry.seq===seq&&entry.workspaceId===workspaceId&&(entry.ownerId==null||entry.ownerId===ownerId)),file=event?.kind==="done"?event.files?.find(entry=>entry.slot===slot):null;if(file==null)throw new Error("Unknown result file.");return resultFiles.read(file)},ackRunEvents:seqs=>{let events=outbox.list().filter(event=>seqs.includes(event.seq));if(outbox.ack(seqs),outbox.flush())for(let event of events)resultFiles.remove(event.files)},endedCheckouts:()=>{if(checkoutRoot==null)return[];let active=new Set(activeCheckouts());return listEndedCheckouts(checkoutRoot).filter(id=>!active.has(id))},clearFinishedCheckouts:ids=>{if(checkoutRoot==null)return[];let active=new Set(activeCheckouts());return ids.filter(id=>!active.has(id)&&clearFinishedCheckout(checkoutRoot,id))},stopAll:()=>{runs.stopAll(),outbox.flush()}}}module.exports={createLocalToolHost:createLocalToolHost2,holdsHome:holdsHome2,isValidSessionId,parseRunRequest,text}}});var require_remotes=__commonJS({"../../apps/web/electron/local-tools/remotes.js"(exports,module){"use strict";var{execFile:nodeExecFile}=__require("child_process"),fs=__require("fs"),path=__require("path"),MAX_FOLDERS=50,MAX_FOLDER_LENGTH=1e3,MAX_REPO_LENGTH=200,READ_TIMEOUT_MS=3e3,MAX_ORIGIN_CACHE_ENTRIES=100,ORIGIN_CACHE_TTL_MS=5*6e4,originCache=new Map,HOST=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)*$/,SEGMENT=/^[A-Za-z0-9_.~-]+$/,SCP_LIKE=/^(?:[^@/\s]+@)?([^@:/\s]+):(?!\/)(.+)$/,URL_SCHEMES=new Set(["https:","http:","ssh:","git:","git+ssh:"]);function repoPath(raw){let segments=raw.replace(/[?#].*$/,"").replace(/\/+$/,"").replace(/\.git$/,"").split("/").filter(segment=>segment.length>0);if(segments.length<2||segments.some(segment=>!SEGMENT.test(segment)||segment==="."||segment===".."))return null;let repo=segments.join("/");return repo.length<=MAX_REPO_LENGTH?repo:null}function normalizeGitRemote(url2){if(typeof url2!="string")return null;let value=url2.trim();if(value.length===0||value.length>2e3)return null;let host,rawPath;if(/^[a-z][a-z0-9+.-]*:\/\//i.test(value)){let parsed;try{parsed=new URL(value)}catch{return null}if(!URL_SCHEMES.has(parsed.protocol))return null;host=parsed.hostname,rawPath=parsed.pathname}else{let scp=SCP_LIKE.exec(value);if(scp==null)return null;host=scp[1],rawPath=scp[2]}if(host=host.toLowerCase(),!HOST.test(host))return null;let repo=repoPath(rawPath);return repo==null?null:{host,repo}}function parseFolders(input){return Array.isArray(input)?[...new Set(input.filter(folder=>typeof folder=="string"&&folder.length<=MAX_FOLDER_LENGTH&&path.isAbsolute(folder)))].slice(0,MAX_FOLDERS):[]}function checkoutRoot(folder,exists){for(let dir=folder;;dir=path.dirname(dir)){if(exists(path.join(dir,".git")))return dir;if(path.dirname(dir)===dir)return null}}function readGitConfigStat(root,statSync2){if(typeof statSync2!="function")return null;try{let stat2=statSync2(path.join(root,".git","config"));return stat2.isFile()?{mtimeMs:stat2.mtimeMs,size:stat2.size}:null}catch{return null}}function readOrigin(folder,{execFile:execFile3,env,exists,statSync:statSync2,now}){let root=checkoutRoot(folder,exists);if(root==null)return Promise.resolve(null);let configStat=readGitConfigStat(root,statSync2),currentTime=now();if(configStat!=null){let cached2=originCache.get(folder);if(cached2!=null&&cached2.execFile===execFile3&&cached2.mtimeMs===configStat.mtimeMs&&cached2.size===configStat.size&¤tTime-cached2.cachedAt<ORIGIN_CACHE_TTL_MS)return Promise.resolve(cached2.origin)}return new Promise(resolve4=>{execFile3("git",["-C",folder,"remote","get-url","origin"],{env:{...env,GIT_TERMINAL_PROMPT:"0"},encoding:"utf8",timeout:READ_TIMEOUT_MS},(error2,stdout)=>{let origin=error2==null?String(stdout):null;if(origin!=null&&configStat!=null){if(originCache.size>=MAX_ORIGIN_CACHE_ENTRIES&&!originCache.has(folder)){let oldestKey=originCache.keys().next().value;oldestKey!==void 0&&originCache.delete(oldestKey)}originCache.set(folder,{mtimeMs:configStat.mtimeMs,size:configStat.size,cachedAt:now(),execFile:execFile3,origin})}else originCache.delete(folder);resolve4(origin)})})}async function readFolderRemotes2(input,{execFile:execFile3=nodeExecFile,env=process.env,exists=fs.existsSync,statSync:statSync2=fs.statSync,now=Date.now}={}){let folders=parseFolders(input);return(await Promise.all(folders.map(async folder=>{let remote=normalizeGitRemote(await readOrigin(folder,{execFile:execFile3,env,exists,statSync:statSync2,now}));return remote==null?null:{folder,...remote}}))).filter(remote=>remote!=null)}module.exports={ORIGIN_CACHE_TTL_MS,normalizeGitRemote,readFolderRemotes:readFolderRemotes2}}});import{chmod as chmod5,link,mkdir as mkdir6,readFile as readFile6,rename as rename6,rm as rm4,writeFile as writeFile5}from"node:fs/promises";import{homedir as homedir3,uptime}from"node:os";import{dirname as dirname6,isAbsolute,join as join8,relative}from"node:path";function configPath2(env){let base=env.XDG_CONFIG_HOME?.trim()||join8(env.HOME||homedir3(),".config");return join8(base,"ando","machine.json")}function stateDirectory(env){return join8(dirname6(configPath2(env)),"machine")}function holdsHome(folder,home=homedir3()){let inside=relative(folder,home);return inside===""||!inside.startsWith("..")&&!isAbsolute(inside)}function needsToolSetup(input){return input.knownFolders+input.addedFolders===0?!1:input.canCheck&&(!input.checked||input.addedFolders>0)||input.toolsConnected===0&&input.addedFolders>0}function approvalCode(request){return`${request.slice(0,4)}-${request.slice(4,8)}`.toUpperCase()}async function readConfig(path){let text;try{text=await readFile6(path,"utf8")}catch(error2){if(error2.code==="ENOENT")return null;throw error2}return JSON.parse(text)}async function writeConfig(path,config2){await mkdir6(dirname6(path),{recursive:!0,mode:448});let temporary=`${path}.${process.pid}.tmp`;await writeFile5(temporary,`${JSON.stringify(config2,null,2)}
|
|
297
|
-
`,{mode:384}),await rename6(temporary,path),await chmod5(path,384)}function holderIsAlive(holder){if(holder.pid===process.pid||Math.abs(holder.bootedAt-bootTime())>BOOT_SLACK_MS)return!1;try{return process.kill(holder.pid,0),!0}catch(error2){return error2.code==="EPERM"}}async function runningConnector(directory){let holder=await readHolder(
|
|
296
|
+
`)){if(!raw.trim())continue;let line;try{line=JSON.parse(raw)}catch{continue}if(provider==="codex"){if(line?.type==="session_meta"&&typeof line.payload?.cwd=="string")return line.payload.cwd}else if(typeof line?.cwd=="string")return line.cwd}return null}catch{return null}finally{fd!=null&&fs.closeSync(fd)}}function claudeProjectDirs(home,folders){let root=path.join(home,".claude","projects"),keys=folders.map(claudeProjectKey);return readdir4(root).filter(entry=>entry.isDirectory()&&keys.some(key=>entry.name===key||entry.name.startsWith(`${key}-`))).map(entry=>path.join(root,entry.name))}function claudeCandidates(home,folders){let files=[];for(let dir of claudeProjectDirs(home,folders))for(let entry of readdir4(dir)){if(!entry.isFile()||!entry.name.endsWith(".jsonl"))continue;let id=entry.name.slice(0,-6);if(!SESSION_ID.test(id))continue;let file=path.join(dir,entry.name);files.push({file,id,mtime:mtime(file)})}return files}function codexCandidates(codexDir){let root=path.join(codexDir,"sessions"),files=[],descending=entries=>entries.filter(e=>e.isDirectory()).sort((a,b)=>b.name.localeCompare(a.name));for(let year of descending(readdir4(root)))for(let month of descending(readdir4(path.join(root,year.name))))for(let day of descending(readdir4(path.join(root,year.name,month.name)))){let dir=path.join(root,year.name,month.name,day.name);for(let entry of readdir4(dir)){let match=entry.isFile()&&/^rollout-.*-([0-9a-f-]{36})\.jsonl$/i.exec(entry.name);if(!match)continue;let file=path.join(dir,entry.name);files.push({file,id:match[1],mtime:mtime(file)})}}return files}function candidates(provider,{home,codexDir,folders}){return(provider==="codex"?codexCandidates(codexDir):claudeCandidates(home,folders)).sort((a,b)=>b.mtime-a.mtime)}function summary(transcript,folder){return{session_id:transcript.sessionId,provider:transcript.provider,folder,...transcript.cwd!=null&&transcript.cwd!==folder?{working_dir:transcript.cwd}:{},git_branch:transcript.gitBranch,title:transcript.customTitle??transcript.title??"(no prompt yet)",started_at:transcript.startedAt==null?null:new Date(transcript.startedAt).toISOString(),last_active_at:transcript.lastAt==null?null:new Date(transcript.lastAt).toISOString(),turn_count:transcript.turnCount,started_by_ando:transcript.startedByAndo}}async function listSessions(input){let home=input.home??os.homedir(),codexDir=codexHome(input.env??process.env,home),limit=Math.min(LIST_LIMIT,Math.max(1,input.limit??LIST_LIMIT)),folders=input.folders,reads=input.budget?.reads??LIST_SCAN_FILES,looks=input.budget?.looks??LIST_HEAD_SCAN_FILES,sessions=[],read=0,looked=0,incomplete=!1;for(let candidate of candidates(input.provider,{home,codexDir,folders})){if(sessions.length>=limit)break;if(read>=reads||looked>=looks){incomplete=!0;break}looked+=1;let folder=folderOf(folders,readHeadCwd(input.provider,candidate.file));if(folder==null)continue;read+=1;let transcript=await parseTranscript(input.provider,candidate.file,{keep:!1,folders});folderOf(folders,transcript.cwd)===folder&&(transcript.sessionId??=candidate.id,sessions.push(summary(transcript,folder)))}return sessions.sort((a,b)=>(b.last_active_at??"").localeCompare(a.last_active_at??"")),{sessions,incomplete}}function groupTurns(entries){let turns=[];for(let entry of entries)(entry.role==="user"||turns.length===0)&&turns.push([]),turns[turns.length-1].push(entry);return turns}async function readSession(input){let home=input.home??os.homedir(),codexDir=codexHome(input.env??process.env,home);if(typeof input.sessionId!="string"||!SESSION_ID.test(input.sessionId))throw new Error("That isn't a session id.");let wanted=input.sessionId.toLowerCase(),candidate=candidates(input.provider,{home,codexDir,folders:input.folders}).find(entry=>entry.id.toLowerCase()===wanted),notFound=new Error("No session with that id in the folders agents may read. list_sessions names the ones there are.");if(candidate==null)throw notFound;let folder=folderOf(input.folders,readHeadCwd(input.provider,candidate.file));if(folder==null)throw notFound;let wantedTurns=Math.min(MAX_TURNS,Math.max(1,input.turns??DEFAULT_TURNS)),transcript=await parseTranscript(input.provider,candidate.file,{keep:!0,maxTurns:wantedTurns,folders:input.folders});if(folderOf(input.folders,transcript.cwd)!==folder)throw notFound;transcript.sessionId??=candidate.id;let turnsElsewhere=transcript.turnsElsewhere,all=groupTurns(transcript.entries),kept=all.slice(-wantedTurns),entries=kept.flat(),truncated=transcript.droppedTurns>0||kept.length<all.length||turnsElsewhere>0,answer=list=>({...summary(transcript,folder),turns_returned:list.filter(entry=>entry.role==="user").length,...turnsElsewhere>0?{turns_elsewhere:turnsElsewhere}:{},truncated,turns:list.map(entry=>({at:entry.at==null?null:new Date(entry.at).toISOString(),role:entry.role,text:entry.text}))}),bytes=list=>Buffer.byteLength(JSON.stringify(answer(list)),"utf8");for(;entries.length>1&&bytes(entries)>MAX_BYTES;)entries=entries.slice(1),truncated=!0;return entries.length===1&&bytes(entries)>MAX_BYTES&&(entries=[{...entries[0],text:clipBytes(entries[0].text,MAX_BYTES-500)}],truncated=!0),answer(entries)}function clipBytes(text,max){let cut=text;for(;Buffer.byteLength(cut,"utf8")>max;)cut=cut.slice(0,Math.max(1,Math.floor(cut.length*max/Buffer.byteLength(cut,"utf8"))-1));return cut===text?text:`${cut.trimEnd()} \u2026`}function absoluteFolders(value){return Array.isArray(value)?value.filter(folder=>typeof folder=="string"&&path.isAbsolute(folder)&&folder.length<=1e3).slice(0,20):[]}async function answerSessionRequest(input,deps2={}){let platform=deps2.platform??process.platform,request=input!=null&&typeof input=="object"?input:{},folders=absoluteFolders(request.folders);if(!PROVIDERS.has(request.provider)||request.kind!=="list"&&request.kind!=="read"||folders.length===0)return{status:"failed",error:"The Ando app couldn't read this request."};if(request.provider==="claude-code"&&platform==="win32")return{status:"failed",error:"Claude Code's sessions on Windows live in WSL, where the Ando app can't read them."};let base={provider:request.provider,folders,home:deps2.home,env:deps2.env};try{let result=request.kind==="list"?await listSessions({...base,limit:typeof request.limit=="number"?request.limit:void 0}).then(({sessions,incomplete})=>incomplete?{sessions,incomplete:!0}:sessions):await readSession({...base,sessionId:request.session_id,turns:typeof request.turns=="number"?request.turns:void 0});return{status:"done",result:JSON.stringify(result)}}catch(error2){return{status:"failed",error:clip(error2?.message??String(error2),400)}}}module.exports={answerSessionRequest,claudeProjectKey,listSessions,readSession,redact:redact2,sessionRoots}}});var require_host=__commonJS({"../../apps/web/electron/local-tools/host.js"(exports,module){"use strict";var{createResultFileStore}=require_result_files(),{randomUUID:randomUUID3}=__require("crypto"),fs=__require("fs"),os=__require("os"),path=__require("path"),{createClaudeRuntime}=require_claude_runtime(),{clearFinishedCheckout,listEndedCheckouts,markTaskEnded,prepareTaskCheckout,sweepTaskCheckouts}=require_checkouts(),{readOriginBase}=require_origin_base(),{createCommandEnvReader,readCommandEnv,readCommandEnvAsync,readFallbackCommandEnv,trustedPath:trustedPath2}=require_command_env(),{createLocalDriverRuntime}=require_drivers(),{ownedGuardRoot}=require_git_guard(),{ownerGithubToken,pushCredentialPaths}=require_credentials(),{createMachineDescriber}=require_machine(),{createRunOutbox}=require_outbox(),{createLocalToolRuns}=require_runs(),{closedPaths}=require_policy(),{holdsHome:holdsHome2,isValidSessionId,limitsDontHoldReason,parseRunRequest,text}=require_run_request(),{codexHome,listToolServers}=require_servers(),{answerSessionRequest}=require_sessions(),{prepareTaskGuard}=require_task_setup(),{findCommand:findCommand2}=require_toolchain(),{lockWindowsGuardRoot,lockWindowsToken,windowsGuardRoot,windowsSpawn}=require_windows(),{runsInWsl,sendRunnerToWsl,toWslPath,wslClaudeSpawn}=require_wsl(),GUARD_GRACE_MS=5*6e4,STALE_GUARD_MS=1440*6e4;function sweepStaleGuards(root,now=Date.now()){let entries;try{entries=fs.readdirSync(root)}catch{return}for(let entry of entries){if(entry===".sentinels")continue;let dir=path.join(root,entry);try{now-fs.statSync(dir).mtimeMs>STALE_GUARD_MS&&fs.rmSync(dir,{recursive:!0,force:!0})}catch{}}}function createTaskRuntime(provider,options){return createLocalDriverRuntime(provider,options)}var CLAUDE_EFFORT_RECHECK_MS=5*6e4;function createClaudeEffortCheck(spawnSync6,now=Date.now){let supported=!1,checkedAt=-1/0;return env=>{if(supported||now()-checkedAt<CLAUDE_EFFORT_RECHECK_MS)return supported;checkedAt=now();let help=spawnSync6("claude",["--help"],{env,encoding:"utf8",timeout:5e3});return supported=help?.status===0&&/--effort\b/.test(help.stdout??""),supported}}function createWslClaudeRuntime({spawn:spawn6,spawnSync:spawnSync6,log:log2,cwd,instructions,runId,policy,servers,githubToken,projectHooks,postAsOwner,effort=null,model=null,guardRoot=null}){let folder=toWslPath(cwd,{spawnSync:spawnSync6}),windowsHome=null;try{windowsHome=toWslPath(os.homedir(),{spawnSync:spawnSync6})}catch{}let windowsGuardRoot2=null;if(typeof guardRoot=="string"&&guardRoot.length>0)try{let parentGuardRoot=path.win32.dirname(guardRoot);windowsGuardRoot2=toWslPath(parentGuardRoot,{spawnSync:spawnSync6})}catch{}return createClaudeRuntime({spawn:wslClaudeSpawn({spawn:spawn6,runnerDir:sendRunnerToWsl({spawnSync:spawnSync6}),run:{runId,folder,windowsHome,windowsGuardRoot:windowsGuardRoot2,policy,servers,githubToken,projectHooks,postAsOwner}}),env:{},cwd,instructions,log:log2,permissionArgs:[],effort,model})}function wslNotStartedHint(run2,platform){return runsInWsl(run2.provider,platform)?/^[A-Za-z]:[\\/]/.test(run2.checkoutOf??run2.folder)?"On Windows, Claude Code runs in WSL, where folders on the Windows drive are slow. Connect a folder in your WSL home instead (under \\\\wsl.localhost), then start the task again.":"On Windows, Claude Code runs in WSL: check that claude starts in this folder from a WSL terminal, then start the task again.":null}function createLocalToolHost2({directory,appName,log:log2,onEvent,platform=process.platform,spawn:spawnProcess,spawnSync:spawnSync6,hostname:hostname3=os.hostname,guardRoot:chosenGuardRoot=platform==="win32"?windowsGuardRoot():path.join(os.tmpdir(),"ando-task-git"),lockToken=lockWindowsToken,lockGuardRoot=root=>lockWindowsGuardRoot(root,{run:spawnSync6,log:log2}),guardGraceMs=GUARD_GRACE_MS,readGithubToken=ownerEnv=>ownerGithubToken({env:ownerEnv,gh:findCommand2("gh",ownerEnv.PATH)}),taskFolders=(()=>[]),inPlaceFolders=(()=>[]),hookFolders=(()=>[]),checkoutRoot=null,mcpProxyOptions:hostMcpProxyOptions=null,ownerCommandEnv:prefetchedCommandEnv=null}){let spawn6=platform==="win32"?windowsSpawn(spawnProcess):spawnProcess,guardRoot=ownedGuardRoot(chosenGuardRoot,{platform,lockWindowsRoot:lockGuardRoot});sweepStaleGuards(guardRoot);let claudeTakesEffort=createClaudeEffortCheck(spawnSync6),ownerCommandEnv=prefetchedCommandEnv??createCommandEnvReader({read:()=>readCommandEnv({spawnSync:spawnSync6,env:process.env,platform}),refresh:()=>readCommandEnvAsync({env:process.env,platform}),readFallback:()=>readFallbackCommandEnv({env:process.env,platform}),onFallback:()=>log2?.warn?.("[Local tools] the login shell didn't report a PATH; using the app's own and the usual install folders")}),applyTaskFolders=current=>{let folders=taskFolders();return folders.length===0?{...current}:{...current,PATH:trustedPath2(current.PATH??"",folders)}},env=()=>applyTaskFolders(ownerCommandEnv());env.ready=()=>{let current=ownerCommandEnv.ready();return current!=null&&typeof current.then=="function"?current.then(applyTaskFolders):applyTaskFolders(current)};let machine=createMachineDescriber({machineFile:path.join(directory,"machine.json"),platform,spawn:spawn6,hostname:hostname3,env,log:log2,username:()=>os.userInfo().username,appName,listServers:provider=>listToolServers(provider,os.homedir(),env())}),outbox=createRunOutbox({file:path.join(directory,"run-events.json"),log:log2,coalesceMs:50}),checkoutByRunId=new Map,runs=null,emit=event=>{if(checkoutRoot!=null&&(event.kind==="done"||event.kind==="failed")){let checkoutId=checkoutByRunId.get(event.runId)??event.runId;checkoutByRunId.delete(event.runId),markTaskEnded(checkoutRoot,checkoutId)}onEvent(outbox.push(event))},activeCheckouts=()=>runs==null?[]:runs.list().map(id=>checkoutByRunId.get(id)??id);checkoutRoot!=null&&sweepTaskCheckouts(checkoutRoot,{active:activeCheckouts});let resultFiles=createResultFileStore(path.join(directory,"result-files"));try{resultFiles.prune(outbox.list().flatMap(event=>event.files??[]))}catch(error2){log2.warn("[Local tools] could not clean up result files",error2)}runs=createLocalToolRuns({collectResultFiles:run2=>resultFiles.collect(run2),log:log2,createRuntime:(provider,{runId,workspaceId=null,cwd,instructions,policy,servers,githubToken=null,projectHooks=!1,postAsOwner=!1,effort=null,model=null})=>{if(runsInWsl(provider,platform))return createWslClaudeRuntime({spawn:spawnProcess,spawnSync:spawnSync6,log:log2,cwd,instructions,guardRoot,runId,policy,servers,githubToken,projectHooks,postAsOwner,effort,model});let ownerEnv=env(),guard=prepareTaskGuard({dir:path.join(guardRoot,runId),cwd,policy,githubToken,ownerEnv,run:spawnSync6,platform,...platform==="win32"?{lockSecret:lockToken}:{}});githubToken!=null&&policy.push!=="never"&&!guard.github&&log2.warn("[Local tools] could not keep the owner's GitHub sign-in to this task; it can't push");let removing=null,removeGuard=()=>{removing??=setTimeout(()=>{try{fs.rmSync(guard.hooksDir,{recursive:!0,force:!0})}catch(error2){log2.warn("[Local tools] could not remove a task's git guard",error2)}},guardGraceMs),removing.unref?.()};try{let extraMcpProxyOptions=typeof hostMcpProxyOptions=="function"?hostMcpProxyOptions({workspaceId,runId,provider}):hostMcpProxyOptions,runtimeMcpProxyOptions=Array.isArray(servers)&&servers.includes("ando")&&workspaceId?{env:ownerEnv,home:os.homedir(),provider,allowAmbientCliCredentials:!0,expectedWorkspaceId:workspaceId,allowPosting:postAsOwner,...extraMcpProxyOptions&&typeof extraMcpProxyOptions=="object"?extraMcpProxyOptions:{}}:!1,runtime=createTaskRuntime(provider,{spawn:spawn6,log:log2,cwd,workspaceId,instructions,policy,servers,guard,ownerEnv,platform,mcpProxyOptions:runtimeMcpProxyOptions,postAsOwner,effort:provider==="claude-code"&&effort!=null&&!claudeTakesEffort(ownerEnv)?null:effort,model,otherFolders:taskFolders().filter(folder=>cwd!==folder&&!cwd.startsWith(`${folder}${path.sep}`)),closedToCodex:checkoutRoot==null?[]:[checkoutRoot],projectHooks});return{...runtime,close(){runtime.close(),removeGuard()}}}catch(error2){throw removeGuard(),error2}},emit,rememberUsage:(run2,checkpoint)=>outbox.rememberUsage(run2.runId,run2.workspaceId,checkpoint),notStartedHint:run2=>wslNotStartedHint(run2,platform)});let starting=new Map,stoppedWhileStarting=new Set;async function placeRun(run2){let limitError=limitsDontHoldReason(run2,platform);if(limitError!=null)return emit({runId:run2.runId,workspaceId:run2.workspaceId,...run2.ownerId==null?{}:{ownerId:run2.ownerId},kind:"failed",sessionId:run2.sessionId??null,error:limitError}),null;let reusingCheckout=checkoutRoot!=null&&run2.checkoutRunId!=null&&run2.checkoutRunId!==run2.runId&&fs.existsSync(path.join(checkoutRoot,run2.checkoutRunId,".git"));if(!fs.existsSync(path.join(run2.folder,".git")))return{};if(checkoutRoot==null||!reusingCheckout&&(run2.policy.files==="never"||inPlaceFolders().includes(run2.folder))){let ownerEnv=env(),folderBase=await readOriginBase({git:findCommand2("git",ownerEnv.PATH)??"git",cwd:run2.folder,env:ownerEnv,spawnSync:spawnSync6,trustRemoteRefs:!0}).catch(()=>null);return folderBase==null?{}:{base:{kind:"folder",branch:folderBase.branch,ref:folderBase.ref.replace(/^refs\/remotes\//u,""),behind:folderBase.behind,fetched:folderBase.fetched}}}try{let ownerEnv=env(),checkoutId=run2.checkoutRunId??run2.runId,checkoutExpired=!1;checkoutId!==run2.runId&&!fs.existsSync(path.join(checkoutRoot,checkoutId,".git"))&&(log2.info?.(`[Local tools] earlier checkout ${checkoutId} is gone; starting a fresh checkout for ${run2.runId}`),checkoutId=run2.runId,checkoutExpired=!0),checkoutByRunId.set(run2.runId,checkoutId);let base=null;return{folder:await prepareTaskCheckout({root:checkoutRoot,folder:run2.folder,runId:checkoutId,git:findCommand2("git",ownerEnv.PATH)??"git",env:ownerEnv,spawnSync:spawnSync6,platform,bare:run2.bareCheckout,onProgress:message=>log2.info?.(message),onBase:found=>{base=found}}),checkoutOf:run2.folder,...base==null?{}:{base},...checkoutExpired?{checkoutExpired:!0}:{}}}catch(error2){return checkoutByRunId.delete(run2.runId),emit({runId:run2.runId,workspaceId:run2.workspaceId,...run2.ownerId==null?{}:{ownerId:run2.ownerId},kind:"failed",sessionId:run2.sessionId??null,error:`Couldn't set up a checkout of ${run2.folder}: ${error2.message}`}),null}}async function startRun(input){let run2=parseRunRequest(input,platform);if(run2==null)return{status:"invalid"};let pending=starting.get(run2.runId);if(pending!=null)return await pending;if(outbox.recall(run2.runId,run2.workspaceId).ended)return{status:"finished"};let start=(async()=>{let maybeEnv=env.ready(),readyEnv=maybeEnv!=null&&typeof maybeEnv.then=="function"?await maybeEnv:maybeEnv,githubToken=run2.policy.push==="never"?null:await readGithubToken(readyEnv),saved=outbox.recall(run2.runId,run2.workspaceId);if(saved.ended)return{status:"finished"};let endStopped=()=>(emit({runId:run2.runId,workspaceId:run2.workspaceId,...run2.ownerId==null?{}:{ownerId:run2.ownerId},kind:"stopped",sessionId:run2.sessionId??saved.sessionId??null,...saved.usageCheckpoint?.usage==null?{}:{usage:saved.usageCheckpoint.usage}}),{status:"finished"});if(stoppedWhileStarting.has(run2.runId))return endStopped();let place=await placeRun(run2);if(place==null)return{status:"finished"};if(stoppedWhileStarting.has(run2.runId))return endStopped();let freshCheckout=place.checkoutExpired===!0,{checkoutExpired:_expired,...placement}=place,placed={...run2,...placement,...freshCheckout?{sessionId:null,continuedSessionId:null,continuedFromRunId:null,continuedUsageBaseline:null,checkoutRunId:run2.runId,midTurnRestart:!1}:{sessionId:saved.sessionId??run2.sessionId,midTurnRestart:run2.midTurnRestart||saved.sessionId!=null},usageCheckpoint:saved.usageCheckpoint},projectHooks=hookFolders().includes(run2.folder);if(!run2.returnFiles)return runs.start(placed,{githubToken,projectHooks});let prepared;try{let ownerEnv=env(),denied=closedPaths(placed.folder,{codexDir:codexHome(ownerEnv),configHome:ownerEnv.XDG_CONFIG_HOME,platform,extra:[directory,guardRoot,...taskFolders().filter(folder=>placed.folder!==folder&&!placed.folder.startsWith(`${folder}${path.sep}`)),...run2.policy.push==="never"?pushCredentialPaths({env:ownerEnv,folder:placed.folder,run:spawnSync6,platform}):[]]});prepared=resultFiles.prepare(placed,denied)}catch(error2){return emit({runId:placed.runId,workspaceId:placed.workspaceId,...placed.ownerId==null?{}:{ownerId:placed.ownerId},kind:"failed",sessionId:placed.sessionId??null,error:`Couldn't prepare file returns from ${placed.folder}: ${error2.message}`}),{status:"failed"}}return runs.start(prepared,{githubToken,projectHooks})})();starting.set(run2.runId,start);try{return await start}finally{starting.delete(run2.runId),stoppedWhileStarting.delete(run2.runId)}}let testing=new Map;async function testTool(input){let run2=parseRunRequest({...input!=null&&typeof input=="object"?input:{},runId:randomUUID3(),prompt:"test"},platform);if(run2==null)return{status:"failed",error:"The Ando app couldn't read this test."};let limitError=limitsDontHoldReason(run2,platform);if(limitError!=null)return{status:"failed",error:limitError};let key=JSON.stringify([run2.workspaceId,run2.provider,run2.folder,run2.policy,[...run2.servers].sort()]),pending=testing.get(key);if(pending!=null)return await pending;let test=runs.test(run2).finally(()=>testing.delete(key));return testing.set(key,test),await test}function steerRun(input){let runId=typeof input?.runId=="string"?input.runId:null,message=text(input?.text,2e4);return runId==null||message==null?!1:runs.steer({runId,text:message})}function stopRun(input){if(typeof input?.runId!="string")return!1;let stopped=runs.stop(input.runId);return starting.has(input.runId)?(stoppedWhileStarting.add(input.runId),!0):stopped}return{machine,env,spawn:spawn6,startRun,testTool,steerRun,stopRun,readSessions:input=>answerSessionRequest(input,{env:env(),platform}),runState:()=>({active:runs.list(),activeRuns:runs.listMeta(),events:outbox.list()}),readRunFile:({seq,slot,workspaceId,ownerId})=>{let event=outbox.list().find(entry=>entry.seq===seq&&entry.workspaceId===workspaceId&&(entry.ownerId==null||entry.ownerId===ownerId)),file=event?.kind==="done"?event.files?.find(entry=>entry.slot===slot):null;if(file==null)throw new Error("Unknown result file.");return resultFiles.read(file)},ackRunEvents:seqs=>{let events=outbox.list().filter(event=>seqs.includes(event.seq));if(outbox.ack(seqs),outbox.flush())for(let event of events)resultFiles.remove(event.files)},endedCheckouts:()=>{if(checkoutRoot==null)return[];let active=new Set(activeCheckouts());return listEndedCheckouts(checkoutRoot).filter(id=>!active.has(id))},clearFinishedCheckouts:ids=>{if(checkoutRoot==null)return[];let active=new Set(activeCheckouts());return ids.filter(id=>!active.has(id)&&clearFinishedCheckout(checkoutRoot,id))},stopAll:()=>{runs.stopAll(),outbox.flush()}}}module.exports={createLocalToolHost:createLocalToolHost2,holdsHome:holdsHome2,isValidSessionId,parseRunRequest,text}}});var require_remotes=__commonJS({"../../apps/web/electron/local-tools/remotes.js"(exports,module){"use strict";var{execFile:nodeExecFile}=__require("child_process"),fs=__require("fs"),path=__require("path"),MAX_FOLDERS=50,MAX_FOLDER_LENGTH=1e3,MAX_REPO_LENGTH=200,READ_TIMEOUT_MS=3e3,MAX_ORIGIN_CACHE_ENTRIES=100,ORIGIN_CACHE_TTL_MS=5*6e4,originCache=new Map,HOST=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)*$/,SEGMENT=/^[A-Za-z0-9_.~-]+$/,SCP_LIKE=/^(?:[^@/\s]+@)?([^@:/\s]+):(?!\/)(.+)$/,URL_SCHEMES=new Set(["https:","http:","ssh:","git:","git+ssh:"]);function repoPath(raw){let segments=raw.replace(/[?#].*$/,"").replace(/\/+$/,"").replace(/\.git$/,"").split("/").filter(segment=>segment.length>0);if(segments.length<2||segments.some(segment=>!SEGMENT.test(segment)||segment==="."||segment===".."))return null;let repo=segments.join("/");return repo.length<=MAX_REPO_LENGTH?repo:null}function normalizeGitRemote(url2){if(typeof url2!="string")return null;let value=url2.trim();if(value.length===0||value.length>2e3)return null;let host,rawPath;if(/^[a-z][a-z0-9+.-]*:\/\//i.test(value)){let parsed;try{parsed=new URL(value)}catch{return null}if(!URL_SCHEMES.has(parsed.protocol))return null;host=parsed.hostname,rawPath=parsed.pathname}else{let scp=SCP_LIKE.exec(value);if(scp==null)return null;host=scp[1],rawPath=scp[2]}if(host=host.toLowerCase(),!HOST.test(host))return null;let repo=repoPath(rawPath);return repo==null?null:{host,repo}}function parseFolders(input){return Array.isArray(input)?[...new Set(input.filter(folder=>typeof folder=="string"&&folder.length<=MAX_FOLDER_LENGTH&&path.isAbsolute(folder)))].slice(0,MAX_FOLDERS):[]}function checkoutRoot(folder,exists){for(let dir=folder;;dir=path.dirname(dir)){if(exists(path.join(dir,".git")))return dir;if(path.dirname(dir)===dir)return null}}function readGitConfigStat(root,statSync2){if(typeof statSync2!="function")return null;try{let stat2=statSync2(path.join(root,".git","config"));return stat2.isFile()?{mtimeMs:stat2.mtimeMs,size:stat2.size}:null}catch{return null}}function readOrigin(folder,{execFile:execFile3,env,exists,statSync:statSync2,now}){let root=checkoutRoot(folder,exists);if(root==null)return Promise.resolve(null);let configStat=readGitConfigStat(root,statSync2),currentTime=now();if(configStat!=null){let cached2=originCache.get(folder);if(cached2!=null&&cached2.execFile===execFile3&&cached2.mtimeMs===configStat.mtimeMs&&cached2.size===configStat.size&¤tTime-cached2.cachedAt<ORIGIN_CACHE_TTL_MS)return Promise.resolve(cached2.origin)}return new Promise(resolve4=>{execFile3("git",["-C",folder,"remote","get-url","origin"],{env:{...env,GIT_TERMINAL_PROMPT:"0"},encoding:"utf8",timeout:READ_TIMEOUT_MS},(error2,stdout)=>{let origin=error2==null?String(stdout):null;if(origin!=null&&configStat!=null){if(originCache.size>=MAX_ORIGIN_CACHE_ENTRIES&&!originCache.has(folder)){let oldestKey=originCache.keys().next().value;oldestKey!==void 0&&originCache.delete(oldestKey)}originCache.set(folder,{mtimeMs:configStat.mtimeMs,size:configStat.size,cachedAt:now(),execFile:execFile3,origin})}else originCache.delete(folder);resolve4(origin)})})}async function readFolderRemotes2(input,{execFile:execFile3=nodeExecFile,env=process.env,exists=fs.existsSync,statSync:statSync2=fs.statSync,now=Date.now}={}){let folders=parseFolders(input);return(await Promise.all(folders.map(async folder=>{let remote=normalizeGitRemote(await readOrigin(folder,{execFile:execFile3,env,exists,statSync:statSync2,now}));return remote==null?null:{folder,...remote}}))).filter(remote=>remote!=null)}module.exports={ORIGIN_CACHE_TTL_MS,normalizeGitRemote,readFolderRemotes:readFolderRemotes2}}});import{chmod as chmod5,link,mkdir as mkdir6,readFile as readFile6,rename as rename6,rm as rm4,writeFile as writeFile5}from"node:fs/promises";import{homedir as homedir3,uptime}from"node:os";import{dirname as dirname6,isAbsolute,join as join9,relative}from"node:path";function configPath2(env){let base=env.XDG_CONFIG_HOME?.trim()||join9(env.HOME||homedir3(),".config");return join9(base,"ando","machine.json")}function stateDirectory(env){return join9(dirname6(configPath2(env)),"machine")}function holdsHome(folder,home=homedir3()){let inside=relative(folder,home);return inside===""||!inside.startsWith("..")&&!isAbsolute(inside)}function needsToolSetup(input){return input.knownFolders+input.addedFolders===0?!1:input.canCheck&&(!input.checked||input.addedFolders>0)||input.toolsConnected===0&&input.addedFolders>0}function approvalCode(request){return`${request.slice(0,4)}-${request.slice(4,8)}`.toUpperCase()}async function readConfig(path){let text;try{text=await readFile6(path,"utf8")}catch(error2){if(error2.code==="ENOENT")return null;throw error2}return JSON.parse(text)}async function writeConfig(path,config2){await mkdir6(dirname6(path),{recursive:!0,mode:448});let temporary=`${path}.${process.pid}.tmp`;await writeFile5(temporary,`${JSON.stringify(config2,null,2)}
|
|
297
|
+
`,{mode:384}),await rename6(temporary,path),await chmod5(path,384)}function holderIsAlive(holder){if(holder.pid===process.pid||Math.abs(holder.bootedAt-bootTime())>BOOT_SLACK_MS)return!1;try{return process.kill(holder.pid,0),!0}catch(error2){return error2.code==="EPERM"}}async function runningConnector(directory){let holder=await readHolder(join9(directory,"connector.lock"));return holder!=null&&holder!=="gone"&&holderIsAlive(holder)?holder.pid:null}async function readHolder(path){try{let holder=JSON.parse(await readFile6(path,"utf8"));return Number.isInteger(holder?.pid)&&Number.isFinite(holder?.bootedAt)?holder:null}catch(error2){return error2.code==="ENOENT"?"gone":null}}async function lockMachine(directory){await mkdir6(directory,{recursive:!0,mode:448});let path=join9(directory,"connector.lock"),claim2=`${path}.${process.pid}.claim`;await writeFile5(claim2,JSON.stringify({pid:process.pid,bootedAt:bootTime()}),{mode:384});try{for(let attempt=0;attempt<3;attempt+=1){try{return await link(claim2,path),()=>rm4(path,{force:!0})}catch(error2){if(error2.code!=="EEXIST")throw error2}let existing=await readHolder(path);if(existing==="gone")continue;if(existing!=null&&holderIsAlive(existing))throw new Error(`Another connector is already running here (process ${existing.pid}).`);let stale=`${path}.${process.pid}.stale`;await rename6(path,stale).then(()=>rm4(stale,{force:!0}),()=>{})}}finally{await rm4(claim2,{force:!0})}throw new Error(`Couldn't lock this machine at ${path}.`)}function carriedEnv(env){return Object.fromEntries(Object.entries(env).filter(entry=>CARRIED_ENV.has(entry[0])&&entry[1]!=null&&entry[1]!==""))}var BOOT_SLACK_MS,bootTime,CARRIED_ENV,init_config=__esm({"../machine/src/config.ts"(){"use strict";BOOT_SLACK_MS=6e4,bootTime=()=>Date.now()-uptime()*1e3;CARRIED_ENV=new Set(["ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN","ANTHROPIC_BASE_URL","AWS_CONFIG_FILE","AWS_DEFAULT_PROFILE","AWS_DEFAULT_REGION","AWS_PROFILE","AWS_REGION","AWS_SDK_LOAD_CONFIG","CLOUDSDK_COMPUTE_REGION","CLOUDSDK_COMPUTE_ZONE","CLOUDSDK_CORE_PROJECT","CLOUDSDK_ROOT_DIR","CLAUDE_CODE_OAUTH_TOKEN","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_VERTEX","CLAUDE_CONFIG_DIR","CODEX_API_KEY","CODEX_HOME","GEMINI_API_KEY","GOOGLE_CLOUD_LOCATION","GOOGLE_CLOUD_PROJECT","GOOGLE_GENAI_USE_VERTEXAI","GOOSE_PROVIDER","OPENAI_API_KEY","OPENAI_BASE_URL","OPENCODE_API_KEY","HTTP_PROXY","HTTPS_PROXY","NO_PROXY","http_proxy","https_proxy","no_proxy"])}});import{styleText}from"node:util";function wantsColor(stream,env=process.env){return env.NO_COLOR!=null&&env.NO_COLOR!==""?!1:env.FORCE_COLOR!=null&&env.FORCE_COLOR!==""?env.FORCE_COLOR!=="0":stream.isTTY===!0&&env.TERM!=="dumb"}function createTerminal(color){let paint=(style,text)=>color?styleText(style,text,{validateStream:!1}):text;return{paint,line(tone,message){if(tone==="plain")return message;let{mark:mark2,style}=MARKS[tone];return color?`${paint(style,mark2)} ${tone==="step"?paint("dim",message):message}`:message},link:url2=>paint(["cyan","underline"],url2),strong:text=>paint("bold",text),quiet:text=>paint("dim",text),state(state){let style=state.startsWith("running")||state==="done"?"green":state==="failed"?"red":"dim";return paint(style,state)}}}var MARKS,init_terminal=__esm({"../machine/src/terminal.ts"(){"use strict";MARKS={ok:{mark:"\u2713",style:"green"},step:{mark:"\u203A",style:"dim"},warn:{mark:"!",style:"yellow"},fail:{mark:"\u2717",style:"red"}}}});import{appendFileSync,existsSync,mkdirSync,readdirSync,readFileSync,statSync,writeFileSync}from"node:fs";import{homedir as homedir4}from"node:os";import{join as join10}from"node:path";function refusedHere(tool){return!isLegacyProvider(tool)||process.platform==="linux"&&tool==="codex"}function exitError(exitCode2,message,cause){return Object.assign(new Error(message,cause===void 0?void 0:{cause}),{exitCode:exitCode2})}function convexErrorExitCode(data){let code2=data&&typeof data=="object"&&"code"in data&&typeof data.code=="string"?data.code:"";return code2==="local_tool_machine_credential_invalid"||code2==="local_tools_disabled"||/(?:unauth|forbid|authorization_|credential|token|permission|revoked)/iu.test(code2)?2:/not_found$/iu.test(code2)?3:1}async function withinTimeout(work,message,timeout=CONNECT_TIMEOUT_MS2){let timer;try{return await Promise.race([work,new Promise((_,reject)=>{timer=setTimeout(()=>reject(new Error(message)),timeout)})])}finally{clearTimeout(timer)}}function log(message,tone="plain",shown=message){console.log(terminal.line(tone,shown));try{let file=logFile();if(existsSync(file)&&statSync(file).size>MAX_LOG_BYTES){let content=readFileSync(file,"utf8"),half=Math.floor(content.length/2),nextNewline=content.indexOf(`
|
|
298
298
|
`,half),kept=nextNewline>=0?content.slice(nextNewline+1):content.slice(half);writeFileSync(file,kept,{mode:384})}appendFileSync(file,`${new Date().toISOString()} ${message}
|
|
299
|
-
`,{mode:384})}catch{}}function readTask(runId,checkoutRoot=CHECKOUT_ROOT){try{return JSON.parse(readFileSync(taskRecordPath(runId,checkoutRoot),"utf8"))}catch{return{}}}function recordTask(runId,fields,checkoutRoot=CHECKOUT_ROOT){try{mkdirSync(checkoutRoot,{recursive:!0,mode:448}),writeFileSync(taskRecordPath(runId,checkoutRoot),JSON.stringify({...readTask(runId,checkoutRoot),...fields}),{mode:384})}catch{}}function listTasks(checkoutRoot=CHECKOUT_ROOT){let names;try{names=readdirSync(checkoutRoot)}catch{return[]}return names.filter(name=>name.endsWith(".task.json")).map(name=>{let runId=name.slice(0,-10);return{runId,...readTask(runId,checkoutRoot)}}).sort((a,b)=>(b.startedAt??0)-(a.startedAt??0))}function readReady(env=process.env){try{return JSON.parse(readFileSync(readyPath(env),"utf8"))}catch{return null}}function saveReady(state,env=process.env){writeFileSync(readyPath(env),JSON.stringify(state),{mode:384})}function readCarriedEnv(env=process.env){try{return JSON.parse(readFileSync(carriedEnvPath(env),"utf8"))}catch{return{}}}function saveCarriedEnv(env=process.env){let path=carriedEnvPath(env),saved=readCarriedEnv(env),merged={...saved,...carriedEnv(env)},changed=JSON.stringify(merged)!==JSON.stringify(saved);return changed&&(writeFileSync(path,JSON.stringify(merged),{mode:384}),log(`Kept for the background connector: ${Object.keys(merged).join(", ")}`)),changed}var HEARTBEAT_MS,CHECKOUT_CLEAR_MS,DEFAULT_URL,DEFAULT_APP_URL,APPROVAL_POLL_MS,APPROVAL_WAIT_MS,MAX_LOG_BYTES,CONNECT_TIMEOUT_MS2,APPROVAL_TIMEOUT_MS,READY_WAIT_MS,STOP_WAIT_MS,RESUBSCRIBE_MS,CHECKOUT_ROOT,BWRAP_APPARMOR_FIX,CODEX_ON_LINUX,ACP_ON_SERVER,LEGACY_PROVIDERS,isLegacyProvider,isValidatorSkewError,readyPath,carriedEnvPath,connectorPath,logFile,terminal,logger,taskRecordPath,init_runtime=__esm({"../machine/src/runtime.ts"(){"use strict";init_config();init_terminal();HEARTBEAT_MS=6e4,CHECKOUT_CLEAR_MS=60*6e4,DEFAULT_URL="https://data.ando.so",DEFAULT_APP_URL="https://app.ando.so",APPROVAL_POLL_MS=2e3,APPROVAL_WAIT_MS=10*6e4,MAX_LOG_BYTES=5*1024*1024,CONNECT_TIMEOUT_MS2=3e4,APPROVAL_TIMEOUT_MS=11*6e4,READY_WAIT_MS=3e4,STOP_WAIT_MS=15e3,RESUBSCRIBE_MS=5e3,CHECKOUT_ROOT=
|
|
299
|
+
`,{mode:384})}catch{}}function readTask(runId,checkoutRoot=CHECKOUT_ROOT){try{return JSON.parse(readFileSync(taskRecordPath(runId,checkoutRoot),"utf8"))}catch{return{}}}function recordTask(runId,fields,checkoutRoot=CHECKOUT_ROOT){try{mkdirSync(checkoutRoot,{recursive:!0,mode:448}),writeFileSync(taskRecordPath(runId,checkoutRoot),JSON.stringify({...readTask(runId,checkoutRoot),...fields}),{mode:384})}catch{}}function listTasks(checkoutRoot=CHECKOUT_ROOT){let names;try{names=readdirSync(checkoutRoot)}catch{return[]}return names.filter(name=>name.endsWith(".task.json")).map(name=>{let runId=name.slice(0,-10);return{runId,...readTask(runId,checkoutRoot)}}).sort((a,b)=>(b.startedAt??0)-(a.startedAt??0))}function readReady(env=process.env){try{return JSON.parse(readFileSync(readyPath(env),"utf8"))}catch{return null}}function saveReady(state,env=process.env){writeFileSync(readyPath(env),JSON.stringify(state),{mode:384})}function readCarriedEnv(env=process.env){try{return JSON.parse(readFileSync(carriedEnvPath(env),"utf8"))}catch{return{}}}function saveCarriedEnv(env=process.env){let path=carriedEnvPath(env),saved=readCarriedEnv(env),merged={...saved,...carriedEnv(env)},changed=JSON.stringify(merged)!==JSON.stringify(saved);return changed&&(writeFileSync(path,JSON.stringify(merged),{mode:384}),log(`Kept for the background connector: ${Object.keys(merged).join(", ")}`)),changed}var HEARTBEAT_MS,CHECKOUT_CLEAR_MS,DEFAULT_URL,DEFAULT_APP_URL,APPROVAL_POLL_MS,APPROVAL_WAIT_MS,MAX_LOG_BYTES,CONNECT_TIMEOUT_MS2,APPROVAL_TIMEOUT_MS,READY_WAIT_MS,STOP_WAIT_MS,RESUBSCRIBE_MS,CHECKOUT_ROOT,BWRAP_APPARMOR_FIX,CODEX_ON_LINUX,ACP_ON_SERVER,LEGACY_PROVIDERS,isLegacyProvider,isValidatorSkewError,readyPath,carriedEnvPath,connectorPath,logFile,terminal,logger,taskRecordPath,init_runtime=__esm({"../machine/src/runtime.ts"(){"use strict";init_config();init_terminal();HEARTBEAT_MS=6e4,CHECKOUT_CLEAR_MS=60*6e4,DEFAULT_URL="https://data.ando.so",DEFAULT_APP_URL="https://app.ando.so",APPROVAL_POLL_MS=2e3,APPROVAL_WAIT_MS=10*6e4,MAX_LOG_BYTES=5*1024*1024,CONNECT_TIMEOUT_MS2=3e4,APPROVAL_TIMEOUT_MS=11*6e4,READY_WAIT_MS=3e4,STOP_WAIT_MS=15e3,RESUBSCRIBE_MS=5e3,CHECKOUT_ROOT=join10(homedir4(),".ando-tasks"),BWRAP_APPARMOR_FIX=`Ubuntu 24.04 and later stop bubblewrap by default. Allow it with:
|
|
300
300
|
sudo tee /etc/apparmor.d/bwrap >/dev/null <<'EOF'
|
|
301
301
|
abi <abi/4.0>,
|
|
302
302
|
include <tunables/global>
|
|
@@ -304,17 +304,17 @@ ${notice}`,log:log2,permissionArgs,effort,model,onClose:cleanup})}catch(error2){
|
|
|
304
304
|
userns,
|
|
305
305
|
}
|
|
306
306
|
EOF
|
|
307
|
-
sudo apparmor_parser -r /etc/apparmor.d/bwrap`,CODEX_ON_LINUX="Codex can't take tasks on a Linux server yet: its sandbox lets a task reach local services such as Docker. Use Claude Code here.",ACP_ON_SERVER="ACP tools (Antigravity CLI, Gemini CLI, OpenCode, Goose) run without an OS sandbox and can't take tasks through ando up. Use Claude Code or Codex here.",LEGACY_PROVIDERS=new Set(["claude-code","codex"]),isLegacyProvider=provider=>LEGACY_PROVIDERS.has(provider),isValidatorSkewError=error2=>/ArgumentValidationError/i.test(String(error2));readyPath=(env=process.env)=>
|
|
307
|
+
sudo apparmor_parser -r /etc/apparmor.d/bwrap`,CODEX_ON_LINUX="Codex can't take tasks on a Linux server yet: its sandbox lets a task reach local services such as Docker. Use Claude Code here.",ACP_ON_SERVER="ACP tools (Antigravity CLI, Gemini CLI, OpenCode, Goose) run without an OS sandbox and can't take tasks through ando up. Use Claude Code or Codex here.",LEGACY_PROVIDERS=new Set(["claude-code","codex"]),isLegacyProvider=provider=>LEGACY_PROVIDERS.has(provider),isValidatorSkewError=error2=>/ArgumentValidationError/i.test(String(error2));readyPath=(env=process.env)=>join10(stateDirectory(env),"ready.json"),carriedEnvPath=(env=process.env)=>join10(stateDirectory(env),"service-env.json"),connectorPath=(env=process.env)=>join10(stateDirectory(env),"connector.mjs"),logFile=(env=process.env)=>join10(stateDirectory(env),"connector.log"),terminal=createTerminal(wantsColor(process.stdout));logger={info:message=>log(message,"step"),warn:(message,error2)=>log(error2==null?message:`${message}: ${String(error2)}`,"warn"),error:(message,error2)=>log(error2==null?message:`${message}: ${String(error2)}`,"fail")},taskRecordPath=(runId,checkoutRoot=CHECKOUT_ROOT)=>join10(checkoutRoot,`${runId}.task.json`)}});import{spawnSync}from"node:child_process";import{copyFileSync,existsSync as existsSync2,mkdirSync as mkdirSync2,readFileSync as readFileSync2,renameSync,rmSync,writeFileSync as writeFileSync2}from"node:fs";import{homedir as homedir5,userInfo}from"node:os";import{dirname as dirname7,join as join11}from"node:path";function systemdValue(value){return`"${value.replace(/(["\\])/g,"\\$1").replace(/%/g,"%%")}"`}function serviceUnit(input){return["[Unit]","Description=Ando machine connector","After=network-online.target","Wants=network-online.target","","[Service]",...Object.entries(input.env).map(([name,value])=>`Environment=${systemdValue(`${name}=${value}`)}`),`ExecStart=${systemdCommandWord(input.node)} ${systemdCommandWord(input.script)} run`,"Restart=on-failure","RestartSec=5","","[Install]","WantedBy=default.target",""].join(`
|
|
308
308
|
`)}function launchdPlist(input){let strings=values=>values.map(value=>` <string>${xml(value)}</string>`);return['<?xml version="1.0" encoding="UTF-8"?>','<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">','<plist version="1.0">',"<dict>"," <key>Label</key>",` <string>${LAUNCHD_LABEL}</string>`," <key>ProgramArguments</key>"," <array>",...strings([input.node,input.script,"run"])," </array>"," <key>EnvironmentVariables</key>"," <dict>",...Object.entries(input.env).flatMap(([name,value])=>[` <key>${xml(name)}</key>`,` <string>${xml(value)}</string>`])," </dict>"," <key>RunAtLoad</key>"," <true/>"," <key>KeepAlive</key>"," <dict>"," <key>SuccessfulExit</key>"," <false/>"," </dict>"," <key>ThrottleInterval</key>"," <integer>5</integer>","</dict>","</plist>",""].join(`
|
|
309
|
-
`)}function detectService(run2=quiet,platform=process.platform){return platform==="darwin"?"launchd":platform!=="linux"?null:run2("systemctl",["--user","show-environment"]).status===0?"systemd":null}function accountName(){try{return userInfo().username}catch{return null}}function foregroundReason(platform=process.platform,systemdRunning=()=>existsSync2("/run/systemd/system"),user=accountName){let plain="There's no service manager here, so this stays running in this terminal.";if(platform!=="linux"||!systemdRunning())return plain;let name=user();return name==null?plain:[`systemd is running, but ${name}'s own systemd session isn't reachable from this shell, so this stays running in this terminal.`,`To run it in the background, log in as ${name} directly (for example over SSH, not with sudo su or su), run: sudo loginctl enable-linger ${name}, then run ando up again.`].join(" ")}function unitPath(kind,env){let home=env.HOME||homedir5();return kind==="launchd"?
|
|
309
|
+
`)}function detectService(run2=quiet,platform=process.platform){return platform==="darwin"?"launchd":platform!=="linux"?null:run2("systemctl",["--user","show-environment"]).status===0?"systemd":null}function accountName(){try{return userInfo().username}catch{return null}}function foregroundReason(platform=process.platform,systemdRunning=()=>existsSync2("/run/systemd/system"),user=accountName){let plain="There's no service manager here, so this stays running in this terminal.";if(platform!=="linux"||!systemdRunning())return plain;let name=user();return name==null?plain:[`systemd is running, but ${name}'s own systemd session isn't reachable from this shell, so this stays running in this terminal.`,`To run it in the background, log in as ${name} directly (for example over SSH, not with sudo su or su), run: sudo loginctl enable-linger ${name}, then run ando up again.`].join(" ")}function unitPath(kind,env){let home=env.HOME||homedir5();return kind==="launchd"?join11(home,"Library","LaunchAgents",`${LAUNCHD_LABEL}.plist`):join11(env.XDG_CONFIG_HOME?.trim()||join11(home,".config"),"systemd","user",`${SYSTEMD_NAME}.service`)}function launchdDomain(run2){let uid=process.getuid?.()??0;return run2("launchctl",["print",`gui/${uid}`]).status===0?`gui/${uid}`:`user/${uid}`}function installedService(env){for(let kind of["systemd","launchd"])if(existsSync2(unitPath(kind,env)))return kind;return null}function writeWhole(path,content){mkdirSync2(dirname7(path),{recursive:!0});let temporary=`${path}.${process.pid}.tmp`;writeFileSync2(temporary,content,{mode:384}),renameSync(temporary,path)}function check(result,doing){if(result.status!==0)throw new Error(`Couldn't ${doing}: ${result.stderr?.trim()||`it ended with ${result.status}`}`)}function placeConnector(from,to){if(existsSync2(to)&&readFileSync2(from).equals(readFileSync2(to)))return!1;let temporary=`${to}.${process.pid}.tmp`;return copyFileSync(from,temporary),renameSync(temporary,to),!0}function stopNow(kind,run2){if(kind==="systemd"){run2("systemctl",["--user","disable","--now",SYSTEMD_NAME]);return}let target=`${launchdDomain(run2)}/${LAUNCHD_LABEL}`;run2("launchctl",["bootout",target]);for(let tries=0;tries<40;tries+=1){if(run2("launchctl",["print",target]).status!==0)return;pause(250)}}function serviceIsRunning(kind,run2=quiet){return kind==="systemd"?run2("systemctl",["--user","is-active","--quiet",SYSTEMD_NAME]).status===0:run2("launchctl",["print",`${launchdDomain(run2)}/${LAUNCHD_LABEL}`]).status===0}function installService(kind,input,run2=quiet){let path=unitPath(kind,input.envFile),text=kind==="systemd"?serviceUnit(input):launchdPlist(input),current=existsSync2(path)?readFileSync2(path,"utf8"):null;if(current!=null&&serviceIsRunning(kind,run2)&¤t===text&&!input.changed)return{started:!1,note:null};if(current!=null&&stopNow(kind,run2),writeWhole(path,text),kind==="launchd")return check(run2("launchctl",["bootstrap",launchdDomain(run2),path]),"start the background service"),{started:!0,note:null};check(run2("systemctl",["--user","daemon-reload"]),"load the service"),check(run2("systemctl",["--user","enable","--now",SYSTEMD_NAME]),"start the background service");let user=userInfo().username;return{started:!0,note:run2("loginctl",["enable-linger",user]).status===0?null:`It stops when you log out. To keep it running, run: sudo loginctl enable-linger ${user}`}}function removeService(env,run2=quiet){let kind=installedService(env);return kind==null?!1:(stopNow(kind,run2),rmSync(unitPath(kind,env),{force:!0}),kind==="systemd"&&run2("systemctl",["--user","daemon-reload"]),!0)}var SYSTEMD_NAME,LAUNCHD_LABEL,quiet,systemdCommandWord,xml,pause,init_service=__esm({"../machine/src/service.ts"(){"use strict";SYSTEMD_NAME="ando-machine",LAUNCHD_LABEL="so.ando.machine",quiet=(command,args)=>{let result=spawnSync(command,args,{encoding:"utf8",stdio:["ignore","ignore","pipe"]});return{status:result.error?1:result.status,stderr:result.stderr}};systemdCommandWord=value=>systemdValue(value).replace(/\$/g,"$$$$");xml=value=>value.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">");pause=ms=>Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,ms)}});import{spawn as spawn3,spawnSync as spawnSync2}from"node:child_process";import{existsSync as existsSync3,readFileSync as readFileSync3,realpathSync}from"node:fs";import{homedir as homedir6}from"node:os";import{join as join12}from"node:path";function formatTaskLine(task){let status=task.status??"running";return` ${terminal.quiet(task.runId.slice(0,8))} ${terminal.state(status)}${" ".repeat(Math.max(0,7-status.length))} ${task.provider??"?"} ${terminal.quiet(task.folder??"")}`}function formatFolderLine(folder,inPlace,hooks){let inPlaceNote=inPlace.has(folder)?terminal.quiet(" (in place)"):"",hooksNote=hooks.has(folder)?terminal.quiet(" (hooks on)"):"";return` ${folder}${inPlaceNote}${hooksNote}`}async function printStatus(asJson,options={}){let env=options.env??process.env,write=options.write??(line=>console.log(line)),config2=await readConfig(configPath2(env)),pid=await runningConnector(stateDirectory(env)),ready=readReady(env),tasks=listTasks(options.checkoutRoot).slice(0,10),inPlace=new Set(ready?.inPlaceFolders??config2?.inPlaceFolders??[]),hooks=new Set(ready?.hookFolders??config2?.hookFolders??[]),background=installedService(env);if(asJson){write(JSON.stringify({connected:config2!=null,machine:config2?.machineName??null,running:pid!=null,pid,background,version:ready?.version??null,folders:ready?.folders??[],...inPlace.size>0?{inPlaceFolders:[...inPlace]}:{},...hooks.size>0?{hookFolders:[...hooks]}:{},tasks:tasks.map(({sessionId:_session,...task})=>task)},null,2));return}if(config2==null){write("Not connected. Run ando up in a repository.");return}let stateLabel=pid==null?"stopped":background==null?"running":"running in the background";write(`${terminal.strong(config2.machineName)}: ${terminal.state(stateLabel)}`);for(let folder of ready?.folders??[])write(formatFolderLine(folder,inPlace,hooks));for(let task of tasks)write(formatTaskLine(task))}function printLogs(follow,lines,options={}){let file=logFile(options.env??process.env),write=options.write??(text=>process.stdout.write(text));if(!existsSync3(file)){write(`No logs yet.
|
|
310
310
|
`);return}let lineCount;if(lines!==void 0){let parsed=Number(lines);if(!Number.isInteger(parsed)||parsed<=0)throw exitError(1,"--lines must be a positive integer.");lineCount=parsed}if(follow){let tailArgs=lineCount!==void 0?["-n",String(lineCount),"-F",file]:["-F",file];(options.followSpawn??spawnSync2)("tail",tailArgs,{stdio:"inherit"});return}let content=readFileSync3(file,"utf8");if(lineCount===void 0){write(content);return}let tail=content.replace(/\n$/u,"").split(`
|
|
311
311
|
`).slice(-lineCount).join(`
|
|
312
312
|
`);tail.length>0&&write(`${tail}
|
|
313
|
-
`)}async function stopConnector(options={}){let env=options.env??process.env,write=options.write??(line=>console.log(line)),state=stateDirectory(env),removed=removeService(env),running=await runningConnector(state);if(running==null&&!removed){write("The connector isn't running.");return}running!=null&&process.kill(running,"SIGTERM");let until=Date.now()+STOP_WAIT_MS;for(;await runningConnector(state)!=null;){if(Date.now()>until)throw new Error("The connector didn't stop. See ando logs.");await new Promise(done=>setTimeout(done,250))}write("Stopped. ando up starts it again.")}function update(){let self=realpathSync(process.argv[1]??""),installed=/[\\/]node_modules[\\/]@andocorp[\\/]cli[\\/]/.test(self)&&!/[\\/]_npx[\\/]/.test(self),options={cwd:homedir6(),stdio:"inherit"};if(installed){let global2=spawnSync2("npm",["install","-g","@andocorp/cli@latest"],options);if(global2.status!==0)return global2.status??1}return spawnSync2("npx",["-y","@andocorp/cli@latest","up"],options).status??1}function attach(prefix,options={}){let checkoutRoot=options.checkoutRoot??CHECKOUT_ROOT,task=listTasks(checkoutRoot).find(candidate=>prefix==null||candidate.runId.startsWith(prefix));if(task?.sessionId==null)throw exitError(3,"No task with a session here. See ando status.");let checkoutCwd=
|
|
313
|
+
`)}async function stopConnector(options={}){let env=options.env??process.env,write=options.write??(line=>console.log(line)),state=stateDirectory(env),removed=removeService(env),running=await runningConnector(state);if(running==null&&!removed){write("The connector isn't running.");return}running!=null&&process.kill(running,"SIGTERM");let until=Date.now()+STOP_WAIT_MS;for(;await runningConnector(state)!=null;){if(Date.now()>until)throw new Error("The connector didn't stop. See ando logs.");await new Promise(done=>setTimeout(done,250))}write("Stopped. ando up starts it again.")}function update(){let self=realpathSync(process.argv[1]??""),installed=/[\\/]node_modules[\\/]@andocorp[\\/]cli[\\/]/.test(self)&&!/[\\/]_npx[\\/]/.test(self),options={cwd:homedir6(),stdio:"inherit"};if(installed){let global2=spawnSync2("npm",["install","-g","@andocorp/cli@latest"],options);if(global2.status!==0)return global2.status??1}return spawnSync2("npx",["-y","@andocorp/cli@latest","up"],options).status??1}function attach(prefix,options={}){let checkoutRoot=options.checkoutRoot??CHECKOUT_ROOT,task=listTasks(checkoutRoot).find(candidate=>prefix==null||candidate.runId.startsWith(prefix));if(task?.sessionId==null)throw exitError(3,"No task with a session here. See ando status.");let checkoutCwd=join12(checkoutRoot,task.checkoutRunId??task.runId),cwd=existsSync3(checkoutCwd)?checkoutCwd:task.folder!=null&&existsSync3(task.folder)?task.folder:null;if(cwd==null)throw exitError(3,`Task ${task.runId.slice(0,8)}'s checkout is no longer on disk.`);let[command,args]=task.provider==="codex"?["codex",["resume",task.sessionId]]:task.provider==="antigravity-cli"?["agy",["--conversation",task.sessionId]]:task.provider==="gemini-cli"?["gemini",["--resume",task.sessionId]]:task.provider==="opencode"?["opencode",["--session",task.sessionId]]:task.provider==="goose"?["goose",["session","--resume","--name",task.sessionId]]:["claude",["--resume",task.sessionId]];return options.runCommand?options.runCommand(command,args,cwd)??1:spawnSync2(command,args,{cwd,stdio:"inherit"}).status??1}async function waitUntilReady(previous){let until=Date.now()+READY_WAIT_MS;for(;Date.now()<until;){let pid=await runningConnector(stateDirectory(process.env));if(pid!=null&&pid!==previous&&readReady()?.pid===pid)return;await new Promise(done=>setTimeout(done,500))}throw new Error("The connector didn't come up in the background. See ando logs.")}async function keepRunning(deps2,kind,previous){let script=connectorPath(),replaced=placeConnector(realpathSync(process.argv[1]??""),script),carried=saveCarriedEnv(),configHome=process.env.XDG_CONFIG_HOME?.trim(),{started,note}=installService(kind,{node:process.execPath,script,env:{PATH:deps2.trustedPath(process.env.PATH??""),...process.env.SHELL?{SHELL:process.env.SHELL}:{},...configHome?{XDG_CONFIG_HOME:configHome}:{}},changed:replaced||carried,envFile:process.env});started&&await waitUntilReady(previous),log(`${started?"Running":"Already running"} in the background. It starts again after a restart. See ando status.`),note!=null&&log(note)}async function detach(){let script=connectorPath();placeConnector(realpathSync(process.argv[1]??""),script),saveCarriedEnv(),spawn3(process.execPath,[script,"run"],{detached:!0,stdio:"ignore"}).unref(),await waitUntilReady(null),log("Running in the background until this server restarts.")}var init_commands=__esm({"../machine/src/commands.ts"(){"use strict";init_config();init_runtime();init_service()}});function fromUsage(usage){return{inputTokens:usage.input_tokens,cachedInputTokens:usage.cached_input_tokens,cacheWriteTokens:usage.cache_write_tokens,outputTokens:usage.output_tokens,reasoningTokens:usage.reasoning_tokens??0,costUsd:usage.cost_usd}}function toUsage(usage){return{input_tokens:usage.inputTokens,cached_input_tokens:usage.cachedInputTokens,cache_write_tokens:usage.cacheWriteTokens,output_tokens:usage.outputTokens,reasoning_tokens:usage.reasoningTokens,cost_usd:usage.costUsd}}function toReport(event){let usage=event.usage==null?{}:{usage:toUsage(event.usage)};switch(event.kind){case"started":return{kind:"started",...event.checkoutRunId==null?{}:{checkout_run_id:event.checkoutRunId}};case"session":return{kind:"session",session_id:event.sessionId};case"step":return{kind:"step",text:event.text,...event.tool==null?{}:{tool:event.tool},...event.target==null?{}:{target:event.target}};case"stopped":return{kind:"stopped",session_id:event.sessionId??null,...usage};case"done":return{kind:"done",session_id:event.sessionId??null,...event.checkoutRunId==null?{}:{checkout_run_id:event.checkoutRunId},result:event.result,...usage};case"failed":return{kind:"failed",session_id:event.sessionId??null,error:event.error}}}function steerText(messages){return[STEER_HEADER,...messages.map(message=>`${message.author_name}: ${message.text}`)].join(`
|
|
314
314
|
|
|
315
315
|
`)}function steerBatches(messages){let batches=[],current=[];for(let message of messages)current.length>0&&steerText([...current,message]).length>MAX_STEER_CHARS&&(batches.push(current),current=[]),current.push(message);return current.length>0&&batches.push(current),batches}function createMachineAgent(input){let{workspaceId,api,host,isRefusal,log:log2}=input,retryMs=input.retryMs??RETRY_MS,handed=new Set,stopped=new Set,ended=new Set,sessions=new Map,starting=new Map,queue=[],sent=new Set,delivering=new Set,lastSeq=0,draining=!1,retryTimer=null,latestRuns=[],latestThreads=[],closed=!1,later=work=>{if(closed)return;setTimeout(work,retryMs).unref?.()};async function drain(){if(!(draining||retryTimer!=null)){draining=!0;try{for(;!closed&&queue.length>0;){let event=queue[0];try{let report=toReport(event);if(event.kind==="done"&&event.files?.length){let ids=[],errors=[];for(let file of event.files){let data;try{if(host.readRunFile==null||api.uploadResultFile==null)throw new Error("File return unavailable.");data=await host.readRunFile({seq:event.seq,slot:file.slot,workspaceId,ownerId:null})}catch{errors.push(`Output ${file.slot+1} could not be read from this device.`);continue}try{let id=await api.uploadResultFile(event.runId,file,data);id!=null?ids.push(id):errors.push(`Output ${file.slot+1} was not accepted because the run ended.`)}catch(error2){if(!isRefusal(error2))throw error2;errors.push(`Output ${file.slot+1} was refused by Ando.`)}}ids.length&&(report.result_file_ids=ids),report.result=[...errors,event.result].join(`
|
|
316
316
|
|
|
317
|
-
`)}await api.report(event.runId,report,event.seq)}catch(error2){if(!isRefusal(error2)){retryTimer=setTimeout(()=>{retryTimer=null,drain()},retryMs),retryTimer.unref?.();return}log2(`Ando refused a report on ${event.runId}; dropping it.`)}queue.shift(),host.ackRunEvents([event.seq])}}finally{draining=!1}}}function enqueue(event){event.workspaceId===workspaceId&&(event.seq<=lastSeq||(lastSeq=event.seq,event.kind==="session"&&event.sessionId!=null&&sessions.set(event.runId,event.sessionId),ENDINGS.has(event.kind)&&ended.add(event.runId),queue.push(event)))}async function endRefusedStart(runId,sessionId,status){ended.has(runId)||host.runState().events.some(event=>event.runId===runId&&ENDINGS.has(event.kind))||await api.report(runId,{kind:"failed",session_id:sessionId,error:REFUSED_START_ERRORS[status]}).catch(error2=>{if(!isRefusal(error2))throw error2}),ended.add(runId)}function stop(run2){if(stopped.has(run2.run_id))return;stopped.add(run2.run_id);let pendingStart=starting.get(run2.run_id);pendingStart!=null&&host.stopRun({runId:run2.run_id})||(async()=>{await pendingStart,!ended.has(run2.run_id)&&(host.stopRun({runId:run2.run_id})||await api.report(run2.run_id,{kind:"stopped",session_id:run2.session_id}))})().catch(error2=>{isRefusal(error2)||(stopped.delete(run2.run_id),later(()=>onRuns(latestRuns)))})}function start(run2){handed.add(run2.run_id);let work=(async()=>{let claimed=run2.status==="queued"?await api.claim(run2.run_id):run2;if(claimed==null)return;let midTurnSessionId=claimed.session_id??sessions.get(claimed.run_id)??null,sessionId=midTurnSessionId??claimed.continued_session_id??null,{status}=await host.startRun({...host.readRunFile!=null&&api.uploadResultFile!=null?{returnFiles:!0}:{},runId:claimed.run_id,workspaceId,ownerId:null,provider:claimed.provider,folder:claimed.folder,prompt:claimed.prompt,sessionId,continuedSessionId:claimed.continued_session_id??null,continuedFromRunId:claimed.continued_from_run_id??null,continuedUsageBaseline:claimed.continued_usage_baseline==null?null:fromUsage(claimed.continued_usage_baseline),checkoutRunId:claimed.checkout_run_id??null,midTurnRestart:midTurnSessionId!=null,agentName:claimed.agent_name,...claimed.post_as_owner===!0?{postAsOwner:!0}:{},policy:claimed.policy,servers:claimed.servers,...claimed.effort==null?{}:{effort:claimed.effort},...claimed.model==null?{}:{model:claimed.model}});status==="started"||status==="running"||status!=="finished"&&await endRefusedStart(claimed.run_id,sessionId,status)})().catch(error2=>{log2(`Couldn't start ${run2.run_id}: ${String(error2)}`),handed.delete(run2.run_id),later(()=>onRuns(latestRuns))});starting.set(run2.run_id,work),work.then(()=>{starting.get(run2.run_id)===work&&starting.delete(run2.run_id)})}function onRuns(runs){latestRuns=runs;for(let run2 of runs)ended.has(run2.run_id)||(run2.stop_requested?stop(run2):handed.has(run2.run_id)||start(run2))}function saveContext(runId,through){api.markContext(runId,through).catch(()=>{later(()=>saveContext(runId,through))})}function onThreads(threads){latestThreads=threads;for(let thread of threads){let runId=thread.run_id;if(delivering.has(runId))continue;if(thread.messages.length===0){saveContext(runId,thread.scanned_through);continue}let key=id=>`${runId}:${id}`,fresh=thread.messages.filter(message=>!sent.has(key(message.id))).sort((a,b)=>a.created_at-b.created_at);fresh.length!==0&&(delivering.add(runId),(async()=>{for(let batch of steerBatches(fresh)){if(!await Promise.resolve(host.steerRun({runId,text:steerText(batch)})).catch(()=>!1))return!1;for(let message of batch)sent.add(key(message.id));saveContext(runId,thread.messages.every(message=>sent.has(key(message.id)))?thread.scanned_through:Math.max(...batch.map(message=>message.created_at)))}return!0})().then(delivered=>{delivering.delete(runId),delivered||later(()=>onThreads(latestThreads))}))}}let answered=new Set;function onSessionRequests(requests){if(!(host.readSessions==null||api.answerSessionRequest==null))for(let request of requests)answered.has(request.request_id)||(answered.add(request.request_id),(async()=>{let answer=await host.readSessions(request).catch(error2=>({status:"failed",error:`The Ando connector couldn't read the session: ${error2 instanceof Error?error2.message:String(error2)}`}));await api.answerSessionRequest(request.request_id,answer)})().catch(error2=>{isRefusal(error2)||answered.delete(request.request_id)}))}function load(){let state=host.runState();for(let id of state.active)handed.add(id);for(let event of[...state.events].sort((a,b)=>a.seq-b.seq))enqueue(event);drain()}return{load,onRuns,onThreads,onSessionRequests,onEvent(event){enqueue(event),drain()},activeRunIds(){let state=host.runState();return[...new Set([...state.active,...state.events.map(event=>event.runId)])]},close(){closed=!0,retryTimer!=null&&clearTimeout(retryTimer)}}}var ENDINGS,MAX_STEER_CHARS,STEER_HEADER,RETRY_MS,REFUSED_START_ERRORS,init_agent=__esm({"../machine/src/agent.ts"(){"use strict";ENDINGS=new Set(["done","failed","stopped"]),MAX_STEER_CHARS=2e4,STEER_HEADER="New in the task's thread in Ando:",RETRY_MS=1e4,REFUSED_START_ERRORS={invalid:"The Ando connector couldn't read this task, so nothing ran.",failed:"The Ando connector couldn't start this task, so nothing ran."}}});async function clearFinishedCheckouts(input){let ended=input.host.endedCheckouts(),cleared=[];for(let start=0;start<ended.length;start+=50){let batch=ended.slice(start,start+50),asked=new Set(batch),finished=(await input.finished(batch)).filter(id=>asked.has(id));finished.length>0&&cleared.push(...input.host.clearFinishedCheckouts(finished))}return cleared}var init_checkout_retirement=__esm({"../machine/src/checkout-retirement.ts"(){"use strict"}});import{spawnSync as spawnSync3}from"node:child_process";import{existsSync as existsSync4,realpathSync as realpathSync2}from"node:fs";function usableFolders(folders,mode=null){for(let folder of folders)if(!existsSync4(folder))throw exitError(1,`${folder} doesn't exist here.`);let absolute=[...new Set(folders.map(folder=>realpathSync2(folder)))];for(let folder of absolute)if(holdsHome(folder))throw exitError(1,`Tasks can write the folders they work in, so ${folder} can't be one: it holds your home folder. Run this from a project folder.`);let autoInPlace=[];for(let folder of absolute){let top=spawnSync3("git",["-C",folder,"rev-parse","--show-toplevel"],{encoding:"utf8"});if(top.status!==0){if(mode==="checkout")throw exitError(1,`${folder} isn't a git repository. Tasks only work in a checkout of their own in a git repository; drop --checkout to run in place.`);autoInPlace.push(folder);continue}let repoRoot=realpathSync2(top.stdout.trim());if(repoRoot!==folder&&mode!=="in-place")throw exitError(1,`${folder} is inside a repository (${repoRoot}). Connect the repository's own folder, or pass --in-place.`)}return{absolute,inPlace:mode==="in-place"?absolute:autoInPlace}}function mergeInPlaceFolders(existing,folders,autoInPlace,mode){let next=new Set(existing??[]);for(let folder of autoInPlace)next.add(folder);if(mode==="in-place")for(let folder of folders)next.add(folder);else if(mode==="checkout")for(let folder of folders)next.delete(folder);return[...next]}function mergeHookFolders(existing,folders,hooks){let next=new Set(existing??[]);if(hooks===!0)for(let folder of folders)next.add(folder);if(hooks===!1)for(let folder of folders)next.delete(folder);return[...next]}var init_folders=__esm({"../machine/src/folders.ts"(){"use strict";init_config();init_runtime()}});function browserOpener(url2,where){let{platform,env,interactive,find}=where;if(!interactive||env.SSH_CONNECTION||env.SSH_TTY||env.SSH_CLIENT)return null;if(platform==="darwin")return{command:"/usr/bin/open",args:[url2]};if(platform==="win32"){let root=env.SystemRoot||env.windir;return root==null?null:{command:`${root}\\System32\\rundll32.exe`,args:["url.dll,FileProtocolHandler",url2]}}if(!env.DISPLAY&&!env.WAYLAND_DISPLAY)return null;let command=find("xdg-open");return command==null?null:{command,args:[url2]}}function openOnEnter(input,open3){let opened=!1,onData=chunk=>{opened||!/[\r\n]/.test(String(chunk))||(opened=!0,open3())};return input.on("data",onData),input.resume(),()=>{input.off("data",onData),input.pause()}}function openLink(opener,start,cantOpen){let said=!1,failed=()=>{said||(said=!0,cantOpen())};try{let child=start(opener.command,opener.args);child.on("error",failed),child.on("exit",code2=>{code2!==0&&code2!=null&&failed()}),child.unref()}catch{failed()}}var init_open_link=__esm({"../machine/src/open-link.ts"(){"use strict"}});import{randomUUID as randomUUID2}from"node:crypto";import{existsSync as existsSync5,rmSync as rmSync2}from"node:fs";import{join as join12}from"node:path";async function selfCheck(input){let runId=randomUUID2(),ending=input.ended(runId),checkoutDir=input.checkoutRoot==null?null:join12(input.checkoutRoot,runId),markName=checkoutDir==null?`${MARK}-${runId}`:MARK,markPath=join12(checkoutDir??input.folder,markName);try{let{status}=await input.startRun({runId,workspaceId:WORKSPACE,provider:input.provider,folder:input.folder,prompt:`Run this exact shell command with your shell tool, then reply done: touch ${markName}`,policy:{network:"never"},bareCheckout:!0,servers:[]});if(status!=="started"&&status!=="finished")return{ok:!1,reason:`the task couldn't start (${status})`};let timer,timedOut=new Promise(resolve4=>{timer=setTimeout(()=>resolve4({kind:"timeout"}),input.waitMs??WAIT_MS)}),end=await Promise.race([ending,timedOut]);return clearTimeout(timer),end.kind==="timeout"?{ok:!1,reason:"the task didn't finish in time"}:end.kind!=="done"?{ok:!1,reason:end.error??`the task ${end.kind}`}:existsSync5(markPath)?{ok:!0}:{ok:!1,reason:"the task said it was done, but its command didn't run, so its sandbox isn't working here"}}finally{checkoutDir!=null?(rmSync2(checkoutDir,{recursive:!0,force:!0}),rmSync2(`${checkoutDir}.ended`,{force:!0}),rmSync2(`${checkoutDir}.task.json`,{force:!0})):rmSync2(markPath,{force:!0})}}var WAIT_MS,MARK,WORKSPACE,ENDINGS2,isEnding,init_self_check=__esm({"../machine/src/self-check.ts"(){"use strict";WAIT_MS=12e4,MARK=".ando-check",WORKSPACE="self-check",ENDINGS2=new Set(["done","failed","stopped"]);isEnding=kind=>ENDINGS2.has(kind)}});import{spawn as spawn3,spawnSync as spawnSync4}from"node:child_process";import{createHash as createHash5,randomBytes as randomBytes2}from"node:crypto";import{hostname}from"node:os";import{join as join13}from"node:path";function linuxSandboxProblem(deps2,env){if(process.platform!=="linux")return null;let missing=["bwrap","socat"].filter(tool=>deps2.findCommand(tool,env.PATH)==null);if(missing.length>0)return`Claude Code tasks here need ${missing.join(" and ")}. Install them with: sudo apt-get install -y bubblewrap socat`;let bwrap=deps2.findCommand("bwrap",env.PATH),tried=spawnSync4(bwrap,["--unshare-user","--ro-bind","/","/","--dev","/dev","true"],{encoding:"utf8",timeout:1e4});return tried.status===0?null:/permission|not permitted|setting up uid map/i.test(tried.stderr??"")?BWRAP_APPARMOR_FIX:`Claude Code's sandbox can't start here: ${(tried.stderr??"").trim()}`}async function fromApproval(deps2,client){let secret=randomBytes2(32).toString("hex"),request=createHash5("sha256").update(secret).digest("hex"),code2=approvalCode(request),appUrl=process.env.ANDO_APP_URL??DEFAULT_APP_URL,name=encodeURIComponent(hostname().slice(0,80)),link2=`${appUrl}/connect/machine?request=${request}&name=${name}`,heading="Approve this device in your browser, from anywhere:";log(heading,"plain",terminal.strong(heading)),log(` ${link2}`,"plain",` ${terminal.link(link2)}`),log(` Check it shows this code: ${code2}`,"plain",` Check it shows this code: ${terminal.strong(code2)}`);let opener=browserOpener(link2,{platform:process.platform,env:process.env,interactive:process.stdin.isTTY===!0&&process.stdout.isTTY===!0,find:command=>deps2.findCommand(command,process.env.PATH)});console.log(opener==null?terminal.quiet("Waiting for your approval..."):`Press ${terminal.strong("Enter")} to open it in this computer's browser. ${terminal.quiet("Waiting for your approval...")}`);let stopListening=opener==null?()=>{}:openOnEnter(process.stdin,()=>openLink(opener,(command,args)=>spawn3(command,args,{detached:!0,stdio:"ignore"}),()=>console.log(terminal.line("warn","Couldn't open a browser here. Use the link above."))));try{let expiresAt=Date.now()+APPROVAL_WAIT_MS;for(;Date.now()<expiresAt;){let machine=await withinTimeout(client.mutation(deps2.web.machineCollectConnect,{secret}),"Couldn't reach Ando.");if(machine!=null)return machine;await new Promise(done=>setTimeout(done,APPROVAL_POLL_MS))}throw exitError(4,"The approval link expired. Run this again.")}finally{stopListening()}}async function openSetup(deps2,folders,inPlaceFolders=[],isolated=!1){let endings=new Map,host=deps2.createHost(event=>{host.ackRunEvents([event.seq]),isEnding(event.kind)&&endings.get(event.runId)?.(event)},()=>folders,()=>inPlaceFolders,void 0,isolated?join13(stateDirectory(process.env),"setup-check"):stateDirectory(process.env)),{tools,signedOut}=await host.machine.get(),sandboxProblem=linuxSandboxProblem(deps2,host.env()),ready=tools.filter(tool=>!signedOut.includes(tool)&&!refusedHere(tool)&&(tool!=="claude-code"||sandboxProblem==null));if(tools.some(tool=>process.platform==="linux"&&tool==="codex")&&logger.warn(CODEX_ON_LINUX),tools.some(tool=>!isLegacyProvider(tool))&&logger.warn(ACP_ON_SERVER),sandboxProblem!=null&&tools.includes("claude-code")&&logger.warn(sandboxProblem),ready.length===0)throw host.stopAll(),new Error(tools.length===0?"Install Claude Code or Codex here first.":"Nothing here can take tasks yet. Fix what's above, or sign in (claude auth login or codex login), then connect again.");return{host,endings,ready}}async function proveTasksRun(setup,folder,inPlace=!1){log("Checking that a task really runs here...","step");let startedAt=Date.now(),check2=await selfCheck({provider:setup.ready[0],folder,checkoutRoot:inPlace?null:CHECKOUT_ROOT,startRun:setup.host.startRun,ended:runId=>new Promise(resolve4=>setup.endings.set(runId,resolve4))});if(!check2.ok)throw new Error(`This device is connected, but it can't run tasks yet: ${check2.reason}. Fix that, then run ando up.`);let seconds=Math.max(1,Math.round((Date.now()-startedAt)/1e3));log(`A real task ran here, in ${seconds}s. This device is ready.`,"ok")}async function connectPendingTools(deps2,config2,client){if(config2.pendingTools==null)return config2;let{folders}=config2.pendingTools,providers=config2.pendingTools.providers;for(;providers.length>0;){let[provider,...rest]=providers;try{await withinTimeout(client.mutation(deps2.web.machineConnectTool,{token:config2.token,provider,folders}),`Couldn't reach Ando at ${config2.url}.`)}catch(error2){if(provider!=null&&!isLegacyProvider(provider)&&isValidatorSkewError(error2))logger.warn(`Ando hasn't rolled out ${provider} on this backend yet; skipping it for now.`);else throw error2}providers=rest;let next={...config2};providers.length>0?next.pendingTools={providers,folders}:delete next.pendingTools,await writeConfig(configPath2(process.env),next)}let finished={...config2};return delete finished.pendingTools,finished}async function connect(deps2,getMachine,url2,folders,timeout=CONNECT_TIMEOUT_MS2,mode=null,hooks=null){if(folders.length===0)throw exitError(1,"Name a folder tasks may use, with --folder <path>.");let{absolute,inPlace}=usableFolders(folders,mode),inPlaceFolders=mergeInPlaceFolders(void 0,absolute,inPlace,mode),hookFolders=mergeHookFolders(void 0,absolute,hooks),setup=await openSetup(deps2,absolute,inPlaceFolders),client=deps2.newClient(url2);try{let machine=await withinTimeout(getMachine(client),`Couldn't reach Ando at ${url2}.`,timeout),config2={url:url2,token:machine.token,workspaceId:machine.workspace_id,machineId:machine.machine_id,machineName:machine.machine_name,pendingTools:{providers:setup.ready,folders:absolute},...inPlaceFolders.length>0?{inPlaceFolders}:{},...hookFolders.length>0?{hookFolders}:{}};await writeConfig(configPath2(process.env),config2);let connected=await connectPendingTools(deps2,config2,client);await proveTasksRun(setup,absolute[0],inPlaceFolders.includes(absolute[0]));let checked={...connected,checked:!0};return await writeConfig(configPath2(process.env),checked),checked}finally{setup.host.stopAll(),client.close()}}async function connectedFolders(deps2,client,token){return(await withinTimeout(client.query(deps2.web.machineConnections,{token}),"Couldn't reach Ando.")).map(row=>({provider:row.provider_url.replace("local-tool://",""),folders:row.folders}))}function buildUpdatedConfig(current,inPlaceFolders,hookFolders){let inPlaceChanged=JSON.stringify(inPlaceFolders)!==JSON.stringify(current.inPlaceFolders??[]),hooksChanged=JSON.stringify(hookFolders)!==JSON.stringify(current.hookFolders??[]),nextConfig={...current};return inPlaceFolders.length>0?nextConfig.inPlaceFolders=inPlaceFolders:delete nextConfig.inPlaceFolders,hookFolders.length>0?nextConfig.hookFolders=hookFolders:delete nextConfig.hookFolders,{nextConfig,inPlaceChanged,hooksChanged}}async function bringUpToDate(deps2,config2,folders,canCheck,mode=null,hooks=null){let{absolute,inPlace}=usableFolders(folders,mode),client=deps2.newClient(config2.url),setup=null;try{let current=await connectPendingTools(deps2,config2,client),tools=await connectedFolders(deps2,client,current.token),known=[...new Set(tools.flatMap(tool=>tool.folders))],added=absolute.filter(folder=>!known.includes(folder)),all=[...known,...added],inPlaceFolders=mergeInPlaceFolders(current.inPlaceFolders,absolute,inPlace,mode),hookFolders=mergeHookFolders(current.hookFolders,absolute,hooks),{nextConfig,inPlaceChanged,hooksChanged}=buildUpdatedConfig(current,inPlaceFolders,hookFolders);if((inPlaceChanged||hooksChanged)&&await writeConfig(configPath2(process.env),nextConfig),hooksChanged)for(let folder of absolute)log(hookFolders.includes(folder)?`${folder}'s own Claude Code hooks will now run in tasks, outside their sandbox.`:`${folder}'s own Claude Code hooks won't run in tasks.`,"ok");if(needsToolSetup({canCheck,checked:nextConfig.checked===!0,toolsConnected:tools.length,knownFolders:known.length,addedFolders:added.length})&&(setup=await openSetup(deps2,all,inPlaceFolders,!canCheck)),await syncAddedFolders(deps2,client,nextConfig,tools,setup?.ready??[],absolute,added,inPlaceFolders,inPlaceChanged),setup==null)return nextConfig;let checkFolder=added[0]??all[0];await proveTasksRun(setup,checkFolder,inPlaceFolders.includes(checkFolder));let checked={...nextConfig,checked:!0};return await writeConfig(configPath2(process.env),checked),checked}finally{setup?.host.stopAll(),client.close()}}async function syncAddedFolders(deps2,client,nextConfig,tools,readyProviders,absolute,added,inPlaceFolders,inPlaceChanged){if(added.length>0){let targets=tools.length>0?tools:readyProviders.map(provider=>({provider,folders:[]}));if(targets.length===0)throw new Error("No tool is connected on this device. Connect one in Studio \u203A Devices first.");await Promise.all(targets.map(target=>withinTimeout(client.mutation(deps2.web.machineConnectTool,{token:nextConfig.token,provider:target.provider,folders:[...target.folders,...added]}),`Couldn't reach Ando at ${nextConfig.url}.`)));for(let folder of added)log(`Agents can now work in ${folder}${inPlaceFolders.includes(folder)?" (in place)":""}.`,"ok")}else if(inPlaceChanged)for(let folder of absolute)log(`Tasks in ${folder} will now run ${inPlaceFolders.includes(folder)?"in the folder itself":"in their own checkout"}.`,"ok")}async function connectMcpEndpoint(deps2,runForeground,saved,state,url2,endpoint,name,foreground){let device=saved;if(!device){let releasePairing=await lockMachine(state),pairing=deps2.newClient(url2);try{if(device=await readConfig(configPath2(process.env)),!device){let machine=await withinTimeout(fromApproval(deps2,pairing),"Device pairing timed out.",APPROVAL_TIMEOUT_MS);device={url:url2,token:machine.token,workspaceId:machine.workspace_id,machineId:machine.machine_id,machineName:machine.machine_name},await writeConfig(configPath2(process.env),device)}}finally{pairing.close(),await releasePairing()}}let registry2=deps2.deviceMcpRegistry(state),scope=JSON.stringify([device.url,device.workspaceId,device.machineId]),entry=await registry2.add(scope,name,endpoint),client=deps2.newClient(device.url);try{await withinTimeout(client.mutation(deps2.web.machineRegisterMcpServer,{token:device.token,...entry}),"Server registration timed out.")}finally{client.close()}log("Registered "+entry.name+" on this device.","ok");let running=await runningConnector(state);if(running!=null){let ready=readReady();if(ready?.pid!==running||!ready.deviceMcpRelay)throw new Error("The running connector does not advertise device MCP support. Run ando stop, then repeat this command with the updated CLI.");return}let release=await lockMachine(state);try{if(foreground)return await runForeground(device,release)}finally{await release()}let service=detectService();return service?await keepRunning(deps2,service,null):await detach()}var fromCode,init_setup=__esm({"../machine/src/setup.ts"(){"use strict";init_commands();init_config();init_folders();init_open_link();init_runtime();init_self_check();init_service();fromCode=(deps2,code2)=>async client=>{try{return await client.mutation(deps2.web.machineRedeemConnectCode,{code:code2,hostname:hostname().slice(0,80)})}catch(error2){if(!isValidatorSkewError(error2)||!/extra field [`'" ]*hostname\b/i.test(String(error2)))throw error2;return await client.mutation(deps2.web.machineRedeemConnectCode,{code:code2})}}}});async function runConnector(deps2,config2,release,version3){let client=deps2.newClient(config2.url);await connectPendingTools(deps2,config2,client);let{token,workspaceId}=config2,stopMcp=deps2.startDeviceMcpRunner({registry:deps2.deviceMcpRegistry(stateDirectory(process.env)),localScope:JSON.stringify([config2.url,workspaceId,config2.machineId]),client,web:deps2.web,scope:{token},log:error2=>logger.warn("Device MCP relay could not report to Ando.",error2)}),folders=[],inPlaceFolders=config2.inPlaceFolders??[],hookFolders=config2.hookFolders??[],folderSeq=0,readFolders=async()=>{let seq=++folderSeq,[connections,latestConfig]=await Promise.all([client.query(deps2.web.machineConnections,{token}),readConfig(configPath2(process.env))]),next=[...new Set(connections.flatMap(row=>row.folders))];return seq===folderSeq&&(folders=next,inPlaceFolders=latestConfig?latestConfig.inPlaceFolders??[]:inPlaceFolders,hookFolders=latestConfig?latestConfig.hookFolders??[]:hookFolders),folders};await withinTimeout(readFolders(),`Couldn't reach Ando at ${config2.url}.`);let agent=null,host=deps2.createHost(event=>{event.kind==="session"&&event.sessionId!=null&&recordTask(event.runId,{sessionId:event.sessionId}),event.kind==="started"&&(recordTask(event.runId,{status:"running"}),log(`Task ${event.runId.slice(0,8)} started.`,"step")),(event.kind==="done"||event.kind==="failed"||event.kind==="stopped")&&(recordTask(event.runId,{status:event.kind,endedAt:Date.now()}),log(`Task ${event.runId.slice(0,8)} ${event.kind}.`,event.kind==="done"?"ok":event.kind==="failed"?"fail":"plain")),agent?.onEvent(event)},()=>folders,()=>inPlaceFolders,()=>hookFolders),startRun=host.startRun;host.startRun=async input=>typeof input.folder=="string"&&holdsHome(input.folder)?{status:"failed"}:refusedHere(String(input.provider))?(log(CODEX_ON_LINUX,"warn"),{status:"failed"}):(typeof input.runId=="string"&&recordTask(input.runId,{provider:String(input.provider),folder:String(input.folder),...typeof input.checkoutRunId=="string"?{checkoutRunId:input.checkoutRunId}:{},status:"running",startedAt:Date.now()}),startRun(input)),agent=createMachineAgent({workspaceId,host,log,isRefusal:error2=>deps2.isConvexError(error2),api:{uploadResultFile:(runId,file,dataBase64)=>client.action(deps2.uploadResultFileFn,{scope:{token},runId,slot:file.slot,sha256:file.sha256,filename:file.filename,contentType:file.contentType,dataBase64}),claim:async runId=>(await readFolders(),client.mutation(deps2.web.machineClaimRun,{token,runId})),report:async(runId,event,eventSeq)=>{await client.mutation(deps2.web.machineReportRun,{token,runId,event,...eventSeq==null?{}:{eventSeq}})},markContext:async(runId,through)=>{await client.mutation(deps2.web.machineMarkRunContext,{token,runId,through})},answerSessionRequest:async(requestId,answer)=>{await client.mutation(deps2.web.machineAnswerSessionRequest,{token,requestId,...answer.status==="done"?{result:answer.result}:{error:answer.error}})}}}),agent.load();let unsubscribe=()=>{},resubscribing,fail=error2=>{if(deps2.isConvexError(error2)){logger.error("Ando stopped this machine's connection",error2),shutdown(0);return}logger.warn("Lost sight of Ando's tasks; trying again",error2),clearTimeout(resubscribing),resubscribing=setTimeout(subscribe,RESUBSCRIBE_MS)};function subscribe(){unsubscribe();let runs=client.onUpdate(deps2.web.machineRuns,{token},rows=>agent?.onRuns(rows),fail),threads=client.onUpdate(deps2.web.machineRunThreadContext,{token},rows=>agent?.onThreads(rows),fail),sessions=client.onUpdate(deps2.web.machineSessionRequests,{token},rows=>agent?.onSessionRequests(rows),fail);unsubscribe=()=>{runs(),threads(),sessions()}}subscribe();let writeReady=()=>saveReady({pid:process.pid,deviceMcpRelay:!0,version:version3,folders,...inPlaceFolders.length>0?{inPlaceFolders}:{},...hookFolders.length>0?{hookFolders}:{}}),heartbeat=async()=>{try{let[described]=await Promise.all([host.machine.get(),readFolders()]);writeReady();let remotes=await deps2.readFolderRemotes(folders,{env:host.env()}),activeRunIds=agent?.activeRunIds()??[],baseReport={token,remotes,activeRunIds,sleeping:!1,sessionReads:typeof host.readSessions=="function",...described.key==null?{}:{machineKey:described.key}};try{await client.mutation(deps2.web.machineReport,{...baseReport,taskSettings:!0,effortUnsupported:described.effortUnsupported??[],signedOutProviders:described.signedOut,servers:Object.entries(described.servers).map(([provider,names])=>({provider,names})),...described.models==null?{}:{models:Object.entries(described.models).map(([provider,models])=>({provider,models}))}})}catch(error2){if(!isValidatorSkewError(error2))throw error2;await client.mutation(deps2.web.machineReport,{...baseReport,signedOutProviders:described.signedOut.filter(isLegacyProvider),servers:Object.entries(described.servers).filter(([provider])=>isLegacyProvider(provider)).map(([provider,names])=>({provider,names}))})}}catch(error2){logger.warn("Couldn't report in to Ando; trying again",error2)}};heartbeat();let timer=setInterval(()=>{heartbeat()},HEARTBEAT_MS),clearCheckouts=async()=>{try{let cleared=await clearFinishedCheckouts({host,finished:async checkoutIds=>await client.query(deps2.web.machineFinishedCheckouts,{token,checkoutIds})});cleared.length>0&&logger.info(`Cleared ${cleared.length} ${cleared.length===1?"checkout":"checkouts"} whose thread is finished.`)}catch(error2){logger.warn("Couldn't check for finished threads' checkouts",error2)}};clearCheckouts();let checkoutTimer=setInterval(()=>{clearCheckouts()},CHECKOUT_CLEAR_MS),stopping=!1;function shutdown(code2){stopping||(stopping=!0,clearInterval(timer),clearInterval(checkoutTimer),stopMcp(),clearTimeout(resubscribing),unsubscribe(),agent?.close(),host.stopAll(),Promise.allSettled([client.close(),release()]).finally(()=>process.exit(code2)))}process.on("SIGTERM",()=>shutdown(0)),process.on("SIGINT",()=>shutdown(0)),writeReady(),log(`${config2.machineName} is ready for tasks.`,"ok"),await new Promise(()=>{})}var init_runner=__esm({"../machine/src/runner.ts"(){"use strict";init_agent();init_checkout_retirement();init_config();init_runtime();init_setup()}});var cli_exports={};__export(cli_exports,{convexErrorExitCode:()=>convexErrorExitCode,runMachine:()=>runMachine,usableFolders:()=>usableFolders});import{spawn as spawn4,spawnSync as spawnSync5}from"node:child_process";import{homedir as homedir7}from"node:os";import{resolve as resolve3}from"node:path";import{parseArgs as parseArgs5}from"node:util";function parseMachineArgs(argv){try{return parseArgs5({args:argv,allowPositionals:!0,options:{url:{type:"string"},mcp:{type:"string"},name:{type:"string"},folder:{type:"string",multiple:!0},"in-place":{type:"boolean"},checkout:{type:"boolean"},hooks:{type:"boolean"},"no-hooks":{type:"boolean"},foreground:{type:"boolean"},json:{type:"boolean"},follow:{type:"boolean",short:"f"},lines:{type:"string",short:"n"},help:{type:"boolean",short:"h"}}})}catch(error2){throw exitError(1,`${error2.message}
|
|
317
|
+
`)}await api.report(event.runId,report,event.seq)}catch(error2){if(!isRefusal(error2)){retryTimer=setTimeout(()=>{retryTimer=null,drain()},retryMs),retryTimer.unref?.();return}log2(`Ando refused a report on ${event.runId}; dropping it.`)}queue.shift(),host.ackRunEvents([event.seq])}}finally{draining=!1}}}function enqueue(event){event.workspaceId===workspaceId&&(event.seq<=lastSeq||(lastSeq=event.seq,event.kind==="session"&&event.sessionId!=null&&sessions.set(event.runId,event.sessionId),ENDINGS.has(event.kind)&&ended.add(event.runId),queue.push(event)))}async function endRefusedStart(runId,sessionId,status){ended.has(runId)||host.runState().events.some(event=>event.runId===runId&&ENDINGS.has(event.kind))||await api.report(runId,{kind:"failed",session_id:sessionId,error:REFUSED_START_ERRORS[status]}).catch(error2=>{if(!isRefusal(error2))throw error2}),ended.add(runId)}function stop(run2){if(stopped.has(run2.run_id))return;stopped.add(run2.run_id);let pendingStart=starting.get(run2.run_id);pendingStart!=null&&host.stopRun({runId:run2.run_id})||(async()=>{await pendingStart,!ended.has(run2.run_id)&&(host.stopRun({runId:run2.run_id})||await api.report(run2.run_id,{kind:"stopped",session_id:run2.session_id}))})().catch(error2=>{isRefusal(error2)||(stopped.delete(run2.run_id),later(()=>onRuns(latestRuns)))})}function start(run2){handed.add(run2.run_id);let work=(async()=>{let claimed=run2.status==="queued"?await api.claim(run2.run_id):run2;if(claimed==null)return;let midTurnSessionId=claimed.session_id??sessions.get(claimed.run_id)??null,sessionId=midTurnSessionId??claimed.continued_session_id??null,{status}=await host.startRun({...host.readRunFile!=null&&api.uploadResultFile!=null?{returnFiles:!0}:{},runId:claimed.run_id,workspaceId,ownerId:null,provider:claimed.provider,folder:claimed.folder,prompt:claimed.prompt,sessionId,continuedSessionId:claimed.continued_session_id??null,continuedFromRunId:claimed.continued_from_run_id??null,continuedUsageBaseline:claimed.continued_usage_baseline==null?null:fromUsage(claimed.continued_usage_baseline),checkoutRunId:claimed.checkout_run_id??null,midTurnRestart:midTurnSessionId!=null,agentName:claimed.agent_name,...claimed.post_as_owner===!0?{postAsOwner:!0}:{},policy:claimed.policy,servers:claimed.servers,...claimed.effort==null?{}:{effort:claimed.effort},...claimed.model==null?{}:{model:claimed.model}});status==="started"||status==="running"||status!=="finished"&&await endRefusedStart(claimed.run_id,sessionId,status)})().catch(error2=>{log2(`Couldn't start ${run2.run_id}: ${String(error2)}`),handed.delete(run2.run_id),later(()=>onRuns(latestRuns))});starting.set(run2.run_id,work),work.then(()=>{starting.get(run2.run_id)===work&&starting.delete(run2.run_id)})}function onRuns(runs){latestRuns=runs;for(let run2 of runs)ended.has(run2.run_id)||(run2.stop_requested?stop(run2):handed.has(run2.run_id)||start(run2))}function saveContext(runId,through){api.markContext(runId,through).catch(()=>{later(()=>saveContext(runId,through))})}function onThreads(threads){latestThreads=threads;for(let thread of threads){let runId=thread.run_id;if(delivering.has(runId))continue;if(thread.messages.length===0){saveContext(runId,thread.scanned_through);continue}let key=id=>`${runId}:${id}`,fresh=thread.messages.filter(message=>!sent.has(key(message.id))).sort((a,b)=>a.created_at-b.created_at);fresh.length!==0&&(delivering.add(runId),(async()=>{for(let batch of steerBatches(fresh)){if(!await Promise.resolve(host.steerRun({runId,text:steerText(batch)})).catch(()=>!1))return!1;for(let message of batch)sent.add(key(message.id));saveContext(runId,thread.messages.every(message=>sent.has(key(message.id)))?thread.scanned_through:Math.max(...batch.map(message=>message.created_at)))}return!0})().then(delivered=>{delivering.delete(runId),delivered||later(()=>onThreads(latestThreads))}))}}let answered=new Set;function onSessionRequests(requests){if(!(host.readSessions==null||api.answerSessionRequest==null))for(let request of requests)answered.has(request.request_id)||(answered.add(request.request_id),(async()=>{let answer=await host.readSessions(request).catch(error2=>({status:"failed",error:`The Ando connector couldn't read the session: ${error2 instanceof Error?error2.message:String(error2)}`}));await api.answerSessionRequest(request.request_id,answer)})().catch(error2=>{isRefusal(error2)||answered.delete(request.request_id)}))}function load(){let state=host.runState();for(let id of state.active)handed.add(id);for(let event of[...state.events].sort((a,b)=>a.seq-b.seq))enqueue(event);drain()}return{load,onRuns,onThreads,onSessionRequests,onEvent(event){enqueue(event),drain()},activeRunIds(){let state=host.runState();return[...new Set([...state.active,...state.events.map(event=>event.runId)])]},close(){closed=!0,retryTimer!=null&&clearTimeout(retryTimer)}}}var ENDINGS,MAX_STEER_CHARS,STEER_HEADER,RETRY_MS,REFUSED_START_ERRORS,init_agent=__esm({"../machine/src/agent.ts"(){"use strict";ENDINGS=new Set(["done","failed","stopped"]),MAX_STEER_CHARS=2e4,STEER_HEADER="New in the task's thread in Ando:",RETRY_MS=1e4,REFUSED_START_ERRORS={invalid:"The Ando connector couldn't read this task, so nothing ran.",failed:"The Ando connector couldn't start this task, so nothing ran."}}});async function clearFinishedCheckouts(input){let ended=input.host.endedCheckouts(),cleared=[];for(let start=0;start<ended.length;start+=50){let batch=ended.slice(start,start+50),asked=new Set(batch),finished=(await input.finished(batch)).filter(id=>asked.has(id));finished.length>0&&cleared.push(...input.host.clearFinishedCheckouts(finished))}return cleared}var init_checkout_retirement=__esm({"../machine/src/checkout-retirement.ts"(){"use strict"}});import{spawnSync as spawnSync3}from"node:child_process";import{existsSync as existsSync4,realpathSync as realpathSync2}from"node:fs";function usableFolders(folders,mode=null){for(let folder of folders)if(!existsSync4(folder))throw exitError(1,`${folder} doesn't exist here.`);let absolute=[...new Set(folders.map(folder=>realpathSync2(folder)))];for(let folder of absolute)if(holdsHome(folder))throw exitError(1,`Tasks can write the folders they work in, so ${folder} can't be one: it holds your home folder. Run this from a project folder.`);let autoInPlace=[];for(let folder of absolute){let top=spawnSync3("git",["-C",folder,"rev-parse","--show-toplevel"],{encoding:"utf8"});if(top.status!==0){if(mode==="checkout")throw exitError(1,`${folder} isn't a git repository. Tasks only work in a checkout of their own in a git repository; drop --checkout to run in place.`);autoInPlace.push(folder);continue}let repoRoot=realpathSync2(top.stdout.trim());if(repoRoot!==folder&&mode!=="in-place")throw exitError(1,`${folder} is inside a repository (${repoRoot}). Connect the repository's own folder, or pass --in-place.`)}return{absolute,inPlace:mode==="in-place"?absolute:autoInPlace}}function mergeInPlaceFolders(existing,folders,autoInPlace,mode){let next=new Set(existing??[]);for(let folder of autoInPlace)next.add(folder);if(mode==="in-place")for(let folder of folders)next.add(folder);else if(mode==="checkout")for(let folder of folders)next.delete(folder);return[...next]}function mergeHookFolders(existing,folders,hooks){let next=new Set(existing??[]);if(hooks===!0)for(let folder of folders)next.add(folder);if(hooks===!1)for(let folder of folders)next.delete(folder);return[...next]}var init_folders=__esm({"../machine/src/folders.ts"(){"use strict";init_config();init_runtime()}});function browserOpener(url2,where){let{platform,env,interactive,find}=where;if(!interactive||env.SSH_CONNECTION||env.SSH_TTY||env.SSH_CLIENT)return null;if(platform==="darwin")return{command:"/usr/bin/open",args:[url2]};if(platform==="win32"){let root=env.SystemRoot||env.windir;return root==null?null:{command:`${root}\\System32\\rundll32.exe`,args:["url.dll,FileProtocolHandler",url2]}}if(!env.DISPLAY&&!env.WAYLAND_DISPLAY)return null;let command=find("xdg-open");return command==null?null:{command,args:[url2]}}function openOnEnter(input,open3){let opened=!1,onData=chunk=>{opened||!/[\r\n]/.test(String(chunk))||(opened=!0,open3())};return input.on("data",onData),input.resume(),()=>{input.off("data",onData),input.pause()}}function openLink(opener,start,cantOpen){let said=!1,failed=()=>{said||(said=!0,cantOpen())};try{let child=start(opener.command,opener.args);child.on("error",failed),child.on("exit",code2=>{code2!==0&&code2!=null&&failed()}),child.unref()}catch{failed()}}var init_open_link=__esm({"../machine/src/open-link.ts"(){"use strict"}});import{randomUUID as randomUUID2}from"node:crypto";import{existsSync as existsSync5,rmSync as rmSync2}from"node:fs";import{join as join13}from"node:path";async function selfCheck(input){let runId=randomUUID2(),ending=input.ended(runId),checkoutDir=input.checkoutRoot==null?null:join13(input.checkoutRoot,runId),markName=checkoutDir==null?`${MARK}-${runId}`:MARK,markPath=join13(checkoutDir??input.folder,markName);try{let{status}=await input.startRun({runId,workspaceId:WORKSPACE,provider:input.provider,folder:input.folder,prompt:`Run this exact shell command with your shell tool, then reply done: touch ${markName}`,policy:{network:"never"},bareCheckout:!0,servers:[]});if(status!=="started"&&status!=="finished")return{ok:!1,reason:`the task couldn't start (${status})`};let timer,timedOut=new Promise(resolve4=>{timer=setTimeout(()=>resolve4({kind:"timeout"}),input.waitMs??WAIT_MS)}),end=await Promise.race([ending,timedOut]);return clearTimeout(timer),end.kind==="timeout"?{ok:!1,reason:"the task didn't finish in time"}:end.kind!=="done"?{ok:!1,reason:end.error??`the task ${end.kind}`}:existsSync5(markPath)?{ok:!0}:{ok:!1,reason:"the task said it was done, but its command didn't run, so its sandbox isn't working here"}}finally{checkoutDir!=null?(rmSync2(checkoutDir,{recursive:!0,force:!0}),rmSync2(`${checkoutDir}.ended`,{force:!0}),rmSync2(`${checkoutDir}.task.json`,{force:!0})):rmSync2(markPath,{force:!0})}}var WAIT_MS,MARK,WORKSPACE,ENDINGS2,isEnding,init_self_check=__esm({"../machine/src/self-check.ts"(){"use strict";WAIT_MS=12e4,MARK=".ando-check",WORKSPACE="self-check",ENDINGS2=new Set(["done","failed","stopped"]);isEnding=kind=>ENDINGS2.has(kind)}});import{spawn as spawn4,spawnSync as spawnSync4}from"node:child_process";import{createHash as createHash5,randomBytes as randomBytes2}from"node:crypto";import{hostname as hostname2}from"node:os";import{join as join14}from"node:path";function linuxSandboxProblem(deps2,env){if(process.platform!=="linux")return null;let missing=["bwrap","socat"].filter(tool=>deps2.findCommand(tool,env.PATH)==null);if(missing.length>0)return`Claude Code tasks here need ${missing.join(" and ")}. Install them with: sudo apt-get install -y bubblewrap socat`;let bwrap=deps2.findCommand("bwrap",env.PATH),tried=spawnSync4(bwrap,["--unshare-user","--ro-bind","/","/","--dev","/dev","true"],{encoding:"utf8",timeout:1e4});return tried.status===0?null:/permission|not permitted|setting up uid map/i.test(tried.stderr??"")?BWRAP_APPARMOR_FIX:`Claude Code's sandbox can't start here: ${(tried.stderr??"").trim()}`}async function fromApproval(deps2,client){let secret=randomBytes2(32).toString("hex"),request=createHash5("sha256").update(secret).digest("hex"),code2=approvalCode(request),appUrl=process.env.ANDO_APP_URL??DEFAULT_APP_URL,name=encodeURIComponent(hostname2().slice(0,80)),link2=`${appUrl}/connect/machine?request=${request}&name=${name}`,heading="Approve this device in your browser, from anywhere:";log(heading,"plain",terminal.strong(heading)),log(` ${link2}`,"plain",` ${terminal.link(link2)}`),log(` Check it shows this code: ${code2}`,"plain",` Check it shows this code: ${terminal.strong(code2)}`);let opener=browserOpener(link2,{platform:process.platform,env:process.env,interactive:process.stdin.isTTY===!0&&process.stdout.isTTY===!0,find:command=>deps2.findCommand(command,process.env.PATH)});console.log(opener==null?terminal.quiet("Waiting for your approval..."):`Press ${terminal.strong("Enter")} to open it in this computer's browser. ${terminal.quiet("Waiting for your approval...")}`);let stopListening=opener==null?()=>{}:openOnEnter(process.stdin,()=>openLink(opener,(command,args)=>spawn4(command,args,{detached:!0,stdio:"ignore"}),()=>console.log(terminal.line("warn","Couldn't open a browser here. Use the link above."))));try{let expiresAt=Date.now()+APPROVAL_WAIT_MS;for(;Date.now()<expiresAt;){let machine=await withinTimeout(client.mutation(deps2.web.machineCollectConnect,{secret}),"Couldn't reach Ando.");if(machine!=null)return machine;await new Promise(done=>setTimeout(done,APPROVAL_POLL_MS))}throw exitError(4,"The approval link expired. Run this again.")}finally{stopListening()}}async function openSetup(deps2,folders,inPlaceFolders=[],isolated=!1){let endings=new Map,host=deps2.createHost(event=>{host.ackRunEvents([event.seq]),isEnding(event.kind)&&endings.get(event.runId)?.(event)},()=>folders,()=>inPlaceFolders,void 0,isolated?join14(stateDirectory(process.env),"setup-check"):stateDirectory(process.env)),{tools,signedOut}=await host.machine.get(),sandboxProblem=linuxSandboxProblem(deps2,host.env()),ready=tools.filter(tool=>!signedOut.includes(tool)&&!refusedHere(tool)&&(tool!=="claude-code"||sandboxProblem==null));if(tools.some(tool=>process.platform==="linux"&&tool==="codex")&&logger.warn(CODEX_ON_LINUX),tools.some(tool=>!isLegacyProvider(tool))&&logger.warn(ACP_ON_SERVER),sandboxProblem!=null&&tools.includes("claude-code")&&logger.warn(sandboxProblem),ready.length===0)throw host.stopAll(),new Error(tools.length===0?"Install Claude Code or Codex here first.":"Nothing here can take tasks yet. Fix what's above, or sign in (claude auth login or codex login), then connect again.");return{host,endings,ready}}async function proveTasksRun(setup,folder,inPlace=!1){log("Checking that a task really runs here...","step");let startedAt=Date.now(),check2=await selfCheck({provider:setup.ready[0],folder,checkoutRoot:inPlace?null:CHECKOUT_ROOT,startRun:setup.host.startRun,ended:runId=>new Promise(resolve4=>setup.endings.set(runId,resolve4))});if(!check2.ok)throw new Error(`This device is connected, but it can't run tasks yet: ${check2.reason}. Fix that, then run ando up.`);let seconds=Math.max(1,Math.round((Date.now()-startedAt)/1e3));log(`A real task ran here, in ${seconds}s. This device is ready.`,"ok")}async function connectPendingTools(deps2,config2,client){if(config2.pendingTools==null)return config2;let{folders}=config2.pendingTools,providers=config2.pendingTools.providers;for(;providers.length>0;){let[provider,...rest]=providers;try{await withinTimeout(client.mutation(deps2.web.machineConnectTool,{token:config2.token,provider,folders}),`Couldn't reach Ando at ${config2.url}.`)}catch(error2){if(provider!=null&&!isLegacyProvider(provider)&&isValidatorSkewError(error2))logger.warn(`Ando hasn't rolled out ${provider} on this backend yet; skipping it for now.`);else throw error2}providers=rest;let next={...config2};providers.length>0?next.pendingTools={providers,folders}:delete next.pendingTools,await writeConfig(configPath2(process.env),next)}let finished={...config2};return delete finished.pendingTools,finished}async function connect(deps2,getMachine,url2,folders,timeout=CONNECT_TIMEOUT_MS2,mode=null,hooks=null){if(folders.length===0)throw exitError(1,"Name a folder tasks may use, with --folder <path>.");let{absolute,inPlace}=usableFolders(folders,mode),inPlaceFolders=mergeInPlaceFolders(void 0,absolute,inPlace,mode),hookFolders=mergeHookFolders(void 0,absolute,hooks),setup=await openSetup(deps2,absolute,inPlaceFolders),client=deps2.newClient(url2);try{let machine=await withinTimeout(getMachine(client),`Couldn't reach Ando at ${url2}.`,timeout),config2={url:url2,token:machine.token,workspaceId:machine.workspace_id,machineId:machine.machine_id,machineName:machine.machine_name,pendingTools:{providers:setup.ready,folders:absolute},...inPlaceFolders.length>0?{inPlaceFolders}:{},...hookFolders.length>0?{hookFolders}:{}};await writeConfig(configPath2(process.env),config2);let connected=await connectPendingTools(deps2,config2,client);await proveTasksRun(setup,absolute[0],inPlaceFolders.includes(absolute[0]));let checked={...connected,checked:!0};return await writeConfig(configPath2(process.env),checked),checked}finally{setup.host.stopAll(),client.close()}}async function connectedFolders(deps2,client,token){return(await withinTimeout(client.query(deps2.web.machineConnections,{token}),"Couldn't reach Ando.")).map(row=>({provider:row.provider_url.replace("local-tool://",""),folders:row.folders}))}function buildUpdatedConfig(current,inPlaceFolders,hookFolders){let inPlaceChanged=JSON.stringify(inPlaceFolders)!==JSON.stringify(current.inPlaceFolders??[]),hooksChanged=JSON.stringify(hookFolders)!==JSON.stringify(current.hookFolders??[]),nextConfig={...current};return inPlaceFolders.length>0?nextConfig.inPlaceFolders=inPlaceFolders:delete nextConfig.inPlaceFolders,hookFolders.length>0?nextConfig.hookFolders=hookFolders:delete nextConfig.hookFolders,{nextConfig,inPlaceChanged,hooksChanged}}async function bringUpToDate(deps2,config2,folders,canCheck,mode=null,hooks=null){let{absolute,inPlace}=usableFolders(folders,mode),client=deps2.newClient(config2.url),setup=null;try{let current=await connectPendingTools(deps2,config2,client),tools=await connectedFolders(deps2,client,current.token),known=[...new Set(tools.flatMap(tool=>tool.folders))],added=absolute.filter(folder=>!known.includes(folder)),all=[...known,...added],inPlaceFolders=mergeInPlaceFolders(current.inPlaceFolders,absolute,inPlace,mode),hookFolders=mergeHookFolders(current.hookFolders,absolute,hooks),{nextConfig,inPlaceChanged,hooksChanged}=buildUpdatedConfig(current,inPlaceFolders,hookFolders);if((inPlaceChanged||hooksChanged)&&await writeConfig(configPath2(process.env),nextConfig),hooksChanged)for(let folder of absolute)log(hookFolders.includes(folder)?`${folder}'s own Claude Code hooks will now run in tasks, outside their sandbox.`:`${folder}'s own Claude Code hooks won't run in tasks.`,"ok");if(needsToolSetup({canCheck,checked:nextConfig.checked===!0,toolsConnected:tools.length,knownFolders:known.length,addedFolders:added.length})&&(setup=await openSetup(deps2,all,inPlaceFolders,!canCheck)),await syncAddedFolders(deps2,client,nextConfig,tools,setup?.ready??[],absolute,added,inPlaceFolders,inPlaceChanged),setup==null)return nextConfig;let checkFolder=added[0]??all[0];await proveTasksRun(setup,checkFolder,inPlaceFolders.includes(checkFolder));let checked={...nextConfig,checked:!0};return await writeConfig(configPath2(process.env),checked),checked}finally{setup?.host.stopAll(),client.close()}}async function syncAddedFolders(deps2,client,nextConfig,tools,readyProviders,absolute,added,inPlaceFolders,inPlaceChanged){if(added.length>0){let targets=tools.length>0?tools:readyProviders.map(provider=>({provider,folders:[]}));if(targets.length===0)throw new Error("No tool is connected on this device. Connect one in Studio \u203A Devices first.");await Promise.all(targets.map(target=>withinTimeout(client.mutation(deps2.web.machineConnectTool,{token:nextConfig.token,provider:target.provider,folders:[...target.folders,...added]}),`Couldn't reach Ando at ${nextConfig.url}.`)));for(let folder of added)log(`Agents can now work in ${folder}${inPlaceFolders.includes(folder)?" (in place)":""}.`,"ok")}else if(inPlaceChanged)for(let folder of absolute)log(`Tasks in ${folder} will now run ${inPlaceFolders.includes(folder)?"in the folder itself":"in their own checkout"}.`,"ok")}async function connectMcpEndpoint(deps2,runForeground,saved,state,url2,endpoint,name,foreground){let device=saved;if(!device){let releasePairing=await lockMachine(state),pairing=deps2.newClient(url2);try{if(device=await readConfig(configPath2(process.env)),!device){let machine=await withinTimeout(fromApproval(deps2,pairing),"Device pairing timed out.",APPROVAL_TIMEOUT_MS);device={url:url2,token:machine.token,workspaceId:machine.workspace_id,machineId:machine.machine_id,machineName:machine.machine_name},await writeConfig(configPath2(process.env),device)}}finally{pairing.close(),await releasePairing()}}let registry2=deps2.deviceMcpRegistry(state),scope=JSON.stringify([device.url,device.workspaceId,device.machineId]),entry=await registry2.add(scope,name,endpoint),client=deps2.newClient(device.url);try{await withinTimeout(client.mutation(deps2.web.machineRegisterMcpServer,{token:device.token,...entry}),"Server registration timed out.")}finally{client.close()}log("Registered "+entry.name+" on this device.","ok");let running=await runningConnector(state);if(running!=null){let ready=readReady();if(ready?.pid!==running||!ready.deviceMcpRelay)throw new Error("The running connector does not advertise device MCP support. Run ando stop, then repeat this command with the updated CLI.");return}let release=await lockMachine(state);try{if(foreground)return await runForeground(device,release)}finally{await release()}let service=detectService();return service?await keepRunning(deps2,service,null):await detach()}var fromCode,init_setup=__esm({"../machine/src/setup.ts"(){"use strict";init_commands();init_config();init_folders();init_open_link();init_runtime();init_self_check();init_service();fromCode=(deps2,code2)=>async client=>{try{return await client.mutation(deps2.web.machineRedeemConnectCode,{code:code2,hostname:hostname2().slice(0,80)})}catch(error2){if(!isValidatorSkewError(error2)||!/extra field [`'" ]*hostname\b/i.test(String(error2)))throw error2;return await client.mutation(deps2.web.machineRedeemConnectCode,{code:code2})}}}});async function runConnector(deps2,config2,release,version3){let client=deps2.newClient(config2.url);await connectPendingTools(deps2,config2,client);let{token,workspaceId}=config2,stopMcp=deps2.startDeviceMcpRunner({registry:deps2.deviceMcpRegistry(stateDirectory(process.env)),localScope:JSON.stringify([config2.url,workspaceId,config2.machineId]),client,web:deps2.web,scope:{token},log:error2=>logger.warn("Device MCP relay could not report to Ando.",error2)}),folders=[],inPlaceFolders=config2.inPlaceFolders??[],hookFolders=config2.hookFolders??[],folderSeq=0,readFolders=async()=>{let seq=++folderSeq,[connections,latestConfig]=await Promise.all([client.query(deps2.web.machineConnections,{token}),readConfig(configPath2(process.env))]),next=[...new Set(connections.flatMap(row=>row.folders))];return seq===folderSeq&&(folders=next,inPlaceFolders=latestConfig?latestConfig.inPlaceFolders??[]:inPlaceFolders,hookFolders=latestConfig?latestConfig.hookFolders??[]:hookFolders),folders};await withinTimeout(readFolders(),`Couldn't reach Ando at ${config2.url}.`);let agent=null,host=deps2.createHost(event=>{event.kind==="session"&&event.sessionId!=null&&recordTask(event.runId,{sessionId:event.sessionId}),event.kind==="started"&&(recordTask(event.runId,{status:"running"}),log(`Task ${event.runId.slice(0,8)} started.`,"step")),(event.kind==="done"||event.kind==="failed"||event.kind==="stopped")&&(recordTask(event.runId,{status:event.kind,endedAt:Date.now()}),log(`Task ${event.runId.slice(0,8)} ${event.kind}.`,event.kind==="done"?"ok":event.kind==="failed"?"fail":"plain")),agent?.onEvent(event)},()=>folders,()=>inPlaceFolders,()=>hookFolders),startRun=host.startRun;host.startRun=async input=>typeof input.folder=="string"&&holdsHome(input.folder)?{status:"failed"}:refusedHere(String(input.provider))?(log(CODEX_ON_LINUX,"warn"),{status:"failed"}):(typeof input.runId=="string"&&recordTask(input.runId,{provider:String(input.provider),folder:String(input.folder),...typeof input.checkoutRunId=="string"?{checkoutRunId:input.checkoutRunId}:{},status:"running",startedAt:Date.now()}),startRun(input)),agent=createMachineAgent({workspaceId,host,log,isRefusal:error2=>deps2.isConvexError(error2),api:{uploadResultFile:(runId,file,dataBase64)=>client.action(deps2.uploadResultFileFn,{scope:{token},runId,slot:file.slot,sha256:file.sha256,filename:file.filename,contentType:file.contentType,dataBase64}),claim:async runId=>(await readFolders(),client.mutation(deps2.web.machineClaimRun,{token,runId})),report:async(runId,event,eventSeq)=>{await client.mutation(deps2.web.machineReportRun,{token,runId,event,...eventSeq==null?{}:{eventSeq}})},markContext:async(runId,through)=>{await client.mutation(deps2.web.machineMarkRunContext,{token,runId,through})},answerSessionRequest:async(requestId,answer)=>{await client.mutation(deps2.web.machineAnswerSessionRequest,{token,requestId,...answer.status==="done"?{result:answer.result}:{error:answer.error}})}}}),agent.load();let unsubscribe=()=>{},resubscribing,fail=error2=>{if(deps2.isConvexError(error2)){logger.error("Ando stopped this machine's connection",error2),shutdown(0);return}logger.warn("Lost sight of Ando's tasks; trying again",error2),clearTimeout(resubscribing),resubscribing=setTimeout(subscribe,RESUBSCRIBE_MS)};function subscribe(){unsubscribe();let runs=client.onUpdate(deps2.web.machineRuns,{token},rows=>agent?.onRuns(rows),fail),threads=client.onUpdate(deps2.web.machineRunThreadContext,{token},rows=>agent?.onThreads(rows),fail),sessions=client.onUpdate(deps2.web.machineSessionRequests,{token},rows=>agent?.onSessionRequests(rows),fail);unsubscribe=()=>{runs(),threads(),sessions()}}subscribe();let writeReady=()=>saveReady({pid:process.pid,deviceMcpRelay:!0,version:version3,folders,...inPlaceFolders.length>0?{inPlaceFolders}:{},...hookFolders.length>0?{hookFolders}:{}}),heartbeat=async()=>{try{let[described]=await Promise.all([host.machine.get(),readFolders()]);writeReady();let remotes=await deps2.readFolderRemotes(folders,{env:host.env()}),activeRunIds=agent?.activeRunIds()??[],baseReport={token,remotes,activeRunIds,sleeping:!1,sessionReads:typeof host.readSessions=="function",...described.key==null?{}:{machineKey:described.key}};try{await client.mutation(deps2.web.machineReport,{...baseReport,taskSettings:!0,effortUnsupported:described.effortUnsupported??[],signedOutProviders:described.signedOut,servers:Object.entries(described.servers).map(([provider,names])=>({provider,names})),...described.models==null?{}:{models:Object.entries(described.models).map(([provider,models])=>({provider,models}))}})}catch(error2){if(!isValidatorSkewError(error2))throw error2;await client.mutation(deps2.web.machineReport,{...baseReport,signedOutProviders:described.signedOut.filter(isLegacyProvider),servers:Object.entries(described.servers).filter(([provider])=>isLegacyProvider(provider)).map(([provider,names])=>({provider,names}))})}}catch(error2){logger.warn("Couldn't report in to Ando; trying again",error2)}};heartbeat();let timer=setInterval(()=>{heartbeat()},HEARTBEAT_MS),clearCheckouts=async()=>{try{let cleared=await clearFinishedCheckouts({host,finished:async checkoutIds=>await client.query(deps2.web.machineFinishedCheckouts,{token,checkoutIds})});cleared.length>0&&logger.info(`Cleared ${cleared.length} ${cleared.length===1?"checkout":"checkouts"} whose thread is finished.`)}catch(error2){logger.warn("Couldn't check for finished threads' checkouts",error2)}};clearCheckouts();let checkoutTimer=setInterval(()=>{clearCheckouts()},CHECKOUT_CLEAR_MS),stopping=!1;function shutdown(code2){stopping||(stopping=!0,clearInterval(timer),clearInterval(checkoutTimer),stopMcp(),clearTimeout(resubscribing),unsubscribe(),agent?.close(),host.stopAll(),Promise.allSettled([client.close(),release()]).finally(()=>process.exit(code2)))}process.on("SIGTERM",()=>shutdown(0)),process.on("SIGINT",()=>shutdown(0)),writeReady(),log(`${config2.machineName} is ready for tasks.`,"ok"),await new Promise(()=>{})}var init_runner=__esm({"../machine/src/runner.ts"(){"use strict";init_agent();init_checkout_retirement();init_config();init_runtime();init_setup()}});var cli_exports={};__export(cli_exports,{convexErrorExitCode:()=>convexErrorExitCode,runMachine:()=>runMachine,usableFolders:()=>usableFolders});import{spawn as spawn5,spawnSync as spawnSync5}from"node:child_process";import{homedir as homedir7}from"node:os";import{resolve as resolve3}from"node:path";import{parseArgs as parseArgs5}from"node:util";function parseMachineArgs(argv){try{return parseArgs5({args:argv,allowPositionals:!0,options:{url:{type:"string"},mcp:{type:"string"},name:{type:"string"},folder:{type:"string",multiple:!0},"in-place":{type:"boolean"},checkout:{type:"boolean"},hooks:{type:"boolean"},"no-hooks":{type:"boolean"},foreground:{type:"boolean"},json:{type:"boolean"},follow:{type:"boolean",short:"f"},lines:{type:"string",short:"n"},help:{type:"boolean",short:"h"}}})}catch(error2){throw exitError(1,`${error2.message}
|
|
318
318
|
Run \`ando up --help\`.`,error2)}}function resolveDefaultFolders(given,here,mode){if(given.length>0)return given;let repository=spawnSync5("git",["rev-parse","--show-toplevel"],{encoding:"utf8"}),top=repository.status===0?repository.stdout.trim():null;return top!=null&&!holdsHome(top)?[top]:mode==="in-place"&&!holdsHome(here)?[here]:[]}async function handleAlreadyRunningUp(saved,running,folders,mode,hooks,foreground,version3){await bringUpToDate(deps,saved,folders,!1,mode,hooks);let service=installedService(process.env);if(!foreground&&service!=null&&serviceIsRunning(service)){await keepRunning(deps,service,running);return}let runningVersion=readReady()?.version;if(runningVersion!=null&&runningVersion!==version3)throw new Error(`The connector running here is ${runningVersion}, so this one (${version3}) hasn't taken over. Run ando stop, then start it again.`);log(`The connector is already running (process ${running}).`)}async function resolveStartConfig(input){if(input.command==="connect"){if(input.code==null||input.url==null)throw exitError(1,USAGE);return connect(deps,fromCode(deps,input.code),input.url,input.folders,CONNECT_TIMEOUT_MS2,input.mode,input.hooks)}if(input.saved!=null)return input.command==="up"?bringUpToDate(deps,input.saved,input.folders,!0,input.mode,input.hooks):input.saved;if(input.command==="up")return connect(deps,client=>fromApproval(deps,client),input.url??DEFAULT_URL,input.folders,APPROVAL_TIMEOUT_MS,input.mode,input.hooks);throw exitError(2,"Not connected yet. Run ando up in a repository.")}async function startConnector(input){let state=stateDirectory(process.env),saved=await readConfig(configPath2(process.env));if(input.mcp!=null){if(input.command!=="up"||!input.name)throw exitError(1,"Use ando up --mcp <url> --name <name>.");return connectMcpEndpoint(deps,(device,release2)=>runConnector(deps,device,release2,input.version),saved,state,input.url??DEFAULT_URL,input.mcp,input.name,input.foreground)}let running=await runningConnector(state);if(input.command==="up"&&saved!=null&&running!=null)return handleAlreadyRunningUp(saved,running,input.folders,input.mode,input.hooks,input.foreground,input.version);input.command==="run"&&Object.assign(process.env,readCarriedEnv());let release=await lockMachine(state);try{let config2=await resolveStartConfig({command:input.command,saved,code:input.code,url:input.url,folders:input.folders,mode:input.mode,hooks:input.hooks}),kind=input.command==="run"||input.foreground?null:detectService();if(kind!=null){await release(),await keepRunning(deps,kind,null);return}if(input.command==="connect"){await release(),await detach();return}input.command==="up"&&!input.foreground&&log(foregroundReason()),await runConnector(deps,config2,release,input.version)}catch(error2){throw await release(),error2}}async function runMachine(argv,version3){let{positionals,values}=parseMachineArgs(argv);if(values["in-place"]===!0&&values.checkout===!0)throw exitError(1,"Pass either --in-place or --checkout, not both.");let mode=values["in-place"]===!0?"in-place":values.checkout===!0?"checkout":null;if(values.hooks===!0&&values["no-hooks"]===!0)throw exitError(1,"Pass either --hooks or --no-hooks, not both.");let hooks=values.hooks===!0?!0:values["no-hooks"]===!0?!1:null,[command,target]=positionals,here=process.cwd();process.env.PATH=(0,import_command_env.trustedPath)(process.env.PATH??"",holdsHome(here)?[]:[here]);let code2=process.env.ANDO_MACHINE_CODE?.trim()||null;if(delete process.env.ANDO_MACHINE_CODE,values.help||command==null){console.log(USAGE);return}if(command==="status")return printStatus(values.json===!0);if(command==="logs")return printLogs(values.follow===!0,values.lines);if(command==="stop")return stopConnector();if(command==="attach")return attach(target);if(command==="update")return update();if(command!=="up"&&command!=="connect"&&command!=="run")throw exitError(1,USAGE);let given=(values.folder??[]).map(folder=>resolve3(folder)),folders=resolveDefaultFolders(given,here,mode);process.chdir(homedir7());try{await startConnector({command,version:version3,code:code2,url:values.url,mcp:values.mcp,name:values.name,folders,mode,hooks,foreground:values.foreground===!0})}catch(error2){throw error2 instanceof ConvexError&&error2.data?.message!=null?exitError(convexErrorExitCode(error2.data),String(error2.data.message),error2):error2}}var import_device_mcp_runner,import_device_mcp_registry,import_host,import_remotes,import_toolchain,import_command_env,web,USAGE,deps,init_cli=__esm({"../machine/src/cli.ts"(){"use strict";init_simple_client();init_api();init_errors();import_device_mcp_runner=__toESM(require_device_mcp_runner(),1),import_device_mcp_registry=__toESM(require_device_mcp_registry(),1),import_host=__toESM(require_host(),1),import_remotes=__toESM(require_remotes(),1),import_toolchain=__toESM(require_toolchain(),1),import_command_env=__toESM(require_command_env(),1);init_commands();init_config();init_runner();init_runtime();init_service();init_setup();init_folders();init_runtime();web=anyApi.web,USAGE=`Let your Ando agents work on this server. It connects out to Ando, so nothing
|
|
319
319
|
connects in, and each task works in its own checkout on its own branch (or in
|
|
320
320
|
the folder itself with --in-place).
|
|
@@ -334,8 +334,8 @@ the folder itself with --in-place).
|
|
|
334
334
|
ando update Move to the newest connector. Tasks pick up
|
|
335
335
|
where they left off.
|
|
336
336
|
ando stop Stop the connector until the next ando up.
|
|
337
|
-
`,deps={newClient:url2=>new ConvexClient(url2,{logger:!1}),web,uploadResultFileFn:anyApi.localToolResultFileUploads.upload,isConvexError:error2=>error2 instanceof ConvexError,createHost:(onEvent,taskFolders=()=>[],inPlaceFolders=()=>[],hookFolders=()=>[],directory=stateDirectory(process.env))=>(0,import_host.createLocalToolHost)({directory,appName:"Ando machine",log:logger,spawn:
|
|
338
|
-
`,{mode:384}),await chmod(temp,384),await rename(temp,path)}async function resolveConfig(env,options){let stored=await readStoredConfig(configPath(env)),apiKey=env.ANDO_API_KEY?.trim()||stored?.apiKey||(options?.readKeychain?await options.readKeychain():null);if(!apiKey)throw new CliError(ExitCode.auth,"Not logged in. Run `ando login`, or set ANDO_API_KEY.");let apiUrl=env.ANDO_API_URL?.trim()||stored?.apiUrl||DEFAULT_API_URL,webUrl=env.ANDO_WEB_URL?.trim()||stored?.webUrl||defaultWebUrl(apiUrl);return{apiKey,apiUrl,webUrl}}function defaultWebUrl(apiUrl){try{let url2=new URL(apiUrl);return url2.hostname.startsWith("api.")?`${url2.protocol}//app.${url2.hostname.slice(4)}`:null}catch{return null}}import{parseArgs as parseArgs6}from"node:util";var package_default={name:"@andocorp/cli",version:"0.5.
|
|
337
|
+
`,deps={newClient:url2=>new ConvexClient(url2,{logger:!1}),web,uploadResultFileFn:anyApi.localToolResultFileUploads.upload,isConvexError:error2=>error2 instanceof ConvexError,createHost:(onEvent,taskFolders=()=>[],inPlaceFolders=()=>[],hookFolders=()=>[],directory=stateDirectory(process.env))=>(0,import_host.createLocalToolHost)({directory,appName:"Ando machine",log:logger,spawn:spawn5,spawnSync:spawnSync5,onEvent,taskFolders,inPlaceFolders,hookFolders,checkoutRoot:CHECKOUT_ROOT}),startDeviceMcpRunner:import_device_mcp_runner.startDeviceMcpRunner,deviceMcpRegistry:import_device_mcp_registry.deviceMcpRegistry,readFolderRemotes:import_remotes.readFolderRemotes,findCommand:import_toolchain.findCommand,trustedPath:import_command_env.trustedPath}}});import{execFile}from"node:child_process";import{chmod,mkdir,readFile,rename,writeFile}from"node:fs/promises";import{homedir}from"node:os";import{dirname,join}from"node:path";import{promisify}from"node:util";var ExitCode={ok:0,usage:1,auth:2,notFound:3,timeout:4,unavailable:5},CliError=class extends Error{exitCode;constructor(exitCode2,message){super(message),this.name="CliError",this.exitCode=exitCode2}},usageError=message=>new CliError(ExitCode.usage,message),EXIT_CODES=new Set(Object.values(ExitCode));function exitCodeOf(error2){if(error2 instanceof CliError)return error2.exitCode;if(error2&&typeof error2=="object"&&"exitCode"in error2){let code2=error2.exitCode;if(typeof code2=="number"&&EXIT_CODES.has(code2))return code2}return ExitCode.unavailable}var KEY_PATTERN=/ando_sk_[A-Za-z0-9_-]+/gu;function redact(text,apiKey){let result=text;return apiKey&&apiKey.length>=8&&(result=result.split(apiKey).join("[redacted]")),result.replace(KEY_PATTERN,"[redacted]")}var execFileAsync=promisify(execFile),DEFAULT_API_URL="https://api.ando.so/v1",KEYCHAIN_ACCOUNT="ando-routines",KEYCHAIN_SERVICES=["ando-cli-key","ando-post-key"];async function readKeychainApiKey(){if(process.platform!=="darwin")return null;for(let service of KEYCHAIN_SERVICES)try{let{stdout}=await execFileAsync("security",["find-generic-password","-a",KEYCHAIN_ACCOUNT,"-s",service,"-w"],{timeout:2e3}),key=stdout.trim();if(key)return key}catch{}return null}function configPath(env){let base=env.XDG_CONFIG_HOME?.trim()||join(env.HOME||homedir(),".config");return join(base,"ando","cli.json")}async function readStoredConfig(path){let text;try{text=await readFile(path,"utf8")}catch(error2){if(error2.code==="ENOENT")return null;throw error2}let parsed;try{parsed=JSON.parse(text)}catch{throw new CliError(ExitCode.auth,`${path} is not valid JSON. Run \`ando login\` again.`)}return typeof parsed.apiKey!="string"||typeof parsed.apiUrl!="string"?null:{apiKey:parsed.apiKey,apiUrl:parsed.apiUrl,...typeof parsed.webUrl=="string"?{webUrl:parsed.webUrl}:{}}}async function writeStoredConfig(path,config2){await mkdir(dirname(path),{recursive:!0,mode:448});let temp=`${path}.${process.pid}.tmp`;await writeFile(temp,`${JSON.stringify(config2,null,2)}
|
|
338
|
+
`,{mode:384}),await chmod(temp,384),await rename(temp,path)}async function resolveConfig(env,options){let stored=await readStoredConfig(configPath(env)),apiKey=env.ANDO_API_KEY?.trim()||stored?.apiKey||(options?.readKeychain?await options.readKeychain():null);if(!apiKey)throw new CliError(ExitCode.auth,"Not logged in. Run `ando login`, or set ANDO_API_KEY.");let apiUrl=env.ANDO_API_URL?.trim()||stored?.apiUrl||DEFAULT_API_URL,webUrl=env.ANDO_WEB_URL?.trim()||stored?.webUrl||defaultWebUrl(apiUrl);return{apiKey,apiUrl,webUrl}}function defaultWebUrl(apiUrl){try{let url2=new URL(apiUrl);return url2.hostname.startsWith("api.")?`${url2.protocol}//app.${url2.hostname.slice(4)}`:url2.hostname.startsWith("staging-api.")?`${url2.protocol}//staging.${url2.hostname.slice(12)}`:null}catch{return null}}function defaultConvexUrl(apiUrl){try{let url2=new URL(apiUrl);return url2.hostname.startsWith("api.")?`${url2.protocol}//data.${url2.hostname.slice(4)}`:url2.hostname.startsWith("staging-api.")?`${url2.protocol}//staging-data.${url2.hostname.slice(12)}`:null}catch{return null}}import{parseArgs as parseArgs6}from"node:util";var package_default={name:"@andocorp/cli",version:"0.5.17",description:"Use Ando from a terminal: post to channels, ask agents, and let agents work on your server.",license:"UNLICENSED",type:"module",bin:{ando:"./dist/cli.js"},files:["dist","README.md"],engines:{node:">=22"},keywords:["ando","agents","ai-agents","claude-code","codex","mcp","cli","team-chat"],homepage:"https://docs.ando.so/docs/connecting-apps-to-ando/claude-code-on-a-server",scripts:{build:"node scripts/build.mjs",test:"node --experimental-strip-types --no-warnings=ExperimentalWarning --test src/*.test.ts scripts/*.test.mjs",typecheck:"tsrs --noEmit -p tsconfig.json","pack:npm":"node scripts/pack-npm.mjs",prepack:"pnpm run build"},devDependencies:{"@ando/machine":"workspace:*","@andocorp/sdk":"workspace:*","@types/node":"^24.7.1",esbuild:"catalog:",tsrs:"0.18.0-ts7.1.0-dev.20260929",typescript:"catalog:typescript-core","proper-lockfile":"4.1.2"},publishConfig:{access:"public"},gitHead:"2b6649a88e6f8f79742b5390679fae0d17552925",andoCliSourceHash:"847504c6c3825f0e609bebd21c7e1db9bd48c5ac974dea7e26664d82fbc63ba6"};var import_proper_lockfile2=__toESM(require_proper_lockfile(),1);import{createHash}from"node:crypto";import{chmod as chmod3,mkdir as mkdir3,readdir,readFile as readFile3,rename as rename3,rm as rm2,stat,writeFile as writeFile3}from"node:fs/promises";import{homedir as homedir2}from"node:os";import{dirname as dirname4,join as join4}from"node:path";import{parseArgs as parseArgs2}from"node:util";import{dirname as dirname2,join as join2}from"node:path";function sanitizeMembershipFilename(id){return id.replace(/[^A-Za-z0-9_.-]/gu,"_")}function agentCredentialsDir(env){return join2(dirname2(configPath(env)),"agents")}function agentCredentialFilePath(env,agentMembershipId){return join2(agentCredentialsDir(env),`${sanitizeMembershipFilename(agentMembershipId)}.json`)}var import_proper_lockfile=__toESM(require_proper_lockfile(),1);import{chmod as chmod2,mkdir as mkdir2,readFile as readFile2,realpath,rename as rename2,rm,writeFile as writeFile2}from"node:fs/promises";import{dirname as dirname3,join as join3,resolve}from"node:path";import{parseArgs}from"node:util";var SWARM_USAGE=`Manage local Antigravity and agent swarms connected to Ando.
|
|
339
339
|
|
|
340
340
|
Usage:
|
|
341
341
|
ando swarm init [--manifest <path>] [--swarm-id <id>] [--label <label>] [--agent <name[:role]>...]
|
|
@@ -386,11 +386,18 @@ Credentials saved (mode 0600): ${safeSummary.credential_path}
|
|
|
386
386
|
`),agents.length===0)io.stdout(`No per-agent credentials found in ${report.credentials_dir}.
|
|
387
387
|
Run \`ando antigravity connect <invite-url> --name <agent>\` to connect one.
|
|
388
388
|
`);else for(let agent of agents){let label=agent.display_name??agent.agent_membership_id,permNote=agent.permissions_ok?"0600 ok":"insecure perms",authNote=agent.auth_ok?"auth ok":`auth failed (${agent.error??"unknown"})`;io.stdout(`- ${label} [${agent.harness}] (${agent.key_prefix}\u2026): ${permNote}, ${authNote}
|
|
389
|
-
`)}return healthy||agents.length===0?ExitCode.ok:ExitCode.auth}async function runAntigravityCommand(args,io){let[subcommand,...rest]=args;switch(subcommand){case void 0:case"help":case"--help":case"-h":return io.stdout(ANTIGRAVITY_USAGE),subcommand===void 0?ExitCode.usage:ExitCode.ok;case"connect":return await runAntigravityConnect(rest,io);case"doctor":return await runAntigravityDoctor(rest,io);default:throw usageError(`Unknown antigravity command "${subcommand}". Run \`ando antigravity --help\`.`)}}import{parseArgs as parseArgs3}from"node:util";import{execFile as execFile2,spawn}from"node:child_process";import{promisify as promisify2}from"node:util";var execFileAsync2=promisify2(execFile2);function formatWorkroomWakePrompt(envelope){let lines=[`Ando Hyperion workroom wake for "${envelope.workroom_id}" (seq ${envelope.from_seq}..${envelope.to_seq}, reasons: ${envelope.trigger_reasons.join(", ")}).`];envelope.self_agent&&lines.push(`Target runtime agent: ${envelope.self_agent}.`),lines.push("New events:");for(let ev of envelope.events.slice(0,20)){let actor=ev.agent?` (${ev.agent})`:"",summary=ev.summary?.trim()||"(no summary)";lines.push(`- [seq ${ev.seq}] ${ev.kind}${actor}: ${summary}`)}return envelope.events.length>20&&lines.push(`- ...and ${envelope.events.length-20} more events.`),lines.push(`Call inspect_workrooms(workroom_id="${envelope.workroom_id}", after_seq=${Math.max(0,envelope.from_seq-1)}, include=["details"]) to read full details before acting.`),lines.join(`
|
|
389
|
+
`)}return healthy||agents.length===0?ExitCode.ok:ExitCode.auth}async function runAntigravityCommand(args,io){let[subcommand,...rest]=args;switch(subcommand){case void 0:case"help":case"--help":case"-h":return io.stdout(ANTIGRAVITY_USAGE),subcommand===void 0?ExitCode.usage:ExitCode.ok;case"connect":return await runAntigravityConnect(rest,io);case"doctor":return await runAntigravityDoctor(rest,io);default:throw usageError(`Unknown antigravity command "${subcommand}". Run \`ando antigravity --help\`.`)}}import{hostname}from"node:os";import{spawn}from"node:child_process";import{accessSync,constants as fsConstants}from"node:fs";import{delimiter,join as join5}from"node:path";function findExecutable(command,pathEnv){if(!pathEnv)return null;for(let dir of pathEnv.split(delimiter)){if(!dir)continue;let candidate=join5(dir,command);try{return accessSync(candidate,fsConstants.X_OK),candidate}catch{}}return null}function resolveBrowserOpener(url2,where){let{platform,env,interactive}=where;if(!interactive||env.SSH_CONNECTION||env.SSH_TTY||env.SSH_CLIENT)return null;if(platform==="darwin")return{command:"/usr/bin/open",args:[url2]};if(platform==="win32"){let root=env.SystemRoot||env.windir;return root==null?null:{command:`${root}\\System32\\rundll32.exe`,args:["url.dll,FileProtocolHandler",url2]}}if(!env.DISPLAY&&!env.WAYLAND_DISPLAY)return null;let command=(where.find??(cmd=>findExecutable(cmd,env.PATH)))("xdg-open");return command==null?null:{command,args:[url2]}}function launchBrowser(opener,onFailure){let reported=!1,fail=()=>{reported||(reported=!0,onFailure())};try{let child=spawn(opener.command,opener.args,{stdio:"ignore",detached:!0});child.on("error",fail),child.on("exit",code2=>{code2!==0&&code2!=null&&fail()}),child.unref()}catch{fail()}}function attachEnterToOpen(input,onOpen){let opened=!1,onData=chunk=>{opened||!/[\r\n]/u.test(String(chunk))||(opened=!0,onOpen())};return input.on("data",onData),input.resume(),()=>{input.off("data",onData),input.pause()}}var PATH_PARAM_RE=/\{[^{}]+\}/g,supportsRequestInitExt=()=>typeof process=="object"&&Number.parseInt(process?.versions?.node?.substring(0,2))>=18&&process.versions.undici;function randomID(){return Math.random().toString(36).slice(2,11)}function createClient(clientOptions){let{baseUrl="",Request:CustomRequest=globalThis.Request,fetch:baseFetch=globalThis.fetch,querySerializer:globalQuerySerializer,bodySerializer:globalBodySerializer,pathSerializer:globalPathSerializer,headers:baseHeaders,requestInitExt=void 0,...baseOptions}={...clientOptions};requestInitExt=supportsRequestInitExt()?requestInitExt:void 0,baseUrl=removeTrailingSlash(baseUrl);let globalMiddlewares=[];async function coreFetch(schemaPath,fetchOptions){let{baseUrl:localBaseUrl,fetch:fetch2=baseFetch,Request:Request2=CustomRequest,headers,params={},parseAs="json",querySerializer:requestQuerySerializer,bodySerializer=globalBodySerializer??defaultBodySerializer,pathSerializer:requestPathSerializer,body,middleware:requestMiddlewares=[],...init}=fetchOptions||{},finalBaseUrl=baseUrl;localBaseUrl&&(finalBaseUrl=removeTrailingSlash(localBaseUrl)??baseUrl);let querySerializer=typeof globalQuerySerializer=="function"?globalQuerySerializer:createQuerySerializer(globalQuerySerializer);requestQuerySerializer&&(querySerializer=typeof requestQuerySerializer=="function"?requestQuerySerializer:createQuerySerializer({...typeof globalQuerySerializer=="object"?globalQuerySerializer:{},...requestQuerySerializer}));let pathSerializer=requestPathSerializer||globalPathSerializer||defaultPathSerializer,serializedBody=body===void 0?void 0:bodySerializer(body,mergeHeaders(baseHeaders,headers,params.header)),finalHeaders=mergeHeaders(serializedBody===void 0||serializedBody instanceof FormData?{}:{"Content-Type":"application/json"},baseHeaders,headers,params.header),finalMiddlewares=[...globalMiddlewares,...requestMiddlewares],requestInit={redirect:"follow",...baseOptions,...init,body:serializedBody,headers:finalHeaders},id,options,request=new Request2(createFinalURL(schemaPath,{baseUrl:finalBaseUrl,params,querySerializer,pathSerializer}),requestInit),response;for(let key in init)key in request||(request[key]=init[key]);if(finalMiddlewares.length){id=randomID(),options=Object.freeze({baseUrl:finalBaseUrl,fetch:fetch2,parseAs,querySerializer,bodySerializer,pathSerializer});for(let m of finalMiddlewares)if(m&&typeof m=="object"&&typeof m.onRequest=="function"){let result=await m.onRequest({request,schemaPath,params,options,id});if(result)if(result instanceof Request2)request=result;else if(result instanceof Response){response=result;break}else throw new Error("onRequest: must return new Request() or Response() when modifying the request")}}if(!response){try{response=await fetch2(request,requestInitExt)}catch(error22){let errorAfterMiddleware=error22;if(finalMiddlewares.length)for(let i2=finalMiddlewares.length-1;i2>=0;i2--){let m=finalMiddlewares[i2];if(m&&typeof m=="object"&&typeof m.onError=="function"){let result=await m.onError({request,error:errorAfterMiddleware,schemaPath,params,options,id});if(result){if(result instanceof Response){errorAfterMiddleware=void 0,response=result;break}if(result instanceof Error){errorAfterMiddleware=result;continue}throw new Error("onError: must return new Response() or instance of Error")}}}if(errorAfterMiddleware)throw errorAfterMiddleware}if(finalMiddlewares.length)for(let i2=finalMiddlewares.length-1;i2>=0;i2--){let m=finalMiddlewares[i2];if(m&&typeof m=="object"&&typeof m.onResponse=="function"){let result=await m.onResponse({request,response,schemaPath,params,options,id});if(result){if(!(result instanceof Response))throw new Error("onResponse: must return new Response() when modifying the response");response=result}}}}let contentLength=response.headers.get("Content-Length");if(response.status===204||request.method==="HEAD"||contentLength==="0"&&!response.headers.get("Transfer-Encoding")?.includes("chunked"))return response.ok?{data:void 0,response}:{error:void 0,response};if(response.ok)return{data:await(async()=>{if(parseAs==="stream")return response.body;if(parseAs==="json"&&!contentLength){let raw=await response.text();return raw?JSON.parse(raw):void 0}return await response[parseAs]()})(),response};let error2=await response.text();try{error2=JSON.parse(error2)}catch{}return{error:error2,response}}return{request(method,url2,init){return coreFetch(url2,{...init,method:method.toUpperCase()})},GET(url2,init){return coreFetch(url2,{...init,method:"GET"})},PUT(url2,init){return coreFetch(url2,{...init,method:"PUT"})},POST(url2,init){return coreFetch(url2,{...init,method:"POST"})},DELETE(url2,init){return coreFetch(url2,{...init,method:"DELETE"})},OPTIONS(url2,init){return coreFetch(url2,{...init,method:"OPTIONS"})},HEAD(url2,init){return coreFetch(url2,{...init,method:"HEAD"})},PATCH(url2,init){return coreFetch(url2,{...init,method:"PATCH"})},TRACE(url2,init){return coreFetch(url2,{...init,method:"TRACE"})},use(...middleware){for(let m of middleware)if(m){if(typeof m!="object"||!("onRequest"in m||"onResponse"in m||"onError"in m))throw new Error("Middleware must be an object with one of `onRequest()`, `onResponse() or `onError()`");globalMiddlewares.push(m)}},eject(...middleware){for(let m of middleware){let i2=globalMiddlewares.indexOf(m);i2!==-1&&globalMiddlewares.splice(i2,1)}}}}function serializePrimitiveParam(name,value,options){if(value==null)return"";if(typeof value=="object")throw new Error("Deeply-nested arrays/objects aren\u2019t supported. Provide your own `querySerializer()` to handle these.");return`${name}=${options?.allowReserved===!0?value:encodeURIComponent(value)}`}function serializeObjectParam(name,value,options){if(!value||typeof value!="object")return"";let values=[],joiner={simple:",",label:".",matrix:";"}[options.style]||"&";if(options.style!=="deepObject"&&options.explode===!1){for(let k in value)values.push(k,options.allowReserved===!0?value[k]:encodeURIComponent(value[k]));let final2=values.join(",");switch(options.style){case"form":return`${name}=${final2}`;case"label":return`.${final2}`;case"matrix":return`;${name}=${final2}`;default:return final2}}for(let k in value){let finalName=options.style==="deepObject"?`${name}[${k}]`:k;values.push(serializePrimitiveParam(finalName,value[k],options))}let final=values.join(joiner);return options.style==="label"||options.style==="matrix"?`${joiner}${final}`:final}function serializeArrayParam(name,value,options){if(!Array.isArray(value))return"";if(options.explode===!1){let joiner2={form:",",spaceDelimited:"%20",pipeDelimited:"|"}[options.style]||",",final=(options.allowReserved===!0?value:value.map(v2=>encodeURIComponent(v2))).join(joiner2);switch(options.style){case"simple":return final;case"label":return`.${final}`;case"matrix":return`;${name}=${final}`;default:return`${name}=${final}`}}let joiner={simple:",",label:".",matrix:";"}[options.style]||"&",values=[];for(let v2 of value)options.style==="simple"||options.style==="label"?values.push(options.allowReserved===!0?v2:encodeURIComponent(v2)):values.push(serializePrimitiveParam(name,v2,options));return options.style==="label"||options.style==="matrix"?`${joiner}${values.join(joiner)}`:values.join(joiner)}function createQuerySerializer(options){return function(queryParams){let search=[];if(queryParams&&typeof queryParams=="object")for(let name in queryParams){let value=queryParams[name];if(value!=null){if(Array.isArray(value)){if(value.length===0)continue;search.push(serializeArrayParam(name,value,{style:"form",explode:!0,...options?.array,allowReserved:options?.allowReserved||!1}));continue}if(typeof value=="object"){search.push(serializeObjectParam(name,value,{style:"deepObject",explode:!0,...options?.object,allowReserved:options?.allowReserved||!1}));continue}search.push(serializePrimitiveParam(name,value,options))}}return search.join("&")}}function defaultPathSerializer(pathname,pathParams){let nextURL=pathname;for(let match of pathname.match(PATH_PARAM_RE)??[]){let name=match.substring(1,match.length-1),explode=!1,style="simple";if(name.endsWith("*")&&(explode=!0,name=name.substring(0,name.length-1)),name.startsWith(".")?(style="label",name=name.substring(1)):name.startsWith(";")&&(style="matrix",name=name.substring(1)),!pathParams||pathParams[name]===void 0||pathParams[name]===null)continue;let value=pathParams[name];if(Array.isArray(value)){nextURL=nextURL.replace(match,serializeArrayParam(name,value,{style,explode}));continue}if(typeof value=="object"){nextURL=nextURL.replace(match,serializeObjectParam(name,value,{style,explode}));continue}if(style==="matrix"){nextURL=nextURL.replace(match,`;${serializePrimitiveParam(name,value)}`);continue}nextURL=nextURL.replace(match,style==="label"?`.${encodeURIComponent(value)}`:encodeURIComponent(value))}return nextURL}function defaultBodySerializer(body,headers){return body instanceof FormData?body:headers&&(headers.get instanceof Function?headers.get("Content-Type")??headers.get("content-type"):headers["Content-Type"]??headers["content-type"])==="application/x-www-form-urlencoded"?new URLSearchParams(body).toString():JSON.stringify(body)}function createFinalURL(pathname,options){let finalURL=`${options.baseUrl}${pathname}`;options.params?.path&&(finalURL=options.pathSerializer(finalURL,options.params.path));let search=options.querySerializer(options.params.query??{});return search.startsWith("?")&&(search=search.substring(1)),search&&(finalURL+=`?${search}`),finalURL}function mergeHeaders(...allHeaders){let finalHeaders=new Headers;for(let h of allHeaders){if(!h||typeof h!="object")continue;let iterator=h instanceof Headers?h.entries():Object.entries(h);for(let[k,v2]of iterator)if(v2===null)finalHeaders.delete(k);else if(Array.isArray(v2))for(let v22 of v2)finalHeaders.append(k,v22);else v2!==void 0&&finalHeaders.set(k,v2)}return finalHeaders}function removeTrailingSlash(url2){return url2.endsWith("/")?url2.substring(0,url2.length-1):url2}function createAuthenticatedFetch(options){let base=new URL(options.baseUrl??"https://api.ando.so/v1"),loopback=["localhost","127.0.0.1","[::1]"].includes(base.hostname);if(base.protocol!=="https:"&&!(base.protocol==="http:"&&loopback)||base.username||base.password||base.search||base.hash)throw new Error("Ando API requires an HTTPS base URL (HTTP is allowed on loopback)");let timeout=options.requestTimeoutMs??3e4;if(!Number.isSafeInteger(timeout)||timeout<=0||timeout>2147483647)throw new Error("requestTimeoutMs must be a positive 32-bit integer");let apiKey=options.apiKey;if(!apiKey.trim()||/[\r\n]/u.test(apiKey))throw new Error("A valid API key is required");let fetchImpl=options.fetch??globalThis.fetch,prefix=base.pathname.replace(/\/$/u,"");return async request=>{let target=new URL(request.url);if(target.origin!==base.origin||!target.pathname.startsWith(`${prefix}/`))throw new Error("Ando API request escaped the configured API origin or prefix");let headers=new Headers(request.headers);headers.set("Authorization",`Bearer ${apiKey}`);let signal=AbortSignal.any([request.signal,AbortSignal.timeout(timeout)]);return signal.throwIfAborted(),fetchImpl(new Request(request,{headers,signal,redirect:"error"}))}}function createAndoApiClient(options){let fetch2=createAuthenticatedFetch(options),base=new URL(options.baseUrl??"https://api.ando.so/v1");return createClient({baseUrl:`${base.origin}${base.pathname.replace(/\/$/u,"")}`,fetch:fetch2})}function createClient2(options){try{return createAndoApiClient({apiKey:options.apiKey,baseUrl:options.apiUrl,...options.fetch?{fetch:options.fetch}:{}})}catch(error2){throw new CliError(ExitCode.usage,`Cannot use API URL ${options.apiUrl}: ${error2.message}`)}}function exitCodeForStatus(status){return status===401||status===403?ExitCode.auth:status===404||status===410?ExitCode.notFound:status===429||status>=500?ExitCode.unavailable:ExitCode.usage}function errorText(error2){if(error2&&typeof error2=="object"){let record2=error2;if(typeof record2.error=="string")return record2.error;if(record2.error&&typeof record2.error=="object"&&typeof record2.error.message=="string")return record2.error.message;if(typeof record2.message=="string")return record2.message}return null}var TransientApiError=class extends CliError{constructor(message){super(ExitCode.unavailable,message)}};async function call(what,request){let result;try{result=await request}catch(error2){let name=error2?.name;throw name==="TimeoutError"||name==="AbortError"?new TransientApiError(`${what} timed out.`):new TransientApiError(`${what} failed: ${error2?.message??String(error2)}`)}let{response}=result;if(response.ok&&result.data!==void 0)return result.data;let status=response.status,detail=errorText(result.error),message=`${what} failed (HTTP ${status})${detail?`: ${detail.replace(/[.!?]?$/u,".")}`:"."}`;throw status===429||status>=500?new TransientApiError(message):status===401?new CliError(ExitCode.auth,`${message} The API key was rejected; run \`ando login\` again.`):status===403?new CliError(ExitCode.auth,`${message} The key needs the messages:read and messages:write scopes, and its member must be in the conversation.`):new CliError(exitCodeForStatus(status),message)}var systemClock={now:()=>Date.now(),sleep:ms=>new Promise(resolve4=>setTimeout(resolve4,ms))},DEFAULT_POLL_INTERVAL_MS=3e3,hasText=message=>(message.content??"").trim().length>0||message.attachments.length>0||message.image_urls.length>0;async function waitForReply(api,input){let clock=input.clock??systemClock,interval=input.pollIntervalMs??DEFAULT_POLL_INTERVAL_MS,deadline=clock.now()+input.timeoutMs,after,pendingId=null,missingIds=new Set;for(;;){try{if(pendingId)try{let detail=await call("Reading the reply",api.GET("/conversation-messages/{messageId}",{params:{path:{messageId:pendingId}}}));if(hasText(detail.data))return detail.data}catch(error2){if(error2 instanceof CliError&&error2.exitCode===ExitCode.notFound){missingIds.add(pendingId),pendingId=null;continue}throw error2}else for(;;){let page=await call("Reading thread replies",api.GET("/conversation-messages/{messageId}/replies",{params:{path:{messageId:input.threadRootId},query:{limit:50,...after?{after}:{}}}})),reply=page.data.items.find(message=>!missingIds.has(message.id)&&(input.authorIds.has(message.authorWorkspaceMembershipId)||input.authorIds.has(message.author_id)));if(reply){if(hasText(reply))return reply;pendingId=reply.id;break}let cursor=page.data.page_info.end_cursor??page.data.page_info.next_cursor;if(cursor&&(after=cursor),!page.data.page_info.has_next_page||!cursor)break}}catch(error2){if(!(error2 instanceof TransientApiError))throw error2;input.onTransientError?.(error2)}let remaining=deadline-clock.now();if(remaining<=0)return null;await clock.sleep(Math.min(interval,remaining))}}import{readFile as readFile4}from"node:fs/promises";var DEFAULT_HTTP_CATCHUP_LIMIT=200;function decodeSignedEdgeTicketScope(ticket){let parts=ticket.trim().split(".");if(parts.length!==3||!parts[1])return{workspaceId:null,workspaceMembershipId:null};try{let normalized=parts[1].replace(/-/gu,"+").replace(/_/gu,"/"),padded=normalized+"=".repeat((4-normalized.length%4)%4),decoded=JSON.parse(Buffer.from(padded,"base64").toString("utf8")),workspaceId=typeof decoded.workspace_id=="string"&&decoded.workspace_id.trim().length>0?decoded.workspace_id.trim():null,workspaceMembershipId=typeof decoded.membership_id=="string"&&decoded.membership_id.trim().length>0?decoded.membership_id.trim():null;return{workspaceId,workspaceMembershipId}}catch{return{workspaceId:null,workspaceMembershipId:null}}}function cursorScopeFromTicket(minted,selfAgent,wakeCapable=!0){return{workspaceId:minted.workspaceId,workspaceMembershipId:minted.workspaceMembershipId,selfAgent,mode:wakeCapable?"wake":"observe",fallbackOrigin:minted.workspaceId||minted.workspaceMembershipId?null:`edge:${normalizeBaseUrl(minted.edgeHttpUrl)}`}}function normalizeBaseUrl(raw){return raw.trim().replace(/\/+$/u,"")}function shouldInvalidateWorkroomTicketForStatus(status){return status===401||status===403||status===409||status===421}async function loadAgentCredential(env,agentId){let path=agentCredentialFilePath(env,agentId),raw;try{raw=await readFile4(path,"utf8")}catch(error2){throw error2.code==="ENOENT"?new CliError(ExitCode.auth,`Agent credential file not found for "${agentId}" at ${path}.`):error2}let parsed;try{parsed=JSON.parse(raw)}catch{throw new CliError(ExitCode.auth,`Agent credential file at ${path} is not valid JSON.`)}if(typeof parsed.api_key!="string"||parsed.api_key.trim().length===0)throw new CliError(ExitCode.auth,`Agent credential file at ${path} is missing api_key.`);return{apiKey:parsed.api_key.trim(),apiUrl:typeof parsed.api_url=="string"&&parsed.api_url.trim().length>0?parsed.api_url.trim():"https://api.ando.so/v1"}}function readWorkroomErrorMessage(body,status){let errObj=body&&typeof body=="object"?body.error:void 0,missingScopes=body&&typeof body=="object"?body.missing_scopes:void 0;return Array.isArray(missingScopes)&&missingScopes.length>0&&missingScopes.every(scope=>typeof scope=="string")?`API key is missing the ${missingScopes.join(", ")} scope${missingScopes.length===1?"":"s"}. Use a key that has them wherever this command reads its key: ANDO_API_KEY, the agent credential, or \`ando login\` for the saved login.`:typeof errObj=="string"?errObj:errObj&&typeof errObj.message=="string"?errObj.message:`HTTP ${status}`}function createApiWorkroomTicketProvider(options){let now=options.now??Date.now,endpoint=`${normalizeBaseUrl(options.apiUrl)}/workrooms/ticket`,cached2=null,inFlight=null;async function mintFresh(){let response=await options.fetchImpl(endpoint,{method:"POST",headers:{"content-type":"application/json","x-api-key":options.apiKey},body:"{}",signal:AbortSignal.timeout(15e3)}),body;try{body=await response.json()}catch{body=null}if(!response.ok){let errMsg=readWorkroomErrorMessage(body,response.status);throw response.status===401||response.status===403?new CliError(ExitCode.auth,`Failed to mint workroom ticket (${response.status}): ${errMsg}`):response.status===409?new CliError(ExitCode.unavailable,`Durable workrooms unavailable (${response.status}): ${errMsg}`):new CliError(ExitCode.unavailable,`Workroom ticket mint failed (${response.status}): ${errMsg}`)}let record2=body,ticket=typeof record2?.ticket=="string"?record2.ticket.trim():"",edgeHttpUrl=typeof record2?.edge_http_url=="string"?normalizeBaseUrl(record2.edge_http_url):"",expiresAtMs=typeof record2?.expires_at_ms=="number"&&Number.isFinite(record2.expires_at_ms)?record2.expires_at_ms:now()+5*6e4;if(!ticket||!edgeHttpUrl)throw new CliError(ExitCode.unavailable,"Workroom ticket response was missing ticket or edge_http_url.");let decodedScope=decodeSignedEdgeTicketScope(ticket),workspaceId=typeof record2.workspace_id=="string"&&record2.workspace_id.trim().length>0?record2.workspace_id.trim():decodedScope.workspaceId,workspaceMembershipId=typeof record2.workspace_membership_id=="string"&&record2.workspace_membership_id.trim().length>0?record2.workspace_membership_id.trim():decodedScope.workspaceMembershipId,minted={ticket,edgeHttpUrl,cellId:typeof record2.cell_id=="string"?record2.cell_id:"unknown",routingGeneration:typeof record2.routing_generation=="number"?record2.routing_generation:0,expiresAtMs,workspaceId,workspaceMembershipId};return cached2=minted,minted}return{async getTicket(forceRefresh=!1){let currentTime=now();return!forceRefresh&&cached2&&cached2.expiresAtMs-currentTime>15e3?cached2:inFlight?await inFlight:(inFlight=mintFresh().finally(()=>{inFlight=null}),await inFlight)},invalidate(){cached2=null}}}function createStaticWorkroomTicketProvider(options){let trimmedTicket=options.ticket.trim(),decoded=decodeSignedEdgeTicketScope(trimmedTicket),staticTicket={ticket:trimmedTicket,edgeHttpUrl:normalizeBaseUrl(options.edgeHttpUrl),cellId:"static",routingGeneration:0,expiresAtMs:options.expiresAtMs??Date.now()+1440*6e4,workspaceId:options.workspaceId??decoded.workspaceId,workspaceMembershipId:options.workspaceMembershipId??decoded.workspaceMembershipId};return{async getTicket(){return staticTicket},invalidate(){}}}async function fetchWorkroomCatchUp(options){let maxPages=Math.max(1,Math.floor(options.maxPages??50)),cursor=Math.max(0,options.afterSeq),latestSeq=cursor,fetchedThroughSeq=cursor,hasMore=!1,collected=[],seenSeqs=new Set;for(let page=0;page<maxPages;page+=1){let url2=`${normalizeBaseUrl(options.edgeHttpUrl)}/v1/workrooms/${encodeURIComponent(options.workroomId)}?after_seq=${cursor}&limit=${DEFAULT_HTTP_CATCHUP_LIMIT}`,response=await options.fetchImpl(url2,{method:"GET",headers:{authorization:`Bearer ${options.ticket}`,accept:"application/json"},signal:options.signal});if(!response.ok)return{ok:!1,status:response.status,message:`HTTP ${response.status} during workroom catch-up`};let data=await response.json(),rawEvents=Array.isArray(data.events)?data.events:[],pageMaxSeq=cursor;for(let raw of rawEvents){if(!raw||typeof raw!="object"||Array.isArray(raw))continue;let ev=raw,seq=typeof ev.seq=="number"?ev.seq:-1;seq<=cursor||seenSeqs.has(seq)||(seenSeqs.add(seq),pageMaxSeq=Math.max(pageMaxSeq,seq),collected.push({...ev,seq,kind:typeof ev.kind=="string"?ev.kind:"chat"}))}if(typeof data.latest_seq=="number"&&data.latest_seq>latestSeq&&(latestSeq=data.latest_seq),pageMaxSeq>latestSeq&&(latestSeq=pageMaxSeq),fetchedThroughSeq=Math.max(fetchedThroughSeq,pageMaxSeq),data.has_more===!0&&pageMaxSeq>cursor){hasMore=!0,cursor=pageMaxSeq;continue}hasMore=!1,fetchedThroughSeq=Math.max(fetchedThroughSeq,latestSeq);break}return collected.sort((a,b)=>a.seq-b.seq),{ok:!0,events:collected,latestSeq,fetchedThroughSeq,hasMore}}async function awaitTicketOrAbort(ticketPromise,signal){if(signal.aborted)return ticketPromise.catch(()=>{}),null;let onAbort=null,abortPromise=new Promise(resolve4=>{onAbort=()=>{ticketPromise.catch(()=>{}),resolve4(null)},signal.addEventListener("abort",onAbort,{once:!0})});try{let ticket=await Promise.race([ticketPromise,abortPromise]);return signal.aborted?null:ticket}finally{onAbort&&signal.removeEventListener("abort",onAbort)}}async function fetchTicketWithBackoff(options){let startAttempt=options.startAttempt??0;if(options.signal.aborted)return null;if(options.once){let ticket=await awaitTicketOrAbort(options.ticketProvider.getTicket(),options.signal);return ticket?{ticket,attempts:startAttempt}:null}let attempt=startAttempt;for(;!options.signal.aborted;)try{let ticket=await awaitTicketOrAbort(options.ticketProvider.getTicket(),options.signal);return ticket?{ticket,attempts:attempt}:null}catch(error2){if(error2 instanceof CliError&&error2.exitCode===ExitCode.auth)throw error2;if(options.signal.aborted)return null;let delayMs=Math.min(options.maxBackoffMs,options.initialBackoffMs*2**Math.min(attempt,6));attempt+=1,options.log(`[${options.workroomId}] ticket mint failed (${error2 instanceof Error?error2.message:String(error2)}); retrying in ${delayMs}ms`);try{await options.sleep(delayMs,options.signal)}catch{return null}}return null}var REQUEST_TIMEOUT_MS=15e3,MIN_POLL_INTERVAL_MS=1e3,MAX_TRANSIENT_ERRORS=12,MAX_LOCAL_LOGIN_WAIT_MS=15*6e4;function buildCliRequesterUserAgent(platform=process.platform){switch(platform){case"darwin":return"Ando CLI (Macintosh)";case"win32":return"Ando CLI (Windows)";case"linux":return"Ando CLI (Linux)";default:return"Ando CLI"}}function defaultCliDeviceName(){let host=hostname().trim().slice(0,80);return host.length>0?host:void 0}function resolveBrowserLoginUrls(input){let rawWeb=input.webUrl?.trim()||input.env.ANDO_WEB_URL?.trim()||defaultWebUrl(input.apiUrl);if(!rawWeb)throw new CliError(ExitCode.usage,"Cannot infer the Ando web URL for browser sign-in from --api-url. Pass --web-url (or set ANDO_WEB_URL), or use `ando login --paste` / `--key-stdin`.");let rawConvex=input.convexUrl?.trim()||input.env.ANDO_CONVEX_URL?.trim()||defaultConvexUrl(input.apiUrl);if(!rawConvex)throw new CliError(ExitCode.usage,"Cannot infer the Ando Convex URL for browser sign-in from --api-url. Pass --convex-url (or set ANDO_CONVEX_URL), or use `ando login --paste` / `--key-stdin`.");return{convexUrl:normalizeBaseUrl(rawConvex),webUrl:normalizeBaseUrl(rawWeb)}}var ConvexTransientError=class extends Error{};async function callConvexPublicMutation(options){let endpoint=`${normalizeBaseUrl(options.convexUrl)}/api/mutation`,timeout=AbortSignal.timeout(REQUEST_TIMEOUT_MS),signal=options.signal?AbortSignal.any([options.signal,timeout]):timeout,response;try{response=await options.fetchImpl(new Request(endpoint,{method:"POST",headers:{"content-type":"application/json",accept:"application/json"},body:JSON.stringify({path:options.path,args:options.args,format:"json"}),signal}))}catch(error2){if(options.signal?.aborted)throw new CliError(ExitCode.auth,"Sign-in cancelled.");let detail=redact(error2 instanceof Error?error2.message:String(error2),options.secretToRedact);throw new ConvexTransientError(`Could not reach ${options.convexUrl}: ${detail}`)}let parsed;try{parsed=await response.json()}catch{parsed=null}if(!response.ok){let errText=parsed&&typeof parsed=="object"&&typeof parsed.errorMessage=="string"?parsed.errorMessage:`HTTP ${response.status}`,safe=redact(errText,options.secretToRedact);throw response.status>=500||response.status===429?new ConvexTransientError(`Ando sign-in service returned ${safe}.`):new CliError(ExitCode.unavailable,`Ando sign-in failed (${response.status}): ${safe}`)}if(!parsed||typeof parsed!="object"||!("status"in parsed))throw new ConvexTransientError("Unexpected response from Ando sign-in service.");let envelope=parsed;if(envelope.status==="success")return envelope.value;let safeMsg=redact(envelope.errorMessage||"Sign-in mutation failed.",options.secretToRedact);throw new CliError(ExitCode.unavailable,`Ando sign-in failed: ${safeMsg}`)}async function sleepWithSignal(ms,clock,signal){return signal.aborted?!1:clock!==systemClock?(await clock.sleep(ms),!signal.aborted):await new Promise(resolve4=>{let onAbort=()=>{clearTimeout(timer),resolve4(!1)},timer=setTimeout(()=>{signal.removeEventListener("abort",onAbort),resolve4(!0)},ms);signal.addEventListener("abort",onAbort,{once:!0})})}function handleRedeemStatus(redeemed,defaultPollMs){switch(redeemed.status){case"approved":if(typeof redeemed.api_key!="string"||redeemed.api_key.trim().length===0)throw new CliError(ExitCode.unavailable,"Ando sign-in response was missing an API key. Run `ando login` to try again.");return{done:!0,result:{apiKey:redeemed.api_key.trim(),keyPrefix:redeemed.key_prefix,scopes:Array.isArray(redeemed.scopes)?redeemed.scopes:[],workspaceId:redeemed.workspace_id,workspaceName:redeemed.workspace_name,workspaceMembershipId:redeemed.workspace_membership_id}};case"pending":return{done:!1,nextDelayMs:Math.max(MIN_POLL_INTERVAL_MS,Math.round((redeemed.poll_after_seconds||2)*1e3))};case"rate_limited":return{done:!1,nextDelayMs:Math.max(defaultPollMs,Math.round((redeemed.retry_after_seconds||2)*1e3))};case"denied":throw new CliError(ExitCode.auth,"Sign-in was denied in the browser.");case"expired":throw new CliError(ExitCode.timeout,"Sign-in session expired before approval. Run `ando login` to try again.");case"consumed":throw new CliError(ExitCode.auth,"Sign-in session was already used or revoked. Run `ando login` to start a new session.");case"membership_inactive":throw new CliError(ExitCode.auth,"The approved workspace membership is not eligible for a CLI API key (guests and archived/deactivated members cannot mint CLI keys).");case"not_found":case"invalid_token":throw new CliError(ExitCode.auth,"Sign-in session is no longer valid. Run `ando login` to try again.");case"unavailable":throw new CliError(ExitCode.unavailable,"Ando CLI sign-in is temporarily unavailable. Try again later or use `ando login --paste`.")}}async function runBrowserLogin(options){let urls=resolveBrowserLoginUrls({apiUrl:options.apiUrl,webUrl:options.webUrl,convexUrl:options.convexUrl,env:options.env}),clock=options.clock??systemClock,platform=options.platform??process.platform,deviceName=options.deviceName??defaultCliDeviceName(),controller=new AbortController,onSignal=()=>controller.abort(new Error("Sign-in cancelled."));process.on("SIGINT",onSignal),process.on("SIGTERM",onSignal);let stopListening=null;try{let started;try{started=await callConvexPublicMutation({convexUrl:urls.convexUrl,path:"cliLoginPublic:startSession",args:{requester_user_agent:buildCliRequesterUserAgent(platform)},fetchImpl:options.fetchImpl,signal:controller.signal})}catch(error2){throw error2 instanceof ConvexTransientError?new CliError(ExitCode.unavailable,error2.message):error2}if(!started.ok){let retryHint=started.retry_after_seconds!=null?` Wait ${started.retry_after_seconds}s and try again.`:"";throw new CliError(ExitCode.unavailable,`${started.message}${retryHint}`)}let approvalUrl=new URL("/cli-login",`${urls.webUrl}/`);approvalUrl.searchParams.set("verificationCode",started.verification_code);let link2=approvalUrl.toString(),opener=options.noOpen===!0?null:resolveBrowserOpener(link2,{platform,env:options.env,interactive:options.stdinIsTty});if(options.stderr(`Sign in to Ando in your browser, from any device:
|
|
390
|
+
`),options.stderr(` ${link2}
|
|
391
|
+
`),options.stderr(` Code: ${started.verification_code}
|
|
392
|
+
`),options.noOpen!==!0&&options.stdinIsTty&&(opener!=null||options.openBrowser!=null)){let doOpen=()=>{options.openBrowser?options.openBrowser(link2):opener!=null&&launchBrowser(opener,()=>{options.stderr(`Could not open a browser automatically. Open this link manually:
|
|
393
|
+
${link2}
|
|
394
|
+
`)})};options.stderr(`Press Enter to open it in your browser, or open the link on another device. Waiting for approval...
|
|
395
|
+
`);let stdinStream=options.stdin??process.stdin;stopListening=attachEnterToOpen(stdinStream,doOpen)}else options.stderr(`Open the link in any browser. Waiting for approval...
|
|
396
|
+
`);let defaultPollMs=Math.max(MIN_POLL_INTERVAL_MS,Math.round((started.poll_after_seconds||2)*1e3)),localDeadline=clock.now()+MAX_LOCAL_LOGIN_WAIT_MS,nextDelayMs=defaultPollMs,transientErrors=0;for(;!controller.signal.aborted;){let remainingMs=localDeadline-clock.now();if(remainingMs<=0)throw new CliError(ExitCode.timeout,"Sign-in session expired before approval. Run `ando login` to try again.");if(!await sleepWithSignal(Math.min(nextDelayMs,remainingMs),clock,controller.signal))throw new CliError(ExitCode.auth,"Sign-in cancelled.");let redeemed;try{redeemed=await callConvexPublicMutation({convexUrl:urls.convexUrl,path:"cliLoginPublic:redeemSession",args:{cli_auth_session_id:started.cli_auth_session_id,poll_token:started.poll_token,...deviceName?{device_name:deviceName}:{}},fetchImpl:options.fetchImpl,signal:controller.signal,secretToRedact:started.poll_token}),transientErrors=0}catch(error2){if(error2 instanceof ConvexTransientError){if(transientErrors+=1,transientErrors>=MAX_TRANSIENT_ERRORS)throw new CliError(ExitCode.unavailable,`${error2.message} Run \`ando login\` to try again.`);nextDelayMs=Math.min(1e4,defaultPollMs*2);continue}throw error2}let step=handleRedeemStatus(redeemed,defaultPollMs);if(step.done)return step.result;nextDelayMs=step.nextDelayMs}throw new CliError(ExitCode.auth,"Sign-in cancelled.")}finally{stopListening?.(),process.off("SIGINT",onSignal),process.off("SIGTERM",onSignal)}}async function probeWorkroomRealtimeAccess(options){let endpoint=`${normalizeBaseUrl(options.apiUrl)}/workrooms/ticket`,response;try{response=await options.fetchImpl(new Request(endpoint,{method:"POST",headers:{"content-type":"application/json","x-api-key":options.apiKey},body:"{}",signal:AbortSignal.timeout(1e4)}))}catch{return{status:"unavailable"}}if(response.ok)return{status:"ready"};if(response.status===409)return{status:"workrooms_disabled"};if(response.status===403){let body=null;try{body=await response.json()}catch{}let rawMissing=body&&typeof body=="object"?body.missing_scopes:void 0,missingScopes=Array.isArray(rawMissing)&&rawMissing.every(scope=>typeof scope=="string")?rawMissing:[],message=redact(readWorkroomErrorMessage(body,response.status),options.apiKey);return missingScopes.length>0?{status:"missing_scope",missingScopes,message}:{status:"forbidden",message}}return{status:"unavailable"}}import{parseArgs as parseArgs3}from"node:util";import{execFile as execFile2,spawn as spawn2}from"node:child_process";import{promisify as promisify2}from"node:util";var execFileAsync2=promisify2(execFile2);function formatWorkroomWakePrompt(envelope){let lines=[`Ando Hyperion workroom wake for "${envelope.workroom_id}" (seq ${envelope.from_seq}..${envelope.to_seq}, reasons: ${envelope.trigger_reasons.join(", ")}).`];envelope.self_agent&&lines.push(`Target runtime agent: ${envelope.self_agent}.`),lines.push("New events:");for(let ev of envelope.events.slice(0,20)){let actor=ev.agent?` (${ev.agent})`:"",summary=ev.summary?.trim()||"(no summary)";lines.push(`- [seq ${ev.seq}] ${ev.kind}${actor}: ${summary}`)}return envelope.events.length>20&&lines.push(`- ...and ${envelope.events.length-20} more events.`),lines.push(`Call inspect_workrooms(workroom_id="${envelope.workroom_id}", after_seq=${Math.max(0,envelope.from_seq-1)}, include=["details"]) to read full details before acting.`),lines.join(`
|
|
390
397
|
`)}function createJsonlStdoutDriver(options){let wakeCapable=options.acknowledgeStdout===!0;return{name:wakeCapable?"stdout-jsonl-acked":"stdout-jsonl",wakeCapable,async deliver(envelope){return options.stdout(`${JSON.stringify(envelope)}
|
|
391
|
-
`),{ok:!0,driver:wakeCapable?"stdout-jsonl-acked":"stdout-jsonl"}}}}var DEFAULT_EXEC_KILL_GRACE_MS=2e3,EXEC_CLEANUP_POLL_MS=25;function signalExecProcessTree(child,pgid,signal){if(pgid!==null)try{process.kill(-pgid,signal)}catch{}try{child.kill(signal)}catch{}}function isProcessGroupAlive(pgid){try{return process.kill(-pgid,0),!0}catch(error2){return error2.code!=="ESRCH"}}function createExecWakeDriver(options){let driverName="exec",killGraceMs=Math.max(50,Math.floor(options.killGraceMs??DEFAULT_EXEC_KILL_GRACE_MS));return{name:driverName,wakeCapable:!0,deliver(envelope){return new Promise(resolve4=>{let child=
|
|
392
|
-
`)})}}}function createAntigravityWakeDriver(options){let fetchImpl=options.fetchImpl??globalThis.fetch,sessionId=options.sessionId?.trim()||"",lsAddress=options.env.ANTIGRAVITY_LS_ADDRESS?.trim()||"",csrfToken=options.env.ANTIGRAVITY_CSRF_TOKEN?.trim()||"",projectId=options.env.ANTIGRAVITY_PROJECT_ID?.trim()||"",runAgentApi=options.execAgentApi??((args,opts)=>execFileAsync2("agentapi",args,opts)),useDirectLs=sessionId.length===0&&lsAddress.length>0&&csrfToken.length>0,driverName=useDirectLs?"antigravity-ls":sessionId.length>0?"antigravity-agentapi-session":"antigravity-agentapi";return{name:driverName,wakeCapable:!0,async deliver(envelope){let prompt=formatWorkroomWakePrompt(envelope);if(useDirectLs)try{let url2=`http://${lsAddress}/product.v1.ConversationService/CreateConversation`,body={title:`Workroom wake: ${envelope.workroom_id} (seq ${envelope.from_seq}..${envelope.to_seq})`,tags:["workroom-wake"],prompt:[{text:prompt}],...projectId?{projectId}:{}},response=await fetchImpl(url2,{method:"POST",headers:{"content-type":"application/json","connect-protocol-version":"1","x-antigravity-csrf-token":csrfToken},body:JSON.stringify(body),signal:AbortSignal.timeout(options.timeoutMs)});if(!response.ok){let text=await response.text().catch(()=>"");return{ok:!1,driver:driverName,error:`Antigravity ConversationService returned HTTP ${response.status}${text?`: ${text.slice(0,300)}`:""}.`}}return{ok:!0,driver:driverName}}catch(error2){return{ok:!1,driver:driverName,error:error2 instanceof Error?error2.message:`Antigravity wake request failed: ${String(error2)}`}}try{return await runAgentApi(sessionId?["send-message",sessionId,prompt]:["new-conversation","--",prompt],{timeout:options.timeoutMs,env:{...process.env,...options.env}}),{ok:!0,driver:driverName}}catch(error2){return{ok:!1,driver:driverName,error:error2 instanceof Error?error2.message:`agentapi wake failed: ${String(error2)}`}}}}}var WORKROOM_ID_RE=/^[A-Za-z0-9._:-]+$/u,MAX_WORKROOM_ID_LENGTH=128;function validateWorkroomId(candidate,original){if(!WORKROOM_ID_RE.test(candidate)||candidate.length>MAX_WORKROOM_ID_LENGTH)throw usageError(`Invalid workroom ID "${original}".`);return candidate}function parseWorkroomReference(raw){let trimmed=raw.trim();if(trimmed.length===0)throw usageError("Workroom ID cannot be empty.");if(trimmed.includes("://")||trimmed.startsWith("/")||trimmed.startsWith("?")||trimmed.startsWith("workroom=")||trimmed.includes("?workroom=")||trimmed.includes("&workroom=")){let extracted;try{let parseInput=trimmed.startsWith("workroom=")?`?${trimmed}`:trimmed.includes("://")||trimmed.startsWith("/")||trimmed.startsWith("?")?trimmed:`https://${trimmed}`;extracted=new URL(parseInput,"https://app.ando.so").searchParams.get("workroom")?.trim()??null}catch{throw usageError(`Invalid workroom URL "${raw}".`)}if(!extracted)throw usageError(`Workroom link "${raw}" is missing a ?workroom=<id> parameter.`);return validateWorkroomId(extracted,raw)}return validateWorkroomId(trimmed,raw)}function isInternalTurnWorkroomId(workroomId){return workroomId.startsWith("wr_")}function isSettledSoloTurnRoom(room){return isInternalTurnWorkroomId(room.workroom_id)&&room.status==="settled"&&room.participants.length<=1}var import_proper_lockfile3=__toESM(require_proper_lockfile(),1);import{createHash as createHash2}from"node:crypto";import{chmod as chmod4,mkdir as mkdir4,readdir as readdir2,readFile as
|
|
393
|
-
`,{mode:384}),await chmod4(temp,384),await rename4(temp,path)}catch(error2){throw await rm3(temp,{force:!0}).catch(()=>{}),error2}}var inProcessDirLocks=new Map;async function withInProcessDirLock(dir,fn){let previous=inProcessDirLocks.get(dir)??Promise.resolve(),releaseCurrent,current=new Promise(resolve4=>{releaseCurrent=resolve4}),tail=previous.then(()=>current);inProcessDirLocks.set(dir,tail),await previous;try{return await fn()}finally{releaseCurrent(),inProcessDirLocks.get(dir)===tail&&inProcessDirLocks.delete(dir)}}async function updateWorkroomState(env,workroomId,scope,updater,defaults){let dir=workroomStateDir(env),path=workroomStateFilePath(env,workroomId,scope),expectedKey=computeWorkroomConsumerKey(scope);return await withInProcessDirLock(dir,async()=>{await mkdir4(dir,{recursive:!0,mode:448});let release=await import_proper_lockfile3.default.lock(dir,{retries:10,stale:1e4,update:5e3});try{let existing=await readWorkroomState(env,workroomId,scope)??createInitialWorkroomState(workroomId,scope,defaults),next={...updater(existing),schema_version:2,workroom_id:workroomId,consumer_key:expectedKey,workspace_id:normalizeScopePart(scope.workspaceId),workspace_membership_id:normalizeScopePart(scope.workspaceMembershipId),self_agent:normalizeScopePart(scope.selfAgent),updated_at:new Date().toISOString()};return await writeAtomicJson(path,next),next}finally{await release()}})}async function listWorkroomStates(env,filter){let dir=workroomStateDir(env),entries;try{entries=await readdir2(dir)}catch(error2){if(error2.code==="ENOENT")return[];throw error2}let normalizedFilterAgent=normalizeScopePart(filter?.selfAgent)?.toLowerCase(),states=[];for(let name of entries){if(!name.endsWith(".json"))continue;let full=join5(dir,name);try{let raw=await readFile4(full,"utf8"),parsed=normalizeLoadedState(JSON.parse(raw),name.slice(0,-5));if(!parsed||filter?.workroomId&&parsed.workroom_id!==filter.workroomId||normalizedFilterAgent&&(parsed.self_agent?.toLowerCase()??"")!==normalizedFilterAgent)continue;states.push(parsed)}catch{}}return states.sort((a,b)=>a.workroom_id.localeCompare(b.workroom_id)||a.consumer_key.localeCompare(b.consumer_key)),states}import{readFile as readFile5}from"node:fs/promises";var DEFAULT_HTTP_CATCHUP_LIMIT=200;function decodeSignedEdgeTicketScope(ticket){let parts=ticket.trim().split(".");if(parts.length!==3||!parts[1])return{workspaceId:null,workspaceMembershipId:null};try{let normalized=parts[1].replace(/-/gu,"+").replace(/_/gu,"/"),padded=normalized+"=".repeat((4-normalized.length%4)%4),decoded=JSON.parse(Buffer.from(padded,"base64").toString("utf8")),workspaceId=typeof decoded.workspace_id=="string"&&decoded.workspace_id.trim().length>0?decoded.workspace_id.trim():null,workspaceMembershipId=typeof decoded.membership_id=="string"&&decoded.membership_id.trim().length>0?decoded.membership_id.trim():null;return{workspaceId,workspaceMembershipId}}catch{return{workspaceId:null,workspaceMembershipId:null}}}function cursorScopeFromTicket(minted,selfAgent,wakeCapable=!0){return{workspaceId:minted.workspaceId,workspaceMembershipId:minted.workspaceMembershipId,selfAgent,mode:wakeCapable?"wake":"observe",fallbackOrigin:minted.workspaceId||minted.workspaceMembershipId?null:`edge:${normalizeBaseUrl(minted.edgeHttpUrl)}`}}function normalizeBaseUrl(raw){return raw.trim().replace(/\/+$/u,"")}function shouldInvalidateWorkroomTicketForStatus(status){return status===401||status===403||status===409||status===421}async function loadAgentCredential(env,agentId){let path=agentCredentialFilePath(env,agentId),raw;try{raw=await readFile5(path,"utf8")}catch(error2){throw error2.code==="ENOENT"?new CliError(ExitCode.auth,`Agent credential file not found for "${agentId}" at ${path}.`):error2}let parsed;try{parsed=JSON.parse(raw)}catch{throw new CliError(ExitCode.auth,`Agent credential file at ${path} is not valid JSON.`)}if(typeof parsed.api_key!="string"||parsed.api_key.trim().length===0)throw new CliError(ExitCode.auth,`Agent credential file at ${path} is missing api_key.`);return{apiKey:parsed.api_key.trim(),apiUrl:typeof parsed.api_url=="string"&&parsed.api_url.trim().length>0?parsed.api_url.trim():"https://api.ando.so/v1"}}function readWorkroomErrorMessage(body,status){let errObj=body&&typeof body=="object"?body.error:void 0,missingScopes=body&&typeof body=="object"?body.missing_scopes:void 0;return Array.isArray(missingScopes)&&missingScopes.length>0&&missingScopes.every(scope=>typeof scope=="string")?`API key is missing the ${missingScopes.join(", ")} scope${missingScopes.length===1?"":"s"}. Use a key that has them wherever this command reads its key: ANDO_API_KEY, the agent credential, or \`ando login\` for the saved login.`:typeof errObj=="string"?errObj:errObj&&typeof errObj.message=="string"?errObj.message:`HTTP ${status}`}function createApiWorkroomTicketProvider(options){let now=options.now??Date.now,endpoint=`${normalizeBaseUrl(options.apiUrl)}/workrooms/ticket`,cached2=null,inFlight=null;async function mintFresh(){let response=await options.fetchImpl(endpoint,{method:"POST",headers:{"content-type":"application/json","x-api-key":options.apiKey},body:"{}",signal:AbortSignal.timeout(15e3)}),body;try{body=await response.json()}catch{body=null}if(!response.ok){let errMsg=readWorkroomErrorMessage(body,response.status);throw response.status===401||response.status===403?new CliError(ExitCode.auth,`Failed to mint workroom ticket (${response.status}): ${errMsg}`):response.status===409?new CliError(ExitCode.unavailable,`Durable workrooms unavailable (${response.status}): ${errMsg}`):new CliError(ExitCode.unavailable,`Workroom ticket mint failed (${response.status}): ${errMsg}`)}let record2=body,ticket=typeof record2?.ticket=="string"?record2.ticket.trim():"",edgeHttpUrl=typeof record2?.edge_http_url=="string"?normalizeBaseUrl(record2.edge_http_url):"",expiresAtMs=typeof record2?.expires_at_ms=="number"&&Number.isFinite(record2.expires_at_ms)?record2.expires_at_ms:now()+5*6e4;if(!ticket||!edgeHttpUrl)throw new CliError(ExitCode.unavailable,"Workroom ticket response was missing ticket or edge_http_url.");let decodedScope=decodeSignedEdgeTicketScope(ticket),workspaceId=typeof record2.workspace_id=="string"&&record2.workspace_id.trim().length>0?record2.workspace_id.trim():decodedScope.workspaceId,workspaceMembershipId=typeof record2.workspace_membership_id=="string"&&record2.workspace_membership_id.trim().length>0?record2.workspace_membership_id.trim():decodedScope.workspaceMembershipId,minted={ticket,edgeHttpUrl,cellId:typeof record2.cell_id=="string"?record2.cell_id:"unknown",routingGeneration:typeof record2.routing_generation=="number"?record2.routing_generation:0,expiresAtMs,workspaceId,workspaceMembershipId};return cached2=minted,minted}return{async getTicket(forceRefresh=!1){let currentTime=now();return!forceRefresh&&cached2&&cached2.expiresAtMs-currentTime>15e3?cached2:inFlight?await inFlight:(inFlight=mintFresh().finally(()=>{inFlight=null}),await inFlight)},invalidate(){cached2=null}}}function createStaticWorkroomTicketProvider(options){let trimmedTicket=options.ticket.trim(),decoded=decodeSignedEdgeTicketScope(trimmedTicket),staticTicket={ticket:trimmedTicket,edgeHttpUrl:normalizeBaseUrl(options.edgeHttpUrl),cellId:"static",routingGeneration:0,expiresAtMs:options.expiresAtMs??Date.now()+1440*6e4,workspaceId:options.workspaceId??decoded.workspaceId,workspaceMembershipId:options.workspaceMembershipId??decoded.workspaceMembershipId};return{async getTicket(){return staticTicket},invalidate(){}}}async function fetchWorkroomCatchUp(options){let maxPages=Math.max(1,Math.floor(options.maxPages??50)),cursor=Math.max(0,options.afterSeq),latestSeq=cursor,fetchedThroughSeq=cursor,hasMore=!1,collected=[],seenSeqs=new Set;for(let page=0;page<maxPages;page+=1){let url2=`${normalizeBaseUrl(options.edgeHttpUrl)}/v1/workrooms/${encodeURIComponent(options.workroomId)}?after_seq=${cursor}&limit=${DEFAULT_HTTP_CATCHUP_LIMIT}`,response=await options.fetchImpl(url2,{method:"GET",headers:{authorization:`Bearer ${options.ticket}`,accept:"application/json"},signal:options.signal});if(!response.ok)return{ok:!1,status:response.status,message:`HTTP ${response.status} during workroom catch-up`};let data=await response.json(),rawEvents=Array.isArray(data.events)?data.events:[],pageMaxSeq=cursor;for(let raw of rawEvents){if(!raw||typeof raw!="object"||Array.isArray(raw))continue;let ev=raw,seq=typeof ev.seq=="number"?ev.seq:-1;seq<=cursor||seenSeqs.has(seq)||(seenSeqs.add(seq),pageMaxSeq=Math.max(pageMaxSeq,seq),collected.push({...ev,seq,kind:typeof ev.kind=="string"?ev.kind:"chat"}))}if(typeof data.latest_seq=="number"&&data.latest_seq>latestSeq&&(latestSeq=data.latest_seq),pageMaxSeq>latestSeq&&(latestSeq=pageMaxSeq),fetchedThroughSeq=Math.max(fetchedThroughSeq,pageMaxSeq),data.has_more===!0&&pageMaxSeq>cursor){hasMore=!0,cursor=pageMaxSeq;continue}hasMore=!1,fetchedThroughSeq=Math.max(fetchedThroughSeq,latestSeq);break}return collected.sort((a,b)=>a.seq-b.seq),{ok:!0,events:collected,latestSeq,fetchedThroughSeq,hasMore}}async function awaitTicketOrAbort(ticketPromise,signal){if(signal.aborted)return ticketPromise.catch(()=>{}),null;let onAbort=null,abortPromise=new Promise(resolve4=>{onAbort=()=>{ticketPromise.catch(()=>{}),resolve4(null)},signal.addEventListener("abort",onAbort,{once:!0})});try{let ticket=await Promise.race([ticketPromise,abortPromise]);return signal.aborted?null:ticket}finally{onAbort&&signal.removeEventListener("abort",onAbort)}}async function fetchTicketWithBackoff(options){let startAttempt=options.startAttempt??0;if(options.signal.aborted)return null;if(options.once){let ticket=await awaitTicketOrAbort(options.ticketProvider.getTicket(),options.signal);return ticket?{ticket,attempts:startAttempt}:null}let attempt=startAttempt;for(;!options.signal.aborted;)try{let ticket=await awaitTicketOrAbort(options.ticketProvider.getTicket(),options.signal);return ticket?{ticket,attempts:attempt}:null}catch(error2){if(error2 instanceof CliError&&error2.exitCode===ExitCode.auth)throw error2;if(options.signal.aborted)return null;let delayMs=Math.min(options.maxBackoffMs,options.initialBackoffMs*2**Math.min(attempt,6));attempt+=1,options.log(`[${options.workroomId}] ticket mint failed (${error2 instanceof Error?error2.message:String(error2)}); retrying in ${delayMs}ms`);try{await options.sleep(delayMs,options.signal)}catch{return null}}return null}var DECISION_ATTENTION_STATUSES=new Set(["needs_human","interrupted","hop_limit_exceeded","budget_exceeded"]);function isAttentionNeededWorkroom(room){return DECISION_ATTENTION_STATUSES.has(room.status)?!0:room.status==="active"&&typeof room.pending_capability=="string"&&room.pending_capability.trim().length>0}function readFiniteNonNegativeInt(value,fallback=0){return typeof value!="number"||!Number.isFinite(value)?fallback:Math.max(0,Math.trunc(value))}function normalizeWorkroomParticipant(raw){if(!raw||typeof raw!="object"||Array.isArray(raw))return null;let rec=raw,agent=typeof rec.agent=="string"?rec.agent.trim():"";if(agent.length===0)return null;let capabilities=Array.isArray(rec.capabilities)?rec.capabilities.filter(cap=>typeof cap=="string"&&cap.trim().length>0):void 0;return{agent,...typeof rec.provider=="string"?{provider:rec.provider}:{},...typeof rec.harness=="string"?{harness:rec.harness}:{},...typeof rec.cred_owner=="string"?{cred_owner:rec.cred_owner}:{},...capabilities?{capabilities}:{},...typeof rec.events=="number"&&Number.isFinite(rec.events)?{events:Math.max(0,Math.trunc(rec.events))}:{},...typeof rec.last_seen_ms=="number"&&Number.isFinite(rec.last_seen_ms)?{last_seen_ms:rec.last_seen_ms}:{},...typeof rec.last_action=="string"?{last_action:rec.last_action}:{},...typeof rec.transport_attached=="boolean"?{transport_attached:rec.transport_attached}:{},...typeof rec.wake_capable=="boolean"?{wake_capable:rec.wake_capable}:{}}}function normalizeWorkroomSummary(raw){if(!raw||typeof raw!="object"||Array.isArray(raw))return null;let rec=raw,workroomId=typeof rec.workroom_id=="string"?rec.workroom_id.trim():"";if(workroomId.length===0)return null;let rawParticipants=Array.isArray(rec.participants)?rec.participants:[],participants=[];for(let item of rawParticipants){let normalized=normalizeWorkroomParticipant(item);normalized&&participants.push(normalized)}return{workroom_id:workroomId,...typeof rec.workspace_id=="string"?{workspace_id:rec.workspace_id}:{},...typeof rec.parent_conversation_id=="string"?{parent_conversation_id:rec.parent_conversation_id}:{},title:typeof rec.title=="string"&&rec.title.trim().length>0?rec.title.trim():workroomId,status:typeof rec.status=="string"&&rec.status.trim().length>0?rec.status.trim():"active",event_count:readFiniteNonNegativeInt(rec.event_count),revision:readFiniteNonNegativeInt(rec.revision),updated_at_ms:readFiniteNonNegativeInt(rec.updated_at_ms),created_at_ms:readFiniteNonNegativeInt(rec.created_at_ms),...typeof rec.latest_agent=="string"?{latest_agent:rec.latest_agent}:{},...typeof rec.latest_summary=="string"?{latest_summary:rec.latest_summary}:{},...typeof rec.pending_capability=="string"||rec.pending_capability===null?{pending_capability:rec.pending_capability}:{},...typeof rec.live_stream_count=="number"&&Number.isFinite(rec.live_stream_count)?{live_stream_count:Math.max(0,Math.trunc(rec.live_stream_count))}:{},participants}}async function fetchWorkroomList(options){let params=new URLSearchParams;options.parentConversationId?.trim()&¶ms.set("parent_conversation_id",options.parentConversationId.trim()),options.capability?.trim()&¶ms.set("capability",options.capability.trim()),options.attentionOnly===!0&¶ms.set("attention_only","true"),options.includeTurnRooms===!0&¶ms.set("include_turn_rooms","true");let qs=params.toString(),url2=`${normalizeBaseUrl(options.edgeHttpUrl)}/v1/workrooms${qs?`?${qs}`:""}`,response=await options.fetchImpl(url2,{method:"GET",headers:{authorization:`Bearer ${options.ticket}`,accept:"application/json"},signal:options.signal}),body;try{body=await response.json()}catch{body=null}if(!response.ok)return{ok:!1,status:response.status,message:readWorkroomErrorMessage(body,response.status)};let record2=body&&typeof body=="object"&&!Array.isArray(body)?body:null;if(!record2||!Array.isArray(record2.workrooms))return{ok:!1,status:response.status,message:"Invalid workroom list response (missing workrooms array)"};let workrooms=[];for(let item of record2.workrooms){let normalized=normalizeWorkroomSummary(item);normalized&&workrooms.push(normalized)}return{ok:!0,workrooms}}async function fetchListWithSingleRefresh(options){let forceRefresh=!1;for(let attempt=0;attempt<2;attempt+=1){let ticket=await options.ticketProvider.getTicket(forceRefresh),result=await fetchWorkroomList({edgeHttpUrl:ticket.edgeHttpUrl,ticket:ticket.ticket,parentConversationId:options.parentConversationId,capability:options.capability,attentionOnly:options.attentionOnly,includeTurnRooms:options.includeTurnRooms,fetchImpl:options.fetchImpl,signal:options.signal});if(result.ok)return{ticket,workrooms:result.workrooms};if(shouldInvalidateWorkroomTicketForStatus(result.status)){if(options.ticketProvider.invalidate(),attempt===0){forceRefresh=!0;continue}if(result.status===401||result.status===403)throw new CliError(ExitCode.auth,`Failed to list workrooms (${result.status}): ${result.message}`)}throw new CliError(ExitCode.unavailable,`Failed to list workrooms (${result.status}): ${result.message}`)}throw new CliError(ExitCode.unavailable,"Failed to list workrooms.")}async function discoverWorkspaceWorkrooms(options){let parentIds=[...new Set((options.parentConversationIds??[]).map(id=>id.trim()).filter(id=>id.length>0))];if(parentIds.length===0)return await fetchListWithSingleRefresh({ticketProvider:options.ticketProvider,capability:options.capability,attentionOnly:options.attentionOnly,includeTurnRooms:options.includeTurnRooms,fetchImpl:options.fetchImpl,signal:options.signal});let byId=new Map,latestTicket=null;for(let parentConversationId of parentIds){let res=await fetchListWithSingleRefresh({ticketProvider:options.ticketProvider,parentConversationId,capability:options.capability,attentionOnly:options.attentionOnly,includeTurnRooms:options.includeTurnRooms,fetchImpl:options.fetchImpl,signal:options.signal});latestTicket=res.ticket;for(let room of res.workrooms){let prev=byId.get(room.workroom_id);(!prev||room.revision>prev.revision||room.updated_at_ms>prev.updated_at_ms)&&byId.set(room.workroom_id,room)}}return{ticket:latestTicket??await options.ticketProvider.getTicket(),workrooms:[...byId.values()]}}function scoreRoomPriority(room,selfAgentLower,capabilitiesLower){if(DECISION_ATTENTION_STATUSES.has(room.status))return 3;let pendingCap=room.pending_capability?.trim().toLowerCase()??"";return pendingCap.length>0&&capabilitiesLower.has(pendingCap)?2:selfAgentLower&&room.participants.some(p=>p.agent.trim().toLowerCase()===selfAgentLower)?1:0}function selectWorkspaceWatchTargets(discovered,options){let remainingSlots=Math.max(0,options.maxRooms-options.pinnedIds.size);if(remainingSlots===0)return[];let eligible=discovered.filter(room=>!(options.pinnedIds.has(room.workroom_id)||room.status==="settled"||options.attentionOnly&&!isAttentionNeededWorkroom(room)||!options.includeTurnRooms&&isInternalTurnWorkroomId(room.workroom_id))),selfAgentLower=options.selfAgent?.trim().toLowerCase()||null,capabilitiesLower=new Set(options.capabilities.map(c=>c.trim().toLowerCase()).filter(c=>c.length>0));return eligible.sort((a,b)=>{let scoreDiff=scoreRoomPriority(b,selfAgentLower,capabilitiesLower)-scoreRoomPriority(a,selfAgentLower,capabilitiesLower);return scoreDiff!==0?scoreDiff:b.updated_at_ms!==a.updated_at_ms?b.updated_at_ms-a.updated_at_ms:a.workroom_id.localeCompare(b.workroom_id)}),eligible.slice(0,remainingSlots)}async function resolveDiscoveredStartSeq(options){let scope=cursorScopeFromTicket(options.ticket,options.selfAgent,options.wakeCapable);if(await readWorkroomState(options.env,options.room.workroom_id,scope))return;if(options.replayExisting)return 0;if(!options.hasCompletedInitialDiscovery)return Math.max(0,options.room.event_count);let seenAtStartup=options.startupEventCounts.get(options.room.workroom_id);return seenAtStartup!==void 0?Math.max(0,seenAtStartup):0}function readNonNegativeSafeInt(value){return typeof value=="number"&&Number.isSafeInteger(value)&&value>=0?value:null}function isSequencedFrame(decoded){return decoded.type==="event"||decoded.type==="interrupt"||decoded.type==="human_control"}function isGapFrame(decoded){return decoded.type==="lagged"||decoded.type==="replay_truncated"||decoded.type==="breaker_tripped"}function handleAwaitingSnapshotFrame(decoded,sync,ctx,controls){if(decoded.type==="snapshot"){let snapshotEventCount=readNonNegativeSafeInt(decoded.workroom.event_count);if(snapshotEventCount===null){controls.startHttpCatchUp();return}if(snapshotEventCount<=sync.catchUpFloor){controls.clearFallbackTimer(),sync.phase="live";return}sync.replayTargetSeq=snapshotEventCount,sync.expectedReplaySeq=sync.catchUpFloor+1,sync.phase="native_replay",controls.armFallbackTimer(sync.nativeReplayFallbackMs);return}if(isSequencedFrame(decoded)){decoded.event.seq>0&&sync.liveBuffer.push(decoded.event),controls.startHttpCatchUp();return}isGapFrame(decoded)&&((decoded.type==="lagged"||decoded.type==="replay_truncated")&&ctx.log(`[${ctx.workroomId}] SSE ${decoded.type}; triggering HTTP catch-up from seq ${ctx.getLastSeenSeq()}`),controls.startHttpCatchUp())}async function handleNativeReplayFrame(decoded,sync,ctx,controls){if(isSequencedFrame(decoded)){let ev=decoded.event;if(ev.seq<=0){await controls.flushReplayBatch(),controls.startHttpCatchUp();return}if(ev.seq<sync.expectedReplaySeq)return;if(ev.seq>sync.expectedReplaySeq){await controls.flushReplayBatch(),sync.liveBuffer.push(ev),ctx.log(`[${ctx.workroomId}] SSE replay gap (expected seq ${sync.expectedReplaySeq}, got ${ev.seq}); falling back to HTTP catch-up`),controls.startHttpCatchUp();return}if(sync.replayBatch.push(ev),sync.expectedReplaySeq=ev.seq+1,ev.seq>=sync.replayTargetSeq){await controls.flushReplayBatch()||(controls.clearFallbackTimer(),sync.phase="live");return}controls.armFallbackTimer(sync.nativeReplayFallbackMs);return}isGapFrame(decoded)&&(await controls.flushReplayBatch(),(decoded.type==="lagged"||decoded.type==="replay_truncated")&&ctx.log(`[${ctx.workroomId}] SSE ${decoded.type}; triggering HTTP catch-up from seq ${ctx.getLastSeenSeq()}`),controls.startHttpCatchUp())}function createFallbackTimerController(){let timer=null,triggered=!1,pending=null,clear=()=>{timer!==null&&(clearTimeout(timer),timer=null),pending=null};return{arm:delayMs=>{clear(),triggered=!1,pending=new Promise(resolve4=>{timer=setTimeout(()=>{timer=null,triggered=!0,resolve4("fallback")},delayMs)})},clear,isTriggered:()=>triggered,getPending:()=>pending}}function createSseParser(onFrame){let buffer="",eventName="message",dataLines=[],lastId=null,retryMs=null,sawField=!1,pendingCr=!1;function dispatch(){if(!sawField&&dataLines.length===0){eventName="message",retryMs=null;return}dataLines.length>0&&onFrame({event:eventName||"message",data:dataLines.join(`
|
|
398
|
+
`),{ok:!0,driver:wakeCapable?"stdout-jsonl-acked":"stdout-jsonl"}}}}var DEFAULT_EXEC_KILL_GRACE_MS=2e3,EXEC_CLEANUP_POLL_MS=25;function signalExecProcessTree(child,pgid,signal){if(pgid!==null)try{process.kill(-pgid,signal)}catch{}try{child.kill(signal)}catch{}}function isProcessGroupAlive(pgid){try{return process.kill(-pgid,0),!0}catch(error2){return error2.code!=="ESRCH"}}function createExecWakeDriver(options){let driverName="exec",killGraceMs=Math.max(50,Math.floor(options.killGraceMs??DEFAULT_EXEC_KILL_GRACE_MS));return{name:driverName,wakeCapable:!0,deliver(envelope){return new Promise(resolve4=>{let child=spawn2(options.command,{shell:!0,detached:process.platform!=="win32",stdio:["pipe","pipe","pipe"],env:{...process.env,...options.env,ANDO_WORKROOM_ID:envelope.workroom_id,ANDO_WORKROOM_AGENT:envelope.self_agent??"",ANDO_WORKROOM_FROM_SEQ:String(envelope.from_seq),ANDO_WORKROOM_TO_SEQ:String(envelope.to_seq),ANDO_WORKROOM_EVENT_COUNT:String(envelope.event_count),ANDO_WORKROOM_REASONS:envelope.trigger_reasons.join(",")}}),pgid=process.platform!=="win32"&&typeof child.pid=="number"&&child.pid>0?child.pid:null,stderrChunks="",settled=!1,timedOut=!1,escalatedToSigkill=!1,childClosed=!1,cleanupTimer=null,finish=receipt=>{settled||(settled=!0,clearTimeout(timeoutHandle),cleanupTimer&&(clearTimeout(cleanupTimer),cleanupTimer=null),resolve4(receipt))},finishTimedOut=()=>{let detail=stderrChunks.trim(),termination=escalatedToSigkill?"SIGKILL":"SIGTERM";finish({ok:!1,driver:driverName,error:detail?`Wake command timed out after ${options.timeoutMs}ms (terminated via ${termination}): ${detail}`:`Wake command timed out after ${options.timeoutMs}ms (terminated via ${termination}).`})},runTimeoutCleanup=(sigkillAt,hardDeadlineAt)=>{if(settled)return;let groupAlive=pgid!==null&&isProcessGroupAlive(pgid);if(childClosed&&!groupAlive){finishTimedOut();return}let now=Date.now();if(now>=sigkillAt&&(escalatedToSigkill=!0,signalExecProcessTree(child,pgid,"SIGKILL"),childClosed&&(pgid===null||!isProcessGroupAlive(pgid)))){finishTimedOut();return}if(now>=hardDeadlineAt){finishTimedOut();return}let nextDelay=escalatedToSigkill?15:Math.min(EXEC_CLEANUP_POLL_MS,Math.max(10,sigkillAt-now));cleanupTimer=setTimeout(()=>{runTimeoutCleanup(sigkillAt,hardDeadlineAt)},nextDelay)},timeoutHandle=setTimeout(()=>{if(settled)return;timedOut=!0,signalExecProcessTree(child,pgid,"SIGTERM");let sigkillAt=Date.now()+killGraceMs,hardDeadlineAt=sigkillAt+Math.max(2e3,killGraceMs);cleanupTimer=setTimeout(()=>{runTimeoutCleanup(sigkillAt,hardDeadlineAt)},Math.min(EXEC_CLEANUP_POLL_MS,killGraceMs))},options.timeoutMs);child.stderr?.setEncoding("utf8"),child.stderr?.on("data",chunk=>{stderrChunks.length<2048&&(stderrChunks+=chunk)}),child.stdout?.resume(),child.on("error",error2=>{childClosed=!0,!timedOut&&finish({ok:!1,driver:driverName,error:`Failed to spawn wake command: ${error2.message}`})}),child.on("exit",()=>{timedOut&&(child.stdin?.destroy(),child.stdout?.destroy(),child.stderr?.destroy())}),child.on("close",(code2,signal)=>{if(childClosed=!0,timedOut)return;if(code2===0){finish({ok:!0,driver:driverName});return}let detail=stderrChunks.trim();finish({ok:!1,driver:driverName,error:detail?`Wake command exited with ${signal?`signal ${signal}`:`code ${code2}`}: ${detail}`:`Wake command exited with ${signal?`signal ${signal}`:`code ${code2}`}.`})}),child.stdin?.on("error",()=>{}),child.stdin?.end(`${JSON.stringify(envelope)}
|
|
399
|
+
`)})}}}function createAntigravityWakeDriver(options){let fetchImpl=options.fetchImpl??globalThis.fetch,sessionId=options.sessionId?.trim()||"",lsAddress=options.env.ANTIGRAVITY_LS_ADDRESS?.trim()||"",csrfToken=options.env.ANTIGRAVITY_CSRF_TOKEN?.trim()||"",projectId=options.env.ANTIGRAVITY_PROJECT_ID?.trim()||"",runAgentApi=options.execAgentApi??((args,opts)=>execFileAsync2("agentapi",args,opts)),useDirectLs=sessionId.length===0&&lsAddress.length>0&&csrfToken.length>0,driverName=useDirectLs?"antigravity-ls":sessionId.length>0?"antigravity-agentapi-session":"antigravity-agentapi";return{name:driverName,wakeCapable:!0,async deliver(envelope){let prompt=formatWorkroomWakePrompt(envelope);if(useDirectLs)try{let url2=`http://${lsAddress}/product.v1.ConversationService/CreateConversation`,body={title:`Workroom wake: ${envelope.workroom_id} (seq ${envelope.from_seq}..${envelope.to_seq})`,tags:["workroom-wake"],prompt:[{text:prompt}],...projectId?{projectId}:{}},response=await fetchImpl(url2,{method:"POST",headers:{"content-type":"application/json","connect-protocol-version":"1","x-antigravity-csrf-token":csrfToken},body:JSON.stringify(body),signal:AbortSignal.timeout(options.timeoutMs)});if(!response.ok){let text=await response.text().catch(()=>"");return{ok:!1,driver:driverName,error:`Antigravity ConversationService returned HTTP ${response.status}${text?`: ${text.slice(0,300)}`:""}.`}}return{ok:!0,driver:driverName}}catch(error2){return{ok:!1,driver:driverName,error:error2 instanceof Error?error2.message:`Antigravity wake request failed: ${String(error2)}`}}try{return await runAgentApi(sessionId?["send-message",sessionId,prompt]:["new-conversation","--",prompt],{timeout:options.timeoutMs,env:{...process.env,...options.env}}),{ok:!0,driver:driverName}}catch(error2){return{ok:!1,driver:driverName,error:error2 instanceof Error?error2.message:`agentapi wake failed: ${String(error2)}`}}}}}var WORKROOM_ID_RE=/^[A-Za-z0-9._:-]+$/u,MAX_WORKROOM_ID_LENGTH=128;function validateWorkroomId(candidate,original){if(!WORKROOM_ID_RE.test(candidate)||candidate.length>MAX_WORKROOM_ID_LENGTH)throw usageError(`Invalid workroom ID "${original}".`);return candidate}function parseWorkroomReference(raw){let trimmed=raw.trim();if(trimmed.length===0)throw usageError("Workroom ID cannot be empty.");if(trimmed.includes("://")||trimmed.startsWith("/")||trimmed.startsWith("?")||trimmed.startsWith("workroom=")||trimmed.includes("?workroom=")||trimmed.includes("&workroom=")){let extracted;try{let parseInput=trimmed.startsWith("workroom=")?`?${trimmed}`:trimmed.includes("://")||trimmed.startsWith("/")||trimmed.startsWith("?")?trimmed:`https://${trimmed}`;extracted=new URL(parseInput,"https://app.ando.so").searchParams.get("workroom")?.trim()??null}catch{throw usageError(`Invalid workroom URL "${raw}".`)}if(!extracted)throw usageError(`Workroom link "${raw}" is missing a ?workroom=<id> parameter.`);return validateWorkroomId(extracted,raw)}return validateWorkroomId(trimmed,raw)}function isInternalTurnWorkroomId(workroomId){return workroomId.startsWith("wr_")}function isSettledSoloTurnRoom(room){return isInternalTurnWorkroomId(room.workroom_id)&&room.status==="settled"&&room.participants.length<=1}var import_proper_lockfile3=__toESM(require_proper_lockfile(),1);import{createHash as createHash2}from"node:crypto";import{chmod as chmod4,mkdir as mkdir4,readdir as readdir2,readFile as readFile5,rename as rename4,rm as rm3,writeFile as writeFile4}from"node:fs/promises";import{dirname as dirname5,join as join6}from"node:path";function sanitizeWorkroomFilename(workroomId){return workroomId.replace(/[^A-Za-z0-9._-]/gu,"_")}function normalizeScopePart(value){let trimmed=value?.trim();return trimmed&&trimmed.length>0?trimmed:null}function computeWorkroomConsumerKey(scope){let workspaceId=normalizeScopePart(scope.workspaceId),membershipId=normalizeScopePart(scope.workspaceMembershipId),selfAgent=normalizeScopePart(scope.selfAgent)?.toLowerCase()??null,mode=scope.mode==="observe"?"observe":"wake",parts=[`ws=${workspaceId??"_"}`,`mem=${membershipId??"_"}`,`agent=${selfAgent??"_"}`,`mode=${mode}`];if(!workspaceId&&!membershipId){let fallbackOrigin=normalizeScopePart(scope.fallbackOrigin);fallbackOrigin&&parts.push(`origin=${fallbackOrigin}`)}return parts.join("|")}function workroomStateDir(env){return join6(dirname5(configPath(env)),"workrooms")}function workroomStateFilePath(env,workroomId,scope){let consumerKey=computeWorkroomConsumerKey(scope),digest=createHash2("sha256").update(`room=${workroomId}\0${consumerKey}`).digest("hex").slice(0,16);return join6(workroomStateDir(env),`${sanitizeWorkroomFilename(workroomId)}--${digest}.json`)}function createInitialWorkroomState(workroomId,scope,options){let initialSeq=Math.max(0,Math.floor(options?.initialSeq??0));return{schema_version:2,workroom_id:workroomId,consumer_key:computeWorkroomConsumerKey(scope),workspace_id:normalizeScopePart(scope.workspaceId),workspace_membership_id:normalizeScopePart(scope.workspaceMembershipId),self_agent:normalizeScopePart(scope.selfAgent),last_seen_seq:initialSeq,last_woken_seq:initialSeq,last_wake_at:null,last_wake_status:"idle",last_wake_error:null,consecutive_wake_failures:0,transport_attached:!1,transport_last_connected_at:null,wake_capable:options?.wakeCapable??!1,wake_driver:options?.wakeDriver??"stdout-jsonl",updated_at:(options?.now??new Date).toISOString()}}function readNonNegativeInt(value){return typeof value=="number"&&Number.isSafeInteger(value)&&value>=0?value:0}function readOptionalString(value){return typeof value=="string"?value:null}function normalizeLoadedState(parsed,fallbackWorkroomId){if(!parsed||typeof parsed!="object"||Array.isArray(parsed))return null;let raw=parsed;if(raw.schema_version!==2)return null;let workroomId=normalizeScopePart(readOptionalString(raw.workroom_id))??fallbackWorkroomId,workspaceId=normalizeScopePart(readOptionalString(raw.workspace_id)),membershipId=normalizeScopePart(readOptionalString(raw.workspace_membership_id)),selfAgent=normalizeScopePart(readOptionalString(raw.self_agent)),consumerKey=normalizeScopePart(readOptionalString(raw.consumer_key))??computeWorkroomConsumerKey({workspaceId,workspaceMembershipId:membershipId,selfAgent,mode:raw.wake_capable===!0?"wake":"observe"}),lastSeen=readNonNegativeInt(raw.last_seen_seq),lastWoken=Math.min(readNonNegativeInt(raw.last_woken_seq),lastSeen),status=raw.last_wake_status==="ok"||raw.last_wake_status==="failed"||raw.last_wake_status==="circuit_open"?raw.last_wake_status:"idle";return{schema_version:2,workroom_id:workroomId,consumer_key:consumerKey,workspace_id:workspaceId,workspace_membership_id:membershipId,self_agent:selfAgent,last_seen_seq:lastSeen,last_woken_seq:lastWoken,last_wake_at:readOptionalString(raw.last_wake_at),last_wake_status:status,last_wake_error:readOptionalString(raw.last_wake_error),consecutive_wake_failures:readNonNegativeInt(raw.consecutive_wake_failures),transport_attached:raw.transport_attached===!0,transport_last_connected_at:readOptionalString(raw.transport_last_connected_at),wake_capable:raw.wake_capable===!0,wake_driver:normalizeScopePart(readOptionalString(raw.wake_driver))??"stdout-jsonl",updated_at:readOptionalString(raw.updated_at)??new Date().toISOString()}}async function readWorkroomState(env,workroomId,scope){let path=workroomStateFilePath(env,workroomId,scope),expectedKey=computeWorkroomConsumerKey(scope),raw;try{raw=await readFile5(path,"utf8")}catch(error2){if(error2.code==="ENOENT")return null;throw error2}try{let loaded=normalizeLoadedState(JSON.parse(raw),workroomId);return!loaded||loaded.workroom_id!==workroomId||loaded.consumer_key!==expectedKey?null:loaded}catch{return null}}async function writeAtomicJson(path,payload){let temp=`${path}.${process.pid}.${Date.now()}.tmp`;try{await writeFile4(temp,`${JSON.stringify(payload,null,2)}
|
|
400
|
+
`,{mode:384}),await chmod4(temp,384),await rename4(temp,path)}catch(error2){throw await rm3(temp,{force:!0}).catch(()=>{}),error2}}var inProcessDirLocks=new Map;async function withInProcessDirLock(dir,fn){let previous=inProcessDirLocks.get(dir)??Promise.resolve(),releaseCurrent,current=new Promise(resolve4=>{releaseCurrent=resolve4}),tail=previous.then(()=>current);inProcessDirLocks.set(dir,tail),await previous;try{return await fn()}finally{releaseCurrent(),inProcessDirLocks.get(dir)===tail&&inProcessDirLocks.delete(dir)}}async function updateWorkroomState(env,workroomId,scope,updater,defaults){let dir=workroomStateDir(env),path=workroomStateFilePath(env,workroomId,scope),expectedKey=computeWorkroomConsumerKey(scope);return await withInProcessDirLock(dir,async()=>{await mkdir4(dir,{recursive:!0,mode:448});let release=await import_proper_lockfile3.default.lock(dir,{retries:10,stale:1e4,update:5e3});try{let existing=await readWorkroomState(env,workroomId,scope)??createInitialWorkroomState(workroomId,scope,defaults),next={...updater(existing),schema_version:2,workroom_id:workroomId,consumer_key:expectedKey,workspace_id:normalizeScopePart(scope.workspaceId),workspace_membership_id:normalizeScopePart(scope.workspaceMembershipId),self_agent:normalizeScopePart(scope.selfAgent),updated_at:new Date().toISOString()};return await writeAtomicJson(path,next),next}finally{await release()}})}async function listWorkroomStates(env,filter){let dir=workroomStateDir(env),entries;try{entries=await readdir2(dir)}catch(error2){if(error2.code==="ENOENT")return[];throw error2}let normalizedFilterAgent=normalizeScopePart(filter?.selfAgent)?.toLowerCase(),states=[];for(let name of entries){if(!name.endsWith(".json"))continue;let full=join6(dir,name);try{let raw=await readFile5(full,"utf8"),parsed=normalizeLoadedState(JSON.parse(raw),name.slice(0,-5));if(!parsed||filter?.workroomId&&parsed.workroom_id!==filter.workroomId||normalizedFilterAgent&&(parsed.self_agent?.toLowerCase()??"")!==normalizedFilterAgent)continue;states.push(parsed)}catch{}}return states.sort((a,b)=>a.workroom_id.localeCompare(b.workroom_id)||a.consumer_key.localeCompare(b.consumer_key)),states}var DECISION_ATTENTION_STATUSES=new Set(["needs_human","interrupted","hop_limit_exceeded","budget_exceeded"]);function isAttentionNeededWorkroom(room){return DECISION_ATTENTION_STATUSES.has(room.status)?!0:room.status==="active"&&typeof room.pending_capability=="string"&&room.pending_capability.trim().length>0}function readFiniteNonNegativeInt(value,fallback=0){return typeof value!="number"||!Number.isFinite(value)?fallback:Math.max(0,Math.trunc(value))}function normalizeWorkroomParticipant(raw){if(!raw||typeof raw!="object"||Array.isArray(raw))return null;let rec=raw,agent=typeof rec.agent=="string"?rec.agent.trim():"";if(agent.length===0)return null;let capabilities=Array.isArray(rec.capabilities)?rec.capabilities.filter(cap=>typeof cap=="string"&&cap.trim().length>0):void 0;return{agent,...typeof rec.provider=="string"?{provider:rec.provider}:{},...typeof rec.harness=="string"?{harness:rec.harness}:{},...typeof rec.cred_owner=="string"?{cred_owner:rec.cred_owner}:{},...capabilities?{capabilities}:{},...typeof rec.events=="number"&&Number.isFinite(rec.events)?{events:Math.max(0,Math.trunc(rec.events))}:{},...typeof rec.last_seen_ms=="number"&&Number.isFinite(rec.last_seen_ms)?{last_seen_ms:rec.last_seen_ms}:{},...typeof rec.last_action=="string"?{last_action:rec.last_action}:{},...typeof rec.transport_attached=="boolean"?{transport_attached:rec.transport_attached}:{},...typeof rec.wake_capable=="boolean"?{wake_capable:rec.wake_capable}:{}}}function normalizeWorkroomSummary(raw){if(!raw||typeof raw!="object"||Array.isArray(raw))return null;let rec=raw,workroomId=typeof rec.workroom_id=="string"?rec.workroom_id.trim():"";if(workroomId.length===0)return null;let rawParticipants=Array.isArray(rec.participants)?rec.participants:[],participants=[];for(let item of rawParticipants){let normalized=normalizeWorkroomParticipant(item);normalized&&participants.push(normalized)}return{workroom_id:workroomId,...typeof rec.workspace_id=="string"?{workspace_id:rec.workspace_id}:{},...typeof rec.parent_conversation_id=="string"?{parent_conversation_id:rec.parent_conversation_id}:{},title:typeof rec.title=="string"&&rec.title.trim().length>0?rec.title.trim():workroomId,status:typeof rec.status=="string"&&rec.status.trim().length>0?rec.status.trim():"active",event_count:readFiniteNonNegativeInt(rec.event_count),revision:readFiniteNonNegativeInt(rec.revision),updated_at_ms:readFiniteNonNegativeInt(rec.updated_at_ms),created_at_ms:readFiniteNonNegativeInt(rec.created_at_ms),...typeof rec.latest_agent=="string"?{latest_agent:rec.latest_agent}:{},...typeof rec.latest_summary=="string"?{latest_summary:rec.latest_summary}:{},...typeof rec.pending_capability=="string"||rec.pending_capability===null?{pending_capability:rec.pending_capability}:{},...typeof rec.live_stream_count=="number"&&Number.isFinite(rec.live_stream_count)?{live_stream_count:Math.max(0,Math.trunc(rec.live_stream_count))}:{},participants}}async function fetchWorkroomList(options){let params=new URLSearchParams;options.parentConversationId?.trim()&¶ms.set("parent_conversation_id",options.parentConversationId.trim()),options.capability?.trim()&¶ms.set("capability",options.capability.trim()),options.attentionOnly===!0&¶ms.set("attention_only","true"),options.includeTurnRooms===!0&¶ms.set("include_turn_rooms","true");let qs=params.toString(),url2=`${normalizeBaseUrl(options.edgeHttpUrl)}/v1/workrooms${qs?`?${qs}`:""}`,response=await options.fetchImpl(url2,{method:"GET",headers:{authorization:`Bearer ${options.ticket}`,accept:"application/json"},signal:options.signal}),body;try{body=await response.json()}catch{body=null}if(!response.ok)return{ok:!1,status:response.status,message:readWorkroomErrorMessage(body,response.status)};let record2=body&&typeof body=="object"&&!Array.isArray(body)?body:null;if(!record2||!Array.isArray(record2.workrooms))return{ok:!1,status:response.status,message:"Invalid workroom list response (missing workrooms array)"};let workrooms=[];for(let item of record2.workrooms){let normalized=normalizeWorkroomSummary(item);normalized&&workrooms.push(normalized)}return{ok:!0,workrooms}}async function fetchListWithSingleRefresh(options){let forceRefresh=!1;for(let attempt=0;attempt<2;attempt+=1){let ticket=await options.ticketProvider.getTicket(forceRefresh),result=await fetchWorkroomList({edgeHttpUrl:ticket.edgeHttpUrl,ticket:ticket.ticket,parentConversationId:options.parentConversationId,capability:options.capability,attentionOnly:options.attentionOnly,includeTurnRooms:options.includeTurnRooms,fetchImpl:options.fetchImpl,signal:options.signal});if(result.ok)return{ticket,workrooms:result.workrooms};if(shouldInvalidateWorkroomTicketForStatus(result.status)){if(options.ticketProvider.invalidate(),attempt===0){forceRefresh=!0;continue}if(result.status===401||result.status===403)throw new CliError(ExitCode.auth,`Failed to list workrooms (${result.status}): ${result.message}`)}throw new CliError(ExitCode.unavailable,`Failed to list workrooms (${result.status}): ${result.message}`)}throw new CliError(ExitCode.unavailable,"Failed to list workrooms.")}async function discoverWorkspaceWorkrooms(options){let parentIds=[...new Set((options.parentConversationIds??[]).map(id=>id.trim()).filter(id=>id.length>0))];if(parentIds.length===0)return await fetchListWithSingleRefresh({ticketProvider:options.ticketProvider,capability:options.capability,attentionOnly:options.attentionOnly,includeTurnRooms:options.includeTurnRooms,fetchImpl:options.fetchImpl,signal:options.signal});let byId=new Map,latestTicket=null;for(let parentConversationId of parentIds){let res=await fetchListWithSingleRefresh({ticketProvider:options.ticketProvider,parentConversationId,capability:options.capability,attentionOnly:options.attentionOnly,includeTurnRooms:options.includeTurnRooms,fetchImpl:options.fetchImpl,signal:options.signal});latestTicket=res.ticket;for(let room of res.workrooms){let prev=byId.get(room.workroom_id);(!prev||room.revision>prev.revision||room.updated_at_ms>prev.updated_at_ms)&&byId.set(room.workroom_id,room)}}return{ticket:latestTicket??await options.ticketProvider.getTicket(),workrooms:[...byId.values()]}}function scoreRoomPriority(room,selfAgentLower,capabilitiesLower){if(DECISION_ATTENTION_STATUSES.has(room.status))return 3;let pendingCap=room.pending_capability?.trim().toLowerCase()??"";return pendingCap.length>0&&capabilitiesLower.has(pendingCap)?2:selfAgentLower&&room.participants.some(p=>p.agent.trim().toLowerCase()===selfAgentLower)?1:0}function selectWorkspaceWatchTargets(discovered,options){let remainingSlots=Math.max(0,options.maxRooms-options.pinnedIds.size);if(remainingSlots===0)return[];let eligible=discovered.filter(room=>!(options.pinnedIds.has(room.workroom_id)||room.status==="settled"||options.attentionOnly&&!isAttentionNeededWorkroom(room)||!options.includeTurnRooms&&isInternalTurnWorkroomId(room.workroom_id))),selfAgentLower=options.selfAgent?.trim().toLowerCase()||null,capabilitiesLower=new Set(options.capabilities.map(c=>c.trim().toLowerCase()).filter(c=>c.length>0));return eligible.sort((a,b)=>{let scoreDiff=scoreRoomPriority(b,selfAgentLower,capabilitiesLower)-scoreRoomPriority(a,selfAgentLower,capabilitiesLower);return scoreDiff!==0?scoreDiff:b.updated_at_ms!==a.updated_at_ms?b.updated_at_ms-a.updated_at_ms:a.workroom_id.localeCompare(b.workroom_id)}),eligible.slice(0,remainingSlots)}async function resolveDiscoveredStartSeq(options){let scope=cursorScopeFromTicket(options.ticket,options.selfAgent,options.wakeCapable);if(await readWorkroomState(options.env,options.room.workroom_id,scope))return;if(options.replayExisting)return 0;if(!options.hasCompletedInitialDiscovery)return Math.max(0,options.room.event_count);let seenAtStartup=options.startupEventCounts.get(options.room.workroom_id);return seenAtStartup!==void 0?Math.max(0,seenAtStartup):0}function readNonNegativeSafeInt(value){return typeof value=="number"&&Number.isSafeInteger(value)&&value>=0?value:null}function isSequencedFrame(decoded){return decoded.type==="event"||decoded.type==="interrupt"||decoded.type==="human_control"}function isGapFrame(decoded){return decoded.type==="lagged"||decoded.type==="replay_truncated"||decoded.type==="breaker_tripped"}function handleAwaitingSnapshotFrame(decoded,sync,ctx,controls){if(decoded.type==="snapshot"){let snapshotEventCount=readNonNegativeSafeInt(decoded.workroom.event_count);if(snapshotEventCount===null){controls.startHttpCatchUp();return}if(snapshotEventCount<=sync.catchUpFloor){controls.clearFallbackTimer(),sync.phase="live";return}sync.replayTargetSeq=snapshotEventCount,sync.expectedReplaySeq=sync.catchUpFloor+1,sync.phase="native_replay",controls.armFallbackTimer(sync.nativeReplayFallbackMs);return}if(isSequencedFrame(decoded)){decoded.event.seq>0&&sync.liveBuffer.push(decoded.event),controls.startHttpCatchUp();return}isGapFrame(decoded)&&((decoded.type==="lagged"||decoded.type==="replay_truncated")&&ctx.log(`[${ctx.workroomId}] SSE ${decoded.type}; triggering HTTP catch-up from seq ${ctx.getLastSeenSeq()}`),controls.startHttpCatchUp())}async function handleNativeReplayFrame(decoded,sync,ctx,controls){if(isSequencedFrame(decoded)){let ev=decoded.event;if(ev.seq<=0){await controls.flushReplayBatch(),controls.startHttpCatchUp();return}if(ev.seq<sync.expectedReplaySeq)return;if(ev.seq>sync.expectedReplaySeq){await controls.flushReplayBatch(),sync.liveBuffer.push(ev),ctx.log(`[${ctx.workroomId}] SSE replay gap (expected seq ${sync.expectedReplaySeq}, got ${ev.seq}); falling back to HTTP catch-up`),controls.startHttpCatchUp();return}if(sync.replayBatch.push(ev),sync.expectedReplaySeq=ev.seq+1,ev.seq>=sync.replayTargetSeq){await controls.flushReplayBatch()||(controls.clearFallbackTimer(),sync.phase="live");return}controls.armFallbackTimer(sync.nativeReplayFallbackMs);return}isGapFrame(decoded)&&(await controls.flushReplayBatch(),(decoded.type==="lagged"||decoded.type==="replay_truncated")&&ctx.log(`[${ctx.workroomId}] SSE ${decoded.type}; triggering HTTP catch-up from seq ${ctx.getLastSeenSeq()}`),controls.startHttpCatchUp())}function createFallbackTimerController(){let timer=null,triggered=!1,pending=null,clear=()=>{timer!==null&&(clearTimeout(timer),timer=null),pending=null};return{arm:delayMs=>{clear(),triggered=!1,pending=new Promise(resolve4=>{timer=setTimeout(()=>{timer=null,triggered=!0,resolve4("fallback")},delayMs)})},clear,isTriggered:()=>triggered,getPending:()=>pending}}function createSseParser(onFrame){let buffer="",eventName="message",dataLines=[],lastId=null,retryMs=null,sawField=!1,pendingCr=!1;function dispatch(){if(!sawField&&dataLines.length===0){eventName="message",retryMs=null;return}dataLines.length>0&&onFrame({event:eventName||"message",data:dataLines.join(`
|
|
394
401
|
`),id:lastId,retryMs}),eventName="message",dataLines=[],retryMs=null,sawField=!1}function processLine(line){if(line.length===0){dispatch();return}if(line.startsWith(":"))return;sawField=!0;let colon=line.indexOf(":"),field=colon===-1?line:line.slice(0,colon),value=colon===-1?"":line.slice(colon+1);switch(value.startsWith(" ")&&(value=value.slice(1)),field){case"event":eventName=value;break;case"data":dataLines.push(value);break;case"id":value.includes("\0")||(lastId=value);break;case"retry":/^\d+$/u.test(value)&&(retryMs=Number.parseInt(value,10));break;default:break}}function feed(chunk){if(chunk.length===0)return;let text=chunk;pendingCr&&(pendingCr=!1,text.startsWith(`
|
|
395
402
|
`)&&(text=text.slice(1))),buffer.length===0&&text.startsWith("\uFEFF")&&(text=text.slice(1)),buffer+=text;let lineStart=0;for(let i2=0;i2<buffer.length;i2+=1){let ch=buffer[i2];ch===`
|
|
396
403
|
`?(processLine(buffer.slice(lineStart,i2)),lineStart=i2+1):ch==="\r"&&(processLine(buffer.slice(lineStart,i2)),i2+1<buffer.length&&buffer[i2+1]===`
|
|
@@ -448,14 +455,14 @@ Watch options:
|
|
|
448
455
|
`),ExitCode.ok;if(states.length===0)return io.stdout(`No local workroom watch state recorded.
|
|
449
456
|
`),ExitCode.ok;for(let s of states){let scopeSummary=`agent=${s.self_agent??"-"}${s.workspace_id?` ws=${s.workspace_id}`:""}`;io.stdout(`${s.workroom_id} ${scopeSummary} seen=${s.last_seen_seq} woken=${s.last_woken_seq} transport_attached=${s.transport_attached} wake_capable=${s.wake_capable} driver=${s.wake_driver} status=${s.last_wake_status}${s.consecutive_wake_failures>0?` failures=${s.consecutive_wake_failures}`:""}
|
|
450
457
|
`)}return ExitCode.ok}async function runWorkroomWatch(args,io,secret){let parsed=parseArgs3({args,options:{all:{type:"boolean"},chat:{type:"string",multiple:!0},"discover-interval-ms":{type:"string"},"max-rooms":{type:"string"},attention:{type:"boolean"},"include-turn-rooms":{type:"boolean"},"replay-existing":{type:"boolean"},agent:{type:"string"},"agent-id":{type:"string"},capability:{type:"string",multiple:!0},"wake-on":{type:"string"},"on-wake":{type:"string"},antigravity:{type:"boolean"},"antigravity-session":{type:"string"},jsonl:{type:"boolean"},"ack-stdout":{type:"boolean"},"after-seq":{type:"string"},"debounce-ms":{type:"string"},"wake-timeout-ms":{type:"string"},"max-wake-failures":{type:"string"},once:{type:"boolean"},"edge-url":{type:"string"},ticket:{type:"string"},"api-url":{type:"string"},quiet:{type:"boolean"},help:{type:"boolean",short:"h"}},allowPositionals:!0,strict:!0});if(parsed.values.help)return io.stdout(WORKROOM_USAGE),ExitCode.ok;let watchAll=parsed.values.all===!0,chatIds=parseChatIdFilters(parsed.values.chat);if(watchAll&&chatIds.length>0)throw usageError("Choose either --all or --chat <chat-id>, not both.");let useDiscovery=watchAll||chatIds.length>0,workroomIds=parseWorkroomIds(parsed.positionals,useDiscovery),rawPolicy=parsed.values["wake-on"]?.trim()||"targeted";if(rawPolicy!=="targeted"&&rawPolicy!=="all")throw usageError('--wake-on must be "targeted" or "all".');let policy=rawPolicy,debounceMs=parseNonNegativeIntOption("--debounce-ms",parsed.values["debounce-ms"],DEFAULT_DEBOUNCE_MS),wakeTimeoutMs=parseBoundedIntOption("--wake-timeout-ms",parsed.values["wake-timeout-ms"],DEFAULT_WAKE_TIMEOUT_MS,{min:1}),maxWakeFailures=parseBoundedIntOption("--max-wake-failures",parsed.values["max-wake-failures"],DEFAULT_MAX_WAKE_FAILURES,{min:1}),discoverIntervalMs=parseBoundedIntOption("--discover-interval-ms",parsed.values["discover-interval-ms"],DEFAULT_DISCOVER_INTERVAL_MS,{min:MIN_DISCOVER_INTERVAL_MS}),maxRooms=parseBoundedIntOption("--max-rooms",parsed.values["max-rooms"],DEFAULT_MAX_WATCHED_ROOMS,{min:1,max:MAX_WATCHED_ROOMS_LIMIT}),initialAfterSeq=parseNonNegativeIntOption("--after-seq",parsed.values["after-seq"]);if(useDiscovery&&initialAfterSeq!==void 0)throw usageError("--after-seq cannot be combined with --all or --chat; use --replay-existing to replay unseen rooms from seq 0.");let fetchImpl=io.fetch??globalThis.fetch,driver=resolveWakeDriver({onWakeCmd:parsed.values["on-wake"]?.trim(),useAntigravity:parsed.values.antigravity===!0||!!parsed.values["antigravity-session"]?.trim(),antigravitySession:parsed.values["antigravity-session"]?.trim(),ackStdout:parsed.values["ack-stdout"]===!0,wakeTimeoutMs,io,fetchImpl}),ticketProvider=await resolveTicketProvider({directEdgeUrl:parsed.values["edge-url"]?.trim(),directTicket:parsed.values.ticket?.trim(),agentId:parsed.values["agent-id"]?.trim(),apiUrlOverride:parsed.values["api-url"]?.trim(),io,secret,fetchImpl}),selfAgent=parsed.values.agent?.trim()||null,capabilities=parsed.values.capability??[],log2=parsed.values.quiet===!0?()=>{}:line=>{io.stderr(`${redact(line,secret.apiKey)}
|
|
451
|
-
`)},controller=new AbortController,onSignal=()=>controller.abort(new Error("Signal received"));process.on("SIGINT",onSignal),process.on("SIGTERM",onSignal);try{if(useDiscovery)return await watchWorkspaceWorkrooms({pinnedWorkroomIds:workroomIds,parentConversationIds:chatIds,includeTurnRooms:parsed.values["include-turn-rooms"]===!0,attentionOnly:parsed.values.attention===!0,replayExisting:parsed.values["replay-existing"]===!0,discoverIntervalMs,maxRooms,env:io.env,selfAgent,policy,capabilities,driver,ticketProvider,fetchImpl,signal:controller.signal,debounceMs,maxWakeFailures,once:parsed.values.once===!0,log:log2}),ExitCode.ok;let watchers=workroomIds.map(workroomId=>watchSingleWorkroom({workroomId,env:io.env,selfAgent,policy,capabilities,driver,ticketProvider,fetchImpl,signal:controller.signal,initialAfterSeq,debounceMs,maxWakeFailures,once:parsed.values.once===!0,log:log2}));try{await Promise.all(watchers)}catch(error2){throw controller.signal.aborted||controller.abort(error2 instanceof Error?error2:new Error(String(error2))),await Promise.allSettled(watchers),error2}}finally{process.off("SIGINT",onSignal),process.off("SIGTERM",onSignal)}return ExitCode.ok}async function runWorkroomCommand(args,io,secret){let[subcommand,...rest]=args;if(!subcommand||subcommand==="--help"||subcommand==="-h")return io.stdout(WORKROOM_USAGE),subcommand?ExitCode.ok:ExitCode.usage;switch(subcommand){case"list":return await runWorkroomList(rest,io,secret);case"watch":return await runWorkroomWatch(rest,io,secret);case"status":return await runWorkroomStatus(rest,io);default:throw usageError(`Unknown workroom subcommand "${subcommand}". Run \`ando workroom --help\`.`)}}var PATH_PARAM_RE=/\{[^{}]+\}/g,supportsRequestInitExt=()=>typeof process=="object"&&Number.parseInt(process?.versions?.node?.substring(0,2))>=18&&process.versions.undici;function randomID(){return Math.random().toString(36).slice(2,11)}function createClient(clientOptions){let{baseUrl="",Request:CustomRequest=globalThis.Request,fetch:baseFetch=globalThis.fetch,querySerializer:globalQuerySerializer,bodySerializer:globalBodySerializer,pathSerializer:globalPathSerializer,headers:baseHeaders,requestInitExt=void 0,...baseOptions}={...clientOptions};requestInitExt=supportsRequestInitExt()?requestInitExt:void 0,baseUrl=removeTrailingSlash(baseUrl);let globalMiddlewares=[];async function coreFetch(schemaPath,fetchOptions){let{baseUrl:localBaseUrl,fetch:fetch2=baseFetch,Request:Request2=CustomRequest,headers,params={},parseAs="json",querySerializer:requestQuerySerializer,bodySerializer=globalBodySerializer??defaultBodySerializer,pathSerializer:requestPathSerializer,body,middleware:requestMiddlewares=[],...init}=fetchOptions||{},finalBaseUrl=baseUrl;localBaseUrl&&(finalBaseUrl=removeTrailingSlash(localBaseUrl)??baseUrl);let querySerializer=typeof globalQuerySerializer=="function"?globalQuerySerializer:createQuerySerializer(globalQuerySerializer);requestQuerySerializer&&(querySerializer=typeof requestQuerySerializer=="function"?requestQuerySerializer:createQuerySerializer({...typeof globalQuerySerializer=="object"?globalQuerySerializer:{},...requestQuerySerializer}));let pathSerializer=requestPathSerializer||globalPathSerializer||defaultPathSerializer,serializedBody=body===void 0?void 0:bodySerializer(body,mergeHeaders(baseHeaders,headers,params.header)),finalHeaders=mergeHeaders(serializedBody===void 0||serializedBody instanceof FormData?{}:{"Content-Type":"application/json"},baseHeaders,headers,params.header),finalMiddlewares=[...globalMiddlewares,...requestMiddlewares],requestInit={redirect:"follow",...baseOptions,...init,body:serializedBody,headers:finalHeaders},id,options,request=new Request2(createFinalURL(schemaPath,{baseUrl:finalBaseUrl,params,querySerializer,pathSerializer}),requestInit),response;for(let key in init)key in request||(request[key]=init[key]);if(finalMiddlewares.length){id=randomID(),options=Object.freeze({baseUrl:finalBaseUrl,fetch:fetch2,parseAs,querySerializer,bodySerializer,pathSerializer});for(let m of finalMiddlewares)if(m&&typeof m=="object"&&typeof m.onRequest=="function"){let result=await m.onRequest({request,schemaPath,params,options,id});if(result)if(result instanceof Request2)request=result;else if(result instanceof Response){response=result;break}else throw new Error("onRequest: must return new Request() or Response() when modifying the request")}}if(!response){try{response=await fetch2(request,requestInitExt)}catch(error22){let errorAfterMiddleware=error22;if(finalMiddlewares.length)for(let i2=finalMiddlewares.length-1;i2>=0;i2--){let m=finalMiddlewares[i2];if(m&&typeof m=="object"&&typeof m.onError=="function"){let result=await m.onError({request,error:errorAfterMiddleware,schemaPath,params,options,id});if(result){if(result instanceof Response){errorAfterMiddleware=void 0,response=result;break}if(result instanceof Error){errorAfterMiddleware=result;continue}throw new Error("onError: must return new Response() or instance of Error")}}}if(errorAfterMiddleware)throw errorAfterMiddleware}if(finalMiddlewares.length)for(let i2=finalMiddlewares.length-1;i2>=0;i2--){let m=finalMiddlewares[i2];if(m&&typeof m=="object"&&typeof m.onResponse=="function"){let result=await m.onResponse({request,response,schemaPath,params,options,id});if(result){if(!(result instanceof Response))throw new Error("onResponse: must return new Response() when modifying the response");response=result}}}}let contentLength=response.headers.get("Content-Length");if(response.status===204||request.method==="HEAD"||contentLength==="0"&&!response.headers.get("Transfer-Encoding")?.includes("chunked"))return response.ok?{data:void 0,response}:{error:void 0,response};if(response.ok)return{data:await(async()=>{if(parseAs==="stream")return response.body;if(parseAs==="json"&&!contentLength){let raw=await response.text();return raw?JSON.parse(raw):void 0}return await response[parseAs]()})(),response};let error2=await response.text();try{error2=JSON.parse(error2)}catch{}return{error:error2,response}}return{request(method,url2,init){return coreFetch(url2,{...init,method:method.toUpperCase()})},GET(url2,init){return coreFetch(url2,{...init,method:"GET"})},PUT(url2,init){return coreFetch(url2,{...init,method:"PUT"})},POST(url2,init){return coreFetch(url2,{...init,method:"POST"})},DELETE(url2,init){return coreFetch(url2,{...init,method:"DELETE"})},OPTIONS(url2,init){return coreFetch(url2,{...init,method:"OPTIONS"})},HEAD(url2,init){return coreFetch(url2,{...init,method:"HEAD"})},PATCH(url2,init){return coreFetch(url2,{...init,method:"PATCH"})},TRACE(url2,init){return coreFetch(url2,{...init,method:"TRACE"})},use(...middleware){for(let m of middleware)if(m){if(typeof m!="object"||!("onRequest"in m||"onResponse"in m||"onError"in m))throw new Error("Middleware must be an object with one of `onRequest()`, `onResponse() or `onError()`");globalMiddlewares.push(m)}},eject(...middleware){for(let m of middleware){let i2=globalMiddlewares.indexOf(m);i2!==-1&&globalMiddlewares.splice(i2,1)}}}}function serializePrimitiveParam(name,value,options){if(value==null)return"";if(typeof value=="object")throw new Error("Deeply-nested arrays/objects aren\u2019t supported. Provide your own `querySerializer()` to handle these.");return`${name}=${options?.allowReserved===!0?value:encodeURIComponent(value)}`}function serializeObjectParam(name,value,options){if(!value||typeof value!="object")return"";let values=[],joiner={simple:",",label:".",matrix:";"}[options.style]||"&";if(options.style!=="deepObject"&&options.explode===!1){for(let k in value)values.push(k,options.allowReserved===!0?value[k]:encodeURIComponent(value[k]));let final2=values.join(",");switch(options.style){case"form":return`${name}=${final2}`;case"label":return`.${final2}`;case"matrix":return`;${name}=${final2}`;default:return final2}}for(let k in value){let finalName=options.style==="deepObject"?`${name}[${k}]`:k;values.push(serializePrimitiveParam(finalName,value[k],options))}let final=values.join(joiner);return options.style==="label"||options.style==="matrix"?`${joiner}${final}`:final}function serializeArrayParam(name,value,options){if(!Array.isArray(value))return"";if(options.explode===!1){let joiner2={form:",",spaceDelimited:"%20",pipeDelimited:"|"}[options.style]||",",final=(options.allowReserved===!0?value:value.map(v2=>encodeURIComponent(v2))).join(joiner2);switch(options.style){case"simple":return final;case"label":return`.${final}`;case"matrix":return`;${name}=${final}`;default:return`${name}=${final}`}}let joiner={simple:",",label:".",matrix:";"}[options.style]||"&",values=[];for(let v2 of value)options.style==="simple"||options.style==="label"?values.push(options.allowReserved===!0?v2:encodeURIComponent(v2)):values.push(serializePrimitiveParam(name,v2,options));return options.style==="label"||options.style==="matrix"?`${joiner}${values.join(joiner)}`:values.join(joiner)}function createQuerySerializer(options){return function(queryParams){let search=[];if(queryParams&&typeof queryParams=="object")for(let name in queryParams){let value=queryParams[name];if(value!=null){if(Array.isArray(value)){if(value.length===0)continue;search.push(serializeArrayParam(name,value,{style:"form",explode:!0,...options?.array,allowReserved:options?.allowReserved||!1}));continue}if(typeof value=="object"){search.push(serializeObjectParam(name,value,{style:"deepObject",explode:!0,...options?.object,allowReserved:options?.allowReserved||!1}));continue}search.push(serializePrimitiveParam(name,value,options))}}return search.join("&")}}function defaultPathSerializer(pathname,pathParams){let nextURL=pathname;for(let match of pathname.match(PATH_PARAM_RE)??[]){let name=match.substring(1,match.length-1),explode=!1,style="simple";if(name.endsWith("*")&&(explode=!0,name=name.substring(0,name.length-1)),name.startsWith(".")?(style="label",name=name.substring(1)):name.startsWith(";")&&(style="matrix",name=name.substring(1)),!pathParams||pathParams[name]===void 0||pathParams[name]===null)continue;let value=pathParams[name];if(Array.isArray(value)){nextURL=nextURL.replace(match,serializeArrayParam(name,value,{style,explode}));continue}if(typeof value=="object"){nextURL=nextURL.replace(match,serializeObjectParam(name,value,{style,explode}));continue}if(style==="matrix"){nextURL=nextURL.replace(match,`;${serializePrimitiveParam(name,value)}`);continue}nextURL=nextURL.replace(match,style==="label"?`.${encodeURIComponent(value)}`:encodeURIComponent(value))}return nextURL}function defaultBodySerializer(body,headers){return body instanceof FormData?body:headers&&(headers.get instanceof Function?headers.get("Content-Type")??headers.get("content-type"):headers["Content-Type"]??headers["content-type"])==="application/x-www-form-urlencoded"?new URLSearchParams(body).toString():JSON.stringify(body)}function createFinalURL(pathname,options){let finalURL=`${options.baseUrl}${pathname}`;options.params?.path&&(finalURL=options.pathSerializer(finalURL,options.params.path));let search=options.querySerializer(options.params.query??{});return search.startsWith("?")&&(search=search.substring(1)),search&&(finalURL+=`?${search}`),finalURL}function mergeHeaders(...allHeaders){let finalHeaders=new Headers;for(let h of allHeaders){if(!h||typeof h!="object")continue;let iterator=h instanceof Headers?h.entries():Object.entries(h);for(let[k,v2]of iterator)if(v2===null)finalHeaders.delete(k);else if(Array.isArray(v2))for(let v22 of v2)finalHeaders.append(k,v22);else v2!==void 0&&finalHeaders.set(k,v2)}return finalHeaders}function removeTrailingSlash(url2){return url2.endsWith("/")?url2.substring(0,url2.length-1):url2}function createAuthenticatedFetch(options){let base=new URL(options.baseUrl??"https://api.ando.so/v1"),loopback=["localhost","127.0.0.1","[::1]"].includes(base.hostname);if(base.protocol!=="https:"&&!(base.protocol==="http:"&&loopback)||base.username||base.password||base.search||base.hash)throw new Error("Ando API requires an HTTPS base URL (HTTP is allowed on loopback)");let timeout=options.requestTimeoutMs??3e4;if(!Number.isSafeInteger(timeout)||timeout<=0||timeout>2147483647)throw new Error("requestTimeoutMs must be a positive 32-bit integer");let apiKey=options.apiKey;if(!apiKey.trim()||/[\r\n]/u.test(apiKey))throw new Error("A valid API key is required");let fetchImpl=options.fetch??globalThis.fetch,prefix=base.pathname.replace(/\/$/u,"");return async request=>{let target=new URL(request.url);if(target.origin!==base.origin||!target.pathname.startsWith(`${prefix}/`))throw new Error("Ando API request escaped the configured API origin or prefix");let headers=new Headers(request.headers);headers.set("Authorization",`Bearer ${apiKey}`);let signal=AbortSignal.any([request.signal,AbortSignal.timeout(timeout)]);return signal.throwIfAborted(),fetchImpl(new Request(request,{headers,signal,redirect:"error"}))}}function createAndoApiClient(options){let fetch2=createAuthenticatedFetch(options),base=new URL(options.baseUrl??"https://api.ando.so/v1");return createClient({baseUrl:`${base.origin}${base.pathname.replace(/\/$/u,"")}`,fetch:fetch2})}function createClient2(options){try{return createAndoApiClient({apiKey:options.apiKey,baseUrl:options.apiUrl,...options.fetch?{fetch:options.fetch}:{}})}catch(error2){throw new CliError(ExitCode.usage,`Cannot use API URL ${options.apiUrl}: ${error2.message}`)}}function exitCodeForStatus(status){return status===401||status===403?ExitCode.auth:status===404||status===410?ExitCode.notFound:status===429||status>=500?ExitCode.unavailable:ExitCode.usage}function errorText(error2){if(error2&&typeof error2=="object"){let record2=error2;if(typeof record2.error=="string")return record2.error;if(record2.error&&typeof record2.error=="object"&&typeof record2.error.message=="string")return record2.error.message;if(typeof record2.message=="string")return record2.message}return null}var TransientApiError=class extends CliError{constructor(message){super(ExitCode.unavailable,message)}};async function call(what,request){let result;try{result=await request}catch(error2){let name=error2?.name;throw name==="TimeoutError"||name==="AbortError"?new TransientApiError(`${what} timed out.`):new TransientApiError(`${what} failed: ${error2?.message??String(error2)}`)}let{response}=result;if(response.ok&&result.data!==void 0)return result.data;let status=response.status,detail=errorText(result.error),message=`${what} failed (HTTP ${status})${detail?`: ${detail.replace(/[.!?]?$/u,".")}`:"."}`;throw status===429||status>=500?new TransientApiError(message):status===401?new CliError(ExitCode.auth,`${message} The API key was rejected; run \`ando login\` again.`):status===403?new CliError(ExitCode.auth,`${message} The key needs the messages:read and messages:write scopes, and its member must be in the conversation.`):new CliError(exitCodeForStatus(status),message)}import{randomUUID}from"node:crypto";var MESSAGE_MAX_LENGTH=4e4;function codeBlock(text){let body=text.replace(/\n+$/u,""),longestRun=Math.max(0,...Array.from(body.matchAll(/`+/gu),match=>match[0].length)),fence="`".repeat(Math.max(3,longestRun+1));return`${fence}
|
|
458
|
+
`)},controller=new AbortController,onSignal=()=>controller.abort(new Error("Signal received"));process.on("SIGINT",onSignal),process.on("SIGTERM",onSignal);try{if(useDiscovery)return await watchWorkspaceWorkrooms({pinnedWorkroomIds:workroomIds,parentConversationIds:chatIds,includeTurnRooms:parsed.values["include-turn-rooms"]===!0,attentionOnly:parsed.values.attention===!0,replayExisting:parsed.values["replay-existing"]===!0,discoverIntervalMs,maxRooms,env:io.env,selfAgent,policy,capabilities,driver,ticketProvider,fetchImpl,signal:controller.signal,debounceMs,maxWakeFailures,once:parsed.values.once===!0,log:log2}),ExitCode.ok;let watchers=workroomIds.map(workroomId=>watchSingleWorkroom({workroomId,env:io.env,selfAgent,policy,capabilities,driver,ticketProvider,fetchImpl,signal:controller.signal,initialAfterSeq,debounceMs,maxWakeFailures,once:parsed.values.once===!0,log:log2}));try{await Promise.all(watchers)}catch(error2){throw controller.signal.aborted||controller.abort(error2 instanceof Error?error2:new Error(String(error2))),await Promise.allSettled(watchers),error2}}finally{process.off("SIGINT",onSignal),process.off("SIGTERM",onSignal)}return ExitCode.ok}async function runWorkroomCommand(args,io,secret){let[subcommand,...rest]=args;if(!subcommand||subcommand==="--help"||subcommand==="-h")return io.stdout(WORKROOM_USAGE),subcommand?ExitCode.ok:ExitCode.usage;switch(subcommand){case"list":return await runWorkroomList(rest,io,secret);case"watch":return await runWorkroomWatch(rest,io,secret);case"status":return await runWorkroomStatus(rest,io);default:throw usageError(`Unknown workroom subcommand "${subcommand}". Run \`ando workroom --help\`.`)}}import{randomUUID}from"node:crypto";var MESSAGE_MAX_LENGTH=4e4;function codeBlock(text){let body=text.replace(/\n+$/u,""),longestRun=Math.max(0,...Array.from(body.matchAll(/`+/gu),match=>match[0].length)),fence="`".repeat(Math.max(3,longestRun+1));return`${fence}
|
|
452
459
|
${body}
|
|
453
460
|
${fence}`}function mention(membershipId,name){let label=name.replace(/[|>\n]/gu," ").trim()||"agent";return`<!workspace_membership:${membershipId}|${label}>`}function checkLength(markdown){if(markdown.trim().length===0)throw usageError("Message is empty. Nothing was posted.");if(markdown.length>MESSAGE_MAX_LENGTH)throw usageError(`Message is ${markdown.length.toLocaleString("en-US")} characters; Ando accepts at most ${MESSAGE_MAX_LENGTH.toLocaleString("en-US")}. Nothing was posted.`)}async function postMessage(api,input){checkLength(input.markdown);let idempotencyKey=input.idempotencyKey??randomUUID(),send2=()=>call("Posting the message",api.POST("/conversations/{conversationId}/messages",{params:{header:{"Idempotency-Key":idempotencyKey},path:{conversationId:input.conversationId}},body:{markdown_content:input.markdown,...input.threadRootId?{thread_root_id:input.threadRootId}:{}}})),result;try{result=await send2()}catch(error2){if(!(error2 instanceof TransientApiError))throw error2;result=await send2()}if("scheduled_message"in result.data)throw new TransientApiError("Ando scheduled the message instead of posting it.");let workspaceId=("legacy_data"in result?result.legacy_data:null)?.workspace_id;return{message:result.data,workspaceId:typeof workspaceId=="string"?workspaceId:null}}async function messageLink(api,webUrl,posted,threadRootId){if(!webUrl)return null;let{message}=posted;try{let workspaceId=posted.workspaceId??(await call("Reading the conversation",api.GET("/conversations/{conversationId}/context",{params:{path:{conversationId:message.conversation_id}}}))).data.workspace_id,path=`/${encodeURIComponent(workspaceId)}/${encodeURIComponent(message.conversation_id)}/${encodeURIComponent(message.id)}`,query=threadRootId?`?thread_root_id=${encodeURIComponent(threadRootId)}`:"";return`${webUrl.replace(/\/$/u,"")}${path}${query}`}catch{return null}}var ID_PATTERN=/^[A-Za-z0-9_-]{8,}$/u,MAX_LISTED=10;function listCandidates(names){let shown=names.slice(0,MAX_LISTED).map(name=>` ${name}`);return names.length>MAX_LISTED&&shown.push(` \u2026and ${names.length-MAX_LISTED} more`),shown.join(`
|
|
454
461
|
`)}var normalize=value=>value.trim().toLowerCase();async function resolveConversation(api,target){let trimmed=target.trim();if(!trimmed.startsWith("#")){if(!ID_PATTERN.test(trimmed))throw usageError(`"${target}" is not a channel. Use #channel-name or a conversation id.`);return{id:trimmed,label:trimmed}}let name=trimmed.slice(1);if(!name)throw usageError("Channel name is empty. Use #channel-name.");let result=await call("Channel search",api.GET("/search/conversations",{params:{query:{q:name}}})),channels=(result.data?.items??result.items??[]).filter(conversation=>conversation.type===0&&conversation.name),exact=channels.filter(conversation=>normalize(conversation.name??"")===normalize(name));if(exact.length===1)return{id:exact[0].id,label:`#${exact[0].name}`};throw exact.length>1?new CliError(ExitCode.notFound,`#${name} matches ${exact.length} channels. Use a conversation id instead:
|
|
455
462
|
${listCandidates(exact.map(conversation=>`#${conversation.name} ${conversation.id}`))}`):new CliError(ExitCode.notFound,channels.length===0?`No channel named #${name} that this key can see.`:`No channel named #${name}. Similar channels:
|
|
456
463
|
${listCandidates(channels.map(conversation=>`#${conversation.name} ${conversation.id}`))}`)}function agentLabel(member){return member.display_name?`@${member.handle} (${member.display_name})`:`@${member.handle}`}var MAX_MEMBER_LOOKUPS=10;async function agentCandidates(api,name){let query=name.replace(/[-_.]+/gu," ").trim()||name,result=await call("Agent search",api.GET("/search/members",{params:{query:{q:query}}})),hits=result.data?.items??result.items??[];return(await Promise.all(hits.slice(0,MAX_MEMBER_LOOKUPS).map(async hit=>{if(hit.principal_type&&hit.principal_type!=="agent")return null;if(hit.principal_type&&hit.handle)return hit;let id=hit.workspace_membership_id??hit.workspaceMembershipId??hit.id;if(!id)return null;try{return await call("Reading a member",api.GET("/members/{memberId}",{params:{path:{memberId:id}}}))}catch(error2){if(error2 instanceof CliError&&error2.exitCode===ExitCode.notFound)return null;throw error2}}))).filter(member=>member?.principal_type==="agent")}async function resolveAgent(api,target){let name=target.trim().replace(/^@/u,"");if(!name)throw usageError("Agent name is empty. Use @agent-name.");let agents=await agentCandidates(api,name),wanted=normalize(name),byHandle=agents.filter(member=>normalize(member.handle)===wanted),exact=byHandle.length>0?byHandle:agents.filter(member=>normalize(member.display_name??"")===wanted);if(exact.length===1){let agent=exact[0];return{membershipId:agent.workspace_membership_id,authorIds:new Set([agent.workspace_membership_id,agent.id,agent.membership_id].filter(Boolean)),name:agent.display_name||agent.handle,handle:agent.handle}}throw exact.length>1?new CliError(ExitCode.notFound,`@${name} matches ${exact.length} agents. Use the handle:
|
|
457
464
|
${listCandidates(exact.map(agentLabel))}`):new CliError(ExitCode.notFound,agents.length===0?`No agent named @${name} in this workspace.`:`No agent named @${name}. Similar agents:
|
|
458
|
-
${listCandidates(agents.map(agentLabel))}`)}
|
|
465
|
+
${listCandidates(agents.map(agentLabel))}`)}import{createHash as createHash3}from"node:crypto";import{basename}from"node:path";var MANAGED_KEYS=new Set(["id","title","scope","revision"]),BLOCK_SCALAR_PATTERN=/^[|>][+-]?\d*$/u,UNSUPPORTED_YAML_START=/^[&*![{]/u;var GENERATED_SOURCE_NOTES_FOOTER=/(?:^|\n)<!-- ando:source-notes -->\n## Recently noted(?:\n|$)/u;function normalizeNewlines(value){return value.replace(/\r\n/gu,`
|
|
459
466
|
`).replace(/\r/gu,`
|
|
460
467
|
`)}function stripGeneratedSourceNotes(body){let normalized=normalizeNewlines(body),match=GENERATED_SOURCE_NOTES_FOOTER.exec(normalized);return match?normalized.slice(0,match.index).replace(/\n+$/u,""):normalized}function normalizeWikiBody(body){return normalizeNewlines(body).replace(/^\n+/u,"").replace(/\n+$/u,"")}function stripUnquotedInlineComment(raw){let match=/\s+#.*$/u.exec(raw);return match?raw.slice(0,match.index).trimEnd():raw}function assertValidTrailingAfterQuote(key,trailing){let rest=trailing.trim();if(!(rest.length===0||rest.startsWith("#")))throw new CliError(ExitCode.usage,`Invalid trailing characters after quoted YAML scalar for frontmatter field "${key}".`)}function parseDoubleQuotedScalar(key,raw){let out="";for(let i2=1;i2<raw.length;i2++){let ch=raw[i2];if(ch==='"')return assertValidTrailingAfterQuote(key,raw.slice(i2+1)),out;if(ch==="\\"&&i2+1<raw.length){let next=raw[++i2];next==="n"?out+=`
|
|
461
468
|
`:next==="r"?out+="\r":next==="t"?out+=" ":next==='"'||next==="\\"?out+=next:out+=`\\${next}`}else out+=ch}throw new CliError(ExitCode.usage,`Unterminated double-quoted YAML scalar for frontmatter field "${key}".`)}function parseSingleQuotedScalar(key,raw){let out="";for(let i2=1;i2<raw.length;i2++){let ch=raw[i2];if(ch==="'"){if(raw[i2+1]==="'"){out+="'",i2++;continue}return assertValidTrailingAfterQuote(key,raw.slice(i2+1)),out}out+=ch}throw new CliError(ExitCode.usage,`Unterminated single-quoted YAML scalar for frontmatter field "${key}".`)}function parseManagedScalar(key,raw){let trimmed=raw.trim();if(trimmed.startsWith('"'))return parseDoubleQuotedScalar(key,trimmed);if(trimmed.startsWith("'"))return parseSingleQuotedScalar(key,trimmed);let withoutComment=stripUnquotedInlineComment(trimmed);if(BLOCK_SCALAR_PATTERN.test(withoutComment))throw new CliError(ExitCode.usage,`Unsupported YAML block scalar for frontmatter field "${key}". Use a single-line scalar.`);if(UNSUPPORTED_YAML_START.test(withoutComment))throw new CliError(ExitCode.usage,`Unsupported YAML syntax for frontmatter field "${key}". Quote the value as a string.`);return withoutComment}function quoteYamlScalar(value){return`"${value.replace(/\\/gu,"\\\\").replace(/"/gu,'\\"').replace(/\n/gu,"\\n").replace(/\r/gu,"\\r").replace(/\t/gu,"\\t")}"`}function parseWikiFrontmatter(markdown){let normalized=normalizeNewlines(markdown);if(!normalized.startsWith(`---
|
|
@@ -473,9 +480,9 @@ ${listCandidates(agents.map(agentLabel))}`)}var systemClock={now:()=>Date.now(),
|
|
|
473
480
|
${normalizedBody}
|
|
474
481
|
`}function hashWikiContent(title,body){let normalizedBody=normalizeWikiBody(body);return createHash3("sha256").update(JSON.stringify([title,normalizedBody])).digest("hex")}function stripControlChars(value){let out="";for(let i2=0;i2<value.length;i2++){let code2=value.charCodeAt(i2);out+=code2<=31||code2===127?" ":value[i2]}return out}function sanitizeFileStem(title,fallbackId){let cleaned=stripControlChars(title.normalize("NFKC")).replace(/[/\\:*?"<>|]+/gu," ").replace(/\.{2,}/gu," ").trim().replace(/^\.+/u,"").trim().replace(/\s+/gu,"-").replace(/-+/gu,"-").replace(/^[.-]+|-+$/gu,"").slice(0,80);if(cleaned.length>0&&cleaned!=="."&&cleaned!=="..")return cleaned;let safeId=fallbackId.replace(/[^A-Za-z0-9._-]+/gu,"-").slice(0,80);return safeId.length>0?safeId:"untitled"}function deriveTitleFromMarkdown(filePath,body){for(let line of normalizeNewlines(body).split(`
|
|
475
482
|
`)){let trimmed=line.trim();if(!trimmed)continue;let heading=/^#\s+(.+?)\s*#*$/u.exec(trimmed);if(heading&&heading[1].trim().length>0)return heading[1].trim().slice(0,200);break}return(basename(filePath).replace(/\.md$/iu,"").replace(/[-_]+/gu," ").trim()||"Untitled").slice(0,200)}var DEFAULT_MCP_URL="https://mcp.ando.so/mcp",MCP_PROTOCOL_VERSION="2025-06-18",MCP_REQUEST_TIMEOUT_MS=3e4,READ_ONLY_SYNTHETIC_PAGE_IDS=new Set(["glossary","agent-notes"]);function parseWikiScope(raw){let value=(raw??"workspace").trim();if(value==="workspace")return{type:"workspace"};let sep=value.indexOf(":");if(sep>0){let type=value.slice(0,sep),id=value.slice(sep+1).trim();if((type==="channel"||type==="member"||type==="repository")&&id.length>0)return{type,id}}throw new CliError(ExitCode.usage,`Invalid --scope "${value}". Use "workspace", "channel:<id>", "member:<id>", or "repository:<owner/name>".`)}function formatWikiScope(scope){return scope.type==="workspace"?"workspace":`${scope.type}:${scope.id}`}function resolveMcpUrl(env,explicit){let raw=explicit?.trim()||env.ANDO_MCP_URL?.trim()||DEFAULT_MCP_URL,parsed;try{parsed=new URL(raw)}catch{throw new CliError(ExitCode.usage,`Invalid MCP URL "${raw}".`)}if(parsed.protocol!=="https:"&&parsed.protocol!=="http:")throw new CliError(ExitCode.usage,`MCP URL must use http or https: "${raw}".`);return parsed.toString()}function parseSseJsonRpc(body,id){for(let frame of body.split(/\r?\n\r?\n/u)){let data=frame.split(/\r?\n/u).filter(line=>line.startsWith("data:")).map(line=>line.slice(5).replace(/^ /u,"")).join(`
|
|
476
|
-
`);if(data)try{let parsed=JSON.parse(data);if(parsed&&typeof parsed=="object"&&parsed.id===id)return parsed}catch{}}return null}function unwrapToolPayload(result,toolName){if(!result||typeof result!="object")throw new CliError(ExitCode.unavailable,`Unexpected empty MCP response from ${toolName}.`);let record2=result,payload=record2.structuredContent;if(payload===void 0&&Array.isArray(record2.content)){let textBlock=record2.content.find(item=>item?.type==="text"&&typeof item.text=="string");if(textBlock?.text!==void 0)try{payload=JSON.parse(textBlock.text)}catch{payload={message:textBlock.text}}}if(record2.isError){let errObj=payload&&typeof payload=="object"?payload:null,detail=errObj?.message||errObj?.error||`${toolName} returned an error.`,code2=errObj?.code;throw code2==="permission_required"||code2==="unauthorized"?new CliError(ExitCode.auth,detail):code2==="page_unavailable"||code2==="not_found"?new CliError(ExitCode.notFound,detail):new CliError(ExitCode.usage,detail)}return payload}function createWikiMcpClient(options){let fetchImpl=options.fetch??globalThis.fetch,nextId=1;async function callTool(name,args){let id=nextId++,response;try{response=await fetchImpl(options.mcpUrl,{method:"POST",headers:{accept:"application/json, text/event-stream","content-type":"application/json",authorization:`Bearer ${options.apiKey}`,"mcp-protocol-version":MCP_PROTOCOL_VERSION},body:JSON.stringify({jsonrpc:"2.0",id,method:"tools/call",params:{name,arguments:args}}),signal:AbortSignal.timeout(MCP_REQUEST_TIMEOUT_MS)})}catch(error2){throw new CliError(ExitCode.unavailable,`Calling ${name} failed: ${error2?.message??String(error2)}`)}if(response.status===401||response.status===403)throw new CliError(ExitCode.auth,`MCP request ${name} rejected (HTTP ${response.status}). Ensure your API key has documents:read and documents:write scopes.`);if(response.status===429||response.status>=500)throw new CliError(ExitCode.unavailable,`MCP request ${name} failed (HTTP ${response.status}).`);let contentType2=response.headers.get("content-type")??"",rawText=await response.text(),rpc;if(contentType2.includes("text/event-stream"))rpc=parseSseJsonRpc(rawText,id);else try{rpc=JSON.parse(rawText)}catch{rpc=null}if(rpc?.error)throw new CliError(ExitCode.unavailable,`MCP error from ${name}: ${rpc.error.message??"unknown error"}`);if(!response.ok||!rpc||rpc.result===void 0)throw new CliError(ExitCode.unavailable,`Unexpected MCP response from ${name} (HTTP ${response.status}).`);return unwrapToolPayload(rpc.result,name)}return{async listPages(scope){let seen=new Map,cursor;for(let page=0;page<200;page++){let result=await callTool("read_wiki_page",{scope,limit:50,...cursor?{cursor}:{}});result?.context&&!READ_ONLY_SYNTHETIC_PAGE_IDS.has(result.context.pageId)&&seen.set(result.context.pageId,{pageId:result.context.pageId,title:result.context.title,revision:result.context.revision,updatedAt:result.context.updatedAt});for(let item of result?.items??[])READ_ONLY_SYNTHETIC_PAGE_IDS.has(item.pageId)||seen.set(item.pageId,{pageId:item.pageId,title:item.title,revision:item.revision,updatedAt:item.updatedAt});if(!result?.hasMore||!result.nextCursor)break;cursor=result.nextCursor}return[...seen.values()].sort((a,b)=>a.pageId.localeCompare(b.pageId))},async readPage(scope,pageId){let cursor,content="",meta2=null,purpose,liveEditing;for(let chunk=0;chunk<100;chunk++){let result=await callTool("read_wiki_page",{scope,pageId,...cursor?{cursor}:{}});if(!result?.page)throw new CliError(ExitCode.notFound,`Page "${pageId}" was not returned by read_wiki_page.`);if(meta2||(meta2={pageId:result.page.pageId,title:result.page.title,revision:result.page.revision,updatedAt:result.page.updatedAt},purpose=result.page.purpose,result.liveEditing&&(liveEditing={activeEditorCount:result.liveEditing.activeEditorCount,hasUnsavedChanges:result.liveEditing.hasUnsavedChanges})),content+=result.page.content,!result.page.hasMore||!result.page.nextCursor)break;cursor=result.page.nextCursor}let editableContent=scope.type==="member"&&purpose==="notes"?stripGeneratedSourceNotes(content):content;return{...meta2,content:editableContent,...liveEditing?{liveEditing}:{}}},async savePage(input){let result=await callTool("save_wiki_page",{scope:input.scope,...input.pageId?{pageId:input.pageId}:{},title:input.title,content:input.content,...input.expectedRevision!==void 0?{expectedRevision:input.expectedRevision}:{},idempotencyKey:input.idempotencyKey});if(result?.result==="stale")return{result:"stale",currentRevision:result.current?.revision??result.currentRevision??0,currentTitle:result.current?.title??input.title,currentContent:result.current?.content??""};if((result?.result==="saved"||result?.result==="replayed")&&typeof result.pageId=="string"&&typeof result.revision=="number")return{result:"saved",pageId:result.pageId,revision:result.revision};throw new CliError(ExitCode.unavailable,`Unexpected save_wiki_page response for "${input.title}".`)}}}import{mkdir as mkdir5}from"node:fs/promises";import{join as join7,resolve as resolve2}from"node:path";import{createHash as createHash4,randomBytes}from"node:crypto";import{constants}from"node:fs";import{open,readdir as readdir3,rename as rename5,unlink}from"node:fs/promises";import{basename as basename2,join as join6}from"node:path";var WIKI_SYNC_STATE_FILE=".ando-wiki-sync.json",WIKI_SYNC_STATE_VERSION=1,CONFLICT_SUFFIX=".conflict.md",RESERVED_CONFLICT_STEM_SUFFIX=".conflict";async function readRegularFileNoFollowWithMode(absPath,displayName){let handle;try{handle=await open(absPath,constants.O_RDONLY|constants.O_NOFOLLOW)}catch(error2){throw error2.code==="ELOOP"?new CliError(ExitCode.usage,`Refusing to sync symlink "${displayName??basename2(absPath)}".`):error2}try{let info=await handle.stat();if(!info.isFile())throw new CliError(ExitCode.usage,`Refusing to sync non-regular file "${displayName??basename2(absPath)}".`);return{content:await handle.readFile("utf8"),mode:info.mode&511}}finally{await handle.close()}}async function readRegularFileNoFollow(absPath,displayName){return(await readRegularFileNoFollowWithMode(absPath,displayName)).content}async function writeFileAtomic(filePath,content,mode=384){let token=randomBytes(12).toString("hex"),temp=`${filePath}.${token}.tmp`,handle=await open(temp,constants.O_WRONLY|constants.O_CREAT|constants.O_EXCL|constants.O_NOFOLLOW,mode);try{await handle.chmod(mode),await handle.writeFile(content,"utf8")}catch(error2){throw await handle.close().catch(()=>{}),await unlink(temp).catch(()=>{}),error2}await handle.close();try{await rename5(temp,filePath)}catch(error2){throw await unlink(temp).catch(()=>{}),error2}}async function readSyncState(syncDir,expectedScope){let statePath=join6(syncDir,WIKI_SYNC_STATE_FILE),raw;try{raw=await readRegularFileNoFollow(statePath,WIKI_SYNC_STATE_FILE)}catch(error2){if(error2.code==="ENOENT")return{version:WIKI_SYNC_STATE_VERSION,scope:expectedScope,pages:{}};throw error2}let parsed;try{parsed=JSON.parse(raw)}catch{throw new CliError(ExitCode.usage,`${statePath} is not valid JSON. Remove or repair it before syncing.`)}if(parsed.version!==WIKI_SYNC_STATE_VERSION||!parsed.pages)throw new CliError(ExitCode.usage,`${statePath} has an unsupported sync state version.`);if(parsed.scope&&parsed.scope!==expectedScope)throw new CliError(ExitCode.usage,`${syncDir} is already synced with scope "${parsed.scope}", not "${expectedScope}". Use a separate folder or pass --scope ${parsed.scope}.`);return{version:WIKI_SYNC_STATE_VERSION,scope:expectedScope,pages:{...parsed.pages}}}async function scanLocalMarkdownFiles(syncDir){let entries;try{entries=await readdir3(syncDir,{withFileTypes:!0})}catch(error2){if(error2.code==="ENOENT")return{files:[],existingEntries:new Set};throw error2}let existingEntries=new Set(entries.map(entry=>entry.name.toLowerCase())),files=[];for(let entry of entries.sort((a,b)=>a.name.localeCompare(b.name))){let{name}=entry;if(name.startsWith(".")||!name.toLowerCase().endsWith(".md")||name.toLowerCase().endsWith(CONFLICT_SUFFIX)||entry.isDirectory())continue;let absPath=join6(syncDir,name),{content:rawText,mode}=await readRegularFileNoFollowWithMode(absPath,name),{meta:meta2,extraLines,body}=parseWikiFrontmatter(rawText),title=meta2.title!==void 0?meta2.title:deriveTitleFromMarkdown(name,body);files.push({filePath:name,absPath,rawText,mode,extraLines,id:meta2.id,title,body,hash:hashWikiContent(title,body),revision:meta2.revision,scope:meta2.scope})}return{files,existingEntries}}function allocateFilename(title,pageId,takenPaths){let stem=sanitizeFileStem(title,pageId);stem.toLowerCase().endsWith(RESERVED_CONFLICT_STEM_SUFFIX)&&(stem=`${stem}-page`);let base=`${stem}.md`;if(!takenPaths.has(base.toLowerCase()))return takenPaths.add(base.toLowerCase()),base;let shortId=pageId.replace(/[^A-Za-z0-9]/gu,"").slice(-6)||"dup",candidate=`${stem}-${shortId}.md`,counter=2;for(;takenPaths.has(candidate.toLowerCase());)candidate=`${stem}-${shortId}-${counter++}.md`;return takenPaths.add(candidate.toLowerCase()),candidate}function conflictFileNameFor(filePath){return`${basename2(filePath).replace(/\.md$/iu,"")}${CONFLICT_SUFFIX}`}function deterministicIdempotencyKey(parts){return`wiki-sync:${createHash4("sha256").update(parts.join("|")).digest("hex").slice(0,32)}`}async function isLocalFileUnchangedOnDisk(local){try{return await readRegularFileNoFollow(local.absPath,local.filePath)===local.rawText}catch(error2){if(error2.code==="ENOENT")return!1;throw error2}}async function readModifiedDiskHash(local){let diskRaw=null;try{diskRaw=await readRegularFileNoFollow(local.absPath,local.filePath)}catch(error2){if(error2.code!=="ENOENT")throw error2}if(diskRaw===local.rawText)return null;if(diskRaw===null)return local.hash;let parsed=parseWikiFrontmatter(diskRaw),title=parsed.meta.title!==void 0?parsed.meta.title:local.title;return hashWikiContent(title,parsed.body)}function formatWikiSyncReport(report){let prefix=report.dryRun?"[dry-run] ":"",lines=[];for(let item of report.pulled)lines.push(`${prefix}pulled ${item.filePath} (rev ${item.revision??"?"})`);for(let item of report.pushed)lines.push(`${prefix}pushed ${item.filePath} (rev ${item.revision??"?"})`);for(let item of report.created)lines.push(`${prefix}created ${item.filePath} (${item.pageId})`);for(let item of report.conflicts)lines.push(`${prefix}conflict ${item.filePath}${item.conflictPath?` -> ${item.conflictPath}`:""}: ${item.reason??"review required"}`);for(let item of report.skipped)lines.push(`${prefix}skipped ${item.filePath}: ${item.reason??"skipped"}`);return lines.push(`${prefix}Synced ${report.scope}: ${report.pulled.length} pulled, ${report.pushed.length} pushed, ${report.created.length} created, ${report.conflicts.length} conflicts, ${report.unchanged} unchanged.`),`${lines.join(`
|
|
483
|
+
`);if(data)try{let parsed=JSON.parse(data);if(parsed&&typeof parsed=="object"&&parsed.id===id)return parsed}catch{}}return null}function unwrapToolPayload(result,toolName){if(!result||typeof result!="object")throw new CliError(ExitCode.unavailable,`Unexpected empty MCP response from ${toolName}.`);let record2=result,payload=record2.structuredContent;if(payload===void 0&&Array.isArray(record2.content)){let textBlock=record2.content.find(item=>item?.type==="text"&&typeof item.text=="string");if(textBlock?.text!==void 0)try{payload=JSON.parse(textBlock.text)}catch{payload={message:textBlock.text}}}if(record2.isError){let errObj=payload&&typeof payload=="object"?payload:null,detail=errObj?.message||errObj?.error||`${toolName} returned an error.`,code2=errObj?.code;throw code2==="permission_required"||code2==="unauthorized"?new CliError(ExitCode.auth,detail):code2==="page_unavailable"||code2==="not_found"?new CliError(ExitCode.notFound,detail):new CliError(ExitCode.usage,detail)}return payload}function createWikiMcpClient(options){let fetchImpl=options.fetch??globalThis.fetch,nextId=1;async function callTool(name,args){let id=nextId++,response;try{response=await fetchImpl(options.mcpUrl,{method:"POST",headers:{accept:"application/json, text/event-stream","content-type":"application/json",authorization:`Bearer ${options.apiKey}`,"mcp-protocol-version":MCP_PROTOCOL_VERSION},body:JSON.stringify({jsonrpc:"2.0",id,method:"tools/call",params:{name,arguments:args}}),signal:AbortSignal.timeout(MCP_REQUEST_TIMEOUT_MS)})}catch(error2){throw new CliError(ExitCode.unavailable,`Calling ${name} failed: ${error2?.message??String(error2)}`)}if(response.status===401||response.status===403)throw new CliError(ExitCode.auth,`MCP request ${name} rejected (HTTP ${response.status}). Ensure your API key has documents:read and documents:write scopes.`);if(response.status===429||response.status>=500)throw new CliError(ExitCode.unavailable,`MCP request ${name} failed (HTTP ${response.status}).`);let contentType2=response.headers.get("content-type")??"",rawText=await response.text(),rpc;if(contentType2.includes("text/event-stream"))rpc=parseSseJsonRpc(rawText,id);else try{rpc=JSON.parse(rawText)}catch{rpc=null}if(rpc?.error)throw new CliError(ExitCode.unavailable,`MCP error from ${name}: ${rpc.error.message??"unknown error"}`);if(!response.ok||!rpc||rpc.result===void 0)throw new CliError(ExitCode.unavailable,`Unexpected MCP response from ${name} (HTTP ${response.status}).`);return unwrapToolPayload(rpc.result,name)}return{async listPages(scope){let seen=new Map,cursor;for(let page=0;page<200;page++){let result=await callTool("read_wiki_page",{scope,limit:50,...cursor?{cursor}:{}});result?.context&&!READ_ONLY_SYNTHETIC_PAGE_IDS.has(result.context.pageId)&&seen.set(result.context.pageId,{pageId:result.context.pageId,title:result.context.title,revision:result.context.revision,updatedAt:result.context.updatedAt});for(let item of result?.items??[])READ_ONLY_SYNTHETIC_PAGE_IDS.has(item.pageId)||seen.set(item.pageId,{pageId:item.pageId,title:item.title,revision:item.revision,updatedAt:item.updatedAt});if(!result?.hasMore||!result.nextCursor)break;cursor=result.nextCursor}return[...seen.values()].sort((a,b)=>a.pageId.localeCompare(b.pageId))},async readPage(scope,pageId){let cursor,content="",meta2=null,purpose,liveEditing;for(let chunk=0;chunk<100;chunk++){let result=await callTool("read_wiki_page",{scope,pageId,...cursor?{cursor}:{}});if(!result?.page)throw new CliError(ExitCode.notFound,`Page "${pageId}" was not returned by read_wiki_page.`);if(meta2||(meta2={pageId:result.page.pageId,title:result.page.title,revision:result.page.revision,updatedAt:result.page.updatedAt},purpose=result.page.purpose,result.liveEditing&&(liveEditing={activeEditorCount:result.liveEditing.activeEditorCount,hasUnsavedChanges:result.liveEditing.hasUnsavedChanges})),content+=result.page.content,!result.page.hasMore||!result.page.nextCursor)break;cursor=result.page.nextCursor}let editableContent=scope.type==="member"&&purpose==="notes"?stripGeneratedSourceNotes(content):content;return{...meta2,content:editableContent,...liveEditing?{liveEditing}:{}}},async savePage(input){let result=await callTool("save_wiki_page",{scope:input.scope,...input.pageId?{pageId:input.pageId}:{},title:input.title,content:input.content,...input.expectedRevision!==void 0?{expectedRevision:input.expectedRevision}:{},idempotencyKey:input.idempotencyKey});if(result?.result==="stale")return{result:"stale",currentRevision:result.current?.revision??result.currentRevision??0,currentTitle:result.current?.title??input.title,currentContent:result.current?.content??""};if((result?.result==="saved"||result?.result==="replayed")&&typeof result.pageId=="string"&&typeof result.revision=="number")return{result:"saved",pageId:result.pageId,revision:result.revision};throw new CliError(ExitCode.unavailable,`Unexpected save_wiki_page response for "${input.title}".`)}}}import{mkdir as mkdir5}from"node:fs/promises";import{join as join8,resolve as resolve2}from"node:path";import{createHash as createHash4,randomBytes}from"node:crypto";import{constants}from"node:fs";import{open,readdir as readdir3,rename as rename5,unlink}from"node:fs/promises";import{basename as basename2,join as join7}from"node:path";var WIKI_SYNC_STATE_FILE=".ando-wiki-sync.json",WIKI_SYNC_STATE_VERSION=1,CONFLICT_SUFFIX=".conflict.md",RESERVED_CONFLICT_STEM_SUFFIX=".conflict";async function readRegularFileNoFollowWithMode(absPath,displayName){let handle;try{handle=await open(absPath,constants.O_RDONLY|constants.O_NOFOLLOW)}catch(error2){throw error2.code==="ELOOP"?new CliError(ExitCode.usage,`Refusing to sync symlink "${displayName??basename2(absPath)}".`):error2}try{let info=await handle.stat();if(!info.isFile())throw new CliError(ExitCode.usage,`Refusing to sync non-regular file "${displayName??basename2(absPath)}".`);return{content:await handle.readFile("utf8"),mode:info.mode&511}}finally{await handle.close()}}async function readRegularFileNoFollow(absPath,displayName){return(await readRegularFileNoFollowWithMode(absPath,displayName)).content}async function writeFileAtomic(filePath,content,mode=384){let token=randomBytes(12).toString("hex"),temp=`${filePath}.${token}.tmp`,handle=await open(temp,constants.O_WRONLY|constants.O_CREAT|constants.O_EXCL|constants.O_NOFOLLOW,mode);try{await handle.chmod(mode),await handle.writeFile(content,"utf8")}catch(error2){throw await handle.close().catch(()=>{}),await unlink(temp).catch(()=>{}),error2}await handle.close();try{await rename5(temp,filePath)}catch(error2){throw await unlink(temp).catch(()=>{}),error2}}async function readSyncState(syncDir,expectedScope){let statePath=join7(syncDir,WIKI_SYNC_STATE_FILE),raw;try{raw=await readRegularFileNoFollow(statePath,WIKI_SYNC_STATE_FILE)}catch(error2){if(error2.code==="ENOENT")return{version:WIKI_SYNC_STATE_VERSION,scope:expectedScope,pages:{}};throw error2}let parsed;try{parsed=JSON.parse(raw)}catch{throw new CliError(ExitCode.usage,`${statePath} is not valid JSON. Remove or repair it before syncing.`)}if(parsed.version!==WIKI_SYNC_STATE_VERSION||!parsed.pages)throw new CliError(ExitCode.usage,`${statePath} has an unsupported sync state version.`);if(parsed.scope&&parsed.scope!==expectedScope)throw new CliError(ExitCode.usage,`${syncDir} is already synced with scope "${parsed.scope}", not "${expectedScope}". Use a separate folder or pass --scope ${parsed.scope}.`);return{version:WIKI_SYNC_STATE_VERSION,scope:expectedScope,pages:{...parsed.pages}}}async function scanLocalMarkdownFiles(syncDir){let entries;try{entries=await readdir3(syncDir,{withFileTypes:!0})}catch(error2){if(error2.code==="ENOENT")return{files:[],existingEntries:new Set};throw error2}let existingEntries=new Set(entries.map(entry=>entry.name.toLowerCase())),files=[];for(let entry of entries.sort((a,b)=>a.name.localeCompare(b.name))){let{name}=entry;if(name.startsWith(".")||!name.toLowerCase().endsWith(".md")||name.toLowerCase().endsWith(CONFLICT_SUFFIX)||entry.isDirectory())continue;let absPath=join7(syncDir,name),{content:rawText,mode}=await readRegularFileNoFollowWithMode(absPath,name),{meta:meta2,extraLines,body}=parseWikiFrontmatter(rawText),title=meta2.title!==void 0?meta2.title:deriveTitleFromMarkdown(name,body);files.push({filePath:name,absPath,rawText,mode,extraLines,id:meta2.id,title,body,hash:hashWikiContent(title,body),revision:meta2.revision,scope:meta2.scope})}return{files,existingEntries}}function allocateFilename(title,pageId,takenPaths){let stem=sanitizeFileStem(title,pageId);stem.toLowerCase().endsWith(RESERVED_CONFLICT_STEM_SUFFIX)&&(stem=`${stem}-page`);let base=`${stem}.md`;if(!takenPaths.has(base.toLowerCase()))return takenPaths.add(base.toLowerCase()),base;let shortId=pageId.replace(/[^A-Za-z0-9]/gu,"").slice(-6)||"dup",candidate=`${stem}-${shortId}.md`,counter=2;for(;takenPaths.has(candidate.toLowerCase());)candidate=`${stem}-${shortId}-${counter++}.md`;return takenPaths.add(candidate.toLowerCase()),candidate}function conflictFileNameFor(filePath){return`${basename2(filePath).replace(/\.md$/iu,"")}${CONFLICT_SUFFIX}`}function deterministicIdempotencyKey(parts){return`wiki-sync:${createHash4("sha256").update(parts.join("|")).digest("hex").slice(0,32)}`}async function isLocalFileUnchangedOnDisk(local){try{return await readRegularFileNoFollow(local.absPath,local.filePath)===local.rawText}catch(error2){if(error2.code==="ENOENT")return!1;throw error2}}async function readModifiedDiskHash(local){let diskRaw=null;try{diskRaw=await readRegularFileNoFollow(local.absPath,local.filePath)}catch(error2){if(error2.code!=="ENOENT")throw error2}if(diskRaw===local.rawText)return null;if(diskRaw===null)return local.hash;let parsed=parseWikiFrontmatter(diskRaw),title=parsed.meta.title!==void 0?parsed.meta.title:local.title;return hashWikiContent(title,parsed.body)}function formatWikiSyncReport(report){let prefix=report.dryRun?"[dry-run] ":"",lines=[];for(let item of report.pulled)lines.push(`${prefix}pulled ${item.filePath} (rev ${item.revision??"?"})`);for(let item of report.pushed)lines.push(`${prefix}pushed ${item.filePath} (rev ${item.revision??"?"})`);for(let item of report.created)lines.push(`${prefix}created ${item.filePath} (${item.pageId})`);for(let item of report.conflicts)lines.push(`${prefix}conflict ${item.filePath}${item.conflictPath?` -> ${item.conflictPath}`:""}: ${item.reason??"review required"}`);for(let item of report.skipped)lines.push(`${prefix}skipped ${item.filePath}: ${item.reason??"skipped"}`);return lines.push(`${prefix}Synced ${report.scope}: ${report.pulled.length} pulled, ${report.pushed.length} pushed, ${report.created.length} created, ${report.conflicts.length} conflicts, ${report.unchanged} unchanged.`),`${lines.join(`
|
|
477
484
|
`)}
|
|
478
|
-
`}async function recordConflict(ctx,input){let conflictPath=conflictFileNameFor(input.local.filePath),remoteHash=hashWikiContent(input.remoteTitle,input.remoteContent);ctx.dryRun||(await writeFileAtomic(join7(ctx.syncDir,conflictPath),renderWikiFrontmatter({id:input.pageId,title:input.remoteTitle,scope:ctx.scopeLabel,revision:input.remoteRevision},input.remoteContent)),ctx.state.pages[input.pageId]={pageId:input.pageId,filePath:input.local.filePath,lastSyncedRevision:input.remoteRevision,lastSyncedHash:remoteHash,reviewRequired:input.reviewRequired,conflictLocalHash:input.conflictLocalHash??input.local.hash}),ctx.report.conflicts.push({pageId:input.pageId,filePath:input.local.filePath,title:input.local.title,revision:input.remoteRevision,conflictPath,reason:input.reason})}async function createUnmarkedPage(ctx,local){if(!local.body.trim()){ctx.report.skipped.push({pageId:"",filePath:local.filePath,title:local.title,reason:"Empty local Markdown file skipped."});return}if(ctx.dryRun){ctx.report.created.push({pageId:"(new)",filePath:local.filePath,title:local.title});return}let saved=await ctx.client.savePage({scope:ctx.scope,title:local.title,content:normalizeWikiBody(local.body),idempotencyKey:deterministicIdempotencyKey(["create",ctx.scopeLabel,local.filePath,local.hash])});if(saved.result!=="saved"){ctx.report.conflicts.push({pageId:"",filePath:local.filePath,title:local.title,reason:"Server returned stale while creating a new page."});return}ctx.state.pages[saved.pageId]={pageId:saved.pageId,filePath:local.filePath,lastSyncedRevision:saved.revision,lastSyncedHash:local.hash},await isLocalFileUnchangedOnDisk(local)&&await writeFileAtomic(local.absPath,renderWikiFrontmatter({id:saved.pageId,title:local.title,scope:ctx.scopeLabel,revision:saved.revision},local.body,local.extraLines),local.mode),ctx.report.created.push({pageId:saved.pageId,filePath:local.filePath,title:local.title,revision:saved.revision})}async function pullRemotePage(ctx,remoteSummary,targetFile,absPath,existingLocal){let{pageId}=remoteSummary;if(ctx.dryRun){ctx.report.pulled.push({pageId,filePath:targetFile,title:remoteSummary.title,revision:remoteSummary.revision});return}let fullRemote=await ctx.client.readPage(ctx.scope,pageId);if(existingLocal){let modifiedHash=await readModifiedDiskHash(existingLocal);if(modifiedHash!==null){let conflictPath=conflictFileNameFor(existingLocal.filePath);await recordConflict(ctx,{pageId,local:existingLocal,remoteTitle:fullRemote.title,remoteContent:fullRemote.content,remoteRevision:fullRemote.revision,reviewRequired:`Local file changed while pulling revision ${fullRemote.revision}; remote saved to ${conflictPath}.`,reason:`Local file changed during pull; remote written to ${conflictPath} to preserve newer edits.`,conflictLocalHash:modifiedHash});return}}await writeFileAtomic(absPath,renderWikiFrontmatter({id:pageId,title:fullRemote.title,scope:ctx.scopeLabel,revision:fullRemote.revision},fullRemote.content,existingLocal?.extraLines??[]),existingLocal?.mode??384),ctx.state.pages[pageId]={pageId,filePath:targetFile,lastSyncedRevision:fullRemote.revision,lastSyncedHash:hashWikiContent(fullRemote.title,fullRemote.content)},ctx.report.pulled.push({pageId,filePath:targetFile,title:fullRemote.title,revision:fullRemote.revision})}async function pushLocalPage(ctx,pageId,local,checkpoint){if(!local.body.trim()){ctx.report.skipped.push({pageId,filePath:local.filePath,title:local.title,revision:checkpoint.lastSyncedRevision,reason:"Empty local body; Ando Wiki pages require non-empty content."});return}if(!ctx.force){let currentRemote=await ctx.client.readPage(ctx.scope,pageId);if(currentRemote.liveEditing&&(currentRemote.liveEditing.activeEditorCount>0||currentRemote.liveEditing.hasUnsavedChanges)){ctx.report.skipped.push({pageId,filePath:local.filePath,title:local.title,revision:currentRemote.revision,reason:"Page has an active live editing session in Ando; skipping push (pass --force to override)."});return}}if(ctx.dryRun){ctx.report.pushed.push({pageId,filePath:local.filePath,title:local.title,revision:checkpoint.lastSyncedRevision+1});return}let saved=await ctx.client.savePage({scope:ctx.scope,pageId,title:local.title,content:normalizeWikiBody(local.body),expectedRevision:checkpoint.lastSyncedRevision,idempotencyKey:deterministicIdempotencyKey(["update",ctx.scopeLabel,pageId,String(checkpoint.lastSyncedRevision),local.hash])});if(saved.result==="saved"){ctx.state.pages[pageId]={pageId,filePath:local.filePath,lastSyncedRevision:saved.revision,lastSyncedHash:local.hash},await isLocalFileUnchangedOnDisk(local)&&await writeFileAtomic(local.absPath,renderWikiFrontmatter({id:pageId,title:local.title,scope:ctx.scopeLabel,revision:saved.revision},local.body,local.extraLines),local.mode),ctx.report.pushed.push({pageId,filePath:local.filePath,title:local.title,revision:saved.revision});return}let fullRemote=await ctx.client.readPage(ctx.scope,pageId),conflictPath=conflictFileNameFor(local.filePath);await recordConflict(ctx,{pageId,local,remoteTitle:fullRemote.title,remoteContent:fullRemote.content,remoteRevision:fullRemote.revision,reviewRequired:`Remote advanced to revision ${fullRemote.revision} during push; remote saved to ${conflictPath}.`,reason:`Remote advanced to revision ${fullRemote.revision}; remote written to ${conflictPath}.`})}async function reconcileDivergedPage(ctx,pageId,local,priorRevision){let fullRemote=await ctx.client.readPage(ctx.scope,pageId),remoteHash=hashWikiContent(fullRemote.title,fullRemote.content);if(remoteHash===local.hash){ctx.dryRun||(priorRevision!==null&&await isLocalFileUnchangedOnDisk(local)&&await writeFileAtomic(local.absPath,renderWikiFrontmatter({id:pageId,title:fullRemote.title,scope:ctx.scopeLabel,revision:fullRemote.revision},local.body,local.extraLines),local.mode),ctx.state.pages[pageId]={pageId,filePath:local.filePath,lastSyncedRevision:fullRemote.revision,lastSyncedHash:remoteHash}),ctx.report.unchanged++;return}let conflictPath=conflictFileNameFor(local.filePath),reviewRequired=priorRevision===null?`Diverged without prior sync checkpoint; remote saved to ${conflictPath}.`:`Both local and remote changed since revision ${priorRevision}; remote saved to ${conflictPath}.`,reason=priorRevision===null?`Local and remote differ with no prior checkpoint; remote written to ${conflictPath}.`:`Both local and remote changed; remote written to ${conflictPath}.`;await recordConflict(ctx,{pageId,local,remoteTitle:fullRemote.title,remoteContent:fullRemote.content,remoteRevision:fullRemote.revision,reviewRequired,reason})}async function reconcileRemotePage(ctx,remoteSummary,local){let{pageId}=remoteSummary,checkpoint=ctx.state.pages[pageId];if(!local){if(checkpoint){ctx.report.skipped.push({pageId,filePath:checkpoint.filePath,title:remoteSummary.title,revision:remoteSummary.revision,reason:"Local file was removed; remote page preserved."});return}let targetFile=allocateFilename(remoteSummary.title,pageId,ctx.takenPaths);await pullRemotePage(ctx,remoteSummary,targetFile,join7(ctx.syncDir,targetFile));return}if(!checkpoint){await reconcileDivergedPage(ctx,pageId,local,null);return}let localChanged=local.hash!==checkpoint.lastSyncedHash,remoteChanged=remoteSummary.revision!==checkpoint.lastSyncedRevision;if(checkpoint.reviewRequired&&checkpoint.conflictLocalHash&&local.hash===checkpoint.conflictLocalHash&&!remoteChanged){ctx.report.conflicts.push({pageId,filePath:local.filePath,title:local.title,revision:remoteSummary.revision,conflictPath:conflictFileNameFor(local.filePath),reason:`Unresolved conflict (${checkpoint.reviewRequired}) Edit ${local.filePath} and re-sync to push.`});return}if(!localChanged&&!remoteChanged){!ctx.dryRun&&(checkpoint.filePath!==local.filePath||checkpoint.reviewRequired)&&(ctx.state.pages[pageId]={pageId,filePath:local.filePath,lastSyncedRevision:checkpoint.lastSyncedRevision,lastSyncedHash:checkpoint.lastSyncedHash}),ctx.report.unchanged++;return}if(!localChanged&&remoteChanged){await pullRemotePage(ctx,remoteSummary,local.filePath,local.absPath,local);return}if(localChanged&&!remoteChanged){await pushLocalPage(ctx,pageId,local,checkpoint);return}await reconcileDivergedPage(ctx,pageId,local,checkpoint.lastSyncedRevision)}async function syncWikiOnce(options){let dryRun=options.dryRun===!0,syncDir=resolve2(options.directory),scopeLabel=formatWikiScope(options.scope);dryRun||await mkdir5(syncDir,{recursive:!0});let state=await readSyncState(syncDir,scopeLabel),{files:localFiles,existingEntries}=await scanLocalMarkdownFiles(syncDir),remotePages=await options.client.listPages(options.scope),report={scope:scopeLabel,directory:syncDir,dryRun,pulled:[],pushed:[],created:[],conflicts:[],skipped:[],unchanged:0},ctx={syncDir,scope:options.scope,scopeLabel,client:options.client,dryRun,force:options.force===!0,state,report,takenPaths:existingEntries},remoteById=new Map(remotePages.map(page=>[page.pageId,page])),checkpointByPath=new Map(Object.values(state.pages).map(entry=>[entry.filePath,entry])),filesById=new Map,unmarkedLocal=[];for(let file of localFiles){let resolvedId=file.id??checkpointByPath.get(file.filePath)?.pageId;if(!resolvedId)unmarkedLocal.push(file);else{let group=filesById.get(resolvedId);group?group.push(file):filesById.set(resolvedId,[file])}}let localById=new Map,duplicatePageIds=new Set;for(let[pageId,group]of filesById)if(group.length>1){duplicatePageIds.add(pageId);let names=group.map(entry=>entry.filePath).join(", ");for(let entry of group)report.conflicts.push({pageId,filePath:entry.filePath,title:entry.title,reason:`Multiple local files reference page id ${pageId} (${names}); resolve duplicates before syncing.`})}else localById.set(pageId,group[0]);for(let local of unmarkedLocal)await createUnmarkedPage(ctx,local);for(let remoteSummary of remotePages)duplicatePageIds.has(remoteSummary.pageId)||await reconcileRemotePage(ctx,remoteSummary,localById.get(remoteSummary.pageId));for(let[pageId,local]of localById)remoteById.has(pageId)||report.skipped.push({pageId,filePath:local.filePath,title:local.title,reason:"Remote page not found in this scope; local file preserved."});return dryRun||await writeFileAtomic(join7(syncDir,WIKI_SYNC_STATE_FILE),`${JSON.stringify(state,null,2)}
|
|
485
|
+
`}async function recordConflict(ctx,input){let conflictPath=conflictFileNameFor(input.local.filePath),remoteHash=hashWikiContent(input.remoteTitle,input.remoteContent);ctx.dryRun||(await writeFileAtomic(join8(ctx.syncDir,conflictPath),renderWikiFrontmatter({id:input.pageId,title:input.remoteTitle,scope:ctx.scopeLabel,revision:input.remoteRevision},input.remoteContent)),ctx.state.pages[input.pageId]={pageId:input.pageId,filePath:input.local.filePath,lastSyncedRevision:input.remoteRevision,lastSyncedHash:remoteHash,reviewRequired:input.reviewRequired,conflictLocalHash:input.conflictLocalHash??input.local.hash}),ctx.report.conflicts.push({pageId:input.pageId,filePath:input.local.filePath,title:input.local.title,revision:input.remoteRevision,conflictPath,reason:input.reason})}async function createUnmarkedPage(ctx,local){if(!local.body.trim()){ctx.report.skipped.push({pageId:"",filePath:local.filePath,title:local.title,reason:"Empty local Markdown file skipped."});return}if(ctx.dryRun){ctx.report.created.push({pageId:"(new)",filePath:local.filePath,title:local.title});return}let saved=await ctx.client.savePage({scope:ctx.scope,title:local.title,content:normalizeWikiBody(local.body),idempotencyKey:deterministicIdempotencyKey(["create",ctx.scopeLabel,local.filePath,local.hash])});if(saved.result!=="saved"){ctx.report.conflicts.push({pageId:"",filePath:local.filePath,title:local.title,reason:"Server returned stale while creating a new page."});return}ctx.state.pages[saved.pageId]={pageId:saved.pageId,filePath:local.filePath,lastSyncedRevision:saved.revision,lastSyncedHash:local.hash},await isLocalFileUnchangedOnDisk(local)&&await writeFileAtomic(local.absPath,renderWikiFrontmatter({id:saved.pageId,title:local.title,scope:ctx.scopeLabel,revision:saved.revision},local.body,local.extraLines),local.mode),ctx.report.created.push({pageId:saved.pageId,filePath:local.filePath,title:local.title,revision:saved.revision})}async function pullRemotePage(ctx,remoteSummary,targetFile,absPath,existingLocal){let{pageId}=remoteSummary;if(ctx.dryRun){ctx.report.pulled.push({pageId,filePath:targetFile,title:remoteSummary.title,revision:remoteSummary.revision});return}let fullRemote=await ctx.client.readPage(ctx.scope,pageId);if(existingLocal){let modifiedHash=await readModifiedDiskHash(existingLocal);if(modifiedHash!==null){let conflictPath=conflictFileNameFor(existingLocal.filePath);await recordConflict(ctx,{pageId,local:existingLocal,remoteTitle:fullRemote.title,remoteContent:fullRemote.content,remoteRevision:fullRemote.revision,reviewRequired:`Local file changed while pulling revision ${fullRemote.revision}; remote saved to ${conflictPath}.`,reason:`Local file changed during pull; remote written to ${conflictPath} to preserve newer edits.`,conflictLocalHash:modifiedHash});return}}await writeFileAtomic(absPath,renderWikiFrontmatter({id:pageId,title:fullRemote.title,scope:ctx.scopeLabel,revision:fullRemote.revision},fullRemote.content,existingLocal?.extraLines??[]),existingLocal?.mode??384),ctx.state.pages[pageId]={pageId,filePath:targetFile,lastSyncedRevision:fullRemote.revision,lastSyncedHash:hashWikiContent(fullRemote.title,fullRemote.content)},ctx.report.pulled.push({pageId,filePath:targetFile,title:fullRemote.title,revision:fullRemote.revision})}async function pushLocalPage(ctx,pageId,local,checkpoint){if(!local.body.trim()){ctx.report.skipped.push({pageId,filePath:local.filePath,title:local.title,revision:checkpoint.lastSyncedRevision,reason:"Empty local body; Ando Wiki pages require non-empty content."});return}if(!ctx.force){let currentRemote=await ctx.client.readPage(ctx.scope,pageId);if(currentRemote.liveEditing&&(currentRemote.liveEditing.activeEditorCount>0||currentRemote.liveEditing.hasUnsavedChanges)){ctx.report.skipped.push({pageId,filePath:local.filePath,title:local.title,revision:currentRemote.revision,reason:"Page has an active live editing session in Ando; skipping push (pass --force to override)."});return}}if(ctx.dryRun){ctx.report.pushed.push({pageId,filePath:local.filePath,title:local.title,revision:checkpoint.lastSyncedRevision+1});return}let saved=await ctx.client.savePage({scope:ctx.scope,pageId,title:local.title,content:normalizeWikiBody(local.body),expectedRevision:checkpoint.lastSyncedRevision,idempotencyKey:deterministicIdempotencyKey(["update",ctx.scopeLabel,pageId,String(checkpoint.lastSyncedRevision),local.hash])});if(saved.result==="saved"){ctx.state.pages[pageId]={pageId,filePath:local.filePath,lastSyncedRevision:saved.revision,lastSyncedHash:local.hash},await isLocalFileUnchangedOnDisk(local)&&await writeFileAtomic(local.absPath,renderWikiFrontmatter({id:pageId,title:local.title,scope:ctx.scopeLabel,revision:saved.revision},local.body,local.extraLines),local.mode),ctx.report.pushed.push({pageId,filePath:local.filePath,title:local.title,revision:saved.revision});return}let fullRemote=await ctx.client.readPage(ctx.scope,pageId),conflictPath=conflictFileNameFor(local.filePath);await recordConflict(ctx,{pageId,local,remoteTitle:fullRemote.title,remoteContent:fullRemote.content,remoteRevision:fullRemote.revision,reviewRequired:`Remote advanced to revision ${fullRemote.revision} during push; remote saved to ${conflictPath}.`,reason:`Remote advanced to revision ${fullRemote.revision}; remote written to ${conflictPath}.`})}async function reconcileDivergedPage(ctx,pageId,local,priorRevision){let fullRemote=await ctx.client.readPage(ctx.scope,pageId),remoteHash=hashWikiContent(fullRemote.title,fullRemote.content);if(remoteHash===local.hash){ctx.dryRun||(priorRevision!==null&&await isLocalFileUnchangedOnDisk(local)&&await writeFileAtomic(local.absPath,renderWikiFrontmatter({id:pageId,title:fullRemote.title,scope:ctx.scopeLabel,revision:fullRemote.revision},local.body,local.extraLines),local.mode),ctx.state.pages[pageId]={pageId,filePath:local.filePath,lastSyncedRevision:fullRemote.revision,lastSyncedHash:remoteHash}),ctx.report.unchanged++;return}let conflictPath=conflictFileNameFor(local.filePath),reviewRequired=priorRevision===null?`Diverged without prior sync checkpoint; remote saved to ${conflictPath}.`:`Both local and remote changed since revision ${priorRevision}; remote saved to ${conflictPath}.`,reason=priorRevision===null?`Local and remote differ with no prior checkpoint; remote written to ${conflictPath}.`:`Both local and remote changed; remote written to ${conflictPath}.`;await recordConflict(ctx,{pageId,local,remoteTitle:fullRemote.title,remoteContent:fullRemote.content,remoteRevision:fullRemote.revision,reviewRequired,reason})}async function reconcileRemotePage(ctx,remoteSummary,local){let{pageId}=remoteSummary,checkpoint=ctx.state.pages[pageId];if(!local){if(checkpoint){ctx.report.skipped.push({pageId,filePath:checkpoint.filePath,title:remoteSummary.title,revision:remoteSummary.revision,reason:"Local file was removed; remote page preserved."});return}let targetFile=allocateFilename(remoteSummary.title,pageId,ctx.takenPaths);await pullRemotePage(ctx,remoteSummary,targetFile,join8(ctx.syncDir,targetFile));return}if(!checkpoint){await reconcileDivergedPage(ctx,pageId,local,null);return}let localChanged=local.hash!==checkpoint.lastSyncedHash,remoteChanged=remoteSummary.revision!==checkpoint.lastSyncedRevision;if(checkpoint.reviewRequired&&checkpoint.conflictLocalHash&&local.hash===checkpoint.conflictLocalHash&&!remoteChanged){ctx.report.conflicts.push({pageId,filePath:local.filePath,title:local.title,revision:remoteSummary.revision,conflictPath:conflictFileNameFor(local.filePath),reason:`Unresolved conflict (${checkpoint.reviewRequired}) Edit ${local.filePath} and re-sync to push.`});return}if(!localChanged&&!remoteChanged){!ctx.dryRun&&(checkpoint.filePath!==local.filePath||checkpoint.reviewRequired)&&(ctx.state.pages[pageId]={pageId,filePath:local.filePath,lastSyncedRevision:checkpoint.lastSyncedRevision,lastSyncedHash:checkpoint.lastSyncedHash}),ctx.report.unchanged++;return}if(!localChanged&&remoteChanged){await pullRemotePage(ctx,remoteSummary,local.filePath,local.absPath,local);return}if(localChanged&&!remoteChanged){await pushLocalPage(ctx,pageId,local,checkpoint);return}await reconcileDivergedPage(ctx,pageId,local,checkpoint.lastSyncedRevision)}async function syncWikiOnce(options){let dryRun=options.dryRun===!0,syncDir=resolve2(options.directory),scopeLabel=formatWikiScope(options.scope);dryRun||await mkdir5(syncDir,{recursive:!0});let state=await readSyncState(syncDir,scopeLabel),{files:localFiles,existingEntries}=await scanLocalMarkdownFiles(syncDir),remotePages=await options.client.listPages(options.scope),report={scope:scopeLabel,directory:syncDir,dryRun,pulled:[],pushed:[],created:[],conflicts:[],skipped:[],unchanged:0},ctx={syncDir,scope:options.scope,scopeLabel,client:options.client,dryRun,force:options.force===!0,state,report,takenPaths:existingEntries},remoteById=new Map(remotePages.map(page=>[page.pageId,page])),checkpointByPath=new Map(Object.values(state.pages).map(entry=>[entry.filePath,entry])),filesById=new Map,unmarkedLocal=[];for(let file of localFiles){let resolvedId=file.id??checkpointByPath.get(file.filePath)?.pageId;if(!resolvedId)unmarkedLocal.push(file);else{let group=filesById.get(resolvedId);group?group.push(file):filesById.set(resolvedId,[file])}}let localById=new Map,duplicatePageIds=new Set;for(let[pageId,group]of filesById)if(group.length>1){duplicatePageIds.add(pageId);let names=group.map(entry=>entry.filePath).join(", ");for(let entry of group)report.conflicts.push({pageId,filePath:entry.filePath,title:entry.title,reason:`Multiple local files reference page id ${pageId} (${names}); resolve duplicates before syncing.`})}else localById.set(pageId,group[0]);for(let local of unmarkedLocal)await createUnmarkedPage(ctx,local);for(let remoteSummary of remotePages)duplicatePageIds.has(remoteSummary.pageId)||await reconcileRemotePage(ctx,remoteSummary,localById.get(remoteSummary.pageId));for(let[pageId,local]of localById)remoteById.has(pageId)||report.skipped.push({pageId,filePath:local.filePath,title:local.title,reason:"Remote page not found in this scope; local file preserved."});return dryRun||await writeFileAtomic(join8(syncDir,WIKI_SYNC_STATE_FILE),`${JSON.stringify(state,null,2)}
|
|
479
486
|
`,384),report}var VERSION=package_default.version,HELP=`ando \u2014 use Ando from a terminal
|
|
480
487
|
|
|
481
488
|
Usage:
|
|
@@ -484,7 +491,7 @@ Usage:
|
|
|
484
491
|
[--in-place] this repository and keep it connected.
|
|
485
492
|
[--hooks] --hooks runs its Claude Code hooks in tasks.
|
|
486
493
|
ando status | logs [-f] [-n <lines>] | stop | update | attach [task]
|
|
487
|
-
ando login [--key-stdin] [--api-url <url>] [--web-url <url>]
|
|
494
|
+
ando login [--paste|--key-stdin] [--no-open] [--api-url <url>] [--web-url <url>] [--convex-url <url>]
|
|
488
495
|
ando antigravity connect <url-or-passcode> [options]
|
|
489
496
|
ando antigravity doctor [--json]
|
|
490
497
|
ando swarm init|enroll|status [--manifest <path>] [--json]
|
|
@@ -509,22 +516,27 @@ Options:
|
|
|
509
516
|
Environment:
|
|
510
517
|
ANDO_API_KEY API key; overrides the saved login.
|
|
511
518
|
ANDO_API_URL API base URL (default ${DEFAULT_API_URL}).
|
|
519
|
+
ANDO_CONVEX_URL Convex URL used for browser login (inferred from API URL by default).
|
|
512
520
|
ANDO_MCP_URL MCP base URL for wiki sync (default ${DEFAULT_MCP_URL}).
|
|
513
|
-
ANDO_WEB_URL Web app URL used for message links.
|
|
521
|
+
ANDO_WEB_URL Web app URL used for browser login and message links.
|
|
514
522
|
|
|
515
523
|
Exit codes:
|
|
516
524
|
0 success, 1 usage, 2 authentication or permission, 3 not found or
|
|
517
525
|
ambiguous, 4 no reply before --timeout, 5 network or server error.
|
|
518
526
|
`,COMMAND_HELP={login:`Usage:
|
|
519
|
-
ando login [--key-stdin] [--api-url <url>] [--web-url <url>] [--json]
|
|
527
|
+
ando login [--paste|--key-stdin] [--no-open] [--api-url <url>] [--web-url <url>] [--convex-url <url>] [--json]
|
|
520
528
|
|
|
521
|
-
|
|
529
|
+
Signs in through your browser (granting messages:read, messages:write, and
|
|
530
|
+
realtime:read for workrooms) and saves the API key owner-only (0600) to
|
|
522
531
|
$XDG_CONFIG_HOME/ando/cli.json (~/.config/ando/cli.json by default).
|
|
523
532
|
|
|
524
533
|
Options:
|
|
525
|
-
--
|
|
534
|
+
--paste Paste an existing API key at a hidden terminal prompt instead of browser sign-in.
|
|
535
|
+
--key-stdin Read an existing API key from standard input instead of browser sign-in.
|
|
536
|
+
--no-open Print the sign-in link and code without prompting to open a local browser.
|
|
526
537
|
--api-url <url> API base URL (default ${DEFAULT_API_URL}).
|
|
527
|
-
--web-url <url> Web app URL used for message links.
|
|
538
|
+
--web-url <url> Web app URL used for browser sign-in and message links.
|
|
539
|
+
--convex-url <url> Convex deployment URL for browser sign-in (inferred from --api-url by default).
|
|
528
540
|
--json Print the saved login metadata as JSON.
|
|
529
541
|
`,send:`Usage:
|
|
530
542
|
ando send <#channel|conversation-id> [text] [--code] [--thread <message-id>] [--json]
|
|
@@ -564,8 +576,11 @@ Options:
|
|
|
564
576
|
--json Print the sync report as JSON.
|
|
565
577
|
`},MACHINE_COMMANDS=new Set(["up","connect","run","status","logs","stop","attach","update"]),DEFAULT_TIMEOUT_SECONDS=120,MAX_TIMEOUT_SECONDS=3600;function parse3(args,options){try{return parseArgs6({args,options:{...options,help:{type:"boolean",short:"h"}},allowPositionals:!0,strict:!0})}catch(error2){throw usageError(`${error2.message}
|
|
566
578
|
Run \`ando --help\`.`)}}async function readText(io,positional){if(positional.length>0)return positional.join(" ");if(io.stdinIsTty)throw usageError("Give the text as an argument or pipe it to standard input.");let{text,truncated}=await io.readStdin(MESSAGE_MAX_LENGTH*2);if(truncated)throw usageError(`Input is longer than ${(MESSAGE_MAX_LENGTH*2).toLocaleString("en-US")} characters; Ando accepts at most ${MESSAGE_MAX_LENGTH.toLocaleString("en-US")}. Nothing was posted.`);return text}function parseTimeout(value){if(value===void 0)return DEFAULT_TIMEOUT_SECONDS*1e3;let seconds=Number(value.replace(/s$/u,""));if(!Number.isFinite(seconds)||seconds<=0||seconds>MAX_TIMEOUT_SECONDS)throw usageError(`--timeout must be a number of seconds between 1 and ${MAX_TIMEOUT_SECONDS}.`);return Math.round(seconds*1e3)}var json=value=>`${JSON.stringify(value,null,2)}
|
|
567
|
-
`;async function login(io,args,secret){let{values}=parse3(args,{"key-stdin":{type:"boolean"},"api-url":{type:"string"},"web-url":{type:"string"},json:{type:"boolean"}});if(values.help)return io.stdout(COMMAND_HELP.login),ExitCode.ok;let apiKey;if(values["key-stdin"])apiKey=(await io.readStdin(4096)).text.trim();else if(io.stdinIsTty)apiKey=(await io.readSecret("Ando API key: ")).trim()
|
|
568
|
-
`)
|
|
579
|
+
`;async function login(io,args,secret){let{values}=parse3(args,{paste:{type:"boolean"},"key-stdin":{type:"boolean"},"no-open":{type:"boolean"},"api-url":{type:"string"},"web-url":{type:"string"},"convex-url":{type:"string"},json:{type:"boolean"}});if(values.help)return io.stdout(COMMAND_HELP.login),ExitCode.ok;if(values.paste&&values["key-stdin"])throw usageError("Choose either --paste or --key-stdin, not both.");let apiUrl=values["api-url"]||io.env.ANDO_API_URL?.trim()||DEFAULT_API_URL,webUrl=values["web-url"]||io.env.ANDO_WEB_URL?.trim(),convexUrl=values["convex-url"]||io.env.ANDO_CONVEX_URL?.trim(),fetchImpl=io.fetch??globalThis.fetch,apiKey,authMethod,browserResult=null;if(values["key-stdin"])authMethod="key-stdin",apiKey=(await io.readStdin(4096)).text.trim();else if(values.paste){if(authMethod="paste",!io.stdinIsTty)throw usageError("Standard input is not a terminal; use --key-stdin.");apiKey=(await io.readSecret("Ando API key: ")).trim()}else authMethod="browser",browserResult=await runBrowserLogin({apiUrl,webUrl,convexUrl,noOpen:values["no-open"]===!0,env:io.env,stderr:io.stderr,stdinIsTty:io.stdinIsTty,fetchImpl,clock:io.clock}),apiKey=browserResult.apiKey;if(!apiKey)throw usageError("No API key given.");secret.apiKey=apiKey;let api=createClient2({apiKey,apiUrl,fetch:fetchImpl});await call("Checking the key",api.GET("/conversations",{params:{query:{limit:1}}}));let realtimeProbe=await probeWorkroomRealtimeAccess({apiUrl,apiKey,fetchImpl}),path=configPath(io.env);if(await writeStoredConfig(path,{apiKey,apiUrl,...webUrl?{webUrl}:{}}),realtimeProbe.status==="missing_scope"){let scopeList=realtimeProbe.missingScopes.join(", "),advice=authMethod==="browser"?"Check your workspace API key scopes in Settings or contact a workspace admin.":"Run `ando login` (browser sign-in) to mint a key with realtime:read automatically.";io.stderr(`Warning: this API key is missing ${scopeList}, so \`ando workroom list/watch\` will fail with 403. ${advice}
|
|
580
|
+
`)}let envApiKey=io.env.ANDO_API_KEY?.trim();envApiKey&&envApiKey!==apiKey&&io.stderr(`Warning: ANDO_API_KEY is set and takes precedence over this login; unset it to use the key just saved.
|
|
581
|
+
`);let realtimeReady=realtimeProbe.status==="ready";if(values.json)io.stdout(json({api_url:apiUrl,auth_method:authMethod,config_path:path,logged_in:!0,realtime_ready:realtimeReady,...realtimeProbe.status==="missing_scope"?{missing_scopes:realtimeProbe.missingScopes}:{},...browserResult?{key_prefix:browserResult.keyPrefix,scopes:browserResult.scopes,workspace_id:browserResult.workspaceId,workspace_membership_id:browserResult.workspaceMembershipId,workspace_name:browserResult.workspaceName}:{}}));else if(browserResult){let target=browserResult.workspaceName?`${browserResult.workspaceName} (${apiUrl})`:apiUrl,scopeNote=browserResult.scopes.length>0?` (scopes: ${browserResult.scopes.join(", ")})`:"";io.stdout(`Logged in to ${target}. Key saved to ${path}${scopeNote}.
|
|
582
|
+
`)}else io.stdout(`Logged in to ${apiUrl}. Key saved to ${path}.
|
|
583
|
+
`);return ExitCode.ok}async function send(io,args,secret){let{values,positionals}=parse3(args,{code:{type:"boolean"},thread:{type:"string"},json:{type:"boolean"}});if(values.help)return io.stdout(COMMAND_HELP.send),ExitCode.ok;let[target,...rest]=positionals;if(!target)throw usageError("Usage: ando send <#channel|conversation-id> [text]");let raw=await readText(io,rest),markdown=values.code?codeBlock(raw):raw.replace(/\n+$/u,""),config2=await resolveConfig(io.env,{readKeychain:io.readKeychain});secret.apiKey=config2.apiKey;let api=createClient2({...config2,fetch:io.fetch}),conversation=await resolveConversation(api,target),posted=await postMessage(api,{conversationId:conversation.id,markdown,...values.thread?{threadRootId:values.thread}:{}});if(values.json)return io.stdout(json(posted.message)),ExitCode.ok;let link2=await messageLink(api,config2.webUrl,posted,values.thread);return io.stdout(link2?`${link2}
|
|
569
584
|
`:`Posted ${posted.message.id} to ${conversation.label}.
|
|
570
585
|
`),ExitCode.ok}async function ask(io,args,secret){let{values,positionals}=parse3(args,{in:{type:"string"},timeout:{type:"string"},json:{type:"boolean"}});if(values.help)return io.stdout(COMMAND_HELP.ask),ExitCode.ok;let[agentName,...rest]=positionals;if(!agentName||!values.in)throw usageError("Usage: ando ask <@agent> [text] --in <#channel|conversation-id>");let timeoutMs=parseTimeout(values.timeout),question=(await readText(io,rest)).replace(/\n+$/u,"");if(!question.trim())throw usageError("Question is empty. Nothing was posted.");let config2=await resolveConfig(io.env,{readKeychain:io.readKeychain});secret.apiKey=config2.apiKey;let api=createClient2({...config2,fetch:io.fetch}),[conversation,agent]=await Promise.all([resolveConversation(api,values.in),resolveAgent(api,agentName)]),posted=await postMessage(api,{conversationId:conversation.id,markdown:`${mention(agent.membershipId,agent.name)} ${question}`}),questionId=posted.message.id,where=await messageLink(api,config2.webUrl,posted)??`message ${questionId} in ${conversation.label}`;io.stderr(`Asked @${agent.handle} in ${conversation.label}; waiting up to ${Math.round(timeoutMs/1e3)} s for a reply.
|
|
571
586
|
`);let warned=!1,reply=await waitForReply(api,{threadRootId:questionId,authorIds:agent.authorIds,timeoutMs,...io.pollIntervalMs?{pollIntervalMs:io.pollIntervalMs}:{},...io.clock?{clock:io.clock}:{},onTransientError:error2=>{warned||(warned=!0,io.stderr(`${error2.message} Still waiting.
|