@andocorp/cli 0.5.4 → 0.5.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +3 -0
  2. package/dist/cli.js +16 -8
  3. package/package.json +2 -2
package/README.md CHANGED
@@ -21,6 +21,9 @@ team. `--json` prints the API's message object instead, for scripts.
21
21
  In the repository agents should work in, run this and approve the link it prints.
22
22
  At a computer with a browser, press Enter to open it; over SSH, open it on any
23
23
  device. The server connects out to Ando: you open no ports and share no SSH keys.
24
+ Ando calls this a local connection; the
25
+ [server guide](https://docs.ando.so/docs/connecting-apps-to-ando/claude-code-on-a-server)
26
+ has every step.
24
27
 
25
28
  ```sh
26
29
  npx -y @andocorp/cli up
package/dist/cli.js CHANGED
@@ -20,7 +20,15 @@ ${thought}`;function createThoughtReporter({post,remove,log:log2,schedule=setTim
20
20
  `;return fs.mkdirSync(path.dirname(dest),{recursive:!0}),fs.writeFileSync(dest,out),fs.chmodSync(dest,fs.lstatSync(src).mode&511),!0}catch{return!1}}function copySetupEntry(src,dest,budget,folder=null){let stat=fs.lstatSync(src);if(stat.isSymbolicLink()){let rawTarget=fs.readlinkSync(src),resolvedTarget=path.resolve(path.dirname(src),rawTarget);fs.mkdirSync(path.dirname(dest),{recursive:!0}),fs.symlinkSync(resolvedTarget,dest);return}if(stat.isFile()){if(budget.bytes+stat.size>MAX_SETUP_BYTES||(budget.bytes+=stat.size,folder!=null&&src===path.join(folder,".claude","settings.local.json")&&rewriteCopiedSettingsLocal(src,dest,folder)))return;fs.mkdirSync(path.dirname(dest),{recursive:!0});try{fs.copyFileSync(src,dest,fs.constants.COPYFILE_FICLONE)}catch{fs.copyFileSync(src,dest)}fs.chmodSync(dest,stat.mode&511);return}if(stat.isDirectory()){fs.mkdirSync(dest,{recursive:!0});for(let entry of fs.readdirSync(src)){if(entry===".git")continue;let childDest=path.join(dest,entry);fs.existsSync(childDest)||copySetupEntry(path.join(src,entry),childDest,budget,folder)}}}function copyGitignoredSetup({git,folder,checkout,spawnSync:spawnSync3,env}){let paths=gitignoredSetupPaths(git,folder,{spawnSync:spawnSync3,env});if(paths.length===0)return 0;let budget={bytes:0},carried=[];for(let rel of paths){let src=path.join(folder,rel),dest=path.join(checkout,rel);try{fs.lstatSync(dest);continue}catch{}try{copySetupEntry(src,dest,budget,folder),carried.push(`/${rel.replace(/^\/+/u,"")}`)}catch{}}if(carried.length>0)try{let excludeFile=path.join(checkout,".git","info","exclude");fs.mkdirSync(path.dirname(excludeFile),{recursive:!0}),fs.appendFileSync(excludeFile,`
21
21
  ${carried.join(`
22
22
  `)}
23
- `)}catch{}return carried.length}var COW_DEPENDENCY_DIRS=["node_modules",".venv","venv"];function escapeRegExp(value){return value.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&")}function isRealSubpath(targetPath,realRoot){try{let realParent=fs.realpathSync(path.dirname(targetPath));return realParent===realRoot||realParent.startsWith(`${realRoot}${path.sep}`)}catch{return!1}}function rewriteTextPrefixes(filePath,prefixes,replacement,realClonedVenv){if(!isRealSubpath(filePath,realClonedVenv))return;let stat;try{stat=fs.lstatSync(filePath)}catch{return}if(!stat.isFile()||stat.isSymbolicLink()||stat.size===0||stat.size>1048576)return;let buf=fs.readFileSync(filePath);if(buf.subarray(0,512).includes(0))return;let original=buf.toString("utf8"),text=original;for(let prefix of prefixes){let pattern=new RegExp(`${escapeRegExp(prefix)}(?=$|[/\\\\\\s"'\`:;)])`,"gu");text=text.replace(pattern,()=>replacement)}if(text===original)return;let mode=stat.mode&511;fs.rmSync(filePath,{force:!0}),fs.writeFileSync(filePath,text,{mode}),fs.chmodSync(filePath,mode)}function isPlainDirectory(dirPath,realClonedVenv){try{let stat=fs.lstatSync(dirPath);if(!stat.isDirectory()||stat.isSymbolicLink())return!1;let realDir=fs.realpathSync(dirPath);return realDir===realClonedVenv||realDir.startsWith(`${realClonedVenv}${path.sep}`)}catch{return!1}}function relocateClonedVenv({folder,clonedVenv,finalCheckout}){let realClonedVenv;try{let venvStat=fs.lstatSync(clonedVenv);if(!venvStat.isDirectory()||venvStat.isSymbolicLink())return;realClonedVenv=fs.realpathSync(clonedVenv)}catch{return}let realFolder=folder;try{realFolder=fs.realpathSync(folder)}catch{}let prefixes=[...new Set([realFolder,folder])].sort((a,b)=>b.length-a.length);rewriteTextPrefixes(path.join(clonedVenv,"pyvenv.cfg"),prefixes,finalCheckout,realClonedVenv);for(let binName of["bin","Scripts"]){let binDir=path.join(clonedVenv,binName);if(!isPlainDirectory(binDir,realClonedVenv))continue;let entries;try{entries=fs.readdirSync(binDir)}catch{continue}for(let entry of entries){let full=path.join(binDir,entry);if(!isRealSubpath(full,realClonedVenv))continue;let stat;try{stat=fs.lstatSync(full)}catch{continue}if(stat.isSymbolicLink()){let rawTarget=fs.readlinkSync(full);if(!path.isAbsolute(rawTarget))continue;let matched=prefixes.find(prefix=>rawTarget===prefix||rawTarget.startsWith(`${prefix}${path.sep}`));matched!=null&&(fs.rmSync(full,{force:!0}),fs.symlinkSync(`${finalCheckout}${rawTarget.slice(matched.length)}`,full));continue}rewriteTextPrefixes(full,prefixes,finalCheckout,realClonedVenv)}}let libDir=path.join(clonedVenv,"lib");if(!isPlainDirectory(libDir,realClonedVenv))return;let pyDirs;try{pyDirs=fs.readdirSync(libDir)}catch{pyDirs=[]}for(let pyName of pyDirs){let pyDir=path.join(libDir,pyName);if(!isPlainDirectory(pyDir,realClonedVenv))continue;let sitePackages=path.join(pyDir,"site-packages");if(!isPlainDirectory(sitePackages,realClonedVenv))continue;let entries;try{entries=fs.readdirSync(sitePackages)}catch{continue}for(let entry of entries)(entry.endsWith(".pth")||entry.endsWith(".egg-link")||entry.startsWith("__editable__")&&entry.endsWith(".py"))&&rewriteTextPrefixes(path.join(sitePackages,entry),prefixes,finalCheckout,realClonedVenv)}}async function cloneGitignoredDependencies({git,folder,checkout,finalCheckout=checkout,spawnSync:spawnSync3,run:run3,env,platform,onProgress}){let cloned=[];if(platform!=="darwin"&&platform!=="linux")return cloned;let cmd=platform==="darwin"?"/bin/cp":"cp",flag=platform==="darwin"?"-RPc":"--reflink=always";for(let name of COW_DEPENDENCY_DIRS){let src=path.join(folder,name),dest=path.join(checkout,name);try{if(!fs.lstatSync(src).isDirectory()||fs.existsSync(dest))continue}catch{continue}if(spawnSync3(git,[...NO_HOOKS,"check-ignore","-q","--",`${name}/`],{cwd:checkout,env,encoding:"utf8",timeout:1e4}).status!==0)continue;let args=platform==="darwin"?[flag,"--",src,dest]:["-RP",flag,"--",src,dest];if(onProgress(`Copying ${name}...`),(await run3(cmd,args,{cwd:checkout,env,timeout:DEPENDENCY_CLONE_MS})).status!==0){await fs.promises.rm(dest,{recursive:!0,force:!0});continue}if(name===".venv"||name==="venv")try{relocateClonedVenv({folder,clonedVenv:dest,finalCheckout})}catch{fs.rmSync(dest,{recursive:!0,force:!0});continue}cloned.push(name)}return cloned}async function prepareTaskCheckout({root,folder,runId,git="git",env=process.env,spawnSync:spawnSync3=childProcess.spawnSync,run:run3=runInBackground,platform=process.platform,bare=!1,onProgress=(()=>{})}){let dir=path.join(root,runId);if(fs.existsSync(path.join(dir,".git")))return dir;let startedAt=Date.now();onProgress(`Making a checkout of ${folder}...`);let inFolder={spawnSync:spawnSync3,env,cwd:folder},top=runGit(git,["rev-parse","--show-toplevel"],inFolder);if(fs.realpathSync(top)!==fs.realpathSync(folder))throw new Error(`${folder} is inside a repository. Connect the repository's own folder.`);let origin=spawnSync3(git,["remote","get-url","origin"],{...inFolder,encoding:"utf8"}),originUrl=origin.status===0?origin.stdout.trim():"";fs.mkdirSync(root,{recursive:!0,mode:448});let partial=`${dir}.partial`;await fs.promises.rm(partial,{recursive:!0,force:!0});let cloned=await run3(git,[...NO_HOOKS,"clone","--quiet","--local","--no-hardlinks","--template=","--",folder,partial],{env,cwd:root,timeout:CLONE_MS});if(cloned.status!==0)throw new Error(`git clone: ${(cloned.stderr||"failed").trim().slice(0,300)}`);let inCheckout={spawnSync:spawnSync3,env,cwd:partial};originUrl?runGit(git,["remote","set-url","origin",originUrl],inCheckout):runGit(git,["remote","remove","origin"],inCheckout),runGit(git,[...NO_HOOKS,"switch","--quiet","-c",`ando/${runId.slice(0,8)}`],inCheckout);let brought=[];if(!bare){brought.push(...await cloneGitignoredDependencies({git,folder,checkout:partial,finalCheckout:dir,spawnSync:spawnSync3,run:run3,env,platform,onProgress}));let carried=copyGitignoredSetup({git,folder,checkout:partial,spawnSync:spawnSync3,env});carried>0&&brought.push(`${carried} ignored ${carried===1?"file or link":"files and links"}`)}fs.renameSync(partial,dir);let seconds=Math.max(1,Math.round((Date.now()-startedAt)/1e3));return onProgress(`Checkout ready in ${seconds}s${brought.length===0?"":`, with ${brought.join(", ")}`}.`),dir}function markTaskEnded(root,runId){try{fs.writeFileSync(path.join(root,`${runId}${ENDED}`),"")}catch{}}function sweepTaskCheckouts(root,{active=(()=>[]),now=Date.now()}={}){let entries;try{entries=fs.readdirSync(root)}catch{return}let running=new Set(active()),entrySet=new Set(entries);for(let entry of entries){if(entry.endsWith(ENDED)){let runId2=entry.slice(0,-ENDED.length);if(running.has(runId2)||entrySet.has(runId2)||entrySet.has(`${runId2}${TASK_RECORD}`))continue;let marker2=path.join(root,entry);try{now-fs.statSync(marker2).mtimeMs>KEEP_MS&&fs.rmSync(marker2,{force:!0})}catch{}continue}let isTaskRecord=entry.endsWith(TASK_RECORD),runId=isTaskRecord?entry.slice(0,-TASK_RECORD.length):entry;if(running.has(runId)||isTaskRecord&&entrySet.has(runId))continue;let base=path.join(root,runId),target=path.join(root,entry),marker=`${base}${ENDED}`;try{let ended=fs.statSync(marker,{throwIfNoEntry:!1});(ended?now-ended.mtimeMs>KEEP_MS:now-fs.statSync(target).mtimeMs>UNFINISHED_KEEP_MS)&&(fs.rmSync(base,{recursive:!0,force:!0}),fs.rmSync(marker,{force:!0}),fs.rmSync(`${base}${TASK_RECORD}`,{force:!0}))}catch{}}}module.exports={markTaskEnded,prepareTaskCheckout,sweepTaskCheckouts}}});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,readdir=listDir){let open=[],visit=(root,depth)=>{if(!closed.some(p=>isWithin(root,p))){if(!closed.some(p=>isWithin(p,root))){open.push(root);return}if(depth<3&&isWithin(root,home)&&root!==home)for(let entry of readdir(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(open)]}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"),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:readFile3=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(readFile3(found))?.[1]}catch{return null}if(script==null)return null;let dir=path.dirname(found),besideNode=path.join(dir,"node.exe"),node=exists(besideNode)?besideNode:findCommand2("node",searchPath,null,{platform:"win32",env});return node==null?null:{file:node,args:[path.join(dir,script)]}}function windowsSpawn(spawn2){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?spawn2(command,args,spawnOptions):spawn2(resolved.file,[...resolved.args,...args],spawnOptions)}}function windowsGuardRoot(env=process.env){return path.win32.join(env.ProgramData||"C:\\ProgramData","Ando","task-git")}function lockWindowsToken(tokenFile,{run:run3=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 run3(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:run3=childProcess.spawnSync,env=process.env}={}){let icacls=path.win32.join(env.SystemRoot||"C:\\Windows","System32","icacls.exe");return run3(icacls,[dir,"/grant","CodexSandboxUsers:(OI)(CI)RX","/T"],{encoding:"utf8",timeout:1e4,windowsHide:!0})?.status===0}module.exports={letSandboxReadGuard,lockWindowsToken,resolveWindowsCommand,windowsEnv,windowsGuardRoot,windowsSpawn}}});var require_command_env=__commonJS({"../../apps/web/electron/local-tools/command-env.js"(exports,module){"use strict";var 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 resolveCommandEnv({spawnSync:spawnSync3,env,platform=process.platform}){if(platform==="win32"){let normalized=windowsEnv(env);return{...normalized,PATH:trustedPath2(normalized.PATH??"")}}let shell=env.SHELL||"/bin/zsh",result=spawnSync3(shell,["-ilc",'printf "%s" "$PATH"'],{encoding:"utf8",timeout:5e3,cwd:os.homedir(),env:{...env,PATH:trustedPath2(env.PATH??"")}}),loginPath=result.status===0?result.stdout.trim():"";return{...env,PATH:trustedPath2(loginPath||(env.PATH??""))}}module.exports={resolveCommandEnv,trustedPath:trustedPath2}}});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"),{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
23
+ `)}catch{}return carried.length}var COW_DEPENDENCY_DIRS=["node_modules",".venv","venv"];function escapeRegExp(value){return value.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&")}function isRealSubpath(targetPath,realRoot){try{let realParent=fs.realpathSync(path.dirname(targetPath));return realParent===realRoot||realParent.startsWith(`${realRoot}${path.sep}`)}catch{return!1}}function rewriteTextPrefixes(filePath,prefixes,replacement,realClonedVenv){if(!isRealSubpath(filePath,realClonedVenv))return;let stat;try{stat=fs.lstatSync(filePath)}catch{return}if(!stat.isFile()||stat.isSymbolicLink()||stat.size===0||stat.size>1048576)return;let buf=fs.readFileSync(filePath);if(buf.subarray(0,512).includes(0))return;let original=buf.toString("utf8"),text=original;for(let prefix of prefixes){let pattern=new RegExp(`${escapeRegExp(prefix)}(?=$|[/\\\\\\s"'\`:;)])`,"gu");text=text.replace(pattern,()=>replacement)}if(text===original)return;let mode=stat.mode&511;fs.rmSync(filePath,{force:!0}),fs.writeFileSync(filePath,text,{mode}),fs.chmodSync(filePath,mode)}function isPlainDirectory(dirPath,realClonedVenv){try{let stat=fs.lstatSync(dirPath);if(!stat.isDirectory()||stat.isSymbolicLink())return!1;let realDir=fs.realpathSync(dirPath);return realDir===realClonedVenv||realDir.startsWith(`${realClonedVenv}${path.sep}`)}catch{return!1}}function relocateClonedVenv({folder,clonedVenv,finalCheckout}){let realClonedVenv;try{let venvStat=fs.lstatSync(clonedVenv);if(!venvStat.isDirectory()||venvStat.isSymbolicLink())return;realClonedVenv=fs.realpathSync(clonedVenv)}catch{return}let realFolder=folder;try{realFolder=fs.realpathSync(folder)}catch{}let prefixes=[...new Set([realFolder,folder])].sort((a,b)=>b.length-a.length);rewriteTextPrefixes(path.join(clonedVenv,"pyvenv.cfg"),prefixes,finalCheckout,realClonedVenv);for(let binName of["bin","Scripts"]){let binDir=path.join(clonedVenv,binName);if(!isPlainDirectory(binDir,realClonedVenv))continue;let entries;try{entries=fs.readdirSync(binDir)}catch{continue}for(let entry of entries){let full=path.join(binDir,entry);if(!isRealSubpath(full,realClonedVenv))continue;let stat;try{stat=fs.lstatSync(full)}catch{continue}if(stat.isSymbolicLink()){let rawTarget=fs.readlinkSync(full);if(!path.isAbsolute(rawTarget))continue;let matched=prefixes.find(prefix=>rawTarget===prefix||rawTarget.startsWith(`${prefix}${path.sep}`));matched!=null&&(fs.rmSync(full,{force:!0}),fs.symlinkSync(`${finalCheckout}${rawTarget.slice(matched.length)}`,full));continue}rewriteTextPrefixes(full,prefixes,finalCheckout,realClonedVenv)}}let libDir=path.join(clonedVenv,"lib");if(!isPlainDirectory(libDir,realClonedVenv))return;let pyDirs;try{pyDirs=fs.readdirSync(libDir)}catch{pyDirs=[]}for(let pyName of pyDirs){let pyDir=path.join(libDir,pyName);if(!isPlainDirectory(pyDir,realClonedVenv))continue;let sitePackages=path.join(pyDir,"site-packages");if(!isPlainDirectory(sitePackages,realClonedVenv))continue;let entries;try{entries=fs.readdirSync(sitePackages)}catch{continue}for(let entry of entries)(entry.endsWith(".pth")||entry.endsWith(".egg-link")||entry.startsWith("__editable__")&&entry.endsWith(".py"))&&rewriteTextPrefixes(path.join(sitePackages,entry),prefixes,finalCheckout,realClonedVenv)}}async function cloneGitignoredDependencies({git,folder,checkout,finalCheckout=checkout,spawnSync:spawnSync3,run:run3,env,platform,onProgress}){let cloned=[];if(platform!=="darwin"&&platform!=="linux")return cloned;let cmd=platform==="darwin"?"/bin/cp":"cp",flag=platform==="darwin"?"-RPc":"--reflink=always";for(let name of COW_DEPENDENCY_DIRS){let src=path.join(folder,name),dest=path.join(checkout,name);try{if(!fs.lstatSync(src).isDirectory()||fs.existsSync(dest))continue}catch{continue}if(spawnSync3(git,[...NO_HOOKS,"check-ignore","-q","--",`${name}/`],{cwd:checkout,env,encoding:"utf8",timeout:1e4}).status!==0)continue;let args=platform==="darwin"?[flag,"--",src,dest]:["-RP",flag,"--",src,dest];if(onProgress(`Copying ${name}...`),(await run3(cmd,args,{cwd:checkout,env,timeout:DEPENDENCY_CLONE_MS})).status!==0){await fs.promises.rm(dest,{recursive:!0,force:!0});continue}if(name===".venv"||name==="venv")try{relocateClonedVenv({folder,clonedVenv:dest,finalCheckout})}catch{fs.rmSync(dest,{recursive:!0,force:!0});continue}cloned.push(name)}return cloned}async function prepareTaskCheckout({root,folder,runId,git="git",env=process.env,spawnSync:spawnSync3=childProcess.spawnSync,run:run3=runInBackground,platform=process.platform,bare=!1,onProgress=(()=>{})}){let dir=path.join(root,runId);if(fs.existsSync(path.join(dir,".git")))return dir;let startedAt=Date.now();onProgress(`Making a checkout of ${folder}...`);let inFolder={spawnSync:spawnSync3,env,cwd:folder},top=runGit(git,["rev-parse","--show-toplevel"],inFolder);if(fs.realpathSync(top)!==fs.realpathSync(folder))throw new Error(`${folder} is inside a repository. Connect the repository's own folder.`);let origin=spawnSync3(git,["remote","get-url","origin"],{...inFolder,encoding:"utf8"}),originUrl=origin.status===0?origin.stdout.trim():"";fs.mkdirSync(root,{recursive:!0,mode:448});let partial=`${dir}.partial`;await fs.promises.rm(partial,{recursive:!0,force:!0});let cloned=await run3(git,[...NO_HOOKS,"clone","--quiet","--local","--no-hardlinks","--template=","--",folder,partial],{env,cwd:root,timeout:CLONE_MS});if(cloned.status!==0)throw new Error(`git clone: ${(cloned.stderr||"failed").trim().slice(0,300)}`);let inCheckout={spawnSync:spawnSync3,env,cwd:partial};originUrl?runGit(git,["remote","set-url","origin",originUrl],inCheckout):runGit(git,["remote","remove","origin"],inCheckout),runGit(git,[...NO_HOOKS,"switch","--quiet","-c",`ando/${runId.slice(0,8)}`],inCheckout);let brought=[];if(!bare){brought.push(...await cloneGitignoredDependencies({git,folder,checkout:partial,finalCheckout:dir,spawnSync:spawnSync3,run:run3,env,platform,onProgress}));let carried=copyGitignoredSetup({git,folder,checkout:partial,spawnSync:spawnSync3,env});carried>0&&brought.push(`${carried} ignored ${carried===1?"file or link":"files and links"}`)}fs.renameSync(partial,dir);let seconds=Math.max(1,Math.round((Date.now()-startedAt)/1e3));return onProgress(`Checkout ready in ${seconds}s${brought.length===0?"":`, with ${brought.join(", ")}`}.`),dir}function markTaskEnded(root,runId){try{fs.writeFileSync(path.join(root,`${runId}${ENDED}`),"")}catch{}}function sweepTaskCheckouts(root,{active=(()=>[]),now=Date.now()}={}){let entries;try{entries=fs.readdirSync(root)}catch{return}let running=new Set(active()),entrySet=new Set(entries);for(let entry of entries){if(entry.endsWith(ENDED)){let runId2=entry.slice(0,-ENDED.length);if(running.has(runId2)||entrySet.has(runId2)||entrySet.has(`${runId2}${TASK_RECORD}`))continue;let marker2=path.join(root,entry);try{now-fs.statSync(marker2).mtimeMs>KEEP_MS&&fs.rmSync(marker2,{force:!0})}catch{}continue}let isTaskRecord=entry.endsWith(TASK_RECORD),runId=isTaskRecord?entry.slice(0,-TASK_RECORD.length):entry;if(running.has(runId)||isTaskRecord&&entrySet.has(runId))continue;let base=path.join(root,runId),target=path.join(root,entry),marker=`${base}${ENDED}`;try{let ended=fs.statSync(marker,{throwIfNoEntry:!1});(ended?now-ended.mtimeMs>KEEP_MS:now-fs.statSync(target).mtimeMs>UNFINISHED_KEEP_MS)&&(fs.rmSync(base,{recursive:!0,force:!0}),fs.rmSync(marker,{force:!0}),fs.rmSync(`${base}${TASK_RECORD}`,{force:!0}))}catch{}}}module.exports={markTaskEnded,prepareTaskCheckout,sweepTaskCheckouts}}});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,readdir=listDir){let open=[],visit=(root,depth)=>{if(!closed.some(p=>isWithin(root,p))){if(!closed.some(p=>isWithin(p,root))){open.push(root);return}if(depth<3&&isWithin(root,home)&&root!==home)for(let entry of readdir(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(open)]}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"),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:readFile3=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(readFile3(found))?.[1]}catch{return null}if(script==null)return null;let dir=path.dirname(found),besideNode=path.join(dir,"node.exe"),node=exists(besideNode)?besideNode:findCommand2("node",searchPath,null,{platform:"win32",env});return node==null?null:{file:node,args:[path.join(dir,script)]}}function windowsSpawn(spawn2){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?spawn2(command,args,spawnOptions):spawn2(resolved.file,[...resolved.args,...args],spawnOptions)}}function windowsGuardRoot(env=process.env){return path.win32.join(env.ProgramData||"C:\\ProgramData","Ando","task-git")}function lockWindowsToken(tokenFile,{run:run3=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 run3(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:run3=childProcess.spawnSync,env=process.env}={}){let icacls=path.win32.join(env.SystemRoot||"C:\\Windows","System32","icacls.exe");return run3(icacls,[dir,"/grant","CodexSandboxUsers:(OI)(CI)RX","/T"],{encoding:"utf8",timeout:1e4,windowsHide:!0})?.status===0}module.exports={letSandboxReadGuard,lockWindowsToken,resolveWindowsCommand,windowsEnv,windowsGuardRoot,windowsSpawn}}});var require_command_env=__commonJS({"../../apps/web/electron/local-tools/command-env.js"(exports,module){"use strict";var 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 resolveCommandEnv({spawnSync:spawnSync3,env,platform=process.platform}){if(platform==="win32"){let normalized=windowsEnv(env);return{...normalized,PATH:trustedPath2(normalized.PATH??"")}}let shell=env.SHELL||"/bin/zsh",result=spawnSync3(shell,["-ilc",'printf "%s" "$PATH"'],{encoding:"utf8",timeout:5e3,cwd:os.homedir(),env:{...env,PATH:trustedPath2(env.PATH??"")}}),loginPath=result.status===0?result.stdout.trim():"";return{...env,PATH:trustedPath2(loginPath||(env.PATH??""))}}module.exports={resolveCommandEnv,trustedPath:trustedPath2}}});var require_python_bridge=__commonJS({"../../apps/web/electron/local-tools/python-bridge.js"(exports,module){"use strict";var PYTHON_SITECUSTOMIZE_PY=["import base64, errno, importlib.util, os, selectors, socket, struct, sys, threading, urllib.parse","","_own_dir = os.path.dirname(os.path.abspath(__file__))","for _p in list(sys.path):"," try:"," if os.path.abspath(_p) == _own_dir:"," continue"," except Exception:"," continue"," _cand = os.path.join(_p, 'sitecustomize.py')"," if os.path.isfile(_cand):"," try:"," _spec = importlib.util.spec_from_file_location('sitecustomize', _cand)"," if _spec and _spec.loader:"," _mod = importlib.util.module_from_spec(_spec)"," _spec.loader.exec_module(_mod)"," except Exception:"," pass"," break","","def _install_ando_sandbox_bridge():"," if os.environ.get('SANDBOX_RUNTIME') != '1' or getattr(socket, '_ando_patched', False):"," return"," socks_raw = os.environ.get('FTP_PROXY') or os.environ.get('ftp_proxy') or os.environ.get('ALL_PROXY') or os.environ.get('all_proxy') or ''"," http_raw = os.environ.get('HTTPS_PROXY') or os.environ.get('https_proxy') or os.environ.get('HTTP_PROXY') or os.environ.get('http_proxy') or ''"," proxy_raw = socks_raw or http_raw"," if not proxy_raw:"," return"," parsed = urllib.parse.urlparse(proxy_raw)"," if not parsed.port or parsed.hostname not in ('localhost', '127.0.0.1', '::1'):"," return"," socket._ando_patched = True"," proxy_port = parsed.port"," proxy_user = urllib.parse.unquote(parsed.username or '')"," proxy_pass = urllib.parse.unquote(parsed.password or '')"," use_socks = (parsed.scheme or '').lower().startswith('socks')",""," _orig_socket = socket.socket"," _orig_getaddrinfo = socket.getaddrinfo"," _ip_to_host = {}",""," def _is_loopback(h):"," if not h:"," return True"," s = str(h).strip('[]').lower()"," return s in ('localhost', 'localhost.', '::1', '0.0.0.0', '::') or s.startswith('127.')",""," def _recv_exact(s, n):"," buf = bytearray()"," while len(buf) < n:"," c = s.recv(n - len(buf))"," if not c:"," raise ConnectionResetError(errno.ECONNRESET, 'Proxy closed stream')"," buf.extend(c)"," return bytes(buf)",""," def _open_socks5(host, port):"," s = _orig_socket(socket.AF_INET, socket.SOCK_STREAM)"," s.settimeout(15.0)"," try:"," s.connect(('127.0.0.1', proxy_port))"," has_auth = bool(proxy_user or proxy_pass)"," s.sendall(b'\\x05\\x02\\x00\\x02' if has_auth else b'\\x05\\x01\\x00')"," ver, method = _recv_exact(s, 2)"," if ver != 5:"," raise ConnectionRefusedError(errno.ECONNREFUSED, 'Invalid SOCKS5 version')"," if method == 2:"," u, p = proxy_user.encode('utf-8'), proxy_pass.encode('utf-8')"," s.sendall(b'\\x01' + bytes([len(u)]) + u + bytes([len(p)]) + p)"," if _recv_exact(s, 2)[1] != 0:"," raise PermissionError(errno.EACCES, 'SOCKS5 auth failed')"," elif method != 0:"," raise PermissionError(errno.EACCES, 'SOCKS5 method rejected')"," try:"," req = b'\\x05\\x01\\x00\\x01' + socket.inet_aton(host) + struct.pack('!H', int(port))"," except OSError:"," hb = host.encode('utf-8')"," req = b'\\x05\\x01\\x00\\x03' + bytes([len(hb)]) + hb + struct.pack('!H', int(port))"," s.sendall(req)"," head = _recv_exact(s, 4)"," if head[1] != 0:"," raise ConnectionRefusedError(errno.ECONNREFUSED, f'Refused {host}:{port}')"," atyp = head[3]"," _recv_exact(s, 6 if atyp == 1 else (_recv_exact(s, 1)[0] + 2 if atyp == 3 else 18))"," s.settimeout(None)"," return s, b''"," except Exception:"," s.close()"," raise",""," def _open_http(host, port):"," s = _orig_socket(socket.AF_INET, socket.SOCK_STREAM)"," s.settimeout(15.0)"," try:"," s.connect(('127.0.0.1', proxy_port))"," tok = base64.b64encode(f'{proxy_user}:{proxy_pass}'.encode('utf-8')).decode('ascii') if (proxy_user or proxy_pass) else ''"," auth = f'Proxy-Authorization: Basic {tok}\\r\\n' if tok else ''"," s.sendall(f'CONNECT {host}:{int(port)} HTTP/1.1\\r\\nHost: {host}:{int(port)}\\r\\n{auth}\\r\\n'.encode('utf-8'))"," buf = bytearray()"," while b'\\r\\n\\r\\n' not in buf:"," c = s.recv(4096)"," if not c:"," raise ConnectionRefusedError(errno.ECONNREFUSED, 'Proxy EOF')"," buf.extend(c)"," idx = buf.index(b'\\r\\n\\r\\n')"," line = bytes(buf[:idx]).decode('latin1', errors='ignore').splitlines()[0]"," if ' 200' not in line:"," raise ConnectionRefusedError(errno.ECONNREFUSED, line)"," s.settimeout(None)"," return s, bytes(buf[idx + 4:])"," except Exception:"," s.close()"," raise",""," def _open_tunnel(host, port):"," clean = str(host).strip('[]')"," dest = _ip_to_host.get(clean, clean)"," return _open_socks5(dest, port) if use_socks else _open_http(dest, port)",""," def _query_dns_tcp(pkt):"," c = os.environ.get('ANDO_SANDBOX_DNS_UPSTREAM')"," if c:"," if ':' in c:"," h, p = c.rsplit(':', 1)"," ups = [(h.strip('[]'), int(p))]"," else:"," ups = [(c.strip('[]'), 53)]"," else:"," ups = [('1.1.1.1', 53), ('8.8.8.8', 53)]"," for ns_h, ns_p in ups:"," try:"," ps, rest = _open_tunnel(ns_h, ns_p)"," try:"," ps.settimeout(8.0)"," ps.sendall(struct.pack('!H', len(pkt)) + pkt)"," buf = bytearray(rest)"," while len(buf) < 2:"," chunk = ps.recv(4096)"," if not chunk:"," raise ConnectionResetError(errno.ECONNRESET, 'DNS EOF')"," buf.extend(chunk)"," alen = struct.unpack('!H', buf[:2])[0]"," while len(buf) < 2 + alen:"," chunk = ps.recv(2 + alen - len(buf))"," if not chunk:"," raise ConnectionResetError(errno.ECONNRESET, 'DNS EOF')"," buf.extend(chunk)"," return bytes(buf[2:2 + alen])"," finally:"," ps.close()"," except Exception:"," continue"," return None",""," _dns_lock, _dns_ports = threading.Lock(), {}"," def _ensure_dns(fam=socket.AF_INET):"," with _dns_lock:"," if fam in _dns_ports:"," return _dns_ports[fam]"," bind_addr = ('::1', 0) if fam == socket.AF_INET6 else ('127.0.0.1', 0)"," u = _orig_socket(fam, socket.SOCK_DGRAM)"," u.bind(bind_addr)"," _dns_ports[fam] = u.getsockname()[1]"," def _reply(pkt, addr):"," ans = _query_dns_tcp(pkt)"," if ans:"," try:"," u.sendto(ans, addr)"," except Exception:"," pass"," def _loop():"," while True:"," try:"," p, a = u.recvfrom(4096)"," threading.Thread(target=_reply, args=(p, a), daemon=True).start()"," except Exception:"," break"," threading.Thread(target=_loop, daemon=True).start()"," return _dns_ports[fam]",""," def _pump_pair(c, ps, rest):"," if rest:"," try:"," c.sendall(rest)"," except Exception:"," pass"," rem, lk = [2], threading.Lock()"," def _dir(src, dst):"," err = False"," try:"," while True:"," d = src.recv(16384)"," if not d:"," try:"," dst.shutdown(socket.SHUT_WR)"," except Exception:"," pass"," break"," dst.sendall(d)"," except Exception:"," err = True"," finally:"," with lk:"," rem[0] -= 1"," done = err or rem[0] <= 0"," if done:"," for s in (c, ps):"," try:"," s.close()"," except Exception:"," pass"," threading.Thread(target=_dir, args=(c, ps), daemon=True).start()"," threading.Thread(target=_dir, args=(ps, c), daemon=True).start()",""," def _start_local_bridge(srv, ps, rest):"," def _run():"," try:"," c, _ = srv.accept()"," except Exception:"," ps.close()"," return"," finally:"," srv.close()"," _pump_pair(c, ps, rest)"," threading.Thread(target=_run, daemon=True).start()",""," class _PatchedSocket(_orig_socket):"," def __init__(self, family=socket.AF_INET, type=socket.SOCK_STREAM, proto=0, fileno=None):"," super().__init__(family, type, proto, fileno)"," self._orig_dns_peer = None"," self._nb_err = None"," self._nb_connecting = False"," def getsockopt(self, level, optname, *args):"," if level == socket.SOL_SOCKET and optname == socket.SO_ERROR and not args and self._nb_err is not None:"," err, self._nb_err, self._nb_connecting = self._nb_err, None, False"," return err"," return super().getsockopt(level, optname, *args)"," def sendto(self, data, *args):"," flags, addr = (0, args[0]) if len(args) == 1 else (args[0], args[1]) if len(args) == 2 else (0, None)"," if self.family in (socket.AF_INET, socket.AF_INET6) and (self.type & socket.SOCK_DGRAM) and isinstance(addr, tuple) and len(addr) >= 2 and addr[1] == 53 and not _is_loopback(addr[0]):"," self._orig_dns_peer = addr"," lh = '::1' if self.family == socket.AF_INET6 else '127.0.0.1'"," return super().sendto(data, flags, (lh, _ensure_dns(self.family)))"," return super().sendto(data, *args)"," def recvfrom(self, bufsize, *args):"," d, a = super().recvfrom(bufsize, *args)"," if self._orig_dns_peer is not None and isinstance(a, tuple) and len(a) >= 2 and a[0] in ('127.0.0.1', '::1'):"," return d, self._orig_dns_peer"," return d, a"," def connect(self, address):"," if not isinstance(address, tuple) or len(address) < 2 or _is_loopback(address[0]):"," return super().connect(address)"," host, port = address[0], address[1]"," lh = '::1' if self.family == socket.AF_INET6 else '127.0.0.1'"," if self.family in (socket.AF_INET, socket.AF_INET6) and (self.type & socket.SOCK_DGRAM) and port == 53:"," self._orig_dns_peer = address"," return super().connect((lh, _ensure_dns(self.family)))"," if self.family not in (socket.AF_INET, socket.AF_INET6) or not (self.type & socket.SOCK_STREAM):"," return super().connect(address)"," if self._nb_connecting:"," if self._nb_err is None:"," raise BlockingIOError(errno.EALREADY, 'Operation already in progress')"," err, self._nb_err, self._nb_connecting = self._nb_err, None, False"," if err != 0:"," raise OSError(err, os.strerror(err))"," return None"," target_host = _ip_to_host.get(host, host)"," if self.gettimeout() == 0.0:"," srv = _orig_socket(self.family, socket.SOCK_STREAM)"," srv.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 4096)"," srv.bind((lh, 0))"," srv.listen(1)"," self.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 4096)"," try:"," super().connect((lh, srv.getsockname()[1]))"," except BlockingIOError:"," pass"," peer, _ = srv.accept()"," srv.close()"," stuffed = 0"," chunk = b'\\x00' * 4096"," with selectors.DefaultSelector() as sel:"," sel.register(self, selectors.EVENT_WRITE)"," while sel.select(0.002):"," try:"," stuffed += super().send(chunk)"," except BlockingIOError:"," pass"," self._nb_connecting = True"," self._nb_err = None"," def _run_nb():"," try:"," ps, rest = _open_tunnel(target_host, port)"," _recv_exact(peer, stuffed)"," try:"," self.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 65536)"," peer.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 65536)"," except Exception:"," pass"," self._nb_err = 0"," except OSError as e:"," self._nb_err = e.errno or errno.ECONNREFUSED"," try:"," peer.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, struct.pack('ii', 1, 0))"," except Exception:"," pass"," peer.close()"," return"," except Exception:"," self._nb_err = errno.ECONNREFUSED"," try:"," peer.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, struct.pack('ii', 1, 0))"," except Exception:"," pass"," peer.close()"," return"," _pump_pair(peer, ps, rest)"," threading.Thread(target=_run_nb, daemon=True).start()"," raise BlockingIOError(errno.EINPROGRESS, 'Operation now in progress')"," ps, rest = _open_tunnel(target_host, port)"," srv = _orig_socket(self.family, socket.SOCK_STREAM)"," srv.bind((lh, 0))"," srv.listen(1)"," _start_local_bridge(srv, ps, rest)"," return super().connect((lh, srv.getsockname()[1]))"," def connect_ex(self, address):"," try:"," self.connect(address)"," return 0"," except OSError as e:"," return e.errno or errno.ECONNREFUSED",""," socket.socket = socket.SocketType = _PatchedSocket",""," def _skip_dns_name(buf, off):"," n = len(buf)"," while off < n:"," ln = buf[off]"," if ln == 0:"," return off + 1"," if (ln & 0xC0) == 0xC0:"," return off + 2 if off + 1 < n else n + 1"," off += 1 + ln"," return n + 1",""," def _parse_dns_A_answers(ans):"," if not ans or len(ans) < 12:"," return []"," flags, qdcount, ancount = struct.unpack('!HHH', ans[2:8])"," if (flags & 0x000F) != 0 or ancount == 0:"," return []"," off = 12"," for _ in range(qdcount):"," off = _skip_dns_name(ans, off) + 4"," if off > len(ans):"," return []"," ips = []"," for _ in range(ancount):"," off = _skip_dns_name(ans, off)"," if off + 10 > len(ans):"," break"," rtype, rclass, _ttl, rdlen = struct.unpack('!HHIH', ans[off:off + 10])"," off += 10"," if off + rdlen > len(ans):"," break"," if rtype == 1 and rclass == 1 and rdlen == 4:"," ips.append(socket.inet_ntoa(ans[off:off + 4]))"," off += rdlen"," return ips",""," def _patched_getaddrinfo(host, port, family=0, type=0, proto=0, flags=0):"," try:"," res = _orig_getaddrinfo(host, port, family, type, proto, flags)"," if isinstance(host, str) and not _is_loopback(host):"," for item in res:"," if not _is_loopback(item[4][0]):"," _ip_to_host[item[4][0]] = host"," return res"," except socket.gaierror as orig_err:"," if not isinstance(host, str) or _is_loopback(host) or family == socket.AF_INET6:"," raise"," q = bytearray(b'\\x12\\x34\\x01\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\x00\\x00')"," for lbl in host.strip('.').split('.'):"," eb = lbl.encode('utf-8')"," q.append(len(eb))"," q.extend(eb)"," ans = _query_dns_tcp(bytes(q + b'\\x00\\x00\\x01\\x00\\x01'))"," ips = _parse_dns_A_answers(ans)"," if not ips:"," raise orig_err"," for ip in ips:"," _ip_to_host[ip] = host"," st = type or socket.SOCK_STREAM"," pr = proto or (socket.IPPROTO_TCP if st == socket.SOCK_STREAM else 0)"," pnum = 0 if port is None else int(port)"," return [(socket.AF_INET, st, pr, '', (ip, pnum)) for ip in ips]",""," socket.getaddrinfo = _patched_getaddrinfo","","try:"," _install_ando_sandbox_bridge()","except Exception:"," pass",""].join(`
24
+ `);module.exports={PYTHON_SITECUSTOMIZE_PY}}});var require_net_bridge=__commonJS({"../../apps/web/electron/local-tools/net-bridge.js"(exports,module){"use strict";function installSandboxNetBridge(){let sym=Symbol.for("ando.sandboxNetBridge");if(process.env.SANDBOX_RUNTIME!=="1"||globalThis[sym])return;function isLoopbackHost(host){if(!host)return!0;let h=String(host).toLowerCase();return h==="localhost"||h==="localhost."||h==="127.0.0.1"||h==="::1"||h==="[::1]"||h==="0.0.0.0"||h==="::"||/^127\.\d+\.\d+\.\d+$/.test(h)}function readProxyConfig(){let raw=process.env.FTP_PROXY||process.env.ftp_proxy||process.env.ALL_PROXY||process.env.all_proxy||process.env.HTTPS_PROXY||process.env.https_proxy||process.env.HTTP_PROXY||process.env.http_proxy;if(!raw)return null;try{let u=new URL(raw),port=Number(u.port);return!port||!isLoopbackHost(u.hostname)?null:{port,useSocks:u.protocol.startsWith("socks"),user:u.username?decodeURIComponent(u.username):"",pass:u.password?decodeURIComponent(u.password):""}}catch{return null}}let proxy=readProxyConfig();if(!proxy)return;globalThis[sym]=!0;let net=__require("net"),dns=__require("dns"),dgram=__require("dgram"),origConnect=net.Socket.prototype.connect,origLookup=dns.lookup,ipToHost=new Map;function buildSocksConnectReq(host,port){if(net.isIPv4(host)){let p=host.split(".").map(Number),req2=Buffer.from([5,1,0,1,p[0],p[1],p[2],p[3],0,0]);return req2.writeUInt16BE(port,8),req2}let hb=Buffer.from(host,"utf8"),req=Buffer.alloc(7+hb.length);return req[0]=5,req[1]=1,req[2]=0,req[3]=3,req[4]=hb.length,hb.copy(req,5),req.writeUInt16BE(port,5+hb.length),req}function socksReplyLength(buf){return buf.length<4?0:buf[3]===3?buf.length<5?0:7+buf[4]:buf[3]===4?22:10}function makeTunnelSocket(connectHost,targetPort,cb){let sock=new net.Socket,settled=!1,fail=(code2,msg)=>{settled||(settled=!0,sock.destroy(),cb(Object.assign(new Error(msg||`connect ${code2} ${connectHost}:${targetPort}`),{code:code2})))},onEarlyClose=()=>fail("ECONNREFUSED","Proxy closed before tunnel established"),finish=rest=>{settled||(settled=!0,sock.removeListener("close",onEarlyClose),sock.setTimeout(0),sock.pause(),cb(null,sock,rest))};return sock.setTimeout(15e3,()=>fail("ETIMEDOUT")),sock.once("error",err=>fail(err.code||"ECONNREFUSED",err.message)),sock.once("close",onEarlyClose),{sock,fail,finish}}function openSocks5Tunnel(connectHost,targetPort,cb){let{sock,fail,finish}=makeTunnelSocket(connectHost,targetPort,cb);return origConnect.call(sock,{host:"127.0.0.1",port:proxy.port,family:4},()=>{sock.setNoDelay(!0);let hasAuth=proxy.user.length>0||proxy.pass.length>0;sock.write(hasAuth?Buffer.from([5,2,0,2]):Buffer.from([5,1,0]));let stage=0,buf=Buffer.alloc(0),onData=chunk=>{if(buf=Buffer.concat([buf,chunk]),stage===0&&buf.length>=2){let method=buf[1];if(buf=buf.subarray(2),method===2){let ub=Buffer.from(proxy.user,"utf8"),pb=Buffer.from(proxy.pass,"utf8");sock.write(Buffer.concat([Buffer.from([1,ub.length]),ub,Buffer.from([pb.length]),pb])),stage=1}else if(method===0)sock.write(buildSocksConnectReq(connectHost,targetPort)),stage=2;else return fail("EACCES","SOCKS5 authentication rejected")}if(stage===1&&buf.length>=2){let status=buf[1];if(buf=buf.subarray(2),status!==0)return fail("EACCES","SOCKS5 credentials rejected");sock.write(buildSocksConnectReq(connectHost,targetPort)),stage=2}if(stage===2){let need=socksReplyLength(buf);if(!need||buf.length<need)return;if(buf[1]!==0)return fail("ECONNREFUSED");sock.removeListener("data",onData),finish(buf.subarray(need))}};sock.on("data",onData)}),sock}function openHttpConnectTunnel(connectHost,targetPort,cb){let{sock,fail,finish}=makeTunnelSocket(connectHost,targetPort,cb);return origConnect.call(sock,{host:"127.0.0.1",port:proxy.port,family:4},()=>{sock.setNoDelay(!0);let auth=proxy.user.length>0||proxy.pass.length>0?`Proxy-Authorization: Basic ${Buffer.from(`${proxy.user}:${proxy.pass}`).toString("base64")}\r
25
+ `:"",target=net.isIPv6(connectHost)?`[${connectHost}]:${targetPort}`:`${connectHost}:${targetPort}`;sock.write(`CONNECT ${target} HTTP/1.1\r
26
+ Host: ${target}\r
27
+ ${auth}\r
28
+ `);let buf=Buffer.alloc(0),onData=chunk=>{buf=Buffer.concat([buf,chunk]);let idx=buf.indexOf(`\r
29
+ \r
30
+ `);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 custom=process.env.ANDO_SANDBOX_DNS_UPSTREAM;if(!custom)return[{host:"1.1.1.1",port:53},{host:"8.8.8.8",port:53}];let idx=custom.lastIndexOf(":");return idx>0?[{host:custom.slice(0,idx),port:Number(custom.slice(idx+1))||53}]:[{host:custom,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=(_a2,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(hostname2,address){if(Array.isArray(address))for(let item of address)item?.address&&!isLoopbackHost(item.address)&&ipToHost.set(item.address,hostname2);else typeof address=="string"&&!isLoopbackHost(address)&&ipToHost.set(address,hostname2)}function fallbackDnsResolve(hostname2,opts,origErr,cb){let fam=opts.family===6?6:4;(fam===6?dns.resolve6:dns.resolve4).call(dns,hostname2,(resErr,list)=>{if(resErr||!list?.length)return cb(origErr||resErr);for(let ip of list)ipToHost.set(ip,hostname2);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(hostname2,options,callback){let cb=typeof options=="function"?options:callback,opts=typeof options=="function"?{}:typeof options=="number"?{family:options}:options||{};return!hostname2||isLoopbackHost(hostname2)||net.isIP(hostname2)!==0?origLookup.call(this,hostname2,options,callback):origLookup.call(this,hostname2,opts,(err,address,family)=>{if(!err&&address)return recordLookupResult(hostname2,address),cb(null,address,family);fallbackDnsResolve(hostname2,opts,err,cb)})},dns.promises?.lookup&&(dns.promises.lookup=(hostname2,options)=>new Promise((resolve2,reject)=>{dns.lookup(hostname2,options,(err,address,family)=>err?reject(err):resolve2(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()})();
31
+ `;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
24
32
  `)}function repoHooksPath(folder,{git,env=process.env,run:run3}){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=run3(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():""},own=ask2(["config","--get","core.hooksPath"]);if(!own)return null;if(own.startsWith("~/")&&(own=path.join(home,own.slice(2))),path.isAbsolute(own))return path.resolve(own);let top=ask2(["rev-parse","--show-toplevel"]);return top?path.resolve(top,own):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(delimiter).filter(Boolean)].join(delimiter)}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=`
25
33
  # A setting that would switch the push hook off or hide a push in an alias.
26
34
  check_key() {
@@ -69,7 +77,7 @@ esac
69
77
  `)}var FORWARDED_HOOKS=["applypatch-msg","pre-applypatch","post-applypatch","pre-commit","pre-merge-commit","prepare-commit-msg","commit-msg","post-commit","pre-rebase","post-checkout","post-merge","pre-receive","update","proc-receive","post-receive","post-update","reference-transaction","pre-auto-gc","post-rewrite","sendemail-validate","fsmonitor-watchman","p4-changelist","p4-prepare-changelist","p4-post-changelist","p4-pre-submit","post-index-change"];function gitGuardFiles(dir,policy,{realGit,realGh=null,githubToken=null,platform=process.platform,sh=null}){let shDir=shellPath(dir,platform),shGit=shellPath(realGit,platform),files=[],github=githubToken!=null&&policy.push!=="never";github&&files.push({name:"gh/token",content:`${githubToken}
70
78
  `,mode:384,secret:!0});let guarded=policy.push==="never"||policy.deploy==="never",chain=["name=${0##*/}",`real=${shellQuote(shGit)}`,'common=$(GIT_CONFIG_COUNT=0 "$real" rev-parse --git-common-dir 2>/dev/null)','own=$(GIT_CONFIG_COUNT=0 "$real" config --get core.hooksPath 2>/dev/null)','[ -n "$own" ] || own="$common/hooks"','case "$own" in "~/"*) own="$HOME/${own#"~/"}" ;; esac','case "$own" in /*|[A-Za-z]:[\\\\/]*) ;; *) own="$(GIT_CONFIG_COUNT=0 "$real" rev-parse --show-toplevel)/$own" ;; esac',`[ "$(cd "$own" 2>/dev/null && pwd -P)" = "$(cd ${shellQuote(shDir)} && pwd -P)" ] && exit 0`],prePush=["#!/bin/sh","# Written by Ando for one task: the push rules its machine's owner set.",...policy.push==="never"?[`echo "Ando: this computer's owner doesn't let tasks push. Hand the change back instead." >&2`,"exit 1"]:[],...policy.deploy==="never"?["while read -r local_ref local_sha remote_ref remote_sha; do",' case "$remote_ref" in'," refs/heads/main|refs/heads/master)",' echo "Ando: tasks may not push to main. Push a branch instead, and say in your result that it needs a pull request." >&2'," exit 1 ;;",' refs/tags/*) echo "Ando: tasks may not push tags." >&2; exit 1 ;;'," esac","done"]:[],...guarded?["exit 0"]:["refs=$(cat)",...chain,`[ -x "$own/$name" ] && { printf '%s\\n' "$refs" | "$own/$name" "$@"; exit $?; }`,"exit 0"],""].join(`
71
79
  `);files.push({name:"pre-push",content:prePush,mode:493});let passThrough=["#!/bin/sh",...chain,'[ -x "$own/$name" ] && exec "$own/$name" "$@"',"exit 0",""].join(`
72
- `);for(let hook of FORWARDED_HOOKS)files.push({name:hook,content:passThrough,mode:493});files.push({name:"bin/git",content:gitShim(policy,shGit,gitGuardEntries(dir,policy,{github,platform})),mode:493});let ghToo=guarded||github;if(ghToo&&files.push({name:"bin/gh",content:ghShim(dir,realGh,policy,github,platform),mode:493}),sh!=null)for(let name of ghToo?["git","gh"]:["git"])files.push({name:`bin/${name}.cmd`,content:windowsLauncher(sh,name),mode:493});let bin=gitGuardBin(dir,platform);return files.push({name:"shell-env.sh",content:[`case ":$PATH:" in ${shellQuote(`:${bin}:`)}*) ;; *) export PATH=${shellQuote(bin)}:"$PATH" ;; esac`,""].join(`
80
+ `);for(let hook of FORWARDED_HOOKS)files.push({name:hook,content:passThrough,mode:493});files.push({name:"bin/git",content:gitShim(policy,shGit,gitGuardEntries(dir,policy,{github,platform})),mode:493});let ghToo=guarded||github;if(ghToo&&files.push({name:"bin/gh",content:ghShim(dir,realGh,policy,github,platform),mode:493}),sh!=null)for(let name of ghToo?["git","gh"]:["git"])files.push({name:`bin/${name}.cmd`,content:windowsLauncher(sh,name),mode:493});let bin=gitGuardBin(dir,platform),allowNetwork=policy.network!=="never";allowNetwork&&(files.push({name:"net-bridge.js",content:NET_BRIDGE_JS,mode:420}),files.push({name:"python/sitecustomize.py",content:PYTHON_SITECUSTOMIZE_PY,mode:420}));let netBridge=pathsOf(platform).join(dir,"net-bridge.js"),nodeOptArg=netBridge.includes(" ")?`"${netBridge}"`:netBridge,pythonDir=pathsOf(platform).join(dir,"python");return files.push({name:"shell-env.sh",content:[`case ":$PATH:" in ${shellQuote(`:${bin}:`)}*) ;; *) export PATH=${shellQuote(bin)}:"$PATH" ;; esac`,...allowNetwork?[`case " \${NODE_OPTIONS:-} " in *${shellQuote(` ${nodeOptArg} `)}*) ;; *) export NODE_OPTIONS="\${NODE_OPTIONS:+$NODE_OPTIONS }--require "${shellQuote(nodeOptArg)} ;; esac`,`case ":\${PYTHONPATH:-}:" in *${shellQuote(`:${pythonDir}:`)}*) ;; *) export PYTHONPATH=${shellQuote(pythonDir)}\${PYTHONPATH:+":$PYTHONPATH"} ;; esac`]:[],""].join(`
73
81
  `),mode:420}),files}function writeGitGuard(dir,policy,{realGit=findGit(process.env.PATH,gitGuardBin(dir)),realGh=findCommand2("gh",process.env.PATH,gitGuardBin(dir)),githubToken=null,platform=process.platform,exists=fs.existsSync,lockSecret=()=>!0}={}){let sh=platform==="win32"?gitShellFor(realGit,exists):null;if(platform==="win32"&&sh==null)throw new Error("Codex tasks on Windows need Git for Windows. Install it from https://git-scm.com and try again.");fs.mkdirSync(dir,{recursive:!0,mode:448});for(let file of gitGuardFiles(dir,policy,{realGit,realGh,githubToken,platform,sh})){let target=path.join(dir,file.name);if(fs.mkdirSync(path.dirname(target),{recursive:!0,mode:448}),!file.secret){fs.writeFileSync(target,file.content,{mode:file.mode});continue}fs.writeFileSync(target,"",{mode:file.mode}),lockSecret(target)?fs.writeFileSync(target,file.content):fs.rmSync(target,{force:!0})}return dir}var PUSH_ADDRESS_PREFIXES=["https://","http://","ssh://","git://","git@","file://","/","~","."],GITHUB_CREDENTIAL_HELPER=[["credential.https://github.com.helper",""],["credential.https://github.com.helper","!gh auth git-credential"]];function gitGuardEntries(dir,policy=null,{github=!1,platform=process.platform}={}){let entries=[["core.hooksPath",shellPath(dir,platform)],...SIGNING_OFF];if(policy?.push==="never")for(let prefix of PUSH_ADDRESS_PREFIXES)entries.push(["url.ando-push-disabled:.pushInsteadOf",prefix]);else github&&entries.push(...GITHUB_CREDENTIAL_HELPER);return entries}function gitGuardEnv(dir,policy=null,{github=!1,platform=process.platform}={}){let entries=gitGuardEntries(dir,policy,{github,platform}),env={GIT_CONFIG_COUNT:String(entries.length)};return entries.forEach(([key,value],index)=>{env[`GIT_CONFIG_KEY_${index}`]=key,env[`GIT_CONFIG_VALUE_${index}`]=value}),env}var GUARD_BYPASS_COMMANDS=["*--no-veri*","*core.hooksPath*","*core.hookspath*","*GIT_CONFIG*","env -*","* env -*","*/env -*","*(env -*","*;env -*","*&env -*","*|env -*","*exec -c*","*unset *GIT*","*/bin/git *","*/bin/git","*git-core*","*xcrun*git*","*send-pack*","*http-push*","*git*alias.*"],MERGE_COMMANDS=["*gh pr merge*","*gh api*merge*","*gh api*Merge*"];function isOwnedPrivately(found,uid){return found.isDirectory()&&found.uid===uid&&(found.mode&63)===0}function ownedGuardRoot(root,{platform=process.platform,getuid=process.getuid,home=os.homedir()}={}){if(platform==="win32")return root;let own=dir=>{fs.mkdirSync(path.dirname(dir),{recursive:!0});try{fs.mkdirSync(dir,{mode:448})}catch(error){if(error.code!=="EEXIST")throw error}return isOwnedPrivately(fs.lstatSync(dir),getuid())};if(own(root))return root;let fallback=path.join(home,".cache","ando-task-git");if(own(fallback))return fallback;throw new Error(`${fallback} isn't this account's alone, so tasks can't be held to their limits.`)}module.exports={ownedGuardRoot,GUARD_BYPASS_COMMANDS,MERGE_COMMANDS,findGit,gitGuardEntries,gitGuardFiles,gitShellFor,gitGuardEnv,githubSignIn,guardedPath,repoHooksPath,writeGitGuard}}});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:run3}){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=run3(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(`
74
82
  `)){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:run3}){if(platform!=="darwin")return null;let dir=env.DEVELOPER_DIR||String(run3("/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:run3=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:run3}),{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:run3})),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:execFile2=childProcess.execFile}={}){return gh==null?Promise.resolve(null):new Promise(resolve2=>{execFile2(gh,["auth","token","--hostname","github.com"],{env:{...env,GH_PROMPT_DISABLED:"1"},encoding:"utf8",timeout:5e3},(error,stdout)=>{let token=error==null&&typeof stdout=="string"?stdout.trim():"";resolve2(/^\S+$/.test(token)?token:null)})})}module.exports={findAll,ownerGithubToken,parseHelper,pushCredentialPaths}}});var require_dist=__commonJS({"../../node_modules/smol-toml/dist/index.cjs"(exports){"use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});function getLineColFromPtr(string,ptr){let lines=string.slice(0,ptr).split(/\r?\n/);return[lines.length,lines.pop().length+1]}function makeCodeBlock(string,line,column){let lines=string.split(/\r?\n/),codeblock="",numberLen=(Math.log10(line+1)|0)+1;for(let i2=line-1;i2<=line+1;i2++){let l=lines[i2-1];l&&(codeblock+=i2.toString().padEnd(numberLen," "),codeblock+=": ",codeblock+=l,codeblock+=`
75
83
  `,i2===line&&(codeblock+=" ".repeat(numberLen+column+2),codeblock+=`^
@@ -86,26 +94,26 @@ ${preamble}`:`[${tableKey}]`),preamble&&tables?`${preamble}
86
94
  ${tables}`:preamble||tables}function stringify(obj,{maxDepth=1e3,numbersAsFloat=!1,strictTemporal=!1}={}){if(extendedTypeOf(obj)!=="object")throw new TypeError("stringify can only be called with an object");let str=stringifyTable(0,obj,"",maxDepth,numbersAsFloat,strictTemporal);return str[str.length-1]!==`
87
95
  `?str+`
88
96
  `:str}var src_default={parse:parse2,stringify,TomlDate,TomlError};exports.TomlDate=TomlDate;exports.TomlError=TomlError;exports.default=src_default;exports.parse=parse2;exports.stringify=stringify}});var require_servers=__commonJS({"../../apps/web/electron/local-tools/servers.js"(exports,module){"use strict";var fs=__require("fs"),os=__require("os"),path=__require("path");function parseToml(text){return require_dist().parse(text)}var CODEX_APPS="ChatGPT apps";function statSignature(file){try{let stat=fs.statSync(file);return stat.isFile()?`${stat.mtimeMs}:${stat.size}`:null}catch{return null}}var claudeConfigCache=null;function readClaudeConfig(home=os.homedir()){let file=path.join(home,".claude.json"),signature=statSignature(file);if(signature==null)return{mcpServers:{},projects:{}};if(claudeConfigCache!=null&&claudeConfigCache.file===file&&claudeConfigCache.signature===signature)return claudeConfigCache.value;let raw;try{raw=fs.readFileSync(file,"utf8")}catch{return{mcpServers:{},projects:{}}}try{let parsed=JSON.parse(raw),mcpServers=parsed?.mcpServers!=null&&typeof parsed.mcpServers=="object"?parsed.mcpServers:{},projects=parsed?.projects!=null&&typeof parsed.projects=="object"?parsed.projects:{},value={mcpServers,projects};return claudeConfigCache={file,signature,value},value}catch{return{mcpServers:{},projects:{}}}}function readClaudeServers(home=os.homedir()){return readClaudeConfig(home).mcpServers}var CodexSettingsError=class extends Error{constructor(file,cause){let detail=cause?.message?String(cause.message).split(`
89
- `)[0]:"unreadable";super(`Ando couldn't read Codex's settings in ${file} (${detail}), so it can't turn off the apps and MCP servers this task may not use. Fix the file, then start the task again.`),this.name="CodexSettingsError"}};function readCodexFile(file){try{return fs.readFileSync(file,"utf8")}catch(error){if(error?.code==="ENOENT"||error?.code==="ENOTDIR")return null;throw new CodexSettingsError(file,error)}}function isTable(value){return value!=null&&typeof value=="object"&&!Array.isArray(value)}function enabledNames(entries,file,key){if(entries==null)return[];if(!isTable(entries))throw new CodexSettingsError(file,new Error(`${key} is not a table`));return Object.entries(entries).filter(([,entry])=>!isTable(entry)||entry.enabled!==!1).map(([name])=>name)}function codexHome(env=process.env,home=os.homedir()){let dir=env.CODEX_HOME?.trim();return dir?path.resolve(home,dir==="~"||dir.startsWith("~/")?path.join(home,dir.slice(1)):dir):path.join(home,".codex")}var codexConfigCache=null;function readCodexConfig(home=os.homedir(),env=process.env){let file=path.join(codexHome(env,home),"config.toml"),signature=statSignature(file);if(signature!=null&&codexConfigCache!=null&&codexConfigCache.file===file&&codexConfigCache.signature===signature)return codexConfigCache.value;let raw=readCodexFile(file);if(raw==null)return{mcpServers:[],plugins:[],appsOn:!0,projects:[]};let config;try{config=parseToml(raw)}catch(error){throw new CodexSettingsError(file,error)}let features=isTable(config.features)?config.features:{},value={mcpServers:enabledNames(config.mcp_servers,file,"mcp_servers"),plugins:enabledNames(config.plugins,file,"plugins"),appsOn:features.apps!==!1,projects:isTable(config.projects)?Object.entries(config.projects).filter(([,entry])=>isTable(entry)&&entry.trust_level==="trusted").map(([folder])=>folder):[]};return signature!=null&&(codexConfigCache={file,signature,value}),value}function listToolServers(provider,home=os.homedir(),env=process.env){if(provider==="claude-code")return Object.keys(readClaudeServers(home)).sort();let codex=readCodexConfig(home,env);return[...codex.appsOn?[CODEX_APPS]:[],...codex.mcpServers,...codex.plugins]}module.exports={CODEX_APPS,CodexSettingsError,codexHome,listToolServers,readClaudeConfig,readClaudeServers,readCodexConfig}}});var require_wsl=__commonJS({"../../apps/web/electron/local-tools/wsl.js"(exports,module){"use strict";var{createHash:createHash2}=__require("crypto"),fs=__require("fs"),path=__require("path"),{shellQuote}=require_shell_quote(),WSL_COMMANDS=["claude","node","bwrap","socat","git","gh"],WSL_NODE_MAJOR=18,RUNNER_FILES=["wsl-task.js","task-setup.js","credentials.js","git-guard.js","linked-paths.js","policy.js","servers.js","shell-quote.js","task-env.js","toolchain.js"];function wslExe(env=process.env){return path.win32.join(env.SystemRoot||"C:\\Windows","System32","wsl.exe")}function loginShellArgs(script){return["-e","sh","-c",'exec "${SHELL:-/bin/sh}" -ilc "$1"',"sh",script]}function defaultWslVersion(listing){let version2=listing.replace(/\0/g,"").split(/\r?\n/).find(row=>row.trim().startsWith("*"))?.trim().split(/\s+/).at(-1);return version2==null||!/^\d+$/.test(version2)?null:Number(version2)}var WSL_SERVER_NAMES=`node -e 'let s;try{s=JSON.parse(fs.readFileSync(os.homedir()+"/.claude.json","utf8")).mcpServers}catch{}console.log("ando-servers:"+JSON.stringify(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:run3,env=process.env}){let wsl=wslExe(env),listing=await run3(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 run3(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}`,"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 run3(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)}}function toWslPath(windowsPath,{spawnSync:spawnSync3,env=process.env}){let result=spawnSync3(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:spawnSync3,env=process.env,sourceDir=__dirname,readFile:readFile3=file=>fs.readFileSync(file,"utf8")}){let files=RUNNER_FILES.map(name=>({name,content:readFile3(path.join(sourceDir,name))})),hash=createHash2("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(`
97
+ `)[0]:"unreadable";super(`Ando couldn't read Codex's settings in ${file} (${detail}), so it can't turn off the apps and MCP servers this task may not use. Fix the file, then start the task again.`),this.name="CodexSettingsError"}};function readCodexFile(file){try{return fs.readFileSync(file,"utf8")}catch(error){if(error?.code==="ENOENT"||error?.code==="ENOTDIR")return null;throw new CodexSettingsError(file,error)}}function isTable(value){return value!=null&&typeof value=="object"&&!Array.isArray(value)}function enabledNames(entries,file,key){if(entries==null)return[];if(!isTable(entries))throw new CodexSettingsError(file,new Error(`${key} is not a table`));return Object.entries(entries).filter(([,entry])=>!isTable(entry)||entry.enabled!==!1).map(([name])=>name)}function codexHome(env=process.env,home=os.homedir()){let dir=env.CODEX_HOME?.trim();return dir?path.resolve(home,dir==="~"||dir.startsWith("~/")?path.join(home,dir.slice(1)):dir):path.join(home,".codex")}var codexConfigCache=null;function readCodexConfig(home=os.homedir(),env=process.env){let file=path.join(codexHome(env,home),"config.toml"),signature=statSignature(file);if(signature!=null&&codexConfigCache!=null&&codexConfigCache.file===file&&codexConfigCache.signature===signature)return codexConfigCache.value;let raw=readCodexFile(file);if(raw==null)return{mcpServers:[],plugins:[],appsOn:!0,projects:[]};let config;try{config=parseToml(raw)}catch(error){throw new CodexSettingsError(file,error)}let features=isTable(config.features)?config.features:{},value={mcpServers:enabledNames(config.mcp_servers,file,"mcp_servers"),plugins:enabledNames(config.plugins,file,"plugins"),appsOn:features.apps!==!1,projects:isTable(config.projects)?Object.entries(config.projects).filter(([,entry])=>isTable(entry)&&entry.trust_level==="trusted").map(([folder])=>folder):[]};return signature!=null&&(codexConfigCache={file,signature,value}),value}function listToolServers(provider,home=os.homedir(),env=process.env){if(provider==="claude-code")return Object.keys(readClaudeServers(home)).sort();let codex=readCodexConfig(home,env);return[...codex.appsOn?[CODEX_APPS]:[],...codex.mcpServers,...codex.plugins]}module.exports={CODEX_APPS,CodexSettingsError,codexHome,listToolServers,readClaudeConfig,readClaudeServers,readCodexConfig}}});var require_wsl=__commonJS({"../../apps/web/electron/local-tools/wsl.js"(exports,module){"use strict";var{createHash:createHash2}=__require("crypto"),fs=__require("fs"),path=__require("path"),{shellQuote}=require_shell_quote(),WSL_COMMANDS=["claude","node","bwrap","socat","git","gh"],WSL_NODE_MAJOR=18,RUNNER_FILES=["wsl-task.js","task-setup.js","credentials.js","full-access.js","git-guard.js","linked-paths.js","net-bridge.js","policy.js","python-bridge.js","servers.js","shell-quote.js","task-env.js","toolchain.js"];function wslExe(env=process.env){return path.win32.join(env.SystemRoot||"C:\\Windows","System32","wsl.exe")}function loginShellArgs(script){return["-e","sh","-c",'exec "${SHELL:-/bin/sh}" -ilc "$1"',"sh",script]}function defaultWslVersion(listing){let version2=listing.replace(/\0/g,"").split(/\r?\n/).find(row=>row.trim().startsWith("*"))?.trim().split(/\s+/).at(-1);return version2==null||!/^\d+$/.test(version2)?null:Number(version2)}var WSL_SERVER_NAMES=`node -e 'let s;try{s=JSON.parse(fs.readFileSync(os.homedir()+"/.claude.json","utf8")).mcpServers}catch{}console.log("ando-servers:"+JSON.stringify(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:run3,env=process.env}){let wsl=wslExe(env),listing=await run3(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 run3(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}`,"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 run3(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)}}function toWslPath(windowsPath,{spawnSync:spawnSync3,env=process.env}){let result=spawnSync3(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:spawnSync3,env=process.env,sourceDir=__dirname,readFile:readFile3=file=>fs.readFileSync(file,"utf8")}){let files=RUNNER_FILES.map(name=>({name,content:readFile3(path.join(sourceDir,name))})),hash=createHash2("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(`
90
98
  `),result=spawnSync3(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(`
91
99
  `).at(-1):"";if(!dir?.startsWith("/"))throw new Error("Ando couldn't set up Claude Code's tasks in WSL");return dir}function wslTaskInput(run3){return`${JSON.stringify(run3)}
92
100
  `}function wslClaudeSpawn({spawn:spawn2,env=process.env,runnerDir,run:run3}){return(_command,args,options={})=>{let child=spawn2(wslExe(env),["--cd",run3.folder,...loginShellArgs(`exec node ${shellQuote(`${runnerDir}/wsl-task.js`)}`)],{stdio:options.stdio,windowsHide:!0});return child.stdin?.write(wslTaskInput({...run3,claudeArgs:args})),child}}module.exports={RUNNER_FILES,WSL_COMMANDS,defaultWslVersion,loginShellArgs,readWslClaude,sendRunnerToWsl,toWslPath,wslClaudeSpawn,wslExe,wslTaskInput}}});var require_machine=__commonJS({"../../apps/web/electron/local-tools/machine.js"(exports,module){"use strict";var{createHash:createHash2,randomUUID:randomUUID3}=__require("crypto"),fs=__require("fs"),path=__require("path"),{listToolServers}=require_servers(),{findCommand:findCommand2}=require_toolchain(),{readWslClaude}=require_wsl(),TOOL_COMMANDS={"claude-code":"claude",codex:"codex"},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(error){if(error.code!=="ENOENT"&&!(error instanceof SyntaxError))throw error}let id=randomUUID3();return fs.mkdirSync(path.dirname(file),{recursive:!0,mode:448}),fs.writeFileSync(file,JSON.stringify({id}),{mode:384}),id}function runCommand(spawn2,command,args,{env,timeout=1e4}={}){return new Promise(resolve2=>{let child;try{child=spawn2(command,args,{env,stdio:["ignore","pipe","ignore"]})}catch(error){resolve2({status:null,stdout:"",error});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",error=>{clearTimeout(timer),resolve2({status:null,stdout,error})}),child.on("close",status=>{clearTimeout(timer),resolve2({status:timedOut?null:status,stdout,error:timedOut?new Error(`${command} timed out`):null})})})}async function readMachineName({platform,run:run3,hostname:hostname2}){if(platform==="darwin"){let result=await run3("/usr/sbin/scutil",["--get","ComputerName"],{timeout:5e3}),name=result.status===0?result.stdout.trim():"";if(name)return name}return hostname2().replace(/\.local$/,"")||"This computer"}async function readHardwareId({platform,run:run3,readFile:readFile3,systemRoot=process.env.SystemRoot||"C:\\Windows"}){if(platform==="win32"){let result=await run3(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 run3("/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=readFile3(file).trim();if(/^[0-9a-f]{32}$/i.test(id))return id.toLowerCase()}catch{}return null}async function readMachineKey({platform,run:run3,readFile:readFile3,username,appName}){if(!username)return null;let hardwareId=await readHardwareId({platform,run:run3,readFile:readFile3});return hardwareId==null?null:createHash2("sha256").update(["ando-local-tool-machine",hardwareId,username,appName].join(`
93
101
  `)).digest("hex")}async function readSignedIn(provider,{run:run3,env}){if(provider==="claude-code"){let result2=await run3("claude",["auth","status"],{env});try{let status=JSON.parse(result2.stdout);return typeof status?.loggedIn=="boolean"?status.loggedIn:null}catch{return null}}let result=await run3("codex",["login","status"],{env});return result.error!=null?null:result.status===0}async function installedTools({run:run3,env,platform,wslClaude}){return(await Promise.all(Object.entries(TOOL_COMMANDS).map(async([provider,command])=>platform==="win32"&&provider==="claude-code"?wslClaude?.ready?provider:null:platform==="win32"?findCommand2(command,env.PATH??"",null,{platform,env})!=null?provider:null:(await run3("/usr/bin/which",[command],{env,timeout:5e3})).status===0?provider:null))).filter(provider=>provider!=null)}function createMachineDescriber({machineFile,platform,spawn:spawn2,hostname:hostname2,env,log:log2,username=()=>"",appName="",readFile:readFile3=file=>fs.readFileSync(file,"utf8"),listServers=listToolServers,readWsl=readWslClaude,cacheMs=DESCRIBE_CACHE_MS,now=Date.now}){let run3=(command,args,options={})=>runCommand(spawn2,command,args,options),cached=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:run3,readFile:readFile3,username:username(),appName})}catch(error){log2.warn("[Local tools] could not read this computer's key",error)}return machineKey}async function describe(started){let commandEnv=env(),wslClaude=platform==="win32"?await readWsl({run:run3}):null,toolsPromise=installedTools({run:run3,env:commandEnv,platform,wslClaude}),namePromise=readMachineName({platform,run:run3,hostname:hostname2}),keyPromise=readKey(),tools=await toolsPromise,[name,checked,key]=await Promise.all([namePromise,Promise.all(tools.map(provider=>wslClaude!=null&&provider==="claude-code"?wslClaude.signedIn:readSignedIn(provider,{run:run3,env:commandEnv}))),keyPromise]),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(error){return log2.warn("[Local tools] could not read a tool's servers",error),[provider,[]]}})),signedOut:tools.filter((_,index)=>signedIn[index]===!1)}}return{get(){if(cached!=null&&now()-cached.at<cacheMs)return Promise.resolve(cached.value);if(inFlight==null){let started=generation;inFlight=describe(started).then(value=>(started===generation&&(cached={at:now(),value}),value)).finally(()=>{started===generation&&(inFlight=null)})}return inFlight},invalidate(){generation+=1,cached=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 readSeq(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(error){try{fs.rmSync(temporary,{force:!0})}catch{}throw error}}function createRunOutbox({file,log:log2,maxEvents=MAX_EVENTS,maxBytes=MAX_BYTES,coalesceMs=0}){let events=[],usageCheckpoints=[],seqFile=`${file.replace(/\.json$/,"")}.seq`,savedSeq=readSeq(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(error){error?.code!=="ENOENT"&&log2.warn("[Local tools] could not restore run events",error)}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}
94
102
  `),savedSeq=targetSeq}replaceFile(file,JSON.stringify({version:1,lastSeq:currentSeq,events,usageCheckpoints})),savedOk=!0}catch(error){savedOk=!1,dirReady=!1,log2.warn("[Local tools] could not save run events",error)}}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}
95
- `),savedSeq=targetSeq}catch(error){dirReady=!1,log2.warn("[Local tools] could not reserve run event sequence",error)}}function scheduleSave(immediate=!1){if(dirty=!0,immediate||coalesceMs<=0){save();return}ensureSeqReserved(nextSeq-1),saveTimer==null&&(saveTimer=setTimeout(()=>{saveTimer=null,dirty&&save()},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(){dirty&&save()}}}module.exports={createRunOutbox}}});var require_linked_paths=__commonJS({"../../apps/web/electron/local-tools/linked-paths.js"(exports,module){"use strict";var fs=__require("fs"),os=__require("os"),path=__require("path"),LINK_SCAN_SKIP=new Set([".git","node_modules",".next","dist","build","target",".venv","venv"]),SYSTEM_ROOTS=new Set(["/etc","/var","/private","/private/etc","/private/var","/tmp","/private/tmp","/Volumes"]);function listDir(dir){try{return fs.readdirSync(dir)}catch{return[]}}function tryRealpath(realpath,target){try{return realpath(target)}catch{return target}}function resolveHome(p,home){return p.startsWith("~/")?path.join(home,p.slice(2)):p}function toLogicalPath(p,folder,realFolder,home,realHome){return realFolder!==folder&&(p===realFolder||p.startsWith(realFolder+path.sep))?path.join(folder,p.slice(realFolder.length)):realHome!==home&&(p===realHome||p.startsWith(realHome+path.sep))?path.join(home,p.slice(realHome.length)):p}function isSameOrParent(candidate,child){if(!candidate||!child)return!1;if(candidate===child)return!0;let prefix=candidate.endsWith(path.sep)?candidate:`${candidate}${path.sep}`;return child.startsWith(prefix)}function isAllowedTarget(target,{folder,home,secrets,settings}){if(!path.isAbsolute(target)||path.parse(target).root===target||isSameOrParent(folder,target)||isSameOrParent(target,home)||isSameOrParent(target,folder)||SYSTEM_ROOTS.has(target)||secrets.some(s=>isSameOrParent(s,target)||isSameOrParent(target,s)))return!1;for(let[config,open]of settings){if(isSameOrParent(target,config))return!1;if(isSameOrParent(config,target)){let first=path.relative(config,target).split(path.sep)[0];if(!open.has(first))return!1}}return!0}function scanSymlinkCandidates(folder,readdir,lstat){let candidates=[];function scan(dir,depth){for(let entry of readdir(dir)){if(LINK_SCAN_SKIP.has(entry))continue;let full=path.join(dir,entry),info;try{info=lstat(full)}catch{continue}info.isSymbolicLink()?candidates.push(full):depth<2&&info.isDirectory()&&scan(full,depth+1)}}return scan(folder,0),candidates}function readAdditionalDirectoryCandidates(folder,home,readFile3){try{let raw=readFile3(path.join(folder,".claude","settings.local.json"),"utf8"),dirs=JSON.parse(raw)?.permissions?.additionalDirectories;return Array.isArray(dirs)?dirs.filter(item=>typeof item=="string"&&item.trim()!=="").map(item=>path.resolve(folder,resolveHome(item.trim(),home))):[]}catch{return[]}}function createLinkedPaths({secretPathsFor,settingsFoldersFor}){return function(folder,{home=os.homedir(),readdir=listDir,lstat=fs.lstatSync,realpath=fs.realpathSync,stat=fs.statSync,readFile:readFile3=fs.readFileSync,codexDir=null,configHome=null,platform=process.platform}={}){if(folder==null)return{linked:[],linkedDirs:[]};let realHome=tryRealpath(realpath,home),realFolder=tryRealpath(realpath,folder),secrets=secretPathsFor({home,codexDir,configHome}),settings=settingsFoldersFor({home,configHome,platform}),candidates=[...scanSymlinkCandidates(folder,readdir,lstat),...readAdditionalDirectoryCandidates(folder,home,readFile3)],linked=[],linkedDirs=[],seen=new Set;for(let candidate of candidates){let resolved,info;try{resolved=toLogicalPath(realpath(candidate),folder,realFolder,home,realHome),info=stat(resolved)}catch{continue}seen.has(resolved)||!isAllowedTarget(resolved,{folder,home,secrets,settings})||(seen.add(resolved),linked.push(resolved),info.isDirectory()&&linkedDirs.push(resolved))}return{linked,linkedDirs}}}function closeSiblingsAlongRoutes(root,targets,readdir,closed,isRootOpenEntry=()=>!1){let routes=targets.map(t=>path.relative(root,t)).filter(rel=>rel!==""&&!rel.startsWith("..")&&!path.isAbsolute(rel)).map(rel=>rel.split(path.sep));if(routes.length===0){for(let entry of readdir(root))isRootOpenEntry(entry)||closed.add(path.join(root,entry));return}function walk(dir,active,depth){let nextNames=new Set(active.map(r=>r[depth]));for(let entry of readdir(dir))nextNames.has(entry)||depth===0&&isRootOpenEntry(entry)||closed.add(path.join(dir,entry));for(let name of nextNames){if(name==null||active.some(r=>r[depth]===name&&r.length===depth+1))continue;let deeper=active.filter(r=>r[depth]===name&&r.length>depth+1);deeper.length>0&&walk(path.join(dir,name),deeper,depth+1)}}walk(root,routes,0)}module.exports={closeSiblingsAlongRoutes,createLinkedPaths}}});var require_policy=__commonJS({"../../apps/web/electron/local-tools/policy.js"(exports,module){"use strict";var fs=__require("fs"),os=__require("os"),path=__require("path"),{GUARD_BYPASS_COMMANDS,MERGE_COMMANDS,gitGuardEnv}=require_git_guard(),{closeSiblingsAlongRoutes,createLinkedPaths}=require_linked_paths(),{CODEX_APPS}=require_servers(),{openableToolchainRoots}=require_toolchain(),DEFAULT_POLICY={files:"allow",commands:"allow",push:"allow",network:"allow",deploy:"never"},PERMISSIONS=new Set(["allow","never"]),SECRET_PATHS=["~/.ssh","~/.config/gh","~/.config/ando","~/.gnupg","~/.netrc","~/.docker","~/.kube","~/.git-credentials","~/.config/git/credentials","~/.npmrc","~/.yarnrc.yml","~/.pypirc","~/.config/pypoetry/auth.toml","~/.config/nix/nix.conf","~/.cargo/credentials","~/.cargo/credentials.toml","~/.gem/credentials","~/.m2/settings.xml","~/.m2/settings-security.xml","~/.gradle/gradle.properties","~/.config/pnpm/rc","~/.config/pnpm/auth.ini","~/Library/Preferences/pnpm/rc","~/Library/Preferences/pnpm/auth.ini","~/AppData/Local/pnpm/config/rc","~/AppData/Local/pnpm/config/auth.ini","~/.claude/projects","~/.claude/.credentials.json","~/.claude.json","~/.codex/sessions","~/.codex/auth.json","~/Library/Keychains"],GIT_METADATA_READ_ONLY=[".git/config",".git/hooks",".git/info"],AWS_METADATA_READ_ONLY=[".aws/config",".aws/credentials"],AWS_CACHE_WRITES=[".aws/sso/cache",".aws/cli/cache"];function codexSecrets(codexDir){return codexDir==null?[]:[path.join(codexDir,"sessions"),path.join(codexDir,"auth.json")]}function movedConfigHome(configHome,home){if(typeof configHome!="string"||!path.isAbsolute(configHome))return null;let dir=path.resolve(configHome);return dir===path.join(home,".config")?null:dir}function configSecrets(configDir){if(configDir==null)return[];let prefix="~/.config/";return[...SECRET_PATHS,...PRIVATE_TOOLCHAIN_PATHS].filter(p=>p.startsWith(prefix)).map(p=>path.join(configDir,p.slice(prefix.length)))}var TOOLCHAIN_HOME_ENTRIES=new Set([".aws",".gitconfig",".config",".local",".cache",".npm",".nvm",".bun",".volta",".asdf",".deno",".cargo",".rustup",".pyenv",".rbenv",".gem",".gradle",".m2","go","Library"]),CONFIG_TOOLCHAIN_ENTRIES=new Set(["git","npm","pnpm","yarn","fnm","nvm","volta","mise","asdf","bun","deno","uv","pip","pypoetry","go","nix","direnv","starship.toml"]),WINDOWS_APPDATA_TOOLCHAIN_ENTRIES={Roaming:new Set(["npm","nvm","fnm","Python","pnpm","uv"]),Local:new Set(["Temp","npm-cache","pnpm","pnpm-cache","pnpm-state","Volta","fnm_multishells","Yarn","node","uv","pip","mise","Programs"])};function settingsFolders(home,configDir,platform){let folders=[[path.join(home,".config"),CONFIG_TOOLCHAIN_ENTRIES]];if(configDir!=null&&folders.push([configDir,CONFIG_TOOLCHAIN_ENTRIES]),platform==="win32"){folders.push([path.join(home,"AppData"),new Set(Object.keys(WINDOWS_APPDATA_TOOLCHAIN_ENTRIES))]);for(let[name,entries]of Object.entries(WINDOWS_APPDATA_TOOLCHAIN_ENTRIES))folders.push([path.join(home,"AppData",name),entries])}return folders}var PRIVATE_TOOLCHAIN_PATHS=["~/.config/gh","~/Library/Keychains","~/Library/Application Support","~/Library/Mail","~/Library/Messages","~/Library/Cookies","~/Library/Safari","~/Library/Containers","~/Library/Group Containers","~/Library/Mobile Documents"];function listDir(dir){try{return fs.readdirSync(dir)}catch{return[]}}var MAX_CLOSED_PATHS=2e3,linkedPaths=createLinkedPaths({secretPathsFor:({home,codexDir,configHome})=>[...[...SECRET_PATHS,...PRIVATE_TOOLCHAIN_PATHS].map(p=>resolveHome(p,home)),...codexSecrets(codexDir),...configSecrets(movedConfigHome(configHome,home))],settingsFoldersFor:({home,configHome,platform})=>settingsFolders(home,movedConfigHome(configHome,home),platform)});function closedPaths(folder,{home=os.homedir(),readdir=listDir,codexDir=null,configHome=null,extra=[],linked=[],log:log2=null,platform=process.platform}={}){let configDir=movedConfigHome(configHome,home),targets=[folder,...linked],filteredExtra=[],extraAncestors=[];for(let p of extra)if(!linked.some(l=>p===l||p.startsWith(l+path.sep))){if(linked.some(l=>l.startsWith(p+path.sep))){extraAncestors.push(p);continue}filteredExtra.push(p)}let closed=new Set([...filteredExtra,...[...SECRET_PATHS,...PRIVATE_TOOLCHAIN_PATHS].map(p=>resolveHome(p,home)),...codexSecrets(codexDir),...configSecrets(configDir)]);for(let ancestor of extraAncestors){let rel=path.relative(home,ancestor);rel!==""&&!rel.startsWith("..")&&!path.isAbsolute(rel)||closeSiblingsAlongRoutes(ancestor,targets,readdir,closed)}closeSiblingsAlongRoutes(home,targets,readdir,closed,entry=>TOOLCHAIN_HOME_ENTRIES.has(entry)||platform==="win32"&&entry==="AppData");for(let[config,open]of settingsFolders(home,configDir,platform))if(!targets.some(t=>t===config||t.startsWith(config+path.sep)))for(let entry of readdir(config))open.has(entry)||closed.add(path.join(config,entry));return closed.size>MAX_CLOSED_PATHS&&log2?.warn(`[Local tools] ${closed.size} paths to close for a task in ${folder}; closing the first ${MAX_CLOSED_PATHS}, so ${closed.size-MAX_CLOSED_PATHS} entries of the home folder stay readable to Codex`),[...closed].slice(0,MAX_CLOSED_PATHS)}function taskClosedPaths({folder,home,readdir,codexDir,configHome=null,credentialPaths,linked=[],log:log2,platform}){return folder==null?[...new Set([...credentialPaths,...SECRET_PATHS.map(p=>resolveHome(p,home)),...codexSecrets(codexDir),...configSecrets(movedConfigHome(configHome,home))])]:closedPaths(folder,{home,readdir,codexDir,configHome,extra:credentialPaths,linked,log:log2,platform})}function gitMetadataPaths(folder,repoHooks,closed){let paths=folder==null?[]:GIT_METADATA_READ_ONLY.map(p=>path.join(folder,p)),hooks=Array.isArray(repoHooks)?repoHooks:[repoHooks];for(let hook of hooks)hook!=null&&path.isAbsolute(hook)&&!closed.some(p=>hook===p||hook.startsWith(p+path.sep))&&paths.push(path.resolve(hook));return[...new Set(paths)]}function guardFolders(hooksDir){return hooksDir==null?[]:[path.dirname(hooksDir),hooksDir]}function otherGuards(hooksDir){return hooksDir==null?[]:[path.dirname(hooksDir)]}var CLAUDE_OUTWARD_TOOLS=["RemoteTrigger","CronCreate","CronDelete","CronList","ScheduleWakeup","PushNotification","SendMessage","SendUserFile","SendFeedback","ShareOnboardingGuide","Artifact","ListAgents","Workflow","Monitor","EnterWorktree","ExitWorktree"],MACH_SERVICES=["com.apple.trustd","com.apple.trustd.agent"],DESCRIPTIONS={files:"edit files",commands:"run commands",push:"push branches",network:"install packages or use the network",deploy:"merge, deploy or push to main"};function resolvePolicy(value){let policy={...DEFAULT_POLICY};if(value==null||typeof value!="object")return policy;for(let key of Object.keys(DEFAULT_POLICY))PERMISSIONS.has(value[key])&&(policy[key]=value[key]);return policy}function resolveHome(p,home){return p.startsWith("~/")?path.join(home,p.slice(2)):p}function rulePath(p){return`/${p.replace(/[\\*?[\]]/g,"\\$&")}`}function claudeReadOnlyAndRules(policy,{folder,home,repoHooks,linkedRepoHooks=[],closed,hooksDir,toolchainReads,linked,linkedDirs}){let hasAws=toolchainReads.includes(path.join(home,".aws")),awsMetadata=hasAws?AWS_METADATA_READ_ONLY.map(p=>path.join(home,p)):[],shellWrites=hasAws&&policy.commands==="allow"?AWS_CACHE_WRITES.map(p=>path.join(home,p)):[],shellReads=[...toolchainReads,...linked,...hooksDir==null?[]:[hooksDir]],gitMetadata=policy.files==="allow"?[...gitMetadataPaths(folder,[repoHooks,...linkedRepoHooks],closed),...linkedDirs.flatMap(dir=>gitMetadataPaths(dir,null,closed))]:[],linkedFiles=linked.filter(p=>!linkedDirs.includes(p)),readOnly=[...policy.files==="never"&&folder!=null?[folder]:[],...policy.files==="never"?linked:[],...gitMetadata,...awsMetadata,...guardFolders(hooksDir)],editRules=[`Edit(${folder==null?"./**":`${rulePath(folder)}/**`})`,...linkedDirs.map(dir=>`Edit(${rulePath(dir)}/**)`),...linkedFiles.map(file=>`Edit(${rulePath(file)})`)];return{filesystem:{denyRead:closed,...shellReads.length>0?{allowRead:shellReads}:{},...shellWrites.length>0?{allowWrite:shellWrites}:{},...readOnly.length>0?{denyWrite:readOnly}:{}},editRules,linkedReadRules:linkedFiles.map(file=>`Read(${rulePath(file)})`),protectedEditRules:[...gitMetadata,...awsMetadata].flatMap(p=>[`Edit(${rulePath(p)})`,`Edit(${rulePath(p)}/**)`])}}function claudeTaskArgs(policy,{servers={},home=os.homedir(),folder=null,readdir,hooksDir=null,repoHooks=null,linkedRepoHooks=[],toolchain=[],codexDir=null,configHome=null,credentialPaths=[],linked=[],linkedDirs=[],log:log2=null}={}){let closed=[...taskClosedPaths({folder,home,readdir,codexDir,configHome,credentialPaths,linked,log:log2}),...otherGuards(hooksDir)],toolchainReads=openableToolchainRoots(toolchain,closed,home,readdir),{filesystem,editRules,linkedReadRules,protectedEditRules}=claudeReadOnlyAndRules(policy,{folder,home,repoHooks,linkedRepoHooks,closed,hooksDir,toolchainReads,linked,linkedDirs}),network={...policy.network==="allow"?{allowedDomains:["*"]}:{allowedDomains:[],strictAllowlist:!0},allowLocalBinding:!0,allowMachLookup:MACH_SERVICES},settings={disableAllHooks:!0,permissions:{blockReadsOutsideWorkingDirectories:!0,...linkedDirs.length>0?{additionalDirectories:linkedDirs}:{},deny:[...closed.flatMap(p=>[`Read(${rulePath(p)})`,`Read(${rulePath(p)}/**)`]),...policy.push==="never"||policy.deploy==="never"?GUARD_BYPASS_COMMANDS.map(pattern=>`Bash(${pattern})`):[],...policy.deploy==="never"?MERGE_COMMANDS.map(pattern=>`Bash(${pattern})`):[],...policy.files==="never"?editRules:[],...protectedEditRules]},sandbox:{enabled:!0,failIfUnavailable:!0,allowUnsandboxedCommands:!1,autoAllowBashIfSandboxed:policy.commands==="allow",excludedCommands:[],filesystem,network}},allowed=["Read",...linkedReadRules,"Glob","Grep","TodoWrite",...policy.commands==="allow"?["Bash"]:[],...policy.files==="allow"?editRules:[],...policy.network==="allow"?["WebFetch","WebSearch"]:[],...Object.keys(servers).map(name=>`mcp__${name}`)],disallowed=[...CLAUDE_OUTWARD_TOOLS,...policy.network==="allow"?[]:["WebFetch","WebSearch"],...policy.commands==="allow"?[]:["Bash"],...policy.files==="allow"?[]:["Edit","MultiEdit","Write","NotebookEdit"]];return["--permission-mode","dontAsk","--setting-sources","","--settings",JSON.stringify(settings),"--allowedTools",allowed.join(","),"--disallowedTools",disallowed.join(","),"--strict-mcp-config","--mcp-config",JSON.stringify({mcpServers:servers})]}function tomlString(value){return JSON.stringify(value)}function codexFilesystem(policy,{closed,hooksDir,repoHooks,linkedRepoHooks=[],folder,linked=[],linkedDirs=linked}){let ownHooks=policy.files==="allow"?[...gitMetadataPaths(folder,[repoHooks,...linkedRepoHooks],closed).filter(p=>!GIT_METADATA_READ_ONLY.some(m=>p===path.join(folder??"",m))),...linkedDirs.flatMap(dir=>gitMetadataPaths(dir,null,closed))]:[],linkedAccess=policy.files==="allow"?"write":"read";return[...closed.map(p=>`${tomlString(p)} = "deny"`),...otherGuards(hooksDir).map(p=>`${tomlString(p)} = "deny"`),...hooksDir==null?[]:[`${tomlString(hooksDir)} = "read"`],...linked.map(p=>`${tomlString(p)} = "${linkedAccess}"`),...policy.files==="allow"?[`":workspace_roots" = { ${['"." = "write"','".git" = "write"',...GIT_METADATA_READ_ONLY.map(p=>`${tomlString(p)} = "read"`)].join(", ")} }`,...[...new Set(ownHooks)].map(p=>`${tomlString(p)} = "read"`)]:['":workspace_roots" = { "." = "read" }']].join(", ")}function codexWindowsSandboxArgs(platform){return platform==="win32"?["-c",'windows.sandbox="elevated"',"--disable","prefer_mxc"]:[]}function mountablePaths(paths,{lstat=fs.lstatSync,realpath=fs.realpathSync}={}){let resolved=paths.flatMap(p=>{try{return[lstat(p).isSymbolicLink()?realpath(p):p]}catch{return[]}}),unique=[...new Set(resolved)];return unique.filter(p=>!unique.some(other=>p.startsWith(`${other}${path.sep}`)))}function codexClosedPaths(options){let closed=taskClosedPaths(options);return options.platform==="linux"?mountablePaths(closed):closed}function codexTaskArgs(policy,{available=[],allowed=[],hooksDir=null,repoHooks=null,linkedRepoHooks=[],github=!1,home=os.homedir(),folder=null,readdir,codexDir=null,configHome=null,credentialPaths=[],linked=[],linkedDirs=linked,log:log2=null,platform=process.platform}={}){let closed=codexClosedPaths({folder,home,readdir,codexDir,configHome,credentialPaths,linked,log:log2,platform}),filesystem=codexFilesystem(policy,{closed,hooksDir,repoHooks,linkedRepoHooks,folder,linked,linkedDirs}),profile=`{ "ando-task" = { extends = ${tomlString(policy.files==="allow"?":workspace":":read-only")}, filesystem = { ${filesystem} }, network = { enabled = ${policy.network==="allow"} } } }`,picked=new Set(allowed),args=["-c",'default_permissions="ando-task"',"-c",`permissions=${profile}`,"--disable","browser_use","--disable","browser_use_external","--disable","computer_use",...codexWindowsSandboxArgs(platform)];picked.has(CODEX_APPS)||args.push("--disable","apps"),policy.commands!=="allow"&&args.push("--disable","shell_tool");let servers=new Map,plugins=[];for(let name of available)if(name!==CODEX_APPS){if(picked.has(name)){name.includes("@")||servers.set(name,'{ default_tools_approval_mode = "approve" }');continue}name.includes("@")?plugins.push(name):servers.set(name,"{ enabled = false }")}if(servers.size>0&&args.push("-c",`mcp_servers={ ${[...servers].map(([name,entry])=>`${tomlString(name)} = ${entry}`).join(", ")} }`),plugins.length>0&&args.push("-c",`plugins={ ${plugins.map(name=>`${tomlString(name)} = { enabled = false }`).join(", ")} }`),hooksDir!=null){let env=gitGuardEnv(hooksDir,policy,{github,platform});args.push("-c","allow_login_shell=false","--disable","shell_snapshot"),args.push("-c",`shell_environment_policy.set={ ${Object.entries(env).map(([key,value])=>`${key} = ${tomlString(value)}`).join(", ")} }`)}return args}var PULL_REQUESTS={never:"You can't open pull requests either.",noMerge:"You can push a branch and open a pull request with `gh pr create`, but you can't merge it. If `gh` isn't signed in, push the branch and say in your result that it needs a pull request.",withToken:"You can push a branch and open a pull request with `gh pr create`. If `gh` isn't signed in, push the branch and say in your result that it needs a pull request."};function policyInstructions(policy,folder,{linked=[]}={}){let never=Object.keys(DESCRIPTIONS).filter(key=>policy[key]==="never"),pullRequests=policy.push==="never"?PULL_REQUESTS.never:policy.deploy==="never"?PULL_REQUESTS.noMerge:PULL_REQUESTS.withToken;return[linked.length>0?`Stay inside ${folder} (and what it links to: ${linked.join(", ")}): do not read or change files outside them.`:`Stay inside ${folder}: do not read or change files outside it.`,...never.length===0?[]:[`You may not ${never.map(key=>DESCRIPTIONS[key]).join(", or ")}. If the task needs it, say so in your result and stop.`],pullRequests].join(`
96
- `)}module.exports={CLAUDE_OUTWARD_TOOLS,DEFAULT_POLICY,SECRET_PATHS,claudeTaskArgs,closedPaths,linkedPaths,mountablePaths,codexTaskArgs,policyInstructions,resolvePolicy}}});var require_runs=__commonJS({"../../apps/web/electron/local-tools/runs.js"(exports,module){"use strict";var{checkpointClaudeUsage}=require_usage(),fs=__require("fs"),path=__require("path"),{linkedPaths,policyInstructions}=require_policy(),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;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(run3,error){let message=error?.message??String(error);return SIGNED_OUT.test(message)?`${run3.toolName??(run3.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 runInstructions(run3){let{linked}=linkedPaths(run3.folder);return[`You are ${run3.toolName} working on a task that ${run3.agentName??"an Ando agent"} started on this computer for its owner, through Ando, their team messenger.`,`Work in ${run3.folder}. Messages that arrive while you work are new context from the task's thread in Ando.`,...run3.checkoutOf==null?[]:[`This is your own checkout of ${run3.checkoutOf}, on a branch of its own, made from 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.`],policyInstructions(run3.policy,run3.folder,{linked}),"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."].join(`
103
+ `),savedSeq=targetSeq}catch(error){dirReady=!1,log2.warn("[Local tools] could not reserve run event sequence",error)}}function scheduleSave(immediate=!1){if(dirty=!0,immediate||coalesceMs<=0){save();return}ensureSeqReserved(nextSeq-1),saveTimer==null&&(saveTimer=setTimeout(()=>{saveTimer=null,dirty&&save()},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(){dirty&&save()}}}module.exports={createRunOutbox}}});var require_full_access=__commonJS({"../../apps/web/electron/local-tools/full-access.js"(exports,module){"use strict";var FULL_ACCESS_ALLOWS=["files","commands","push","network","deploy"],CODEX_FULL_ACCESS_ARGS=["-c",'default_permissions=":danger-full-access"'],SANDBOX_NOTICE='Your commands run in a sandbox. If one fails because of it (a browser that will not start, a system service or a path it refuses), do not work around it: say in your result what it stopped, and that the owner can turn on "Full access" for this computer in Studio > Devices.';function fullAccessRunsHere(platform=process.platform){return platform==="darwin"}function hasFullAccess(policy){return policy.full_access==="allow"}function applyFullAccess(policy,platform){if(fullAccessRunsHere(platform)||(policy.full_access="never"),hasFullAccess(policy))for(let key of FULL_ACCESS_ALLOWS)policy[key]="allow";return policy}function fullAccessScope(folder){return`Work in ${folder}. You have full access to this computer, with no sandbox: you can do anything its owner can here, such as starting a browser to take screenshots. Leave what the task doesn't need alone.`}function claudeFullAccessArgs({servers={},outwardTools}){let settings={disableAllHooks:!0,sandbox:{enabled:!1}},allowed=["Read","Glob","Grep","TodoWrite","Bash","Edit","WebFetch","WebSearch"];return["--permission-mode","dontAsk","--setting-sources","","--settings",JSON.stringify(settings),"--allowedTools",[...allowed,...Object.keys(servers).map(name=>`mcp__${name}`)].join(","),"--disallowedTools",outwardTools.join(","),"--strict-mcp-config","--mcp-config",JSON.stringify({mcpServers:servers})]}module.exports={CODEX_FULL_ACCESS_ARGS,SANDBOX_NOTICE,applyFullAccess,claudeFullAccessArgs,fullAccessRunsHere,fullAccessScope,hasFullAccess}}});var require_linked_paths=__commonJS({"../../apps/web/electron/local-tools/linked-paths.js"(exports,module){"use strict";var fs=__require("fs"),os=__require("os"),path=__require("path"),LINK_SCAN_SKIP=new Set([".git","node_modules",".next","dist","build","target",".venv","venv"]),SYSTEM_ROOTS=new Set(["/etc","/var","/private","/private/etc","/private/var","/tmp","/private/tmp","/Volumes"]);function listDir(dir){try{return fs.readdirSync(dir)}catch{return[]}}function tryRealpath(realpath,target){try{return realpath(target)}catch{return target}}function resolveHome(p,home){return p.startsWith("~/")?path.join(home,p.slice(2)):p}function toLogicalPath(p,folder,realFolder,home,realHome){return realFolder!==folder&&(p===realFolder||p.startsWith(realFolder+path.sep))?path.join(folder,p.slice(realFolder.length)):realHome!==home&&(p===realHome||p.startsWith(realHome+path.sep))?path.join(home,p.slice(realHome.length)):p}function isSameOrParent(candidate,child){if(!candidate||!child)return!1;if(candidate===child)return!0;let prefix=candidate.endsWith(path.sep)?candidate:`${candidate}${path.sep}`;return child.startsWith(prefix)}function isAllowedTarget(target,{folder,home,secrets,settings}){if(!path.isAbsolute(target)||path.parse(target).root===target||isSameOrParent(folder,target)||isSameOrParent(target,home)||isSameOrParent(target,folder)||SYSTEM_ROOTS.has(target)||secrets.some(s=>isSameOrParent(s,target)||isSameOrParent(target,s)))return!1;for(let[config,open]of settings){if(isSameOrParent(target,config))return!1;if(isSameOrParent(config,target)){let first=path.relative(config,target).split(path.sep)[0];if(!open.has(first))return!1}}return!0}function scanSymlinkCandidates(folder,readdir,lstat){let candidates=[];function scan(dir,depth){for(let entry of readdir(dir)){if(LINK_SCAN_SKIP.has(entry))continue;let full=path.join(dir,entry),info;try{info=lstat(full)}catch{continue}info.isSymbolicLink()?candidates.push(full):depth<2&&info.isDirectory()&&scan(full,depth+1)}}return scan(folder,0),candidates}function readAdditionalDirectoryCandidates(folder,home,readFile3){try{let raw=readFile3(path.join(folder,".claude","settings.local.json"),"utf8"),dirs=JSON.parse(raw)?.permissions?.additionalDirectories;return Array.isArray(dirs)?dirs.filter(item=>typeof item=="string"&&item.trim()!=="").map(item=>path.resolve(folder,resolveHome(item.trim(),home))):[]}catch{return[]}}function createLinkedPaths({secretPathsFor,settingsFoldersFor}){return function(folder,{home=os.homedir(),readdir=listDir,lstat=fs.lstatSync,realpath=fs.realpathSync,stat=fs.statSync,readFile:readFile3=fs.readFileSync,codexDir=null,configHome=null,platform=process.platform}={}){if(folder==null)return{linked:[],linkedDirs:[]};let realHome=tryRealpath(realpath,home),realFolder=tryRealpath(realpath,folder),secrets=secretPathsFor({home,codexDir,configHome}),settings=settingsFoldersFor({home,configHome,platform}),candidates=[...scanSymlinkCandidates(folder,readdir,lstat),...readAdditionalDirectoryCandidates(folder,home,readFile3)],linked=[],linkedDirs=[],seen=new Set;for(let candidate of candidates){let resolved,info;try{resolved=toLogicalPath(realpath(candidate),folder,realFolder,home,realHome),info=stat(resolved)}catch{continue}seen.has(resolved)||!isAllowedTarget(resolved,{folder,home,secrets,settings})||(seen.add(resolved),linked.push(resolved),info.isDirectory()&&linkedDirs.push(resolved))}return{linked,linkedDirs}}}function closeSiblingsAlongRoutes(root,targets,readdir,closed,isRootOpenEntry=()=>!1){let routes=targets.map(t=>path.relative(root,t)).filter(rel=>rel!==""&&!rel.startsWith("..")&&!path.isAbsolute(rel)).map(rel=>rel.split(path.sep));if(routes.length===0){for(let entry of readdir(root))isRootOpenEntry(entry)||closed.add(path.join(root,entry));return}function walk(dir,active,depth){let nextNames=new Set(active.map(r=>r[depth]));for(let entry of readdir(dir))nextNames.has(entry)||depth===0&&isRootOpenEntry(entry)||closed.add(path.join(dir,entry));for(let name of nextNames){if(name==null||active.some(r=>r[depth]===name&&r.length===depth+1))continue;let deeper=active.filter(r=>r[depth]===name&&r.length>depth+1);deeper.length>0&&walk(path.join(dir,name),deeper,depth+1)}}walk(root,routes,0)}module.exports={closeSiblingsAlongRoutes,createLinkedPaths}}});var require_policy=__commonJS({"../../apps/web/electron/local-tools/policy.js"(exports,module){"use strict";var fs=__require("fs"),os=__require("os"),path=__require("path"),{GUARD_BYPASS_COMMANDS,MERGE_COMMANDS,gitGuardEnv}=require_git_guard(),full=require_full_access(),{CODEX_FULL_ACCESS_ARGS,SANDBOX_NOTICE,applyFullAccess,fullAccessRunsHere,hasFullAccess}=full,{closeSiblingsAlongRoutes,createLinkedPaths}=require_linked_paths(),{CODEX_APPS}=require_servers(),{openableToolchainRoots}=require_toolchain(),DEFAULT_POLICY={files:"allow",commands:"allow",push:"allow",network:"allow",deploy:"never",full_access:"never"},PERMISSIONS=new Set(["allow","never"]),SECRET_PATHS=["~/.ssh","~/.config/gh","~/.config/ando","~/.gnupg","~/.netrc","~/.docker","~/.kube","~/.git-credentials","~/.config/git/credentials","~/.npmrc","~/.yarnrc.yml","~/.pypirc","~/.config/pypoetry/auth.toml","~/.config/nix/nix.conf","~/.cargo/credentials","~/.cargo/credentials.toml","~/.gem/credentials","~/.m2/settings.xml","~/.m2/settings-security.xml","~/.gradle/gradle.properties","~/.config/pnpm/rc","~/.config/pnpm/auth.ini","~/Library/Preferences/pnpm/rc","~/Library/Preferences/pnpm/auth.ini","~/AppData/Local/pnpm/config/rc","~/AppData/Local/pnpm/config/auth.ini","~/.claude/projects","~/.claude/.credentials.json","~/.claude.json","~/.codex/sessions","~/.codex/auth.json","~/Library/Keychains"],GIT_METADATA_READ_ONLY=[".git/config",".git/hooks",".git/info"],AWS_METADATA_READ_ONLY=[".aws/config",".aws/credentials"],AWS_CACHE_WRITES=[".aws/sso/cache",".aws/cli/cache"];function codexSecrets(codexDir){return codexDir==null?[]:[path.join(codexDir,"sessions"),path.join(codexDir,"auth.json")]}function movedConfigHome(configHome,home){if(typeof configHome!="string"||!path.isAbsolute(configHome))return null;let dir=path.resolve(configHome);return dir===path.join(home,".config")?null:dir}function configSecrets(configDir){if(configDir==null)return[];let prefix="~/.config/";return[...SECRET_PATHS,...PRIVATE_TOOLCHAIN_PATHS].filter(p=>p.startsWith(prefix)).map(p=>path.join(configDir,p.slice(prefix.length)))}var TOOLCHAIN_HOME_ENTRIES=new Set([".aws",".gitconfig",".config",".local",".cache",".npm",".nvm",".bun",".volta",".asdf",".deno",".cargo",".rustup",".pyenv",".rbenv",".gem",".gradle",".m2","go","Library"]),CONFIG_TOOLCHAIN_ENTRIES=new Set(["git","npm","pnpm","yarn","fnm","nvm","volta","mise","asdf","bun","deno","uv","pip","pypoetry","go","nix","direnv","starship.toml"]),WINDOWS_APPDATA_TOOLCHAIN_ENTRIES={Roaming:new Set(["npm","nvm","fnm","Python","pnpm","uv"]),Local:new Set(["Temp","npm-cache","pnpm","pnpm-cache","pnpm-state","Volta","fnm_multishells","Yarn","node","uv","pip","mise","Programs"])};function settingsFolders(home,configDir,platform){let folders=[[path.join(home,".config"),CONFIG_TOOLCHAIN_ENTRIES]];if(configDir!=null&&folders.push([configDir,CONFIG_TOOLCHAIN_ENTRIES]),platform==="win32"){folders.push([path.join(home,"AppData"),new Set(Object.keys(WINDOWS_APPDATA_TOOLCHAIN_ENTRIES))]);for(let[name,entries]of Object.entries(WINDOWS_APPDATA_TOOLCHAIN_ENTRIES))folders.push([path.join(home,"AppData",name),entries])}return folders}var PRIVATE_TOOLCHAIN_PATHS=["~/.config/gh","~/Library/Keychains","~/Library/Application Support","~/Library/Mail","~/Library/Messages","~/Library/Cookies","~/Library/Safari","~/Library/Containers","~/Library/Group Containers","~/Library/Mobile Documents"];function listDir(dir){try{return fs.readdirSync(dir)}catch{return[]}}var MAX_CLOSED_PATHS=2e3,linkedPaths=createLinkedPaths({secretPathsFor:({home,codexDir,configHome})=>[...[...SECRET_PATHS,...PRIVATE_TOOLCHAIN_PATHS].map(p=>resolveHome(p,home)),...codexSecrets(codexDir),...configSecrets(movedConfigHome(configHome,home))],settingsFoldersFor:({home,configHome,platform})=>settingsFolders(home,movedConfigHome(configHome,home),platform)});function closedPaths(folder,{home=os.homedir(),readdir=listDir,codexDir=null,configHome=null,extra=[],linked=[],log:log2=null,platform=process.platform}={}){let configDir=movedConfigHome(configHome,home),targets=[folder,...linked],filteredExtra=[],extraAncestors=[];for(let p of extra)if(!linked.some(l=>p===l||p.startsWith(l+path.sep))){if(linked.some(l=>l.startsWith(p+path.sep))){extraAncestors.push(p);continue}filteredExtra.push(p)}let closed=new Set([...filteredExtra,...[...SECRET_PATHS,...PRIVATE_TOOLCHAIN_PATHS].map(p=>resolveHome(p,home)),...codexSecrets(codexDir),...configSecrets(configDir)]);for(let ancestor of extraAncestors){let rel=path.relative(home,ancestor);rel!==""&&!rel.startsWith("..")&&!path.isAbsolute(rel)||closeSiblingsAlongRoutes(ancestor,targets,readdir,closed)}closeSiblingsAlongRoutes(home,targets,readdir,closed,entry=>TOOLCHAIN_HOME_ENTRIES.has(entry)||platform==="win32"&&entry==="AppData");for(let[config,open]of settingsFolders(home,configDir,platform))if(!targets.some(t=>t===config||t.startsWith(config+path.sep)))for(let entry of readdir(config))open.has(entry)||closed.add(path.join(config,entry));return closed.size>MAX_CLOSED_PATHS&&log2?.warn(`[Local tools] ${closed.size} paths to close for a task in ${folder}; closing the first ${MAX_CLOSED_PATHS}, so ${closed.size-MAX_CLOSED_PATHS} entries of the home folder stay readable to Codex`),[...closed].slice(0,MAX_CLOSED_PATHS)}function taskClosedPaths({folder,home,readdir,codexDir,configHome=null,credentialPaths,linked=[],log:log2,platform}){return folder==null?[...new Set([...credentialPaths,...SECRET_PATHS.map(p=>resolveHome(p,home)),...codexSecrets(codexDir),...configSecrets(movedConfigHome(configHome,home))])]:closedPaths(folder,{home,readdir,codexDir,configHome,extra:credentialPaths,linked,log:log2,platform})}function gitMetadataPaths(folder,repoHooks,closed){let paths=folder==null?[]:GIT_METADATA_READ_ONLY.map(p=>path.join(folder,p)),hooks=Array.isArray(repoHooks)?repoHooks:[repoHooks];for(let hook of hooks)hook!=null&&path.isAbsolute(hook)&&!closed.some(p=>hook===p||hook.startsWith(p+path.sep))&&paths.push(path.resolve(hook));return[...new Set(paths)]}function guardFolders(hooksDir){return hooksDir==null?[]:[path.dirname(hooksDir),hooksDir]}function otherGuards(hooksDir){return hooksDir==null?[]:[path.dirname(hooksDir)]}var CLAUDE_OUTWARD_TOOLS=["RemoteTrigger","CronCreate","CronDelete","CronList","ScheduleWakeup","PushNotification","SendMessage","SendUserFile","SendFeedback","ShareOnboardingGuide","Artifact","ListAgents","Workflow","Monitor","EnterWorktree","ExitWorktree"],MACH_SERVICES=["com.apple.trustd","com.apple.trustd.agent"],DESCRIPTIONS={files:"edit files",commands:"run commands",push:"push branches",network:"install packages or use the network",deploy:"merge, deploy or push to main"};function resolvePolicy(value,{platform=process.platform}={}){let policy={...DEFAULT_POLICY};if(value==null||typeof value!="object")return policy;for(let key of Object.keys(DEFAULT_POLICY))PERMISSIONS.has(value[key])&&(policy[key]=value[key]);return applyFullAccess(policy,platform)}function resolveHome(p,home){return p.startsWith("~/")?path.join(home,p.slice(2)):p}function rulePath(p){return`/${p.replace(/[\\*?[\]]/g,"\\$&")}`}function claudeReadOnlyAndRules(policy,{folder,home,repoHooks,linkedRepoHooks=[],closed,hooksDir,toolchainReads,linked,linkedDirs}){let hasAws=toolchainReads.includes(path.join(home,".aws")),awsMetadata=hasAws?AWS_METADATA_READ_ONLY.map(p=>path.join(home,p)):[],shellWrites=hasAws&&policy.commands==="allow"?AWS_CACHE_WRITES.map(p=>path.join(home,p)):[],shellReads=[...toolchainReads,...linked,...hooksDir==null?[]:[hooksDir]],gitMetadata=policy.files==="allow"?[...gitMetadataPaths(folder,[repoHooks,...linkedRepoHooks],closed),...linkedDirs.flatMap(dir=>gitMetadataPaths(dir,null,closed))]:[],linkedFiles=linked.filter(p=>!linkedDirs.includes(p)),readOnly=[...policy.files==="never"&&folder!=null?[folder]:[],...policy.files==="never"?linked:[],...gitMetadata,...awsMetadata,...guardFolders(hooksDir)],editRules=[`Edit(${folder==null?"./**":`${rulePath(folder)}/**`})`,...linkedDirs.map(dir=>`Edit(${rulePath(dir)}/**)`),...linkedFiles.map(file=>`Edit(${rulePath(file)})`)];return{filesystem:{denyRead:closed,...shellReads.length>0?{allowRead:shellReads}:{},...shellWrites.length>0?{allowWrite:shellWrites}:{},...readOnly.length>0?{denyWrite:readOnly}:{}},editRules,linkedReadRules:linkedFiles.map(file=>`Read(${rulePath(file)})`),protectedEditRules:[...gitMetadata,...awsMetadata].flatMap(p=>[`Edit(${rulePath(p)})`,`Edit(${rulePath(p)}/**)`])}}function claudeTaskArgs(policy,options={}){return hasFullAccess(policy)?full.claudeFullAccessArgs({servers:options.servers,outwardTools:CLAUDE_OUTWARD_TOOLS}):claudeSandboxedArgs(policy,options)}function claudeSandboxedArgs(policy,{servers={},home=os.homedir(),folder=null,readdir,hooksDir=null,repoHooks=null,linkedRepoHooks=[],toolchain=[],codexDir=null,configHome=null,credentialPaths=[],linked=[],linkedDirs=[],log:log2=null}={}){let closed=[...taskClosedPaths({folder,home,readdir,codexDir,configHome,credentialPaths,linked,log:log2}),...otherGuards(hooksDir)],toolchainReads=openableToolchainRoots(toolchain,closed,home,readdir),{filesystem,editRules,linkedReadRules,protectedEditRules}=claudeReadOnlyAndRules(policy,{folder,home,repoHooks,linkedRepoHooks,closed,hooksDir,toolchainReads,linked,linkedDirs}),network={...policy.network==="allow"?{allowedDomains:["*"]}:{allowedDomains:[],strictAllowlist:!0},allowLocalBinding:!0,allowMachLookup:MACH_SERVICES},settings={disableAllHooks:!0,permissions:{blockReadsOutsideWorkingDirectories:!0,...linkedDirs.length>0?{additionalDirectories:linkedDirs}:{},deny:[...closed.flatMap(p=>[`Read(${rulePath(p)})`,`Read(${rulePath(p)}/**)`]),...policy.push==="never"||policy.deploy==="never"?GUARD_BYPASS_COMMANDS.map(pattern=>`Bash(${pattern})`):[],...policy.deploy==="never"?MERGE_COMMANDS.map(pattern=>`Bash(${pattern})`):[],...policy.files==="never"?editRules:[],...protectedEditRules]},sandbox:{enabled:!0,failIfUnavailable:!0,allowUnsandboxedCommands:!1,autoAllowBashIfSandboxed:policy.commands==="allow",excludedCommands:[],filesystem,network}},allowed=["Read",...linkedReadRules,"Glob","Grep","TodoWrite",...policy.commands==="allow"?["Bash"]:[],...policy.files==="allow"?editRules:[],...policy.network==="allow"?["WebFetch","WebSearch"]:[],...Object.keys(servers).map(name=>`mcp__${name}`)],disallowed=[...CLAUDE_OUTWARD_TOOLS,...policy.network==="allow"?[]:["WebFetch","WebSearch"],...policy.commands==="allow"?[]:["Bash"],...policy.files==="allow"?[]:["Edit","MultiEdit","Write","NotebookEdit"]];return["--permission-mode","dontAsk","--setting-sources","","--settings",JSON.stringify(settings),"--allowedTools",allowed.join(","),"--disallowedTools",disallowed.join(","),"--strict-mcp-config","--mcp-config",JSON.stringify({mcpServers:servers})]}function tomlString(value){return JSON.stringify(value)}function codexFilesystem(policy,{closed,hooksDir,repoHooks,linkedRepoHooks=[],folder,linked=[],linkedDirs=linked}){let ownHooks=policy.files==="allow"?[...gitMetadataPaths(folder,[repoHooks,...linkedRepoHooks],closed).filter(p=>!GIT_METADATA_READ_ONLY.some(m=>p===path.join(folder??"",m))),...linkedDirs.flatMap(dir=>gitMetadataPaths(dir,null,closed))]:[],linkedAccess=policy.files==="allow"?"write":"read";return[...closed.map(p=>`${tomlString(p)} = "deny"`),...otherGuards(hooksDir).map(p=>`${tomlString(p)} = "deny"`),...hooksDir==null?[]:[`${tomlString(hooksDir)} = "read"`],...linked.map(p=>`${tomlString(p)} = "${linkedAccess}"`),...policy.files==="allow"?[`":workspace_roots" = { ${['"." = "write"','".git" = "write"',...GIT_METADATA_READ_ONLY.map(p=>`${tomlString(p)} = "read"`)].join(", ")} }`,...[...new Set(ownHooks)].map(p=>`${tomlString(p)} = "read"`)]:['":workspace_roots" = { "." = "read" }']].join(", ")}function codexWindowsSandboxArgs(platform){return platform==="win32"?["-c",'windows.sandbox="elevated"',"--disable","prefer_mxc"]:[]}function mountablePaths(paths,{lstat=fs.lstatSync,realpath=fs.realpathSync}={}){let resolved=paths.flatMap(p=>{try{return[lstat(p).isSymbolicLink()?realpath(p):p]}catch{return[]}}),unique=[...new Set(resolved)];return unique.filter(p=>!unique.some(other=>p.startsWith(`${other}${path.sep}`)))}function codexClosedPaths(options){let closed=taskClosedPaths(options);return options.platform==="linux"?mountablePaths(closed):closed}function codexPermissionArgs(policy,{hooksDir,repoHooks,linkedRepoHooks,linkedDirs,...paths}){if(hasFullAccess(policy))return CODEX_FULL_ACCESS_ARGS;let closed=codexClosedPaths(paths),{folder,linked}=paths,filesystem=codexFilesystem(policy,{closed,hooksDir,repoHooks,linkedRepoHooks,folder,linked,linkedDirs});return["-c",'default_permissions="ando-task"',"-c",`permissions=${`{ "ando-task" = { extends = ${tomlString(policy.files==="allow"?":workspace":":read-only")}, filesystem = { ${filesystem} }, network = { enabled = ${policy.network==="allow"} } } }`}`]}function codexTaskArgs(policy,{available=[],allowed=[],hooksDir=null,repoHooks=null,linkedRepoHooks=[],github=!1,home=os.homedir(),folder=null,readdir,codexDir=null,configHome=null,credentialPaths=[],linked=[],linkedDirs=linked,log:log2=null,platform=process.platform}={}){let picked=new Set(allowed),args=[...codexPermissionArgs(policy,{folder,home,readdir,codexDir,configHome,credentialPaths,linked,log:log2,platform,hooksDir,repoHooks,linkedRepoHooks,linkedDirs}),"--disable","browser_use","--disable","browser_use_external","--disable","computer_use",...hasFullAccess(policy)?[]:codexWindowsSandboxArgs(platform)];picked.has(CODEX_APPS)||args.push("--disable","apps"),policy.commands!=="allow"&&args.push("--disable","shell_tool");let servers=new Map,plugins=[];for(let name of available)if(name!==CODEX_APPS){if(picked.has(name)){name.includes("@")||servers.set(name,'{ default_tools_approval_mode = "approve" }');continue}name.includes("@")?plugins.push(name):servers.set(name,"{ enabled = false }")}if(servers.size>0&&args.push("-c",`mcp_servers={ ${[...servers].map(([name,entry])=>`${tomlString(name)} = ${entry}`).join(", ")} }`),plugins.length>0&&args.push("-c",`plugins={ ${plugins.map(name=>`${tomlString(name)} = { enabled = false }`).join(", ")} }`),hooksDir!=null){let env=gitGuardEnv(hooksDir,policy,{github,platform});args.push("-c","allow_login_shell=false","--disable","shell_snapshot"),args.push("-c",`shell_environment_policy.set={ ${Object.entries(env).map(([key,value])=>`${key} = ${tomlString(value)}`).join(", ")} }`)}return args}var PULL_REQUESTS={never:"You can't open pull requests either.",noMerge:"You can push a branch and open a pull request with `gh pr create`, but you can't merge it. If `gh` isn't signed in, push the branch and say in your result that it needs a pull request.",withToken:"You can push a branch and open a pull request with `gh pr create`. If `gh` isn't signed in, push the branch and say in your result that it needs a pull request."};function policyInstructions(policy,folder,{linked=[],platform=process.platform}={}){let never=Object.keys(DESCRIPTIONS).filter(key=>policy[key]==="never"),pullRequests=policy.push==="never"?PULL_REQUESTS.never:policy.deploy==="never"?PULL_REQUESTS.noMerge:PULL_REQUESTS.withToken,scope=linked.length>0?`Stay inside ${folder} (and what it links to: ${linked.join(", ")}): do not read or change files outside them.`:`Stay inside ${folder}: do not read or change files outside it.`;return[hasFullAccess(policy)?full.fullAccessScope(folder):scope,...hasFullAccess(policy)||!fullAccessRunsHere(platform)?[]:[SANDBOX_NOTICE],...never.length===0?[]:[`You may not ${never.map(key=>DESCRIPTIONS[key]).join(", or ")}. If the task needs it, say so in your result and stop.`],pullRequests].join(`
104
+ `)}module.exports={CLAUDE_OUTWARD_TOOLS,DEFAULT_POLICY,SECRET_PATHS,claudeTaskArgs,closedPaths,linkedPaths,mountablePaths,codexTaskArgs,fullAccessRunsHere,policyInstructions,resolvePolicy}}});var require_runs=__commonJS({"../../apps/web/electron/local-tools/runs.js"(exports,module){"use strict";var{checkpointClaudeUsage}=require_usage(),fs=__require("fs"),path=__require("path"),{linkedPaths,policyInstructions}=require_policy(),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;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(run3,error){let message=error?.message??String(error);return SIGNED_OUT.test(message)?`${run3.toolName??(run3.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 runInstructions(run3){let{linked}=linkedPaths(run3.folder);return[`You are ${run3.toolName} working on a task that ${run3.agentName??"an Ando agent"} started on this computer for its owner, through Ando, their team messenger.`,`Work in ${run3.folder}. Messages that arrive while you work are new context from the task's thread in Ando.`,...run3.checkoutOf==null?[]:[`This is your own checkout of ${run3.checkoutOf}, on a branch of its own, made from 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.`],policyInstructions(run3.policy,run3.folder,{linked}),"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."].join(`
97
105
 
98
106
  `)}function createLocalToolRuns({createRuntime,emit,log:log2,rememberUsage=()=>{},exists=fs.existsSync}){let runs=new Map,tests=new Set;function report(run3,event){try{emit({runId:run3.runId,workspaceId:run3.workspaceId,...run3.ownerId==null?{}:{ownerId:run3.ownerId},...event})}catch(error){log2.warn("[Local tools] could not report a run",error)}}let closing=!1;function createRunRuntime(run3,setup={}){return createRuntime(run3.provider,{runId:run3.runId,cwd:run3.folder,instructions:runInstructions(run3),policy:run3.policy,servers:run3.servers??[],...setup})}async function execute(run3,runtime){let reportedSession=run3.sessionId??null,noteSession=sessionId=>{typeof sessionId!="string"||sessionId===reportedSession||(reportedSession=sessionId,report(run3,{kind:"session",sessionId}))},previous=run3.usageCheckpoint??null,lastUsage=checkpointClaudeUsage(previous,null,reportedSession)?.usage??null,saveUsage=(usage,sessionId=null)=>{if(noteSession(sessionId),run3.provider!=="claude-code")return usage;let checkpoint=checkpointClaudeUsage(previous,usage,reportedSession);if(checkpoint!=null)try{rememberUsage(run3,checkpoint)}catch(error){log2.warn("[Local tools] could not checkpoint usage",error)}return lastUsage=checkpoint?.usage??null,lastUsage},resuming=run3.sessionId!=null;try{let result=await runtime.runTurn({key:run3.runId,sessionId:run3.sessionId??null,text:resuming?"The Ando desktop app restarted while you were working on this task. Carry on where you left off.":run3.prompt,newSessionText:async()=>run3.prompt,answerSteers:!0,onStarted:()=>report(run3,{kind:"started"}),onSession:noteSession,onUsage:saveUsage,onMessage:message=>{noteSession(message?.session_id);for(let entry of claudeRunSteps(message,run3.folder))report(run3,{kind:"step",...entry})},onThought:run3.provider==="codex"?thought=>{let text=clip(thought);text&&report(run3,{kind:"step",text})}:void 0});noteSession(result.sessionId);let usage=saveUsage(result.usage);if(runs.get(run3.runId)?.stopping){report(run3,{kind:"stopped",sessionId:reportedSession,...usage==null?{}:{usage}});return}report(run3,{kind:"done",sessionId:result.sessionId??reportedSession,result:result.reply.trim(),...usage==null?{}:{usage}})}catch(error){if(closing)return;if(runs.get(run3.runId)?.stopping){report(run3,{kind:"stopped",sessionId:reportedSession,...lastUsage==null?{}:{usage:lastUsage}});return}report(run3,{kind:"failed",sessionId:reportedSession,error:describeFailure(run3,error)})}finally{runtime.close(),runs.delete(run3.runId)}}return{start(run3,setup={}){if(runs.has(run3.runId))return{status:"running"};if(!exists(run3.folder))return report(run3,{kind:"failed",sessionId:run3.sessionId??null,error:`${run3.folder} isn't on this computer.`}),{status:"failed"};let runtime;try{runtime=createRunRuntime(run3,setup)}catch(error){return report(run3,{kind:"failed",sessionId:run3.sessionId??null,error:describeFailure(run3,error)}),{status:"failed"}}return runs.set(run3.runId,{runtime,run:run3}),execute(run3,runtime),{status:"started"}},async test(run3,{timeoutMs=TEST_TIMEOUT_MS}={}){let failed=error=>({status:"failed",error:describeFailure(run3,error)});if(!exists(run3.folder))return failed(new Error(`${run3.folder} isn't on this computer.`));let runtime;try{runtime=createRunRuntime(run3)}catch(error){return failed(error)}tests.add(runtime);let timer;try{return await Promise.race([runtime.runTurn({key:run3.runId,sessionId:null,text:TEST_PROMPT}),new Promise((_,reject)=>{timer=setTimeout(()=>reject(new Error(`${run3.toolName} didn't answer within ${Math.round(timeoutMs/6e4)} minutes.`)),timeoutMs)})]),{status:"passed"}}catch(error){return failed(error)}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()],stopAll(){closing=!0;for(let{runtime}of runs.values())runtime.close();for(let runtime of tests)runtime.close();runs.clear()}}}module.exports={claudeRunSteps,createLocalToolRuns,runInstructions}}});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 readdir(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 time=Date.parse(value);return Number.isFinite(time)?time: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(`
99
107
  `):""}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(`
100
108
  `)[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&&noteTime(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)&&notePrompt(transcript,at,text,keep):payload.role==="assistant"&&note(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)&&noteTime(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(`
101
- `)){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 readdir(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 readdir(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(readdir(root)))for(let month of descending(readdir(path.join(root,year.name))))for(let day of descending(readdir(path.join(root,year.name,month.name)))){let dir=path.join(root,year.name,month.name,day.name);for(let entry of readdir(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,deps={}){let platform=deps.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:deps.home,env:deps.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(error){return{status:"failed",error:clip(error?.message??String(error),400)}}}module.exports={answerSessionRequest,claudeProjectKey,listSessions,readSession,redact:redact2,sessionRoots}}});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"]),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)_/,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){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 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 fs=__require("fs"),os=__require("os"),path=__require("path"),{pushCredentialPaths}=require_credentials(),{findGit,gitGuardEnv,githubSignIn,guardedPath,repoHooksPath,writeGitGuard}=require_git_guard(),{claudeTaskArgs,linkedPaths}=require_policy(),{codexHome,readClaudeServers}=require_servers(),{taskEnv}=require_task_env(),{findCommand:findCommand2,toolchainRoots}=require_toolchain();function prepareTaskGuard({dir,cwd,policy,githubToken=null,ownerEnv,run:run3,platform=process.platform,lockSecret}){let realGit=findGit(ownerEnv.PATH),hooksDir=writeGitGuard(dir,policy,{realGit,realGh:findCommand2("gh",ownerEnv.PATH),githubToken,platform,lockSecret}),{linkedDirs}=linkedPaths(cwd,{home:ownerEnv.HOME||os.homedir(),codexDir:codexHome(ownerEnv),configHome:ownerEnv.XDG_CONFIG_HOME,platform}),linkedRepoHooks=linkedDirs.map(linkedDir=>repoHooksPath(linkedDir,{git:realGit,env:ownerEnv,run:run3})).filter(p=>p!=null);return{hooksDir,repoHooks:repoHooksPath(cwd,{git:realGit,env:ownerEnv,run:run3}),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:run3,platform}):[]}}function guardedTaskEnv(ownerEnv,policy,guard,platform=process.platform){return{...taskEnv(ownerEnv,policy),...gitGuardEnv(guard.hooksDir,policy,{github:guard.github,platform}),PATH:guardedPath(guard.hooksDir,ownerEnv.PATH,platform)}}function claudeTaskLaunch({policy,cwd,servers,guard,ownerEnv,extraClosed=[],home=os.homedir(),log:log2=null}){let own=readClaudeServers(home),picked=Object.fromEntries(servers.filter(name=>name in own).map(name=>[name,own[name]])),codexDir=codexHome(ownerEnv),configHome=ownerEnv.XDG_CONFIG_HOME,{linked,linkedDirs}=linkedPaths(cwd,{home,codexDir,configHome});return{env:{...guardedTaskEnv(ownerEnv,policy,guard),CLAUDE_ENV_FILE:path.join(guard.hooksDir,"shell-env.sh")},permissionArgs:claudeTaskArgs(policy,{servers:picked,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,log:log2})}}module.exports={claudeTaskLaunch,guardedTaskEnv,prepareTaskGuard}}});var require_host=__commonJS({"../../apps/web/electron/local-tools/host.js"(exports,module){"use strict";var{randomUUID:randomUUID3}=__require("crypto"),fs=__require("fs"),os=__require("os"),path=__require("path"),{createClaudeRuntime}=require_claude_runtime(),{createCodexRuntime}=require_codex_runtime(),{markTaskEnded,prepareTaskCheckout,sweepTaskCheckouts}=require_checkouts(),{resolveCommandEnv,trustedPath:trustedPath2}=require_command_env(),{ownedGuardRoot}=require_git_guard(),{ownerGithubToken}=require_credentials(),{TOOL_COMMANDS,UUID,createMachineDescriber}=require_machine(),{createRunOutbox}=require_outbox(),{createLocalToolRuns}=require_runs(),{codexTaskArgs,linkedPaths,resolvePolicy}=require_policy(),{codexHome,listToolServers}=require_servers(),{answerSessionRequest}=require_sessions(),{claudeTaskLaunch,guardedTaskEnv,prepareTaskGuard}=require_task_setup(),{findCommand:findCommand2}=require_toolchain(),{letSandboxReadGuard,lockWindowsToken,windowsGuardRoot,windowsSpawn}=require_windows(),{sendRunnerToWsl,toWslPath,wslClaudeSpawn}=require_wsl(),TOOL_NAMES={"claude-code":"Claude Code",codex:"Codex"},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){let dir=path.join(root,entry);try{now-fs.statSync(dir).mtimeMs>STALE_GUARD_MS&&fs.rmSync(dir,{recursive:!0,force:!0})}catch{}}}function text(value,limit){return typeof value=="string"&&value.trim()&&value.length<=limit?value:null}function limitsDontHold(run3,platform){return platform==="linux"&&run3.provider==="codex"&&run3.policy.network!=="never"}var 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.";function parseRunRequest(input){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);return folder==null||!path.isAbsolute(folder)||prompt==null?null:{runId:value.runId,workspaceId,ownerId:text(value.ownerId,200),provider:value.provider,toolName:TOOL_NAMES[value.provider],folder,prompt,sessionId:text(value.sessionId,200),agentName:text(value.agentName,200),policy:resolvePolicy(value.policy),bareCheckout:value.bareCheckout===!0,servers:Array.isArray(value.servers)?value.servers.filter(name=>text(name,200)!=null).slice(0,50):[]}}function createTaskRuntime(provider,{spawn:spawn2,log:log2,cwd,instructions,policy,servers,guard,ownerEnv,platform=process.platform,letSandboxGuard=letSandboxReadGuard,otherFolders=[],closedToCodex=[]}){if(provider==="codex"){let{linked,linkedDirs}=linkedPaths(cwd,{home:os.homedir(),codexDir:codexHome(ownerEnv),configHome:ownerEnv.XDG_CONFIG_HOME,platform});return createCodexRuntime({spawn:spawn2,env:guardedTaskEnv(ownerEnv,policy,guard,platform),cwd,instructions,log:log2,sandbox:null,windowsSandbox:platform==="win32",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",os.homedir(),ownerEnv),allowed:servers,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,log:log2,platform})})}let{env,permissionArgs}=claudeTaskLaunch({policy,cwd,servers,guard,ownerEnv,log:log2,extraClosed:otherFolders});return createClaudeRuntime({spawn:spawn2,env,cwd,instructions,log:log2,permissionArgs})}function createWslClaudeRuntime({spawn:spawn2,spawnSync:spawnSync3,log:log2,cwd,instructions,runId,policy,servers,githubToken}){let folder=toWslPath(cwd,{spawnSync:spawnSync3}),windowsHome=null;try{windowsHome=toWslPath(os.homedir(),{spawnSync:spawnSync3})}catch{}return createClaudeRuntime({spawn:wslClaudeSpawn({spawn:spawn2,runnerDir:sendRunnerToWsl({spawnSync:spawnSync3}),run:{runId,folder,windowsHome,policy,servers,githubToken}}),env:{},cwd,instructions,log:log2,permissionArgs:[]})}function createLocalToolHost2({directory,appName,log:log2,onEvent,platform=process.platform,spawn:spawnProcess,spawnSync:spawnSync3,hostname:hostname2=os.hostname,guardRoot:chosenGuardRoot=platform==="win32"?windowsGuardRoot():path.join(os.tmpdir(),"ando-task-git"),lockToken=lockWindowsToken,guardGraceMs=GUARD_GRACE_MS,readGithubToken=ownerEnv=>ownerGithubToken({env:ownerEnv,gh:findCommand2("gh",ownerEnv.PATH)}),taskFolders=(()=>[]),inPlaceFolders=(()=>[]),checkoutRoot=null}){let spawn2=platform==="win32"?windowsSpawn(spawnProcess):spawnProcess,guardRoot=ownedGuardRoot(chosenGuardRoot,{platform});sweepStaleGuards(guardRoot);let commandEnv=null,env=()=>{commandEnv??=resolveCommandEnv({spawnSync:spawnSync3,env:process.env,platform});let folders=taskFolders();return folders.length===0?{...commandEnv}:{...commandEnv,PATH:trustedPath2(commandEnv.PATH??"",folders)}},machine=createMachineDescriber({machineFile:path.join(directory,"machine.json"),platform,spawn:spawn2,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}),emit=event=>{checkoutRoot!=null&&(event.kind==="done"||event.kind==="failed")&&markTaskEnded(checkoutRoot,event.runId),onEvent(outbox.push(event))};checkoutRoot!=null&&sweepTaskCheckouts(checkoutRoot);let runs=createLocalToolRuns({log:log2,createRuntime:(provider,{runId,cwd,instructions,policy,servers,githubToken=null})=>{if(provider==="claude-code"&&platform==="win32")return createWslClaudeRuntime({spawn:spawnProcess,spawnSync:spawnSync3,log:log2,cwd,instructions,runId,policy,servers,githubToken});let ownerEnv=env(),guard=prepareTaskGuard({dir:path.join(guardRoot,runId),cwd,policy,githubToken,ownerEnv,run:spawnSync3,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(error){log2.warn("[Local tools] could not remove a task's git guard",error)}},guardGraceMs),removing.unref?.()};try{let runtime=createTaskRuntime(provider,{spawn:spawn2,log:log2,cwd,instructions,policy,servers,guard,ownerEnv,platform,otherFolders:taskFolders().filter(folder=>cwd!==folder&&!cwd.startsWith(`${folder}${path.sep}`)),closedToCodex:checkoutRoot==null?[]:[checkoutRoot]});return{...runtime,close(){runtime.close(),removeGuard()}}}catch(error){throw removeGuard(),error}},emit,rememberUsage:(run3,checkpoint)=>outbox.rememberUsage(run3.runId,run3.workspaceId,checkpoint)}),starting=new Map,stoppedWhileStarting=new Set;async function placeRun(run3){if(limitsDontHold(run3,platform))return emit({runId:run3.runId,workspaceId:run3.workspaceId,...run3.ownerId==null?{}:{ownerId:run3.ownerId},kind:"failed",sessionId:run3.sessionId??null,error:LIMITS_DONT_HOLD_ERROR}),null;if(checkoutRoot==null||run3.policy.files==="never"||inPlaceFolders().includes(run3.folder)||!fs.existsSync(path.join(run3.folder,".git")))return{};try{let ownerEnv=env();return{folder:await prepareTaskCheckout({root:checkoutRoot,folder:run3.folder,runId:run3.runId,git:findCommand2("git",ownerEnv.PATH)??"git",env:ownerEnv,spawnSync:spawnSync3,platform,bare:run3.bareCheckout,onProgress:message=>log2.info?.(message)}),checkoutOf:run3.folder}}catch(error){return emit({runId:run3.runId,workspaceId:run3.workspaceId,...run3.ownerId==null?{}:{ownerId:run3.ownerId},kind:"failed",sessionId:run3.sessionId??null,error:`Couldn't set up a checkout of ${run3.folder}: ${error.message}`}),null}}async function startRun(input){let run3=parseRunRequest(input);if(run3==null)return{status:"invalid"};let pending=starting.get(run3.runId);if(pending!=null)return await pending;if(outbox.recall(run3.runId,run3.workspaceId).ended)return{status:"finished"};let start=(async()=>{let githubToken=run3.policy.push==="never"?null:await readGithubToken(env()),saved=outbox.recall(run3.runId,run3.workspaceId);if(saved.ended)return{status:"finished"};let endStopped=()=>(emit({runId:run3.runId,workspaceId:run3.workspaceId,...run3.ownerId==null?{}:{ownerId:run3.ownerId},kind:"stopped",sessionId:run3.sessionId??saved.sessionId??null,...saved.usageCheckpoint?.usage==null?{}:{usage:saved.usageCheckpoint.usage}}),{status:"finished"});if(stoppedWhileStarting.has(run3.runId))return endStopped();let place=await placeRun(run3);return place==null?{status:"finished"}:stoppedWhileStarting.has(run3.runId)?endStopped():runs.start({...run3,...place,sessionId:run3.sessionId??saved.sessionId,usageCheckpoint:saved.usageCheckpoint},{githubToken})})();starting.set(run3.runId,start);try{return await start}finally{starting.delete(run3.runId),stoppedWhileStarting.delete(run3.runId)}}let testing=new Map;async function testTool(input){let run3=parseRunRequest({...input!=null&&typeof input=="object"?input:{},runId:randomUUID3(),prompt:"test"});if(run3==null)return{status:"failed",error:"The Ando app couldn't read this test."};if(limitsDontHold(run3,platform))return{status:"failed",error:LIMITS_DONT_HOLD_ERROR};let key=JSON.stringify([run3.workspaceId,run3.provider,run3.folder,run3.policy,[...run3.servers].sort()]),pending=testing.get(key);if(pending!=null)return await pending;let test=runs.test(run3).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:spawn2,startRun,testTool,steerRun,stopRun,readSessions:input=>answerSessionRequest(input,{env:env(),platform}),runState:()=>({active:runs.list(),events:outbox.list()}),ackRunEvents:seqs=>outbox.ack(seqs),stopAll:()=>{runs.stopAll(),outbox.flush()}}}module.exports={createLocalToolHost:createLocalToolHost2,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(url){if(typeof url!="string")return null;let value=url.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 stat=statSync2(path.join(root,".git","config"));return stat.isFile()?{mtimeMs:stat.mtimeMs,size:stat.size}:null}catch{return null}}function readOrigin(folder,{execFile:execFile2,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 cached=originCache.get(folder);if(cached!=null&&cached.execFile===execFile2&&cached.mtimeMs===configStat.mtimeMs&&cached.size===configStat.size&&currentTime-cached.cachedAt<ORIGIN_CACHE_TTL_MS)return Promise.resolve(cached.origin)}return new Promise(resolve2=>{execFile2("git",["-C",folder,"remote","get-url","origin"],{env:{...env,GIT_TERMINAL_PROMPT:"0"},encoding:"utf8",timeout:READ_TIMEOUT_MS},(error,stdout)=>{let origin=error==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:execFile2,origin})}else originCache.delete(folder);resolve2(origin)})})}async function readFolderRemotes2(input,{execFile:execFile2=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:execFile2,env,exists,statSync:statSync2,now}));return remote==null?null:{folder,...remote}}))).filter(remote=>remote!=null)}module.exports={ORIGIN_CACHE_TTL_MS,normalizeGitRemote,readFolderRemotes:readFolderRemotes2}}});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"};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,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(`
109
+ `)){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 readdir(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 readdir(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(readdir(root)))for(let month of descending(readdir(path.join(root,year.name))))for(let day of descending(readdir(path.join(root,year.name,month.name)))){let dir=path.join(root,year.name,month.name,day.name);for(let entry of readdir(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,deps={}){let platform=deps.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:deps.home,env:deps.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(error){return{status:"failed",error:clip(error?.message??String(error),400)}}}module.exports={answerSessionRequest,claudeProjectKey,listSessions,readSession,redact:redact2,sessionRoots}}});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"]),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)_/,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){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 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 fs=__require("fs"),os=__require("os"),path=__require("path"),{pushCredentialPaths}=require_credentials(),{findGit,gitGuardEnv,githubSignIn,guardedPath,repoHooksPath,writeGitGuard}=require_git_guard(),{claudeTaskArgs,linkedPaths}=require_policy(),{codexHome,readClaudeServers}=require_servers(),{taskEnv}=require_task_env(),{findCommand:findCommand2,toolchainRoots}=require_toolchain();function prepareTaskGuard({dir,cwd,policy,githubToken=null,ownerEnv,run:run3,platform=process.platform,lockSecret}){let realGit=findGit(ownerEnv.PATH),hooksDir=writeGitGuard(dir,policy,{realGit,realGh:findCommand2("gh",ownerEnv.PATH),githubToken,platform,lockSecret}),{linkedDirs}=linkedPaths(cwd,{home:ownerEnv.HOME||os.homedir(),codexDir:codexHome(ownerEnv),configHome:ownerEnv.XDG_CONFIG_HOME,platform}),linkedRepoHooks=linkedDirs.map(linkedDir=>repoHooksPath(linkedDir,{git:realGit,env:ownerEnv,run:run3})).filter(p=>p!=null);return{hooksDir,repoHooks:repoHooksPath(cwd,{git:realGit,env:ownerEnv,run:run3}),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:run3,platform}):[]}}function guardedTaskEnv(ownerEnv,policy,guard,platform=process.platform){return{...taskEnv(ownerEnv,policy),...gitGuardEnv(guard.hooksDir,policy,{github:guard.github,platform}),PATH:guardedPath(guard.hooksDir,ownerEnv.PATH,platform)}}function claudeTaskLaunch({policy,cwd,servers,guard,ownerEnv,extraClosed=[],home=os.homedir(),log:log2=null}){let own=readClaudeServers(home),picked=Object.fromEntries(servers.filter(name=>name in own).map(name=>[name,own[name]])),codexDir=codexHome(ownerEnv),configHome=ownerEnv.XDG_CONFIG_HOME,{linked,linkedDirs}=linkedPaths(cwd,{home,codexDir,configHome});return{env:{...guardedTaskEnv(ownerEnv,policy,guard),CLAUDE_ENV_FILE:path.join(guard.hooksDir,"shell-env.sh")},permissionArgs:claudeTaskArgs(policy,{servers:picked,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,log:log2})}}module.exports={claudeTaskLaunch,guardedTaskEnv,prepareTaskGuard}}});var require_host=__commonJS({"../../apps/web/electron/local-tools/host.js"(exports,module){"use strict";var{randomUUID:randomUUID3}=__require("crypto"),fs=__require("fs"),os=__require("os"),path=__require("path"),{createClaudeRuntime}=require_claude_runtime(),{createCodexRuntime}=require_codex_runtime(),{markTaskEnded,prepareTaskCheckout,sweepTaskCheckouts}=require_checkouts(),{resolveCommandEnv,trustedPath:trustedPath2}=require_command_env(),{ownedGuardRoot}=require_git_guard(),{ownerGithubToken}=require_credentials(),{TOOL_COMMANDS,UUID,createMachineDescriber}=require_machine(),{createRunOutbox}=require_outbox(),{createLocalToolRuns}=require_runs(),{codexTaskArgs,linkedPaths,resolvePolicy}=require_policy(),{codexHome,listToolServers}=require_servers(),{answerSessionRequest}=require_sessions(),{claudeTaskLaunch,guardedTaskEnv,prepareTaskGuard}=require_task_setup(),{findCommand:findCommand2}=require_toolchain(),{letSandboxReadGuard,lockWindowsToken,windowsGuardRoot,windowsSpawn}=require_windows(),{sendRunnerToWsl,toWslPath,wslClaudeSpawn}=require_wsl(),TOOL_NAMES={"claude-code":"Claude Code",codex:"Codex"},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){let dir=path.join(root,entry);try{now-fs.statSync(dir).mtimeMs>STALE_GUARD_MS&&fs.rmSync(dir,{recursive:!0,force:!0})}catch{}}}function text(value,limit){return typeof value=="string"&&value.trim()&&value.length<=limit?value:null}function limitsDontHold(run3,platform){return platform==="linux"&&run3.provider==="codex"&&run3.policy.network!=="never"}var 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.";function parseRunRequest(input,platform=process.platform){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);return folder==null||!path.isAbsolute(folder)||prompt==null?null:{runId:value.runId,workspaceId,ownerId:text(value.ownerId,200),provider:value.provider,toolName:TOOL_NAMES[value.provider],folder,prompt,sessionId:text(value.sessionId,200),agentName:text(value.agentName,200),policy:resolvePolicy(value.policy,{platform}),bareCheckout:value.bareCheckout===!0,servers:Array.isArray(value.servers)?value.servers.filter(name=>text(name,200)!=null).slice(0,50):[]}}function createTaskRuntime(provider,{spawn:spawn2,log:log2,cwd,instructions,policy,servers,guard,ownerEnv,platform=process.platform,letSandboxGuard=letSandboxReadGuard,otherFolders=[],closedToCodex=[]}){if(provider==="codex"){let{linked,linkedDirs}=linkedPaths(cwd,{home:os.homedir(),codexDir:codexHome(ownerEnv),configHome:ownerEnv.XDG_CONFIG_HOME,platform});return createCodexRuntime({spawn:spawn2,env:guardedTaskEnv(ownerEnv,policy,guard,platform),cwd,instructions,log:log2,sandbox:null,windowsSandbox:platform==="win32",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",os.homedir(),ownerEnv),allowed:servers,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,log:log2,platform})})}let{env,permissionArgs}=claudeTaskLaunch({policy,cwd,servers,guard,ownerEnv,log:log2,extraClosed:otherFolders});return createClaudeRuntime({spawn:spawn2,env,cwd,instructions,log:log2,permissionArgs})}function createWslClaudeRuntime({spawn:spawn2,spawnSync:spawnSync3,log:log2,cwd,instructions,runId,policy,servers,githubToken}){let folder=toWslPath(cwd,{spawnSync:spawnSync3}),windowsHome=null;try{windowsHome=toWslPath(os.homedir(),{spawnSync:spawnSync3})}catch{}return createClaudeRuntime({spawn:wslClaudeSpawn({spawn:spawn2,runnerDir:sendRunnerToWsl({spawnSync:spawnSync3}),run:{runId,folder,windowsHome,policy,servers,githubToken}}),env:{},cwd,instructions,log:log2,permissionArgs:[]})}function createLocalToolHost2({directory,appName,log:log2,onEvent,platform=process.platform,spawn:spawnProcess,spawnSync:spawnSync3,hostname:hostname2=os.hostname,guardRoot:chosenGuardRoot=platform==="win32"?windowsGuardRoot():path.join(os.tmpdir(),"ando-task-git"),lockToken=lockWindowsToken,guardGraceMs=GUARD_GRACE_MS,readGithubToken=ownerEnv=>ownerGithubToken({env:ownerEnv,gh:findCommand2("gh",ownerEnv.PATH)}),taskFolders=(()=>[]),inPlaceFolders=(()=>[]),checkoutRoot=null}){let spawn2=platform==="win32"?windowsSpawn(spawnProcess):spawnProcess,guardRoot=ownedGuardRoot(chosenGuardRoot,{platform});sweepStaleGuards(guardRoot);let commandEnv=null,env=()=>{commandEnv??=resolveCommandEnv({spawnSync:spawnSync3,env:process.env,platform});let folders=taskFolders();return folders.length===0?{...commandEnv}:{...commandEnv,PATH:trustedPath2(commandEnv.PATH??"",folders)}},machine=createMachineDescriber({machineFile:path.join(directory,"machine.json"),platform,spawn:spawn2,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}),emit=event=>{checkoutRoot!=null&&(event.kind==="done"||event.kind==="failed")&&markTaskEnded(checkoutRoot,event.runId),onEvent(outbox.push(event))};checkoutRoot!=null&&sweepTaskCheckouts(checkoutRoot);let runs=createLocalToolRuns({log:log2,createRuntime:(provider,{runId,cwd,instructions,policy,servers,githubToken=null})=>{if(provider==="claude-code"&&platform==="win32")return createWslClaudeRuntime({spawn:spawnProcess,spawnSync:spawnSync3,log:log2,cwd,instructions,runId,policy,servers,githubToken});let ownerEnv=env(),guard=prepareTaskGuard({dir:path.join(guardRoot,runId),cwd,policy,githubToken,ownerEnv,run:spawnSync3,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(error){log2.warn("[Local tools] could not remove a task's git guard",error)}},guardGraceMs),removing.unref?.()};try{let runtime=createTaskRuntime(provider,{spawn:spawn2,log:log2,cwd,instructions,policy,servers,guard,ownerEnv,platform,otherFolders:taskFolders().filter(folder=>cwd!==folder&&!cwd.startsWith(`${folder}${path.sep}`)),closedToCodex:checkoutRoot==null?[]:[checkoutRoot]});return{...runtime,close(){runtime.close(),removeGuard()}}}catch(error){throw removeGuard(),error}},emit,rememberUsage:(run3,checkpoint)=>outbox.rememberUsage(run3.runId,run3.workspaceId,checkpoint)}),starting=new Map,stoppedWhileStarting=new Set;async function placeRun(run3){if(limitsDontHold(run3,platform))return emit({runId:run3.runId,workspaceId:run3.workspaceId,...run3.ownerId==null?{}:{ownerId:run3.ownerId},kind:"failed",sessionId:run3.sessionId??null,error:LIMITS_DONT_HOLD_ERROR}),null;if(checkoutRoot==null||run3.policy.files==="never"||inPlaceFolders().includes(run3.folder)||!fs.existsSync(path.join(run3.folder,".git")))return{};try{let ownerEnv=env();return{folder:await prepareTaskCheckout({root:checkoutRoot,folder:run3.folder,runId:run3.runId,git:findCommand2("git",ownerEnv.PATH)??"git",env:ownerEnv,spawnSync:spawnSync3,platform,bare:run3.bareCheckout,onProgress:message=>log2.info?.(message)}),checkoutOf:run3.folder}}catch(error){return emit({runId:run3.runId,workspaceId:run3.workspaceId,...run3.ownerId==null?{}:{ownerId:run3.ownerId},kind:"failed",sessionId:run3.sessionId??null,error:`Couldn't set up a checkout of ${run3.folder}: ${error.message}`}),null}}async function startRun(input){let run3=parseRunRequest(input,platform);if(run3==null)return{status:"invalid"};let pending=starting.get(run3.runId);if(pending!=null)return await pending;if(outbox.recall(run3.runId,run3.workspaceId).ended)return{status:"finished"};let start=(async()=>{let githubToken=run3.policy.push==="never"?null:await readGithubToken(env()),saved=outbox.recall(run3.runId,run3.workspaceId);if(saved.ended)return{status:"finished"};let endStopped=()=>(emit({runId:run3.runId,workspaceId:run3.workspaceId,...run3.ownerId==null?{}:{ownerId:run3.ownerId},kind:"stopped",sessionId:run3.sessionId??saved.sessionId??null,...saved.usageCheckpoint?.usage==null?{}:{usage:saved.usageCheckpoint.usage}}),{status:"finished"});if(stoppedWhileStarting.has(run3.runId))return endStopped();let place=await placeRun(run3);return place==null?{status:"finished"}:stoppedWhileStarting.has(run3.runId)?endStopped():runs.start({...run3,...place,sessionId:run3.sessionId??saved.sessionId,usageCheckpoint:saved.usageCheckpoint},{githubToken})})();starting.set(run3.runId,start);try{return await start}finally{starting.delete(run3.runId),stoppedWhileStarting.delete(run3.runId)}}let testing=new Map;async function testTool(input){let run3=parseRunRequest({...input!=null&&typeof input=="object"?input:{},runId:randomUUID3(),prompt:"test"},platform);if(run3==null)return{status:"failed",error:"The Ando app couldn't read this test."};if(limitsDontHold(run3,platform))return{status:"failed",error:LIMITS_DONT_HOLD_ERROR};let key=JSON.stringify([run3.workspaceId,run3.provider,run3.folder,run3.policy,[...run3.servers].sort()]),pending=testing.get(key);if(pending!=null)return await pending;let test=runs.test(run3).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:spawn2,startRun,testTool,steerRun,stopRun,readSessions:input=>answerSessionRequest(input,{env:env(),platform}),runState:()=>({active:runs.list(),events:outbox.list()}),ackRunEvents:seqs=>outbox.ack(seqs),stopAll:()=>{runs.stopAll(),outbox.flush()}}}module.exports={createLocalToolHost:createLocalToolHost2,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(url){if(typeof url!="string")return null;let value=url.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 stat=statSync2(path.join(root,".git","config"));return stat.isFile()?{mtimeMs:stat.mtimeMs,size:stat.size}:null}catch{return null}}function readOrigin(folder,{execFile:execFile2,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 cached=originCache.get(folder);if(cached!=null&&cached.execFile===execFile2&&cached.mtimeMs===configStat.mtimeMs&&cached.size===configStat.size&&currentTime-cached.cachedAt<ORIGIN_CACHE_TTL_MS)return Promise.resolve(cached.origin)}return new Promise(resolve2=>{execFile2("git",["-C",folder,"remote","get-url","origin"],{env:{...env,GIT_TERMINAL_PROMPT:"0"},encoding:"utf8",timeout:READ_TIMEOUT_MS},(error,stdout)=>{let origin=error==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:execFile2,origin})}else originCache.delete(folder);resolve2(origin)})})}async function readFolderRemotes2(input,{execFile:execFile2=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:execFile2,env,exists,statSync:statSync2,now}));return remote==null?null:{folder,...remote}}))).filter(remote=>remote!=null)}module.exports={ORIGIN_CACHE_TTL_MS,normalizeGitRemote,readFolderRemotes:readFolderRemotes2}}});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"};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,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(`
102
110
 
103
111
  `)}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{await api.report(event.runId,toReport(event),event.seq)}catch(error){if(!isRefusal(error)){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(error=>{if(!isRefusal(error))throw error}),ended.add(runId)}function stop(run3){if(stopped.has(run3.run_id))return;stopped.add(run3.run_id);let pendingStart=starting.get(run3.run_id);pendingStart!=null&&host.stopRun({runId:run3.run_id})||(async()=>{await pendingStart,!ended.has(run3.run_id)&&(host.stopRun({runId:run3.run_id})||await api.report(run3.run_id,{kind:"stopped",session_id:run3.session_id}))})().catch(error=>{isRefusal(error)||(stopped.delete(run3.run_id),later(()=>onRuns(latestRuns)))})}function start(run3){handed.add(run3.run_id);let work=(async()=>{let claimed=run3.status==="queued"?await api.claim(run3.run_id):run3;if(claimed==null)return;let sessionId=claimed.session_id??sessions.get(claimed.run_id)??null,{status}=await host.startRun({runId:claimed.run_id,workspaceId,ownerId:null,provider:claimed.provider,folder:claimed.folder,prompt:claimed.prompt,sessionId,agentName:claimed.agent_name,policy:claimed.policy,servers:claimed.servers});status==="started"||status==="running"||status!=="finished"&&await endRefusedStart(claimed.run_id,sessionId,status)})().catch(error=>{log2(`Couldn't start ${run3.run_id}: ${String(error)}`),handed.delete(run3.run_id),later(()=>onRuns(latestRuns))});starting.set(run3.run_id,work),work.then(()=>{starting.get(run3.run_id)===work&&starting.delete(run3.run_id)})}function onRuns(runs){latestRuns=runs;for(let run3 of runs)ended.has(run3.run_id)||(run3.stop_requested?stop(run3):handed.has(run3.run_id)||start(run3))}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(error=>({status:"failed",error:`The Ando connector couldn't read the session: ${error instanceof Error?error.message:String(error)}`}));await api.answerSessionRequest(request.request_id,answer)})().catch(error=>{isRefusal(error)||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."}}});function browserOpener(url,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:[url]};if(platform==="win32"){let root=env.SystemRoot||env.windir;return root==null?null:{command:`${root}\\System32\\rundll32.exe`,args:["url.dll,FileProtocolHandler",url]}}if(!env.DISPLAY&&!env.WAYLAND_DISPLAY)return null;let command=find("xdg-open");return command==null?null:{command,args:[url]}}function openOnEnter(input,open){let opened=!1,onData=chunk=>{opened||!/[\r\n]/.test(String(chunk))||(opened=!0,open())};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,rmSync}from"node:fs";import{join as join2}from"node:path";async function selfCheck(input){let runId=randomUUID2(),ending=input.ended(runId),checkoutDir=input.checkoutRoot==null?null:join2(input.checkoutRoot,runId),markName=checkoutDir==null?`${MARK}-${runId}`:MARK,markPath=join2(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(resolve2=>{timer=setTimeout(()=>resolve2({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}`}:existsSync(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?(rmSync(checkoutDir,{recursive:!0,force:!0}),rmSync(`${checkoutDir}.ended`,{force:!0}),rmSync(`${checkoutDir}.task.json`,{force:!0})):rmSync(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{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:url=>paint(["cyan","underline"],url),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{spawnSync}from"node:child_process";import{copyFileSync,existsSync as existsSync2,mkdirSync,readFileSync,renameSync,rmSync as rmSync2,writeFileSync}from"node:fs";import{homedir as homedir2,userInfo}from"node:os";import{dirname as dirname2,join as join3}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(`
104
112
  `)}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(`
105
113
  `)}function detectService(run3=quiet,platform=process.platform){return platform==="darwin"?"launchd":platform!=="linux"?null:run3("systemctl",["--user","show-environment"]).status===0?"systemd":null}function unitPath(kind,env){let home=env.HOME||homedir2();return kind==="launchd"?join3(home,"Library","LaunchAgents",`${LAUNCHD_LABEL}.plist`):join3(env.XDG_CONFIG_HOME?.trim()||join3(home,".config"),"systemd","user",`${SYSTEMD_NAME}.service`)}function launchdDomain(run3){let uid=process.getuid?.()??0;return run3("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){mkdirSync(dirname2(path),{recursive:!0});let temporary=`${path}.${process.pid}.tmp`;writeFileSync(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)&&readFileSync(from).equals(readFileSync(to)))return!1;let temporary=`${to}.${process.pid}.tmp`;return copyFileSync(from,temporary),renameSync(temporary,to),!0}function stopNow(kind,run3){if(kind==="systemd"){run3("systemctl",["--user","disable","--now",SYSTEMD_NAME]);return}let target=`${launchdDomain(run3)}/${LAUNCHD_LABEL}`;run3("launchctl",["bootout",target]);for(let tries=0;tries<40;tries+=1){if(run3("launchctl",["print",target]).status!==0)return;pause(250)}}function serviceIsRunning(kind,run3=quiet){return kind==="systemd"?run3("systemctl",["--user","is-active","--quiet",SYSTEMD_NAME]).status===0:run3("launchctl",["print",`${launchdDomain(run3)}/${LAUNCHD_LABEL}`]).status===0}function installService(kind,input,run3=quiet){let path=unitPath(kind,input.envFile),text=kind==="systemd"?serviceUnit(input):launchdPlist(input),current=existsSync2(path)?readFileSync(path,"utf8"):null;if(current!=null&&serviceIsRunning(kind,run3)&&current===text&&!input.changed)return{started:!1,note:null};if(current!=null&&stopNow(kind,run3),writeWhole(path,text),kind==="launchd")return check(run3("launchctl",["bootstrap",launchdDomain(run3),path]),"start the background service"),{started:!0,note:null};check(run3("systemctl",["--user","daemon-reload"]),"load the service"),check(run3("systemctl",["--user","enable","--now",SYSTEMD_NAME]),"start the background service");let user=userInfo().username;return{started:!0,note:run3("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,run3=quiet){let kind=installedService(env);return kind==null?!1:(stopNow(kind,run3),rmSync2(unitPath(kind,env),{force:!0}),kind==="systemd"&&run3("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,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;");pause=ms=>Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,ms)}});import{chmod as chmod2,link,mkdir as mkdir2,readFile as readFile2,rename as rename2,rm,writeFile as writeFile2}from"node:fs/promises";import{homedir as homedir3,uptime}from"node:os";import{dirname as dirname3,isAbsolute,join as join4,relative}from"node:path";function configPath2(env){let base=env.XDG_CONFIG_HOME?.trim()||join4(env.HOME||homedir3(),".config");return join4(base,"ando","machine.json")}function stateDirectory(env){return join4(dirname3(configPath2(env)),"machine")}function holdsHome(folder,home=homedir3()){let inside=relative(folder,home);return inside===""||!inside.startsWith("..")&&!isAbsolute(inside)}function approvalCode(request){return`${request.slice(0,4)}-${request.slice(4,8)}`.toUpperCase()}async function readConfig(path){let text;try{text=await readFile2(path,"utf8")}catch(error){if(error.code==="ENOENT")return null;throw error}return JSON.parse(text)}async function writeConfig(path,config){await mkdir2(dirname3(path),{recursive:!0,mode:448});let temporary=`${path}.${process.pid}.tmp`;await writeFile2(temporary,`${JSON.stringify(config,null,2)}
106
114
  `,{mode:384}),await rename2(temporary,path),await chmod2(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(error){return error.code==="EPERM"}}async function runningConnector(directory){let holder=await readHolder(join4(directory,"connector.lock"));return holder!=null&&holder!=="gone"&&holderIsAlive(holder)?holder.pid:null}async function readHolder(path){try{let holder=JSON.parse(await readFile2(path,"utf8"));return Number.isInteger(holder?.pid)&&Number.isFinite(holder?.bootedAt)?holder:null}catch(error){return error.code==="ENOENT"?"gone":null}}async function lockMachine(directory){await mkdir2(directory,{recursive:!0,mode:448});let path=join4(directory,"connector.lock"),claim=`${path}.${process.pid}.claim`;await writeFile2(claim,JSON.stringify({pid:process.pid,bootedAt:bootTime()}),{mode:384});try{for(let attempt=0;attempt<3;attempt+=1){try{return await link(claim,path),()=>rm(path,{force:!0})}catch(error){if(error.code!=="EEXIST")throw error}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 rename2(path,stale).then(()=>rm(stale,{force:!0}),()=>{})}}finally{await rm(claim,{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","OPENAI_API_KEY","OPENAI_BASE_URL","HTTP_PROXY","HTTPS_PROXY","NO_PROXY","http_proxy","https_proxy","no_proxy"])}});var cli_exports={};__export(cli_exports,{runMachine:()=>runMachine});import{spawn,spawnSync as spawnSync2}from"node:child_process";import{createHash,randomBytes}from"node:crypto";import{appendFileSync,existsSync as existsSync3,mkdirSync as mkdirSync2,readdirSync,readFileSync as readFileSync2,realpathSync,statSync,writeFileSync as writeFileSync2}from"node:fs";import{homedir as homedir4,hostname}from"node:os";import{join as join5,resolve}from"node:path";import{parseArgs as parseArgs2}from"node:util";function log(message,tone="plain",shown=message){console.log(terminal.line(tone,shown));try{let file=logFile();if(existsSync3(file)&&statSync(file).size>MAX_LOG_BYTES){let content=readFileSync2(file,"utf8"),half=Math.floor(content.length/2),nextNewline=content.indexOf(`
107
115
  `,half),kept=nextNewline>=0?content.slice(nextNewline+1):content.slice(half);writeFileSync2(file,kept,{mode:384})}appendFileSync(file,`${new Date().toISOString()} ${message}
108
- `,{mode:384})}catch{}}function createHost(onEvent,taskFolders=()=>[],inPlaceFolders=()=>[]){return(0,import_host.createLocalToolHost)({directory:stateDirectory(process.env),appName:"Ando machine",log:logger,spawn,spawnSync:spawnSync2,onEvent,taskFolders,inPlaceFolders,checkoutRoot:CHECKOUT_ROOT})}function refusedHere(tool){return process.platform==="linux"&&tool==="codex"}function linuxSandboxProblem(env){if(process.platform!=="linux")return null;let missing=["bwrap","socat"].filter(tool=>(0,import_toolchain.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 tried=spawnSync2((0,import_toolchain.findCommand)("bwrap",env.PATH),["--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 withinTimeout(work,message,timeout=CONNECT_TIMEOUT_MS){let timer;try{return await Promise.race([work,new Promise((_,reject)=>{timer=setTimeout(()=>reject(new Error(message)),timeout)})])}finally{clearTimeout(timer)}}async function fromApproval(client){let secret=randomBytes(32).toString("hex"),request=createHash("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 machine in your browser, on any device:";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=>(0,import_toolchain.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)=>spawn(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(web.machineCollectConnect,{secret}),"Couldn't reach Ando.");if(machine!=null)return machine;await new Promise(done=>setTimeout(done,APPROVAL_POLL_MS))}throw new Error("The approval link expired. Run this again.")}finally{stopListening()}}function usableFolders(folders,mode=null){for(let folder of folders)if(!existsSync3(folder))throw new Error(`${folder} doesn't exist here.`);let absolute=[...new Set(folders.map(folder=>realpathSync(folder)))];for(let folder of absolute)if(holdsHome(folder))throw new Error(`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=spawnSync2("git",["-C",folder,"rev-parse","--show-toplevel"],{encoding:"utf8"});if(top.status!==0){if(mode==="checkout")throw new Error(`${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=realpathSync(top.stdout.trim());if(repoRoot!==folder&&mode!=="in-place")throw new Error(`${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]}async function openSetup(folders,inPlaceFolders=[]){let endings=new Map,host=createHost(event=>{host.ackRunEvents([event.seq]),isEnding(event.kind)&&endings.get(event.runId)?.(event)},()=>folders,()=>inPlaceFolders),{tools,signedOut}=await host.machine.get(),sandboxProblem=linuxSandboxProblem(host.env()),ready=tools.filter(tool=>!signedOut.includes(tool)&&!refusedHere(tool)&&(tool!=="claude-code"||sandboxProblem==null));if(tools.some(refusedHere)&&logger.warn(CODEX_ON_LINUX),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(resolve2=>setup.endings.set(runId,resolve2))});if(!check2.ok)throw new Error(`This machine 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 machine is ready.`,"ok")}async function connect(getMachine,url,folders,timeout=CONNECT_TIMEOUT_MS,mode=null){if(folders.length===0)throw new Error("Name a folder tasks may use, with --folder <path>.");let{absolute,inPlace}=usableFolders(folders,mode),inPlaceFolders=mergeInPlaceFolders(void 0,absolute,inPlace,mode),setup=await openSetup(absolute,inPlaceFolders),client=newClient(url);try{let machine=await withinTimeout(getMachine(client),`Couldn't reach Ando at ${url}.`,timeout),config={url,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}:{}};await writeConfig(configPath2(process.env),config);let connected=await connectPendingTools(config,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 bringUpToDate(config,folders,canCheck,mode=null){let{absolute,inPlace}=usableFolders(folders,mode),client=newClient(config.url),setup=null;try{let current=await connectPendingTools(config,client),tools=await connectedFolders(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),inPlaceChanged=JSON.stringify(inPlaceFolders)!==JSON.stringify(current.inPlaceFolders??[]),{inPlaceFolders:_prevInPlace,...restConfig}=current,nextConfig={...restConfig,...inPlaceFolders.length>0?{inPlaceFolders}:{}};if(inPlaceChanged&&await writeConfig(configPath2(process.env),nextConfig),canCheck&&(nextConfig.checked!==!0||added.length>0)&&(setup=await openSetup(all,inPlaceFolders)),added.length>0){let targets=tools.length>0?tools:(setup?.ready??[]).map(provider=>({provider,folders:[]}));if(targets.length===0)throw new Error("No tool is connected on this machine. Connect one in Studio first.");await Promise.all(targets.map(target=>withinTimeout(client.mutation(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");if(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 connectPendingTools(config,client){if(config.pendingTools==null)return config;let{folders}=config.pendingTools,providers=config.pendingTools.providers;for(;providers.length>0;){let[provider,...rest]=providers;await withinTimeout(client.mutation(web.machineConnectTool,{token:config.token,provider,folders}),`Couldn't reach Ando at ${config.url}.`),providers=rest,await writeConfig(configPath2(process.env),{...config,pendingTools:{providers,folders}})}let{pendingTools:_done,...finished}=config;return await writeConfig(configPath2(process.env),finished),log(`Connected ${config.machineName}.`,"ok"),finished}function readTask(runId){try{return JSON.parse(readFileSync2(taskRecordPath(runId),"utf8"))}catch{return{}}}function recordTask(runId,fields){try{mkdirSync2(CHECKOUT_ROOT,{recursive:!0,mode:448}),writeFileSync2(taskRecordPath(runId),JSON.stringify({...readTask(runId),...fields}),{mode:384})}catch{}}function listTasks(){let names=[];try{names=readdirSync(CHECKOUT_ROOT)}catch{return[]}return names.filter(name=>name.endsWith(".task.json")).map(name=>{let runId=name.slice(0,-10);return{runId,...readTask(runId)}}).sort((a,b)=>(b.startedAt??0)-(a.startedAt??0))}function readReady(){try{return JSON.parse(readFileSync2(readyPath(),"utf8"))}catch{return null}}async function printStatus(asJson){let config=await readConfig(configPath2(process.env)),pid=await runningConnector(stateDirectory(process.env)),ready=readReady(),tasks=listTasks().slice(0,10),inPlace=new Set(ready?.inPlaceFolders??config?.inPlaceFolders??[]);if(asJson){console.log(JSON.stringify({connected:config!=null,machine:config?.machineName??null,running:pid!=null,pid,background:installedService(process.env),version:ready?.version??null,folders:ready?.folders??[],...inPlace.size>0?{inPlaceFolders:[...inPlace]}:{},tasks:tasks.map(({sessionId:_session,...task})=>task)},null,2));return}if(config==null){console.log("Not connected. Run ando up in a repository.");return}let background=installedService(process.env);console.log(`${terminal.strong(config.machineName)}: ${terminal.state(pid==null?"stopped":background==null?"running":"running in the background")}`);for(let folder of ready?.folders??[])console.log(` ${folder}${inPlace.has(folder)?terminal.quiet(" (in place)"):""}`);for(let task of tasks){let status=task.status??"running";console.log(` ${terminal.quiet(task.runId.slice(0,8))} ${terminal.state(status)}${" ".repeat(Math.max(0,7-status.length))} ${task.provider??"?"} ${terminal.quiet(task.folder??"")}`)}}function printLogs(follow,lines){if(!existsSync3(logFile())){console.log("No logs yet.");return}let lineCount;if(lines!==void 0){let parsed=Number(lines);if(!Number.isInteger(parsed)||parsed<=0)throw new Error("--lines must be a positive integer.");lineCount=parsed}if(follow){let tailArgs=lineCount!==void 0?["-n",String(lineCount),"-F",logFile()]:["-F",logFile()];spawnSync2("tail",tailArgs,{stdio:"inherit"});return}let content=readFileSync2(logFile(),"utf8");if(lineCount===void 0){process.stdout.write(content);return}let tail=content.replace(/\n$/u,"").split(`
116
+ `,{mode:384})}catch{}}function createHost(onEvent,taskFolders=()=>[],inPlaceFolders=()=>[]){return(0,import_host.createLocalToolHost)({directory:stateDirectory(process.env),appName:"Ando machine",log:logger,spawn,spawnSync:spawnSync2,onEvent,taskFolders,inPlaceFolders,checkoutRoot:CHECKOUT_ROOT})}function refusedHere(tool){return process.platform==="linux"&&tool==="codex"}function linuxSandboxProblem(env){if(process.platform!=="linux")return null;let missing=["bwrap","socat"].filter(tool=>(0,import_toolchain.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 tried=spawnSync2((0,import_toolchain.findCommand)("bwrap",env.PATH),["--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 withinTimeout(work,message,timeout=CONNECT_TIMEOUT_MS){let timer;try{return await Promise.race([work,new Promise((_,reject)=>{timer=setTimeout(()=>reject(new Error(message)),timeout)})])}finally{clearTimeout(timer)}}async function fromApproval(client){let secret=randomBytes(32).toString("hex"),request=createHash("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=>(0,import_toolchain.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)=>spawn(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(web.machineCollectConnect,{secret}),"Couldn't reach Ando.");if(machine!=null)return machine;await new Promise(done=>setTimeout(done,APPROVAL_POLL_MS))}throw new Error("The approval link expired. Run this again.")}finally{stopListening()}}function usableFolders(folders,mode=null){for(let folder of folders)if(!existsSync3(folder))throw new Error(`${folder} doesn't exist here.`);let absolute=[...new Set(folders.map(folder=>realpathSync(folder)))];for(let folder of absolute)if(holdsHome(folder))throw new Error(`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=spawnSync2("git",["-C",folder,"rev-parse","--show-toplevel"],{encoding:"utf8"});if(top.status!==0){if(mode==="checkout")throw new Error(`${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=realpathSync(top.stdout.trim());if(repoRoot!==folder&&mode!=="in-place")throw new Error(`${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]}async function openSetup(folders,inPlaceFolders=[]){let endings=new Map,host=createHost(event=>{host.ackRunEvents([event.seq]),isEnding(event.kind)&&endings.get(event.runId)?.(event)},()=>folders,()=>inPlaceFolders),{tools,signedOut}=await host.machine.get(),sandboxProblem=linuxSandboxProblem(host.env()),ready=tools.filter(tool=>!signedOut.includes(tool)&&!refusedHere(tool)&&(tool!=="claude-code"||sandboxProblem==null));if(tools.some(refusedHere)&&logger.warn(CODEX_ON_LINUX),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(resolve2=>setup.endings.set(runId,resolve2))});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 connect(getMachine,url,folders,timeout=CONNECT_TIMEOUT_MS,mode=null){if(folders.length===0)throw new Error("Name a folder tasks may use, with --folder <path>.");let{absolute,inPlace}=usableFolders(folders,mode),inPlaceFolders=mergeInPlaceFolders(void 0,absolute,inPlace,mode),setup=await openSetup(absolute,inPlaceFolders),client=newClient(url);try{let machine=await withinTimeout(getMachine(client),`Couldn't reach Ando at ${url}.`,timeout),config={url,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}:{}};await writeConfig(configPath2(process.env),config);let connected=await connectPendingTools(config,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 bringUpToDate(config,folders,canCheck,mode=null){let{absolute,inPlace}=usableFolders(folders,mode),client=newClient(config.url),setup=null;try{let current=await connectPendingTools(config,client),tools=await connectedFolders(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),inPlaceChanged=JSON.stringify(inPlaceFolders)!==JSON.stringify(current.inPlaceFolders??[]),{inPlaceFolders:_prevInPlace,...restConfig}=current,nextConfig={...restConfig,...inPlaceFolders.length>0?{inPlaceFolders}:{}};if(inPlaceChanged&&await writeConfig(configPath2(process.env),nextConfig),canCheck&&(nextConfig.checked!==!0||added.length>0)&&(setup=await openSetup(all,inPlaceFolders)),added.length>0){let targets=tools.length>0?tools:(setup?.ready??[]).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(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");if(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 connectPendingTools(config,client){if(config.pendingTools==null)return config;let{folders}=config.pendingTools,providers=config.pendingTools.providers;for(;providers.length>0;){let[provider,...rest]=providers;await withinTimeout(client.mutation(web.machineConnectTool,{token:config.token,provider,folders}),`Couldn't reach Ando at ${config.url}.`),providers=rest,await writeConfig(configPath2(process.env),{...config,pendingTools:{providers,folders}})}let{pendingTools:_done,...finished}=config;return await writeConfig(configPath2(process.env),finished),log(`Connected ${config.machineName}.`,"ok"),finished}function readTask(runId){try{return JSON.parse(readFileSync2(taskRecordPath(runId),"utf8"))}catch{return{}}}function recordTask(runId,fields){try{mkdirSync2(CHECKOUT_ROOT,{recursive:!0,mode:448}),writeFileSync2(taskRecordPath(runId),JSON.stringify({...readTask(runId),...fields}),{mode:384})}catch{}}function listTasks(){let names=[];try{names=readdirSync(CHECKOUT_ROOT)}catch{return[]}return names.filter(name=>name.endsWith(".task.json")).map(name=>{let runId=name.slice(0,-10);return{runId,...readTask(runId)}}).sort((a,b)=>(b.startedAt??0)-(a.startedAt??0))}function readReady(){try{return JSON.parse(readFileSync2(readyPath(),"utf8"))}catch{return null}}async function printStatus(asJson){let config=await readConfig(configPath2(process.env)),pid=await runningConnector(stateDirectory(process.env)),ready=readReady(),tasks=listTasks().slice(0,10),inPlace=new Set(ready?.inPlaceFolders??config?.inPlaceFolders??[]);if(asJson){console.log(JSON.stringify({connected:config!=null,machine:config?.machineName??null,running:pid!=null,pid,background:installedService(process.env),version:ready?.version??null,folders:ready?.folders??[],...inPlace.size>0?{inPlaceFolders:[...inPlace]}:{},tasks:tasks.map(({sessionId:_session,...task})=>task)},null,2));return}if(config==null){console.log("Not connected. Run ando up in a repository.");return}let background=installedService(process.env);console.log(`${terminal.strong(config.machineName)}: ${terminal.state(pid==null?"stopped":background==null?"running":"running in the background")}`);for(let folder of ready?.folders??[])console.log(` ${folder}${inPlace.has(folder)?terminal.quiet(" (in place)"):""}`);for(let task of tasks){let status=task.status??"running";console.log(` ${terminal.quiet(task.runId.slice(0,8))} ${terminal.state(status)}${" ".repeat(Math.max(0,7-status.length))} ${task.provider??"?"} ${terminal.quiet(task.folder??"")}`)}}function printLogs(follow,lines){if(!existsSync3(logFile())){console.log("No logs yet.");return}let lineCount;if(lines!==void 0){let parsed=Number(lines);if(!Number.isInteger(parsed)||parsed<=0)throw new Error("--lines must be a positive integer.");lineCount=parsed}if(follow){let tailArgs=lineCount!==void 0?["-n",String(lineCount),"-F",logFile()]:["-F",logFile()];spawnSync2("tail",tailArgs,{stdio:"inherit"});return}let content=readFileSync2(logFile(),"utf8");if(lineCount===void 0){process.stdout.write(content);return}let tail=content.replace(/\n$/u,"").split(`
109
117
  `).slice(-lineCount).join(`
110
118
  `);tail.length>0&&process.stdout.write(`${tail}
111
119
  `)}async function stopConnector(){let state=stateDirectory(process.env),removed=removeService(process.env),running=await runningConnector(state);if(running==null&&!removed){console.log("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))}console.log("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:homedir4(),stdio:"inherit"};if(installed){let global=spawnSync2("npm",["install","-g","@andocorp/cli@latest"],options);if(global.status!==0)return global.status??1}return spawnSync2("npx",["-y","@andocorp/cli@latest","up"],options).status??1}function attach(prefix){let task=listTasks().find(candidate=>prefix==null||candidate.runId.startsWith(prefix));if(task?.sessionId==null)throw new Error("No task with a session here. See ando status.");let checkoutCwd=join5(CHECKOUT_ROOT,task.runId),cwd=existsSync3(checkoutCwd)?checkoutCwd:task.folder!=null&&existsSync3(task.folder)?task.folder:null;if(cwd==null)throw new Error(`Task ${task.runId.slice(0,8)}'s checkout is no longer on disk.`);let[command,args]=task.provider==="codex"?["codex",["resume",task.sessionId]]:["claude",["--resume",task.sessionId]];return spawnSync2(command,args,{cwd,stdio:"inherit"}).status??1}async function run(config,release,version2){let client=newClient(config.url);await connectPendingTools(config,client);let{token,workspaceId}=config,folders=[],inPlaceFolders=config.inPlaceFolders??[],folderSeq=0,readFolders=async()=>{let seq=++folderSeq,[connections,latestConfig]=await Promise.all([client.query(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),folders};await withinTimeout(readFolders(),`Couldn't reach Ando at ${config.url}.`);let agent=null,host=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),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),status:"running",startedAt:Date.now()}),startRun(input)),agent=createMachineAgent({workspaceId,host,log,isRefusal:error=>error instanceof ConvexError,api:{claim:async runId=>(await readFolders(),client.mutation(web.machineClaimRun,{token,runId})),report:(runId,event,eventSeq)=>client.mutation(web.machineReportRun,{token,runId,event,...eventSeq==null?{}:{eventSeq}}),markContext:(runId,through)=>client.mutation(web.machineMarkRunContext,{token,runId,through}),answerSessionRequest:(requestId,answer)=>client.mutation(web.machineAnswerSessionRequest,{token,requestId,...answer.status==="done"?{result:answer.result}:{error:answer.error}})}}),agent.load();let unsubscribe=()=>{},resubscribing,fail=error=>{if(error instanceof ConvexError){logger.error("Ando stopped this machine's connection",error),shutdown(0);return}logger.warn("Lost sight of Ando's tasks; trying again",error),clearTimeout(resubscribing),resubscribing=setTimeout(subscribe,RESUBSCRIBE_MS)};function subscribe(){unsubscribe();let runs=client.onUpdate(web.machineRuns,{token},rows=>agent?.onRuns(rows),fail),threads=client.onUpdate(web.machineRunThreadContext,{token},rows=>agent?.onThreads(rows),fail),sessions=client.onUpdate(web.machineSessionRequests,{token},rows=>agent?.onSessionRequests(rows),fail);unsubscribe=()=>{runs(),threads(),sessions()}}subscribe();let saveReady=()=>writeFileSync2(readyPath(),JSON.stringify({pid:process.pid,version:version2,folders,...inPlaceFolders.length>0?{inPlaceFolders}:{}}),{mode:384}),heartbeat=async()=>{try{let[described]=await Promise.all([host.machine.get(),readFolders()]);saveReady(),await client.mutation(web.machineReport,{token,signedOutProviders:described.signedOut,servers:Object.entries(described.servers).map(([provider,names])=>({provider,names})),remotes:await(0,import_remotes.readFolderRemotes)(folders,{env:host.env()}),activeRunIds:agent?.activeRunIds()??[],sleeping:!1,sessionReads:typeof host.readSessions=="function",...described.key==null?{}:{machineKey:described.key}})}catch(error){logger.warn("Couldn't report in to Ando; trying again",error)}};heartbeat();let timer=setInterval(()=>{heartbeat()},HEARTBEAT_MS),stopping=!1;function shutdown(code2){stopping||(stopping=!0,clearInterval(timer),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)),saveReady(),log(`${config.machineName} is ready for tasks.`,"ok"),await new Promise(()=>{})}function saveCarriedEnv(){let path=carriedEnvPath(),saved=readCarriedEnv(),merged={...saved,...carriedEnv(process.env)},changed=JSON.stringify(merged)!==JSON.stringify(saved);return changed&&(writeFileSync2(path,JSON.stringify(merged),{mode:384}),log(`Kept for the background connector: ${Object.keys(merged).join(", ")}`)),changed}function readCarriedEnv(){try{return JSON.parse(readFileSync2(carriedEnvPath(),"utf8"))}catch{return{}}}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(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:(0,import_command_env.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(),spawn(process.execPath,[script,"run"],{detached:!0,stdio:"ignore"}).unref(),await waitUntilReady(null),log("Running in the background until this server restarts.")}async function runMachine(argv,version2){let{positionals,values}=parseArgs2({args:argv,allowPositionals:!0,options:{url:{type:"string"},folder:{type:"string",multiple:!0},"in-place":{type:"boolean"},checkout:{type:"boolean"},foreground:{type:"boolean"},json:{type:"boolean"},follow:{type:"boolean",short:"f"},lines:{type:"string",short:"n"},help:{type:"boolean",short:"h"}}});if(values["in-place"]===!0&&values.checkout===!0)throw new Error("Pass either --in-place or --checkout, not both.");let mode=values["in-place"]===!0?"in-place":values.checkout===!0?"checkout":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 new Error(USAGE);let given=(values.folder??[]).map(folder=>resolve(folder)),repository=spawnSync2("git",["rev-parse","--show-toplevel"],{encoding:"utf8"}),top=repository.status===0?repository.stdout.trim():null,defaultFolder=top!=null&&!holdsHome(top)?[top]:mode==="in-place"&&!holdsHome(here)?[here]:[],folders=given.length>0?given:defaultFolder;process.chdir(homedir4());let state=stateDirectory(process.env);try{let saved=await readConfig(configPath2(process.env)),running=await runningConnector(state);if(command==="up"&&saved!=null&&running!=null){await bringUpToDate(saved,folders,!1,mode);let service=installedService(process.env);if(values.foreground!==!0&&service!=null&&serviceIsRunning(service)){await keepRunning(service,running);return}let runningVersion=readReady()?.version;if(runningVersion!=null&&runningVersion!==version2)throw new Error(`The connector running here is ${runningVersion}, so this one (${version2}) hasn't taken over. Run ando stop, then start it again.`);log(`The connector is already running (process ${running}).`);return}command==="run"&&Object.assign(process.env,readCarriedEnv());let release=await lockMachine(state);try{let config;if(command==="connect"){if(code2==null||values.url==null)throw new Error(USAGE);config=await connect(fromCode(code2),values.url,folders,CONNECT_TIMEOUT_MS,mode)}else if(saved!=null)config=command==="up"?await bringUpToDate(saved,folders,!0,mode):saved;else if(command==="up")config=await connect(fromApproval,values.url??DEFAULT_URL,folders,APPROVAL_TIMEOUT_MS,mode);else throw new Error("Not connected yet. Run ando up in a repository.");let kind=command==="run"||values.foreground===!0?null:detectService();if(kind!=null){await release(),await keepRunning(kind,null);return}if(command==="connect"){await release(),await detach();return}command==="up"&&values.foreground!==!0&&log("There's no service manager here, so this stays running in this terminal."),await run(config,release,version2)}catch(error){throw await release(),error}}catch(error){throw error instanceof ConvexError&&error.data?.message!=null?new Error(String(error.data.message)):error}}var import_host,import_remotes,import_toolchain,import_command_env,HEARTBEAT_MS,DEFAULT_URL,DEFAULT_APP_URL,APPROVAL_POLL_MS,APPROVAL_WAIT_MS,MAX_LOG_BYTES,CONNECT_TIMEOUT_MS,APPROVAL_TIMEOUT_MS,web,USAGE,newClient,CHECKOUT_ROOT,READY_WAIT_MS,STOP_WAIT_MS,RESUBSCRIBE_MS,readyPath,carriedEnvPath,connectorPath,logFile,terminal,logger,BWRAP_APPARMOR_FIX,CODEX_ON_LINUX,fromCode,connectedFolders,taskRecordPath,init_cli=__esm({"../machine/src/cli.ts"(){"use strict";init_simple_client();init_api();init_errors();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_agent();init_open_link();init_self_check();init_terminal();init_service();init_config();HEARTBEAT_MS=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_MS=3e4,APPROVAL_TIMEOUT_MS=11*6e4,web=anyApi.web,USAGE=`Let your Ando agents work on this server. It connects out to Ando, so nothing
@@ -139,7 +147,7 @@ ${fence}`}function mention(membershipId,name){let label=name.replace(/[|>\n]/gu,
139
147
  ${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:
140
148
  ${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(error){if(error instanceof CliError&&error.exitCode===ExitCode.notFound)return null;throw error}}))).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:
141
149
  ${listCandidates(exact.map(agentLabel))}`):new CliError(ExitCode.notFound,agents.length===0?`No agent named @${name} in this workspace.`:`No agent named @${name}. Similar agents:
142
- ${listCandidates(agents.map(agentLabel))}`)}var systemClock={now:()=>Date.now(),sleep:ms=>new Promise(resolve2=>setTimeout(resolve2,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(error){if(error instanceof CliError&&error.exitCode===ExitCode.notFound){missingIds.add(pendingId),pendingId=null;continue}throw error}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(error){if(!(error instanceof TransientApiError))throw error;input.onTransientError?.(error)}let remaining=deadline-clock.now();if(remaining<=0)return null;await clock.sleep(Math.min(interval,remaining))}}var VERSION="0.5.4",HELP=`ando \u2014 use Ando from a terminal
150
+ ${listCandidates(agents.map(agentLabel))}`)}var systemClock={now:()=>Date.now(),sleep:ms=>new Promise(resolve2=>setTimeout(resolve2,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(error){if(error instanceof CliError&&error.exitCode===ExitCode.notFound){missingIds.add(pendingId),pendingId=null;continue}throw error}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(error){if(!(error instanceof TransientApiError))throw error;input.onTransientError?.(error)}let remaining=deadline-clock.now();if(remaining<=0)return null;await clock.sleep(Math.min(interval,remaining))}}var VERSION="0.5.5",HELP=`ando \u2014 use Ando from a terminal
143
151
 
144
152
  Usage:
145
153
  ando up [--folder <path>...] Let your agents work on this server: connect
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@andocorp/cli",
3
- "version": "0.5.4",
3
+ "version": "0.5.5",
4
4
  "description": "Use Ando from a terminal: post to channels, ask agents, and let agents work on your server.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -23,7 +23,7 @@
23
23
  "cli",
24
24
  "team-chat"
25
25
  ],
26
- "homepage": "https://docs.ando.so/docs/external-agents#connect-a-server",
26
+ "homepage": "https://docs.ando.so/docs/connecting-apps-to-ando/claude-code-on-a-server",
27
27
  "repository": {
28
28
  "type": "git",
29
29
  "url": "git+https://github.com/Ando-Corporation/ando.git",