@andocorp/cli 0.5.2 → 0.5.4

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 +44 -17
  2. package/dist/cli.js +11 -11
  3. package/package.json +12 -1
package/README.md CHANGED
@@ -18,25 +18,52 @@ team. `--json` prints the API's message object instead, for scripts.
18
18
 
19
19
  ## Let your agents work on a server
20
20
 
21
- In the repository agents should work in, run this and approve the link it prints,
22
- on any device. The server connects out to Ando: you open no ports and share no
23
- SSH keys.
21
+ In the repository agents should work in, run this and approve the link it prints.
22
+ At a computer with a browser, press Enter to open it; over SSH, open it on any
23
+ device. The server connects out to Ando: you open no ports and share no SSH keys.
24
24
 
25
25
  ```sh
26
26
  npx -y @andocorp/cli up
27
27
  ```
28
28
 
29
- Each task works in its own checkout under `~/.ando-tasks`, on its own branch, so
30
- your folder is never touched; gitignored `.env*` files, `.claude/settings.local.json`,
31
- gitignored symlinks (such as `code -> ../code`), and paths matched by
32
- `.worktreeinclude` are carried over automatically, and linked companion folders
33
- stay accessible. Pass `--in-place` (`npx -y @andocorp/cli up --in-place`) to run
34
- tasks directly in the folder itself instead (`--checkout` switches back). `up`
35
- keeps the connector running in the background and starts it again after a restart.
36
- Run it again in another repository to add that one. `ando status`, `logs`, `update`
37
- and `stop` manage it, and `ando attach` opens a task's session in your terminal.
38
- In a container, `up` stays in the foreground: keep `~/.config/ando` on a volume
39
- to reconnect without approving again.
29
+ `up` then runs one small real task to check the machine works, saying what it is
30
+ doing, and keeps the connector running in the background, starting it again
31
+ after a restart. Run it again in another repository to add that one.
32
+
33
+ Each task works in its own checkout under `~/.ando-tasks`, on its own branch,
34
+ made from what you've committed, so your folder is never touched. The checkout
35
+ also brings what git doesn't hold:
36
+
37
+ - gitignored `.env*` files and `.claude/settings.local.json`
38
+ - gitignored symlinks (such as `code -> ../code`); the task may open what they
39
+ link to
40
+ - gitignored paths that `.worktreeinclude` names
41
+ - `node_modules`, `.venv` and `venv` at the top of the repository, copied
42
+ without using more disk where the file system supports it (APFS, Btrfs, XFS)
43
+
44
+ Uncommitted changes to tracked files stay out, and nothing is taken from inside
45
+ an ignored folder unless `.worktreeinclude` names it.
46
+
47
+ | Command | What it does |
48
+ | ------------------------------ | --------------------------------------------------------------------------- |
49
+ | `ando up [--folder <path>...]` | Connect a repository and keep it connected |
50
+ | `ando up --in-place` | Run tasks in the folder itself, not a checkout (`--checkout` switches back) |
51
+ | `ando up --foreground` | Stay in this terminal instead of the background |
52
+ | `ando status [--json]` | What's connected, and recent tasks |
53
+ | `ando logs [-f] [-n <lines>]` | What the connector has been doing |
54
+ | `ando attach [task]` | Open a task's session here, outside its limits |
55
+ | `ando update` | Move to the newest connector; tasks pick up where they left off |
56
+ | `ando stop` | Stop the connector until the next `ando up` |
57
+
58
+ If the account has an `~/.aws` folder, a task's `aws` commands use it, with
59
+ `AWS_PROFILE` and `AWS_REGION` from the shell where you ran `up`. A task can
60
+ refresh single sign-on tokens but cannot change `~/.aws/config` or
61
+ `~/.aws/credentials`.
62
+
63
+ At a terminal, output is coloured and marked by how each step went. Piped
64
+ output, `NO_COLOR` and `ando logs` get plain text. In a container, `up` stays in
65
+ the foreground: keep `~/.config/ando` on a volume to reconnect without approving
66
+ again.
40
67
 
