@andocorp/cli 0.5.7 → 0.5.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +3 -3
- package/package.json +3 -3
package/dist/cli.js
CHANGED
|
@@ -184,13 +184,13 @@ ${notice}`,log:log2,permissionArgs})}let launch=resolveAcpLaunch(provider,ownerE
|
|
|
184
184
|
|
|
185
185
|
`)}await api.report(event.runId,report,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 midTurnSessionId=claimed.session_id??sessions.get(claimed.run_id)??null,sessionId=midTurnSessionId??claimed.continued_session_id??null,{status}=await host.startRun({...host.readRunFile!=null&&api.uploadResultFile!=null?{returnFiles:!0}:{},runId:claimed.run_id,workspaceId,ownerId:null,provider:claimed.provider,folder:claimed.folder,prompt:claimed.prompt,sessionId,continuedSessionId:claimed.continued_session_id??null,continuedFromRunId:claimed.continued_from_run_id??null,continuedUsageBaseline:claimed.continued_usage_baseline==null?null:fromUsage(claimed.continued_usage_baseline),checkoutRunId:claimed.checkout_run_id??null,midTurnRestart:midTurnSessionId!=null,agentName:claimed.agent_name,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(`
|
|
186
186
|
`)}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(`
|
|
187
|
-
`)}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)&¤t===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,"&").replace(/</g,"<").replace(/>/g,">");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)}
|
|
187
|
+
`)}function detectService(run3=quiet,platform=process.platform){return platform==="darwin"?"launchd":platform!=="linux"?null:run3("systemctl",["--user","show-environment"]).status===0?"systemd":null}function accountName(){try{return userInfo().username}catch{return null}}function foregroundReason(platform=process.platform,systemdRunning=()=>existsSync2("/run/systemd/system"),user=accountName){let plain="There's no service manager here, so this stays running in this terminal.";if(platform!=="linux"||!systemdRunning())return plain;let name=user();return name==null?plain:[`systemd is running, but ${name}'s own systemd session isn't reachable from this shell, so this stays running in this terminal.`,`To run it in the background, log in as ${name} directly (for example over SSH, not with sudo su or su), run: sudo loginctl enable-linger ${name}, then run ando up again.`].join(" ")}function unitPath(kind,env){let home=env.HOME||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)&¤t===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,"&").replace(/</g,"<").replace(/>/g,">");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)}
|
|
188
188
|
`,{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","GEMINI_API_KEY","GOOGLE_CLOUD_LOCATION","GOOGLE_CLOUD_PROJECT","GOOGLE_GENAI_USE_VERTEXAI","GOOSE_PROVIDER","OPENAI_API_KEY","OPENAI_BASE_URL","OPENCODE_API_KEY","HTTP_PROXY","HTTPS_PROXY","NO_PROXY","http_proxy","https_proxy","no_proxy"])}});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(`
|
|
189
189
|
`,half),kept=nextNewline>=0?content.slice(nextNewline+1):content.slice(half);writeFileSync2(file,kept,{mode:384})}appendFileSync(file,`${new Date().toISOString()} ${message}
|
|
190
190
|
`,{mode:384})}catch{}}function createHost(onEvent,taskFolders=()=>[],inPlaceFolders=()=>[],hookFolders=()=>[]){return(0,import_host.createLocalToolHost)({directory:stateDirectory(process.env),appName:"Ando machine",log:logger,spawn,spawnSync:spawnSync2,onEvent,taskFolders,inPlaceFolders,hookFolders,checkoutRoot:CHECKOUT_ROOT})}function refusedHere(tool){return!isLegacyProvider(tool)||process.platform==="linux"&&tool==="codex"}function linuxSandboxProblem(env){if(process.platform!=="linux")return null;let missing=["bwrap","socat"].filter(tool=>(0,import_toolchain.findCommand)(tool,env.PATH)==null);if(missing.length>0)return`Claude Code tasks here need ${missing.join(" and ")}. Install them with: sudo apt-get install -y bubblewrap socat`;let tried=spawnSync2((0,import_toolchain.findCommand)("bwrap",env.PATH),["--unshare-user","--ro-bind","/","/","--dev","/dev","true"],{encoding:"utf8",timeout:1e4});return tried.status===0?null:/permission|not permitted|setting up uid map/i.test(tried.stderr??"")?BWRAP_APPARMOR_FIX:`Claude Code's sandbox can't start here: ${(tried.stderr??"").trim()}`}async function withinTimeout(work,message,timeout=CONNECT_TIMEOUT_MS){let timer;try{return await Promise.race([work,new Promise((_,reject)=>{timer=setTimeout(()=>reject(new Error(message)),timeout)})])}finally{clearTimeout(timer)}}async function fromApproval(client){let secret=randomBytes(32).toString("hex"),request=createHash("sha256").update(secret).digest("hex"),code2=approvalCode(request),appUrl=process.env.ANDO_APP_URL??DEFAULT_APP_URL,name=encodeURIComponent(hostname().slice(0,80)),link2=`${appUrl}/connect/machine?request=${request}&name=${name}`,heading="Approve this device in your browser, from anywhere:";log(heading,"plain",terminal.strong(heading)),log(` ${link2}`,"plain",` ${terminal.link(link2)}`),log(` Check it shows this code: ${code2}`,"plain",` Check it shows this code: ${terminal.strong(code2)}`);let opener=browserOpener(link2,{platform:process.platform,env:process.env,interactive:process.stdin.isTTY===!0&&process.stdout.isTTY===!0,find:command=>(0,import_toolchain.findCommand)(command,process.env.PATH)});console.log(opener==null?terminal.quiet("Waiting for your approval..."):`Press ${terminal.strong("Enter")} to open it in this computer's browser. ${terminal.quiet("Waiting for your approval...")}`);let stopListening=opener==null?()=>{}:openOnEnter(process.stdin,()=>openLink(opener,(command,args)=>spawn(command,args,{detached:!0,stdio:"ignore"}),()=>console.log(terminal.line("warn","Couldn't open a browser here. Use the link above."))));try{let expiresAt=Date.now()+APPROVAL_WAIT_MS;for(;Date.now()<expiresAt;){let machine=await withinTimeout(client.mutation(web.machineCollectConnect,{secret}),"Couldn't reach Ando.");if(machine!=null)return machine;await new Promise(done=>setTimeout(done,APPROVAL_POLL_MS))}throw new Error("The approval link expired. Run this again.")}finally{stopListening()}}function usableFolders(folders,mode=null){for(let folder of folders)if(!existsSync3(folder))throw new Error(`${folder} doesn't exist here.`);let absolute=[...new Set(folders.map(folder=>realpathSync(folder)))];for(let folder of absolute)if(holdsHome(folder))throw new Error(`Tasks can write the folders they work in, so ${folder} can't be one: it holds your home folder. Run this from a project folder.`);let autoInPlace=[];for(let folder of absolute){let top=spawnSync2("git",["-C",folder,"rev-parse","--show-toplevel"],{encoding:"utf8"});if(top.status!==0){if(mode==="checkout")throw new Error(`${folder} isn't a git repository. Tasks only work in a checkout of their own in a git repository; drop --checkout to run in place.`);autoInPlace.push(folder);continue}let repoRoot=realpathSync(top.stdout.trim());if(repoRoot!==folder&&mode!=="in-place")throw new Error(`${folder} is inside a repository (${repoRoot}). Connect the repository's own folder, or pass --in-place.`)}return{absolute,inPlace:mode==="in-place"?absolute:autoInPlace}}function mergeInPlaceFolders(existing,folders,autoInPlace,mode){let next=new Set(existing??[]);for(let folder of autoInPlace)next.add(folder);if(mode==="in-place")for(let folder of folders)next.add(folder);else if(mode==="checkout")for(let folder of folders)next.delete(folder);return[...next]}function mergeHookFolders(existing,folders,hooks){let next=new Set(existing??[]);if(hooks===!0)for(let folder of folders)next.add(folder);if(hooks===!1)for(let folder of folders)next.delete(folder);return[...next]}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(tool=>process.platform==="linux"&&tool==="codex")&&logger.warn(CODEX_ON_LINUX),tools.some(tool=>!isLegacyProvider(tool))&&logger.warn(ACP_ON_SERVER),sandboxProblem!=null&&tools.includes("claude-code")&&logger.warn(sandboxProblem),ready.length===0)throw host.stopAll(),new Error(tools.length===0?"Install Claude Code or Codex here first.":"Nothing here can take tasks yet. Fix what's above, or sign in (claude auth login or codex login), then connect again.");return{host,endings,ready}}async function proveTasksRun(setup,folder,inPlace=!1){log("Checking that a task really runs here...","step");let startedAt=Date.now(),check2=await selfCheck({provider:setup.ready[0],folder,checkoutRoot:inPlace?null:CHECKOUT_ROOT,startRun:setup.host.startRun,ended:runId=>new Promise(resolve2=>setup.endings.set(runId,resolve2))});if(!check2.ok)throw new Error(`This device is connected, but it can't run tasks yet: ${check2.reason}. Fix that, then run ando up.`);let seconds=Math.max(1,Math.round((Date.now()-startedAt)/1e3));log(`A real task ran here, in ${seconds}s. This device is ready.`,"ok")}async function connect(getMachine,url,folders,timeout=CONNECT_TIMEOUT_MS,mode=null,hooks=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),hookFolders=mergeHookFolders(void 0,absolute,hooks),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}:{},...hookFolders.length>0?{hookFolders}:{}};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,hooks=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??[]),hookFolders=mergeHookFolders(current.hookFolders,absolute,hooks),hooksChanged=JSON.stringify(hookFolders)!==JSON.stringify(current.hookFolders??[]),{inPlaceFolders:_prevInPlace,hookFolders:_prevHooks,...restConfig}=current,nextConfig={...restConfig,...inPlaceFolders.length>0?{inPlaceFolders}:{},...hookFolders.length>0?{hookFolders}:{}};if((inPlaceChanged||hooksChanged)&&await writeConfig(configPath2(process.env),nextConfig),hooksChanged)for(let folder of absolute)log(hookFolders.includes(folder)?`${folder}'s own Claude Code hooks will now run in tasks, outside their sandbox.`:`${folder}'s own Claude Code hooks won't run in tasks.`,"ok");if(canCheck&&(nextConfig.checked!==!0||added.length>0)&&(setup=await openSetup(all,inPlaceFolders)),added.length>0){let targets=tools.length>0?tools:(setup?.ready??[]).map(provider=>({provider,folders:[]}));if(targets.length===0)throw new Error("No tool is connected on this device. Connect one in Studio \u203A Devices first.");await Promise.all(targets.map(target=>withinTimeout(client.mutation(web.machineConnectTool,{token:nextConfig.token,provider:target.provider,folders:[...target.folders,...added]}),`Couldn't reach Ando at ${nextConfig.url}.`)));for(let folder of added)log(`Agents can now work in ${folder}${inPlaceFolders.includes(folder)?" (in place)":""}.`,"ok")}else if(inPlaceChanged)for(let folder of absolute)log(`Tasks in ${folder} will now run ${inPlaceFolders.includes(folder)?"in the folder itself":"in their own checkout"}.`,"ok");if(setup==null)return nextConfig;let checkFolder=added[0]??all[0];await proveTasksRun(setup,checkFolder,inPlaceFolders.includes(checkFolder));let checked={...nextConfig,checked:!0};return await writeConfig(configPath2(process.env),checked),checked}finally{setup?.host.stopAll(),client.close()}}async function connectPendingTools(config,client){if(config.pendingTools==null)return config;let{folders}=config.pendingTools,providers=config.pendingTools.providers;for(;providers.length>0;){let[provider,...rest]=providers;try{await withinTimeout(client.mutation(web.machineConnectTool,{token:config.token,provider,folders}),`Couldn't reach Ando at ${config.url}.`)}catch(error){if(provider!=null&&!isLegacyProvider(provider)&&isValidatorSkewError(error))logger.warn(`Ando hasn't rolled out ${provider} on this backend yet; skipping it for now.`);else throw error}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??[]),hooks=new Set(ready?.hookFolders??config?.hookFolders??[]);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]}:{},...hooks.size>0?{hookFolders:[...hooks]}:{},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)"):""}${hooks.has(folder)?terminal.quiet(" (hooks on)"):""}`);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(`
|
|
191
191
|
`).slice(-lineCount).join(`
|
|
192
192
|
`);tail.length>0&&process.stdout.write(`${tail}
|
|
193
|
-
`)}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.checkoutRunId??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]]:task.provider==="gemini-cli"?["gemini",["--resume",task.sessionId]]:task.provider==="opencode"?["opencode",["--session",task.sessionId]]:task.provider==="goose"?["goose",["session","--resume","--name",task.sessionId]]:["claude",["--resume",task.sessionId]];return 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??[],hookFolders=config.hookFolders??[],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,hookFolders=latestConfig?latestConfig.hookFolders??[]:hookFolders),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,()=>hookFolders),startRun=host.startRun;host.startRun=async input=>typeof input.folder=="string"&&holdsHome(input.folder)?{status:"failed"}:refusedHere(String(input.provider))?(log(CODEX_ON_LINUX,"warn"),{status:"failed"}):(typeof input.runId=="string"&&recordTask(input.runId,{provider:String(input.provider),folder:String(input.folder),...typeof input.checkoutRunId=="string"?{checkoutRunId:input.checkoutRunId}:{},status:"running",startedAt:Date.now()}),startRun(input)),agent=createMachineAgent({workspaceId,host,log,isRefusal:error=>error instanceof ConvexError,api:{uploadResultFile:(runId,file,dataBase64)=>client.action(anyApi.localToolResultFileUploads.upload,{scope:{token},runId,slot:file.slot,sha256:file.sha256,filename:file.filename,contentType:file.contentType,dataBase64}),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}:{},...hookFolders.length>0?{hookFolders}:{}}),{mode:384}),heartbeat=async()=>{try{let[described]=await Promise.all([host.machine.get(),readFolders()]);saveReady();let remotes=await(0,import_remotes.readFolderRemotes)(folders,{env:host.env()}),activeRunIds=agent?.activeRunIds()??[],baseReport={token,remotes,activeRunIds,sleeping:!1,sessionReads:typeof host.readSessions=="function",...described.key==null?{}:{machineKey:described.key}};try{await client.mutation(web.machineReport,{...baseReport,signedOutProviders:described.signedOut,servers:Object.entries(described.servers).map(([provider,names])=>({provider,names}))})}catch(error){if(!(described.signedOut.some(p=>!isLegacyProvider(p))||Object.keys(described.servers).some(p=>!isLegacyProvider(p)))||!isValidatorSkewError(error))throw error;await client.mutation(web.machineReport,{...baseReport,signedOutProviders:described.signedOut.filter(isLegacyProvider),servers:Object.entries(described.servers).filter(([provider])=>isLegacyProvider(provider)).map(([provider,names])=>({provider,names}))})}}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"},hooks:{type:"boolean"},"no-hooks":{type:"boolean"},foreground:{type:"boolean"},json:{type:"boolean"},follow:{type:"boolean",short:"f"},lines:{type:"string",short:"n"},help:{type:"boolean",short:"h"}}});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;if(values.hooks===!0&&values["no-hooks"]===!0)throw new Error("Pass either --hooks or --no-hooks, not both.");let hooks=values.hooks===!0?!0:values["no-hooks"]===!0?!1:null,[command,target]=positionals,here=process.cwd();process.env.PATH=(0,import_command_env.trustedPath)(process.env.PATH??"",holdsHome(here)?[]:[here]);let code2=process.env.ANDO_MACHINE_CODE?.trim()||null;if(delete process.env.ANDO_MACHINE_CODE,values.help||command==null){console.log(USAGE);return}if(command==="status")return printStatus(values.json===!0);if(command==="logs")return printLogs(values.follow===!0,values.lines);if(command==="stop")return stopConnector();if(command==="attach")return attach(target);if(command==="update")return update();if(command!=="up"&&command!=="connect"&&command!=="run")throw 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,hooks);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,hooks)}else if(saved!=null)config=command==="up"?await bringUpToDate(saved,folders,!0,mode,hooks):saved;else if(command==="up")config=await connect(fromApproval,values.url??DEFAULT_URL,folders,APPROVAL_TIMEOUT_MS,mode,hooks);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,LEGACY_PROVIDERS,isLegacyProvider,isValidatorSkewError,BWRAP_APPARMOR_FIX,CODEX_ON_LINUX,ACP_ON_SERVER,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
|
|
193
|
+
`)}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.checkoutRunId??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]]:task.provider==="gemini-cli"?["gemini",["--resume",task.sessionId]]:task.provider==="opencode"?["opencode",["--session",task.sessionId]]:task.provider==="goose"?["goose",["session","--resume","--name",task.sessionId]]:["claude",["--resume",task.sessionId]];return 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??[],hookFolders=config.hookFolders??[],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,hookFolders=latestConfig?latestConfig.hookFolders??[]:hookFolders),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,()=>hookFolders),startRun=host.startRun;host.startRun=async input=>typeof input.folder=="string"&&holdsHome(input.folder)?{status:"failed"}:refusedHere(String(input.provider))?(log(CODEX_ON_LINUX,"warn"),{status:"failed"}):(typeof input.runId=="string"&&recordTask(input.runId,{provider:String(input.provider),folder:String(input.folder),...typeof input.checkoutRunId=="string"?{checkoutRunId:input.checkoutRunId}:{},status:"running",startedAt:Date.now()}),startRun(input)),agent=createMachineAgent({workspaceId,host,log,isRefusal:error=>error instanceof ConvexError,api:{uploadResultFile:(runId,file,dataBase64)=>client.action(anyApi.localToolResultFileUploads.upload,{scope:{token},runId,slot:file.slot,sha256:file.sha256,filename:file.filename,contentType:file.contentType,dataBase64}),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}:{},...hookFolders.length>0?{hookFolders}:{}}),{mode:384}),heartbeat=async()=>{try{let[described]=await Promise.all([host.machine.get(),readFolders()]);saveReady();let remotes=await(0,import_remotes.readFolderRemotes)(folders,{env:host.env()}),activeRunIds=agent?.activeRunIds()??[],baseReport={token,remotes,activeRunIds,sleeping:!1,sessionReads:typeof host.readSessions=="function",...described.key==null?{}:{machineKey:described.key}};try{await client.mutation(web.machineReport,{...baseReport,signedOutProviders:described.signedOut,servers:Object.entries(described.servers).map(([provider,names])=>({provider,names}))})}catch(error){if(!(described.signedOut.some(p=>!isLegacyProvider(p))||Object.keys(described.servers).some(p=>!isLegacyProvider(p)))||!isValidatorSkewError(error))throw error;await client.mutation(web.machineReport,{...baseReport,signedOutProviders:described.signedOut.filter(isLegacyProvider),servers:Object.entries(described.servers).filter(([provider])=>isLegacyProvider(provider)).map(([provider,names])=>({provider,names}))})}}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"},hooks:{type:"boolean"},"no-hooks":{type:"boolean"},foreground:{type:"boolean"},json:{type:"boolean"},follow:{type:"boolean",short:"f"},lines:{type:"string",short:"n"},help:{type:"boolean",short:"h"}}});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;if(values.hooks===!0&&values["no-hooks"]===!0)throw new Error("Pass either --hooks or --no-hooks, not both.");let hooks=values.hooks===!0?!0:values["no-hooks"]===!0?!1:null,[command,target]=positionals,here=process.cwd();process.env.PATH=(0,import_command_env.trustedPath)(process.env.PATH??"",holdsHome(here)?[]:[here]);let code2=process.env.ANDO_MACHINE_CODE?.trim()||null;if(delete process.env.ANDO_MACHINE_CODE,values.help||command==null){console.log(USAGE);return}if(command==="status")return printStatus(values.json===!0);if(command==="logs")return printLogs(values.follow===!0,values.lines);if(command==="stop")return stopConnector();if(command==="attach")return attach(target);if(command==="update")return update();if(command!=="up"&&command!=="connect"&&command!=="run")throw 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,hooks);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,hooks)}else if(saved!=null)config=command==="up"?await bringUpToDate(saved,folders,!0,mode,hooks):saved;else if(command==="up")config=await connect(fromApproval,values.url??DEFAULT_URL,folders,APPROVAL_TIMEOUT_MS,mode,hooks);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(foregroundReason()),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,LEGACY_PROVIDERS,isLegacyProvider,isValidatorSkewError,BWRAP_APPARMOR_FIX,CODEX_ON_LINUX,ACP_ON_SERVER,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
|
|
194
194
|
connects in, and each task works in its own checkout on its own branch (or in
|
|
195
195
|
the folder itself with --in-place).
|
|
196
196
|
|
|
@@ -224,7 +224,7 @@ ${fence}`}function mention(membershipId,name){let label=name.replace(/[|>\n]/gu,
|
|
|
224
224
|
${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:
|
|
225
225
|
${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:
|
|
226
226
|
${listCandidates(exact.map(agentLabel))}`):new CliError(ExitCode.notFound,agents.length===0?`No agent named @${name} in this workspace.`:`No agent named @${name}. Similar agents:
|
|
227
|
-
${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.
|
|
227
|
+
${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.9",HELP=`ando \u2014 use Ando from a terminal
|
|
228
228
|
|
|
229
229
|
Usage:
|
|
230
230
|
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.
|
|
3
|
+
"version": "0.5.9",
|
|
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": {
|
|
@@ -34,8 +34,8 @@
|
|
|
34
34
|
"esbuild": "^0.28.2",
|
|
35
35
|
"tsrs": "0.18.0-ts7.1.0-dev.20260929",
|
|
36
36
|
"typescript": "npm:@typescript/typescript6@^6.0.2",
|
|
37
|
-
"@
|
|
38
|
-
"@
|
|
37
|
+
"@ando/machine": "0.0.0",
|
|
38
|
+
"@andocorp/sdk": "0.3.0-next.0"
|
|
39
39
|
},
|
|
40
40
|
"publishConfig": {
|
|
41
41
|
"access": "public"
|