41
68
  Tasks run as the account that started it, so use one with only what agents need.
42
69
  Linux tasks run in Claude Code, which needs `bubblewrap` and `socat`; `ando up`
@@ -89,6 +116,6 @@ pnpm --filter @andocorp/cli run build && node packages/cli/dist/cli.js --help
89
116
  Against a local stack, log in with `--api-url http://127.0.0.1:<convex site
90
117
  port>/public-api/v1 --web-url http://dev.ando.so:<web port>`.
91
118
 
92
- The package is `private` until its npm name is settled: `@andocorp/cli`
93
- 0.3.2 on npm is the earlier Toolkit CLI, which this package does not replace
94
- command for command.
119
+ A merge to main that changes `version` in `package.json` publishes that version
120
+ to npm (`.github/workflows/publish-cli.yml`). Bump `VERSION` in `src/run.ts` in
121
+ the same change.
package/dist/cli.js CHANGED
@@ -16,11 +16,11 @@ ${thought}`;function createThoughtReporter({post,remove,log:log2,schedule=setTim
16
16
 
17
17
  `)||turn.last||"");let unanswered=turn.answerSteers?turn.steers.filter(steer=>!steer.answered):[];for(let steer of unanswered)steer.handedOn=!0;if(unanswered.length>0){startTurn(state,threadId,turn,unansweredSteersText(unanswered)).catch(turn.reject);return}turn.resolve(turn.replies.filter(Boolean).join(`
18
18
 
19
- `))}async function startTurn(state,threadId,turn,text){Object.assign(turn,{final:[],last:"",turnId:null,steers:[]}),state.turns.set(threadId,turn);try{let response=await request(state,"turn/start",{threadId,input:[{type:"text",text,text_elements:[]}]});turn.turnId??=response?.turn?.id??null}catch(error){throw state.turns.get(threadId)===turn&&state.turns.delete(threadId),error}}async function openThread(state,sessionId){let shared={cwd,approvalPolicy:"never",...sandbox==null?{}:{sandbox},developerInstructions:instructions};if(sessionId&&state.loadedThreads.has(sessionId))return{threadId:sessionId,resumed:!0};if(sessionId)try{return await request(state,"thread/resume",{...shared,threadId:sessionId}),state.loadedThreads.add(sessionId),{threadId:sessionId,resumed:!0}}catch(error){log2.warn("[Local agents] could not resume Codex thread",error)}let threadId=(await request(state,"thread/start",shared))?.thread?.id;if(typeof threadId!="string")throw new Error("Codex returned no thread");return state.loadedThreads.add(threadId),{threadId,resumed:!1}}return{async runTurn({key,sessionId,text,newSessionText,onThought,onStarted,onSession,answerSteers=!1}){if(closed)throw stopped();server??=startServer();let state=server;await state.ready;let{threadId,resumed}=await openThread(state,sessionId);onSession?.(threadId);let input=resumed||!newSessionText?text:await newSessionText();if(closed)throw stopped();state.threadsByKey.set(key,threadId);let turn={onThought,answerSteers,replies:[]},reply=new Promise((resolve2,reject)=>{Object.assign(turn,{resolve:resolve2,reject})});await startTurn(state,threadId,turn,input),onStarted?.();let answered=await reply,usage=state.usageByThread.get(threadId);return{sessionId:threadId,reply:answered,...usage==null?{}:{usage}}},async steer({key,text}){let state=server,threadId=state?.threadsByKey.get(key),turn=threadId&&state.turns.get(threadId);if(!turn?.turnId)return!1;let steers=turn.answerSteers?turn.steers:null,steer={id:randomUUID3(),text,taken:!1,answered:!1,handedOn:!1};steers?.push(steer);try{return await request(state,"turn/steer",{threadId,input:[{type:"text",text,text_elements:[]}],expectedTurnId:turn.turnId,...steers==null?{}:{clientUserMessageId:steer.id}}),!0}catch(error){if(steer.handedOn)return!0;if(steers?.splice(steers.indexOf(steer),1),/no active turn|expected.*turn|turn.*mismatch/i.test(error.message))return!1;throw error}},close(){closed=!0,server?.child.kill(),server=null}}}module.exports={createCodexRuntime}}});var require_checkouts=__commonJS({"../../apps/web/electron/local-tools/checkouts.js"(exports,module){"use strict";var childProcess=__require("child_process"),fs=__require("fs"),os=__require("os"),path=__require("path"),KEEP_MS=10080*6e4,UNFINISHED_KEEP_MS=720*60*6e4,ENDED=".ended",TASK_RECORD=".task.json",WORKTREE_INCLUDE=".worktreeinclude",MAX_SETUP_BYTES=250*1024*1024,NO_HOOKS=["-c",`core.hooksPath=${os.devNull}`,"-c",`core.excludesFile=${os.devNull}`];function runGit(git,args,{spawnSync:spawnSync3,env,cwd}){let result=spawnSync3(git,args,{cwd,env,encoding:"utf8",timeout:12e4});if(result.status!==0)throw new Error(`git ${args[0]}: ${(result.stderr||result.error?.message||"failed").trim().slice(0,300)}`);return(result.stdout??"").trim()}function splitNull(text){return(text??"").split("\0").map(entry=>entry.replace(/\/+$/u,"")).filter(Boolean)}var SETUP_SCAN_SKIP=new Set([".git","node_modules",".next","dist","build","target",".venv","venv"]);function isSymbolicLink(filePath){try{return fs.lstatSync(filePath).isSymbolicLink()}catch{return!1}}function isAutoCarriedIgnoredPath(rel,folder){let base=path.posix.basename(rel);return base===".env"||base.startsWith(".env.")||rel===".claude/settings.local.json"?!0:isSymbolicLink(path.join(folder,rel))}function collectAutoCarriedFromIgnoredEntry(rel,folder,candidates,depth=0){if(isAutoCarriedIgnoredPath(rel,folder)){candidates.add(rel);return}if(depth>=4||rel.split("/").some(segment=>SETUP_SCAN_SKIP.has(segment)))return;let full=path.join(folder,rel);try{if(!fs.lstatSync(full).isDirectory())return;for(let entry of fs.readdirSync(full))SETUP_SCAN_SKIP.has(entry)||collectAutoCarriedFromIgnoredEntry(`${rel}/${entry}`,folder,candidates,depth+1)}catch{}}function readPatternFileLines(filePath){try{return fs.readFileSync(filePath,"utf8").split(/\r?\n/u).map(line=>line.trim().replace(/^\/+/u,"").replace(/\/+$/u,"")).filter(line=>line.length>0&&!line.startsWith("#")&&!line.startsWith("!"))}catch{return[]}}function gitignoredSetupPaths(git,folder,{spawnSync:spawnSync3,env}){let inFolder={cwd:folder,env,encoding:"utf8",timeout:3e4},candidates=new Set,standard=spawnSync3(git,[...NO_HOOKS,"ls-files","-z","--others","--ignored","--exclude-standard","--directory"],inFolder);if(standard.status===0)for(let rel of splitNull(standard.stdout))collectAutoCarriedFromIgnoredEntry(rel,folder,candidates);let ignorePatterns=new Set([...readPatternFileLines(path.join(folder,".gitignore")),...readPatternFileLines(path.join(folder,".git","info","exclude")),...readPatternFileLines(path.join(folder,WORKTREE_INCLUDE))]);for(let pattern of ignorePatterns)isSymbolicLink(path.join(folder,pattern))&&candidates.add(pattern);if(fs.existsSync(path.join(folder,WORKTREE_INCLUDE))){let included=spawnSync3(git,[...NO_HOOKS,"ls-files","-z","--others","--ignored",`--exclude-from=${WORKTREE_INCLUDE}`,"--directory"],inFolder),nonSymlinks=(included.status===0?splitNull(included.stdout):[]).filter(rel=>!isSymbolicLink(path.join(folder,rel)));if(nonSymlinks.length>0){let verified=spawnSync3(git,[...NO_HOOKS,"check-ignore","-z","--stdin"],{...inFolder,input:`${nonSymlinks.join("\0")}\0`});if(verified.status===0)for(let rel of splitNull(verified.stdout))candidates.add(rel)}}return[...candidates].filter(rel=>rel!==".git"&&!rel.startsWith(".git/")&&!rel.split("/").includes(".."))}function rewriteCopiedSettingsLocal(src,dest,folder){try{let raw=fs.readFileSync(src,"utf8"),parsed=JSON.parse(raw),dirs=parsed?.permissions?.additionalDirectories;if(!Array.isArray(dirs))return!1;parsed.permissions.additionalDirectories=dirs.map(item=>{if(typeof item!="string")return item;let trimmed=item.trim();return trimmed===""||trimmed.startsWith("~/")||path.isAbsolute(trimmed)?item:path.resolve(folder,trimmed)});let out=`${JSON.stringify(parsed,null,2)}
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;let budget={bytes:0},linkedNames=[];for(let rel of paths){let src=path.join(folder,rel),dest=path.join(checkout,rel);try{fs.lstatSync(dest);continue}catch{}try{fs.lstatSync(src).isSymbolicLink()&&linkedNames.push(`/${rel.replace(/^\/+/u,"")}`),copySetupEntry(src,dest,budget,folder)}catch{}}if(linkedNames.length>0)try{let excludeFile=path.join(checkout,".git","info","exclude");fs.mkdirSync(path.dirname(excludeFile),{recursive:!0}),fs.appendFileSync(excludeFile,`
21
- ${linkedNames.join(`
19
+ `))}async function startTurn(state,threadId,turn,text){Object.assign(turn,{final:[],last:"",turnId:null,steers:[]}),state.turns.set(threadId,turn);try{let response=await request(state,"turn/start",{threadId,input:[{type:"text",text,text_elements:[]}]});turn.turnId??=response?.turn?.id??null}catch(error){throw state.turns.get(threadId)===turn&&state.turns.delete(threadId),error}}async function openThread(state,sessionId){let shared={cwd,approvalPolicy:"never",...sandbox==null?{}:{sandbox},developerInstructions:instructions};if(sessionId&&state.loadedThreads.has(sessionId))return{threadId:sessionId,resumed:!0};if(sessionId)try{return await request(state,"thread/resume",{...shared,threadId:sessionId}),state.loadedThreads.add(sessionId),{threadId:sessionId,resumed:!0}}catch(error){log2.warn("[Local agents] could not resume Codex thread",error)}let threadId=(await request(state,"thread/start",shared))?.thread?.id;if(typeof threadId!="string")throw new Error("Codex returned no thread");return state.loadedThreads.add(threadId),{threadId,resumed:!1}}return{async runTurn({key,sessionId,text,newSessionText,onThought,onStarted,onSession,answerSteers=!1}){if(closed)throw stopped();server??=startServer();let state=server;await state.ready;let{threadId,resumed}=await openThread(state,sessionId);onSession?.(threadId);let input=resumed||!newSessionText?text:await newSessionText();if(closed)throw stopped();state.threadsByKey.set(key,threadId);let turn={onThought,answerSteers,replies:[]},reply=new Promise((resolve2,reject)=>{Object.assign(turn,{resolve:resolve2,reject})});await startTurn(state,threadId,turn,input),onStarted?.();let answered=await reply,usage=state.usageByThread.get(threadId);return{sessionId:threadId,reply:answered,...usage==null?{}:{usage}}},async steer({key,text}){let state=server,threadId=state?.threadsByKey.get(key),turn=threadId&&state.turns.get(threadId);if(!turn?.turnId)return!1;let steers=turn.answerSteers?turn.steers:null,steer={id:randomUUID3(),text,taken:!1,answered:!1,handedOn:!1};steers?.push(steer);try{return await request(state,"turn/steer",{threadId,input:[{type:"text",text,text_elements:[]}],expectedTurnId:turn.turnId,...steers==null?{}:{clientUserMessageId:steer.id}}),!0}catch(error){if(steer.handedOn)return!0;if(steers?.splice(steers.indexOf(steer),1),/no active turn|expected.*turn|turn.*mismatch/i.test(error.message))return!1;throw error}},close(){closed=!0,server?.child.kill(),server=null}}}module.exports={createCodexRuntime}}});var require_checkouts=__commonJS({"../../apps/web/electron/local-tools/checkouts.js"(exports,module){"use strict";var childProcess=__require("child_process"),fs=__require("fs"),os=__require("os"),path=__require("path"),KEEP_MS=10080*6e4,UNFINISHED_KEEP_MS=720*60*6e4,ENDED=".ended",TASK_RECORD=".task.json",WORKTREE_INCLUDE=".worktreeinclude",MAX_SETUP_BYTES=250*1024*1024,NO_HOOKS=["-c",`core.hooksPath=${os.devNull}`,"-c",`core.excludesFile=${os.devNull}`];function runGit(git,args,{spawnSync:spawnSync3,env,cwd}){let result=spawnSync3(git,args,{cwd,env,encoding:"utf8",timeout:12e4});if(result.status!==0)throw new Error(`git ${args[0]}: ${(result.stderr||result.error?.message||"failed").trim().slice(0,300)}`);return(result.stdout??"").trim()}var DEPENDENCY_CLONE_MS=5*6e4,CLONE_MS=10*6e4;function runInBackground(cmd,args,{cwd,env,timeout}){return new Promise(resolve2=>{childProcess.execFile(cmd,args,{cwd,env,timeout,encoding:"utf8"},(error,stdout,stderr)=>resolve2({status:error==null?0:typeof error.code=="number"?error.code:null,stdout,stderr:stderr||error?.message||""}))})}function splitNull(text){return(text??"").split("\0").map(entry=>entry.replace(/\/+$/u,"")).filter(Boolean)}var CLAUDE_LOCAL_SETTINGS=".claude/settings.local.json";function isSymbolicLink(filePath){try{return fs.lstatSync(filePath).isSymbolicLink()}catch{return!1}}function isAutoCarriedIgnoredPath(rel,folder){let base=path.posix.basename(rel);return base===".env"||base.startsWith(".env.")||rel===CLAUDE_LOCAL_SETTINGS?!0:isSymbolicLink(path.join(folder,rel))}function readPatternFileLines(filePath){try{return fs.readFileSync(filePath,"utf8").split(/\r?\n/u).map(line=>line.trim().replace(/^\/+/u,"").replace(/\/+$/u,"")).filter(line=>line.length>0&&!line.startsWith("#")&&!line.startsWith("!"))}catch{return[]}}function gitignoredSetupPaths(git,folder,{spawnSync:spawnSync3,env}){let inFolder={cwd:folder,env,encoding:"utf8",timeout:3e4},candidates=new Set,standard=spawnSync3(git,[...NO_HOOKS,"ls-files","-z","--others","--ignored","--exclude-standard","--directory"],inFolder);if(standard.status===0)for(let rel of splitNull(standard.stdout))isAutoCarriedIgnoredPath(rel,folder)?candidates.add(rel):rel===".claude"&&fs.existsSync(path.join(folder,CLAUDE_LOCAL_SETTINGS))&&candidates.add(CLAUDE_LOCAL_SETTINGS);let ignorePatterns=new Set([...readPatternFileLines(path.join(folder,".gitignore")),...readPatternFileLines(path.join(folder,".git","info","exclude")),...readPatternFileLines(path.join(folder,WORKTREE_INCLUDE))]);for(let pattern of ignorePatterns)isSymbolicLink(path.join(folder,pattern))&&candidates.add(pattern);if(fs.existsSync(path.join(folder,WORKTREE_INCLUDE))){let included=spawnSync3(git,[...NO_HOOKS,"ls-files","-z","--others","--ignored",`--exclude-from=${WORKTREE_INCLUDE}`,"--directory"],inFolder),nonSymlinks=(included.status===0?splitNull(included.stdout):[]).filter(rel=>!isSymbolicLink(path.join(folder,rel)));if(nonSymlinks.length>0){let verified=spawnSync3(git,[...NO_HOOKS,"check-ignore","-z","--stdin"],{...inFolder,input:`${nonSymlinks.join("\0")}\0`});if(verified.status===0)for(let rel of splitNull(verified.stdout))candidates.add(rel)}}return[...candidates].filter(rel=>rel!==".git"&&!rel.startsWith(".git/")&&!rel.split("/").includes(".."))}function rewriteCopiedSettingsLocal(src,dest,folder){try{let raw=fs.readFileSync(src,"utf8"),parsed=JSON.parse(raw),dirs=parsed?.permissions?.additionalDirectories;if(!Array.isArray(dirs))return!1;parsed.permissions.additionalDirectories=dirs.map(item=>{if(typeof item!="string")return item;let trimmed=item.trim();return trimmed===""||trimmed.startsWith("~/")||path.isAbsolute(trimmed)?item:path.resolve(folder,trimmed)});let out=`${JSON.stringify(parsed,null,2)}
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
+ ${carried.join(`
22
22
  `)}
23
- `)}catch{}}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)}}function cloneGitignoredDependencies({git,folder,checkout,finalCheckout=checkout,spawnSync:spawnSync3,env,platform}){if(platform!=="darwin"&&platform!=="linux")return;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;if(spawnSync3(cmd,platform==="darwin"?[flag,"--",src,dest]:["-RP",flag,"--",src,dest],{cwd:checkout,env,encoding:"utf8",timeout:3e4}).status!==0){fs.rmSync(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})}}}function prepareTaskCheckout({root,folder,runId,git="git",env=process.env,spawnSync:spawnSync3=childProcess.spawnSync,platform=process.platform}){let dir=path.join(root,runId);if(fs.existsSync(path.join(dir,".git")))return dir;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`;fs.rmSync(partial,{recursive:!0,force:!0}),runGit(git,[...NO_HOOKS,"clone","--quiet","--local","--no-hardlinks","--template=","--",folder,partial],{spawnSync:spawnSync3,env,cwd:root});let inCheckout={spawnSync:spawnSync3,env,cwd:partial};return 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),cloneGitignoredDependencies({git,folder,checkout:partial,finalCheckout:dir,spawnSync:spawnSync3,env,platform}),copyGitignoredSetup({git,folder,checkout:partial,spawnSync:spawnSync3,env}),fs.renameSync(partial,dir),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_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
24
24
  `)}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
25
  # A setting that would switch the push hook off or hide a push in an alias.
26
26
  check_key() {
@@ -98,17 +98,17 @@ ${tables}`:preamble||tables}function stringify(obj,{maxDepth=1e3,numbersAsFloat=
98
98
  `)}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
99
  `):""}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
100
  `)[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),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;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:prepareTaskCheckout({root:checkoutRoot,folder:run3.folder,runId:run3.runId,git:findCommand2("git",ownerEnv.PATH)??"git",env:ownerEnv,spawnSync:spawnSync3,platform}),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"};if(stoppedWhileStarting.has(run3.runId))return 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"};let place=placeRun(run3);return place==null?{status:"finished"}: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(`
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(`
102
102
 
103
- `)}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);(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."}}});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"},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{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(`
103
+ `)}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
104
  `)}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
105
  `)}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
- `,{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){console.log(message);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(`
106
+ `,{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
107
  `,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));log("Approve this machine in your browser, on any device:"),log(` ${appUrl}/connect/machine?request=${request}&name=${name}`),log(` Check it shows this code: ${code2}`);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.")}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...");let 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.`);log("A real task ran here. This machine is ready.")}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)":""}.`)}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"}.`);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}.`),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(`${config.machineName}: ${pid==null?"stopped":background==null?"running":"running in the background"}`);for(let folder of ready?.folders??[])console.log(` ${folder}${inPlace.has(folder)?" (in place)":""}`);for(let task of tasks)console.log(` ${task.runId.slice(0,8)} ${task.status??"running"} ${task.provider??"?"} ${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(`
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(`
109
109
  `).slice(-lineCount).join(`
110
110
  `);tail.length>0&&process.stdout.write(`${tail}
111
- `)}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.`)),(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}.`)),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),{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.`),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,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_self_check();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
111
+ `)}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
112
112
  connects in, and each task works in its own checkout on its own branch (or in
113
113
  the folder itself with --in-place).
114
114
 
@@ -123,7 +123,7 @@ the folder itself with --in-place).
123
123
  ando update Move to the newest connector. Tasks pick up
124
124
  where they left off.
125
125
  ando stop Stop the connector until the next ando up.
126
- `,newClient=url=>new ConvexClient(url,{logger:!1}),CHECKOUT_ROOT=join5(homedir4(),".ando-tasks"),READY_WAIT_MS=3e4,STOP_WAIT_MS=15e3,RESUBSCRIBE_MS=5e3,readyPath=()=>join5(stateDirectory(process.env),"ready.json"),carriedEnvPath=()=>join5(stateDirectory(process.env),"service-env.json"),connectorPath=()=>join5(stateDirectory(process.env),"connector.mjs"),logFile=()=>join5(stateDirectory(process.env),"connector.log");logger={info:log,warn:(message,error)=>log(error==null?message:`${message}: ${String(error)}`),error:(message,error)=>log(error==null?message:`${message}: ${String(error)}`)};BWRAP_APPARMOR_FIX=`Ubuntu 24.04 and later stop bubblewrap by default. Allow it with:
126
+ `,newClient=url=>new ConvexClient(url,{logger:!1}),CHECKOUT_ROOT=join5(homedir4(),".ando-tasks"),READY_WAIT_MS=3e4,STOP_WAIT_MS=15e3,RESUBSCRIBE_MS=5e3,readyPath=()=>join5(stateDirectory(process.env),"ready.json"),carriedEnvPath=()=>join5(stateDirectory(process.env),"service-env.json"),connectorPath=()=>join5(stateDirectory(process.env),"connector.mjs"),logFile=()=>join5(stateDirectory(process.env),"connector.log"),terminal=createTerminal(wantsColor(process.stdout));logger={info:message=>log(message,"step"),warn:(message,error)=>log(error==null?message:`${message}: ${String(error)}`,"warn"),error:(message,error)=>log(error==null?message:`${message}: ${String(error)}`,"fail")};BWRAP_APPARMOR_FIX=`Ubuntu 24.04 and later stop bubblewrap by default. Allow it with:
127
127
  sudo tee /etc/apparmor.d/bwrap >/dev/null <<'EOF'
128
128
  abi <abi/4.0>,
129
129
  include <tunables/global>
@@ -139,7 +139,7 @@ ${fence}`}function mention(membershipId,name){let label=name.replace(/[|>\n]/gu,
139
139
  ${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
140
  ${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
141
  ${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.2",HELP=`ando \u2014 use Ando from a terminal
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
143
143
 
144
144
  Usage:
145
145
  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.2",
3
+ "version": "0.5.4",
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": {
@@ -13,6 +13,17 @@
13
13
  "engines": {
14
14
  "node": ">=22"
15
15
  },
16
+ "keywords": [
17
+ "ando",
18
+ "agents",
19
+ "ai-agents",
20
+ "claude-code",
21
+ "codex",
22
+ "mcp",
23
+ "cli",
24
+ "team-chat"
25
+ ],
26
+ "homepage": "https://docs.ando.so/docs/external-agents#connect-a-server",
16
27
  "repository": {
17
28
  "type": "git",
18
29
  "url": "git+https://github.com/Ando-Corporation/ando.git",