@reason-machines/cli-linux-x64 0.2.512 → 0.2.513
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/bin/reason +1 -1
- package/bin/vm-hands/{api-credentials-tsbx6cpa.js → api-credentials-bj9h63yg.js} +1 -1
- package/bin/vm-hands/{api-nwnptsbc.js → api-ns726td3.js} +1 -1
- package/bin/vm-hands/{connect-cli-ymqe88y2.js → connect-cli-gh0ewjrx.js} +1 -1
- package/bin/vm-hands/{local-automation-ta2k7hz3.js → local-automation-wzxz22mp.js} +1 -1
- package/bin/vm-hands/{local-capabilities-8xm0j4yv.js → local-capabilities-rh2h4qwg.js} +1 -1
- package/bin/vm-hands/{local-display-session-36ypnvvr.js → local-display-session-4qk31c9s.js} +1 -1
- package/bin/vm-hands/local-display-video-d38n8w7v.js +2 -0
- package/bin/vm-hands/{local-managed-process-c1pd7k4g.js → local-managed-process-9y2tcq5s.js} +1 -1
- package/bin/vm-hands/{managed-runtime-cf3m8ygn.js → managed-runtime-hkc87vav.js} +1 -1
- package/bin/vm-hands/{permissions-mtp3nv7w.js → permissions-6vgmaeat.js} +1 -1
- package/bin/vm-hands/{serve-service-612sfna9.js → serve-service-6rjsmgtm.js} +1 -1
- package/bin/vm-hands/{status-vc1z4d4q.js → status-gavcwz6k.js} +1 -1
- package/bin/vm-hands/version-jfv30xwt.js +2 -0
- package/bin/vm-hands/vm-hands-entry-lite-10txe4yb.js +2 -0
- package/bin/vm-hands/{vm-hands-entry-lite-h2j0q0en.js → vm-hands-entry-lite-3r7d9pk1.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-tarerak1.js → vm-hands-entry-lite-bzdbpx7v.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-58yq5qb3.js → vm-hands-entry-lite-c8r6jyj2.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-fa71c1fj.js → vm-hands-entry-lite-d3kkk24g.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-21pw3ra3.js → vm-hands-entry-lite-ebmw8nv0.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-ac708gr9.js → vm-hands-entry-lite-ee109spc.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-xynhzesa.js → vm-hands-entry-lite-f9ezhnqw.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-fqas8pts.js → vm-hands-entry-lite-gdbb55w3.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-pn8e1xf9.js → vm-hands-entry-lite-gpezb160.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-s3tt2trs.js → vm-hands-entry-lite-kean8gnh.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-55mpsgz3.js → vm-hands-entry-lite-mby8j0ss.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-bqqfmgaz.js → vm-hands-entry-lite-s0wv36ha.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-8z4k86tg.js → vm-hands-entry-lite-v38e60gh.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-kjznqmwj.js → vm-hands-entry-lite-v7qr6t6f.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-08fnapbd.js → vm-hands-entry-lite-whaeqrzh.js} +1 -1
- package/bin/vm-hands/vm-hands-entry-lite.js +1 -1
- package/bin/vm-hands/{vm-hands-executor-yk90fyff.js → vm-hands-executor-etdrts7k.js} +1 -1
- package/bin/vm-hands/{vm-hands-op-runner-545vwzvp.js → vm-hands-op-runner-8zjcz4w7.js} +1 -1
- package/bin/vm-hands/{vm-hands-runtime-wr0m4gny.js → vm-hands-runtime-p26hr2sr.js} +3 -3
- package/package.json +1 -1
- package/bin/vm-hands/local-display-video-xaxjazsp.js +0 -2
- package/bin/vm-hands/version-3fc9wwez.js +0 -2
- package/bin/vm-hands/vm-hands-entry-lite-42117xc5.js +0 -2
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Mn,Co,Wt}from"./vm-hands-entry-lite-k1wghndy.js";import{Rn,Ve,mo,On,In,Dn,Tr,x}from"./vm-hands-entry-lite-
|
|
2
|
+
import{Mn,Co,Wt}from"./vm-hands-entry-lite-k1wghndy.js";import{Rn,Ve,mo,On,In,Dn,Tr,x}from"./vm-hands-entry-lite-gdbb55w3.js";import{At}from"./vm-hands-entry-lite-024t90qh.js";import{Nr}from"./vm-hands-entry-lite-m7pkmatv.js";import{j}from"./vm-hands-entry-lite-3p7zk3yt.js";import{a}from"./vm-hands-entry-lite-0sh835na.js";import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{execFile as z,spawn as H}from"child_process";import{randomBytes as Qe}from"crypto";import{chmodSync as De,existsSync as I,lstatSync as _e,mkdirSync as we,readFileSync as Re,rmSync as ee,writeFileSync as g}from"fs";import{connect as de}from"net";import{join as y}from"path";var S=32,w=76;var B="./desktop-wallpaper-0pjhgyfk.jpg";var O="./dock-browser-afp005mt.png";var F="./dock-files-rywdm96b.png";var k="./dock-terminal-s41cj1jp.png";var K=`# Sets the X root window background and _XROOTPMAP_ID, as feh --bg-fill does.
|
|
3
3
|
# The native Blaxel image ships no feh, hsetroot or compositor, but it does ship
|
|
4
4
|
# python3-gi and libX11. tint2 reads _XROOTPMAP_ID to draw its transparent panel.
|
|
5
5
|
# Usage: DISPLAY=:99 python3 set-root-wallpaper.py IMAGE
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{H}from"./vm-hands-entry-lite-39qv4sqt.js";import{D,R,b}from"./vm-hands-entry-lite-1zd088yv.js";import{je,gr,_r,Sn,En,at}from"./vm-hands-entry-lite-
|
|
2
|
+
import{H}from"./vm-hands-entry-lite-39qv4sqt.js";import{D,R,b}from"./vm-hands-entry-lite-1zd088yv.js";import{je,gr,_r,Sn,En,at}from"./vm-hands-entry-lite-3r7d9pk1.js";import{Mr}from"./vm-hands-entry-lite-3p7zk3yt.js";import{p,lt,An,_e,we}from"./vm-hands-entry-lite-psjcmgj8.js";import{v,h}from"./vm-hands-entry-lite-ymqb2927.js";import{a,nr,Uo}from"./vm-hands-entry-lite-0sh835na.js";import{an,y,t,k,o,d,ps,Oe,$i,u,i,W,g,ee,s,n,cn}from"./vm-hands-entry-lite-qzcac2mf.js";import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{se,A}from"./vm-hands-entry-lite-qz74j563.js";import{randomUUID as Q}from"crypto";import{spawn as Le}from"child_process";import{existsSync as Z,lstatSync as me,mkdirSync as We,readFileSync as Ne,realpathSync as G,rmSync as Ve,writeFileSync as He}from"fs";import{dirname as Ue,join as j,relative as qe,sep as Je}from"path";var Se=["process.run.v1","process.full.v1"],xe=600000,Pe=1800000,Ee=20000,ne="process.cancel.v1",ie=i({action:n("start"),request_id:t().uuid(),command:t().min(1).max(16000).refine((e)=>!e.includes("\x00")),cwd:t().min(1).max(4096).refine((e)=>!e.includes("\x00")&&!e.startsWith("/")&&!e.split(/[\\/]/).includes("..")).describe("Path relative to the granted device root; omit to use that root. Must not start with /, contain a .. path segment, or contain a NUL character.").optional(),mode:s(["host","confined"]).default("host"),timeout_ms:o().int().min(1000).max(Pe).default(xe).describe("Absolute process budget including queue and startup time. Defaults to ten minutes; longer explicit requests require the selected root's advertised max_timeout_ms. Retrying never renews the deadline.")}).strict(),K={device_id:t().uuid(),root_id:t().uuid()},Re=g("action",[ie.extend(K),i({...K,action:n("inspect"),process_id:t().uuid(),after:o().int().min(0).default(0),wait_ms:o().int().min(0).max(Ee).default(0).describe("Wait for new output or a state change, bounded by this call's wait budget. Expiring this wait does not cancel the process or extend its deadline.")}).strict(),i({...K,action:n("cancel"),process_id:t().uuid()}).strict()]),Fe=an(Re,{io:"input"}),Ke=ie.extend({process_brain_fence:t().uuid(),process_expires_at:y.datetime()}).strict(),J=i({version:n(1),process_id:t().uuid(),state:s(["starting","running","exited","cancelled","expired","uncertain"]),exit_code:o().int().nullable(),first_cursor:o().int().min(0),next_cursor:o().int().min(0),truncated:d(),observed_at:y.datetime(),output:u(i({cursor:o().int().min(1),stream:s(["stdout","stderr"]),text:t().max(32768)}).strict()).max(128)}).strict().refine((e)=>{if(Buffer.byteLength(JSON.stringify(e))>1e5||e.next_cursor<e.first_cursor-1)return!1;if((e.state==="starting"||e.state==="running"||e.state==="uncertain")&&e.exit_code!==null)return!1;if(e.state==="exited"&&(e.exit_code===null||e.exit_code<0||e.exit_code>255))return!1;if(e.state==="cancelled"&&e.exit_code!==130||e.state==="expired"&&e.exit_code!==124)return!1;let _=e.first_cursor-1;for(let l of e.output){if(l.cursor<=_||l.cursor>e.next_cursor)return!1;_=l.cursor}return!0});function ae(e){return Se.includes(e)}var Xe=i({operation_constraints:ee(t(),Oe())}),Ye=i({ready:n(!0),version:n(1),execution_mode:s(["host","confined"]),max_timeout_ms:o().int().min(1000).optional()});var Ie=i({version:n(1),process_id:t().uuid(),state:s(["queued","cancelled_before_start","not_started"]),exit_code:ps(),output:u($i()).length(0),first_cursor:n(0),next_cursor:n(0),truncated:n(!1),cancellation_requested:n(!1),reason_code:s(["cancelled_before_start","process_journal_capacity","path_not_found","process_timeout_unsupported"]).optional(),expires_at:y.datetime().optional().describe("Accepted absolute process deadline. Reading, waiting and retrying do not extend it.")}).strict(),De=i({...J.shape,state:s(["queued","starting","running","exited","cancelled","expired","uncertain","cancelled_before_start","not_started"]),observed_at:y.datetime().optional(),expires_at:y.datetime().optional().describe("Accepted absolute process deadline. Reading, waiting and retrying do not extend it."),cancellation_requested:d(),reason_code:t().nullable().optional(),execution_authority:n("lost").optional().describe("Historical receipt only; the current Brain cannot control this older-generation process."),recovery:i({cause:n("brain_generation_changed"),terminal_confirmed:d(),next_step:s(["inspect_until_terminal","reconcile_effects_before_new_intent"])}).strict().optional().describe("Historical process recovery only. An unconfirmed outcome forbids replay. A confirmed terminal observation proves the old process stopped, not that its command had no effects. Reconcile the result; only restart still-needed, safely repeatable work with a new request_id and current authority. Respect user cancellation."),last_observed_state:J.shape.state.or(n("cancelled_before_start")).nullable().optional().describe("Last saved observation before authority was lost; a running observation does not establish current child liveness.")}).strict(),$e=an(De),Qe=W([J,Ie.refine((e)=>e.state==="cancelled_before_start")]),X=i({version:n(1),process_id:t().uuid(),state:s(["exited","cancelled","expired"]),exit_code:o().int().min(0).max(255),observed_at:y.datetime()}).strict().refine((e)=>(e.state!=="cancelled"||e.exit_code===130)&&(e.state!=="expired"||e.exit_code===124)),Ze=i({process_terminal_observation:X}).strict();var Ki="preview.serve.v1",Ji=43200000;var ce="preview.open.v1",de=1,_n="gid_proxy_v1",Zi="egress",yn=/^(?:\*\.)?[a-z0-9](?:[a-z0-9.-]{0,251}[a-z0-9])?(?::[1-9][0-9]{0,4})?$/,Ce=i({version:n(_n),allowed_domains:u(t().max(260).regex(yn)).max(1024)}).strict(),Ae=cn((e)=>H(e)!==null,"invalid workspace"),ke=i({version:n(1),request_id:k(),session_id:k(),command:t().min(1).max(16000).refine((e)=>!e.includes("\x00")),port:o().int().min(1024).max(65535),workspace:Ae,egress:Ce.optional()}).strict(),Xi=ke.extend({expires_at:y.datetime()}).strict();var Me=4,Te=5000;function Y(e,c,_){let l=null;try{l=lt(e)}catch{}An({deviceRelayUrl:l?.deviceRelayUrl??"",binding:l?.binding??null,jobId:c,port:l?.binding.port??0,reason:l?_:"binding_invalid"})}function le(e){let c=new Map;return{open(_){let l=(x)=>Y(_,e.claim.operation_id,x),C;try{C=lt(_)}catch{return l("binding_invalid")}let{binding:w,deviceRelayUrl:z}=C,E=e.claim.owner;if(!E||w.organizationId!==E.organization_id||w.userId!==E.user_id||w.deviceId!==E.device_id||w.rootId!==e.claim.root_id||w.jobId!==e.claim.operation_id||w.fenceId!==e.claim.operation_id||w.generation!==de||w.expiresAtMs>Math.min(Date.now()+p.lifetimeMs+Te,e.expiresAtMs))return l("binding_mismatch");if(w.expiresAtMs<=Date.now())return l("binding_expired");if(c.get(w.port)?.abort(),c.delete(w.port),c.size>=Me)return l("preview_capacity");let L=new AbortController;c.set(w.port,L);let P=we({binding:w,deniedPorts:e.deniedPorts,readCurrentJob:async()=>{if(L.signal.aborted)return null;let x=await e.inspect();return x?{binding:w,executorLaunchId:e.executorLaunchId,job:x}:null}});_e({binding:w,deviceRelayUrl:z,port:P,signal:L.signal}).then((x)=>x.closed,(x)=>{let I=x instanceof Error?x.message:"preview_failed";if(I!=="preview_not_authorized")process.stderr.write(`${JSON.stringify({event:"worker_preview.open_failed",job_id:w.jobId,port:w.port,reason_code:I})}
|
|
3
3
|
`)}).finally(()=>{if(c.get(w.port)===L)c.delete(w.port)})},dispose(){for(let _ of c.values())_.abort();c.clear()}}}class ot extends r{observation;constructor(e){super("process_authority_lost","Process authority was lost; the owned process group has stopped.");this.observation=e}}var fe=256,B=new Map,he="preview.serve.v1",V=new Map;function be(e){let c=V.get(e.operation_id);if(c){if(c.claim!==e)throw M("process_authority_lost");return c}if(V.size>=fe)throw M("process_journal_capacity");let _={claim:e,executing:!1,cancelRequested:!1,phase:"pending"};return V.set(e.operation_id,_),_}function pe(e){return{version:1,process_id:e,state:"cancelled_before_start",exit_code:null,output:[],first_cursor:0,next_cursor:0,truncated:!1,cancellation_requested:!1,reason_code:"cancelled_before_start"}}var ue=(e)=>new Promise((c)=>setTimeout(c,e)),M=(e="process_outcome_uncertain")=>new r(e,"The managed process outcome could not be confirmed; inspect its saved receipt before starting another intent.");function ze(e=a(),c=Ge()){let _=Ue(Mr({},e)),l=qe(nr(e),_),[C,...w]=l.split(Je);return{directory:j(c,l,"processes"),previous:[j(_,"processes"),...C==="reason"?[j(c,"ara",...w,"processes")]:[]]}}function Ge(){if(process.platform!=="darwin")throw new r("process_unavailable","Managed Mac process execution is unavailable.");let e=Uo();if(!e)throw new r("process_unavailable","The private per-user process directory is unavailable.");return e}async function fr(e){if(!e.claim.owner||e.signal.aborted||e.expiresAtMs<=Date.now())throw M("process_authority_lost");let c=be(e.claim);if(c.executing)throw M("process_busy");if(c.executing=!0,c.cancelRequested)return c.phase="settling",pe(e.claim.operation_id);c.phase="starting";let _=e.journals??ze();We(_.directory,{recursive:!0,mode:448});let l=gr({runtimeDirectory:G(_.directory),previousRuntimeDirectories:(_.previous??[]).filter((m)=>Z(m)).map((m)=>G(m)),root:e.root,runId:JSON.stringify([e.claim.owner,e.claim.run_id,e.claim.root_id,e.claim.operation_id]),maxScopes:fe});try{for(let m of[e.root,e.cwd])if(!je(G(m),l.journalDirectory))throw new r("process_journal_inside_workspace","The selected root contains the private process journal. Select an existing narrower granted workspace root outside the journal; no command was dispatched.")}catch(m){throw l.disposeSocket(),m}let C=me(l.journalDirectory),w=e.claim.capability===he,z=()=>B.set(e.claim.operation_id,{path:l.journalDirectory,ino:C.ino,dev:C.dev,anyCompletion:w}),E=l.launchDirectory,L=j(E,"config.json"),P={url:"",transport:"local_job_ipc",directShell:{mode:e.mode,executable:e.shell,jobId:e.claim.operation_id},workerVersion:D,protocolVersion:2,workerArtifactSha256:b,workerEntrypoint:R,targetGeneration:1,fenceId:Q(),...process.platform==="win32"?{bashExecutable:se()}:{},workRoot:e.root,workspaceAliasPath:e.root,repoPath:e.cwd,jobEnvPath:j(E,"unused.env"),replSocketPath:j(E,"unused.sock"),readyPath:j(E,"ready.json"),directTerminalReceiptPath:j(E,"terminal.json"),launchId:Q(),expiresAtMs:e.expiresAtMs+5000,bashTimeoutMs:60000,replTimeoutMs:1000,allowedTools:["bash"],managedJobs:{journalDirectory:l.journalDirectory,scopeId:l.scopeId},jobControlSocketPath:l.socketPath,...e.prefix?{bashCommandPrefix:e.prefix}:{},...e.jobsUser?{jobsUser:e.jobsUser}:{}},x;try{He(L,JSON.stringify(P),{mode:384});let m=Sn({configPath:L,root:e.cwd,grantedRoot:e.root,workRoot:e.root,temporaryDirectory:E});x=e.spawnWorker?.(L,P)??Le(m.command,m.args,{...m.options,env:e.environment,stdio:[En,"ignore","ignore"]})}catch(m){throw l.disposeSocket(),m}let I=!1,F=new Promise((m,S)=>{x.once("exit",(f)=>{I=!0,m(f)}),x.once("error",(f)=>{I=!0,S(f)})});F.catch(()=>{});let ge={root:e.root,runId:e.claim.run_id,scopeId:l.scopeId,socketPath:l.socketPath,generation:1,fenceId:P.fenceId,executorLaunchId:P.launchId,expiresAtMs:P.expiresAtMs},N=async(m)=>{let S=await _r(ge,{type:"job",version:2,generation:1,id:Q(),jobId:e.claim.operation_id,...m==="start"?{action:m,input:{script:e.command,leaseExpiresAtMs:e.expiresAtMs}}:m==="inspect"?{action:m,input:{after:0}}:m==="probe"?{action:"inspect",input:{after:Number.MAX_SAFE_INTEGER}}:{action:m,input:{}}},new AbortController().signal);if(!S.ok)throw M(S.error);return S.job},U=!1,q=!1,te,re=()=>{U=!0,at(x,"SIGTERM")};e.signal.addEventListener("abort",re,{once:!0});let T,oe=0,ve=async(m)=>{let S=[...m.output],f={version:1,process_id:e.claim.operation_id,state:m.state,exit_code:m.exitCode,first_cursor:m.firstCursor,next_cursor:m.nextCursor,truncated:m.truncated,output:S,observed_at:new Date().toISOString()};while(Buffer.byteLength(JSON.stringify(f))>90000&&S.length)S.shift(),f.truncated=!0,f.first_cursor=S[0]?.cursor??f.next_cursor+1;T=J.parse(f),await e.emit(T),oe=Date.now()};try{let m=Math.min(Date.now()+1e4,e.expiresAtMs);while(!Z(P.readyPath)){if(I)throw new r("process_start_failed","The managed process supervisor exited before accepting a command; no command was dispatched.");if(e.signal.aborted||Date.now()>=m)throw M("process_start_unconfirmed");await ue(25)}let S=JSON.parse(Ne(P.readyPath,"utf8"));if(S.launchId!==P.launchId||S.fenceId!==P.fenceId||S.workerArtifactSha256!==b)throw M();if(e.signal.throwIfAborted(),c.cancelRequested)return pe(e.claim.operation_id);let f;try{q=!0,f=await N("start")}catch(O){if(!(O instanceof r)||O.code!=="hands_job_result_unknown")throw O;f=await N("inspect")}if(c.phase="running",c.cancel=async()=>{await N("cancel")},w&&e.preview)c.tunnels=le({claim:e.claim,executorLaunchId:P.launchId,expiresAtMs:e.expiresAtMs,deniedPorts:e.preview.deniedPorts,inspect:async()=>c.phase==="running"&&!I?await N("probe"):null});if(c.cancelRequested)await c.cancel(),f=await N("inspect");for(;;){if(!["starting","running"].includes(f.state))c.phase="settling",c.cancel=void 0;if(!T||T.state!==f.state||T.next_cursor!==f.nextCursor&&Date.now()-oe>=5000)await ve(f);if(!["starting","running"].includes(f.state))break;if(e.signal.aborted||I)throw M();await ue(1000);try{f=await N("inspect"),te=void 0}catch(O){if(!(O instanceof r)||O.code!=="hands_job_result_unknown"||e.signal.aborted||I||Date.now()-(te??=Date.now())>120000)throw O}}if(!T||T.state==="uncertain")throw M();return T}finally{if(c.phase="settling",c.cancel=void 0,c.tunnels?.dispose(),c.tunnels=void 0,await c.cancelInFlight?.catch(()=>{}),e.signal.removeEventListener("abort",re),!I&&!U)at(x,"SIGTERM");let m,S=await Promise.race([F.then((f)=>({code:f})),new Promise((f)=>{m=setTimeout(()=>f(null),6000)})]).finally(()=>{clearTimeout(m)});if(!S){try{at(x,"SIGKILL")}catch{}try{await F}finally{if(I)l.disposeSocket()}throw M("process_cleanup_unconfirmed")}try{if((U||e.signal.aborted)&&S.code===0&&q){v(E);let f=JSON.parse(h(P.directTerminalReceiptPath)),O=X.safeParse(f.observation);if(Object.keys(f).length===4&&f.launch_id===P.launchId&&f.fence_id===P.fenceId&&f.scope_id===l.scopeId&&O.success&&O.data.process_id===e.claim.operation_id){if(w)z();throw new ot(O.data)}}}catch(f){if(f instanceof ot)throw f}finally{if(I)l.disposeSocket()}if(S.code!==0&&!U&&q)throw M("process_cleanup_unconfirmed");if(!U&&S.code===0&&(T&&["exited","cancelled","expired"].includes(T.state)||!q&&c.cancelRequested)||w&&S.code===0&&!q)z()}}async function $s(e,c){if(c.kind===ce&&e.capability===he){let C=V.get(e.operation_id);if(C?.claim===e&&C.tunnels)C.tunnels.open(c.payload);else Y(c.payload,e.operation_id,"server_not_running");return!0}if(c.kind!==ne||!ae(e.capability)||!e.owner||c.payload.process_id!==e.operation_id)return!1;let _=V.get(e.operation_id);if(_&&_.claim!==e)return!1;let l=be(e);if(l.cancelRequested=!0,l.phase==="running"&&l.cancel)l.cancelInFlight??=l.cancel(),await l.cancelInFlight;return!0}function Bs(e,c){V.delete(e);let _=B.get(e);if(!_||c!=="succeeded"&&!_.anyCompletion)return B.delete(e),!1;try{let l=me(_.path);if(!l.isDirectory()||l.isSymbolicLink()||l.ino!==_.ino||l.dev!==_.dev||!A(l)||G(_.path)!==_.path||Z(j(_.path,"owner.lock")))return!1;return Ve(_.path,{recursive:!0}),B.delete(e),!0}catch{return!1}}
|
|
4
4
|
export{Ki,Ji,_n,Zi,yn,Xi,ot,fr,$s,Bs};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Qe}from"./vm-hands-entry-lite-
|
|
2
|
+
import{Qe}from"./vm-hands-entry-lite-10txe4yb.js";import{a}from"./vm-hands-entry-lite-0sh835na.js";import{randomUUID as L}from"crypto";import{spawnSync as b}from"child_process";import{chmodSync as ee,cpSync as te,existsSync as x,lstatSync as A,mkdirSync as Y,readdirSync as ne,readFileSync as w,readlinkSync as re,realpathSync as T,renameSync as E,rmdirSync as ie,rmSync as g,symlinkSync as M,writeFileSync as oe}from"fs";import{dirname as I,join as u,relative as se,resolve as ce}from"path";var Zn="so.ara.cli",k=[Zn,"com.reasonmachines.cli"],F="5LJFSBRY2F";function Gr(e){return`(${e.map((t)=>`identifier "${t}"`).join(" or ")}) and anchor apple generic and certificate 1[field.1.2.840.113635.100.6.2.6] exists and certificate leaf[field.1.2.840.113635.100.6.1.13] exists and certificate leaf[subject.OU] = "${F}"`}var G="ReasonBackgroundIdentity",Io="Contents/Helpers/ReasonPermissionTile",ae="so.ara.cli.permission-tile",Ne=Gr([ae,"com.reasonmachines.cli.permission-tile"]),v="AraBackgroundIdentity",ue="Reason",Ce=Gr(k),de=`anchor apple generic and (${k.map((e)=>`identifier "${e}"`).join(" or ")}) and certificate leaf[subject.OU] = "${F}"`;class h extends Error{code;constructor(e,t){super(t);this.code=e;this.name="MacOSBackgroundIdentityError"}}var R="/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister";function le(e=a()){return u(e,"Library","Application Support","Reason","Background","Reason.app")}function O(e=a()){return u(e,"Library","Application Support","Ara","Background","Ara.app")}function fe(e){try{return A(e).isFile()}catch{return!1}}function D(e){return[G,v].map((t)=>u(e,"Contents","MacOS",t)).find(fe)??null}function d(e){try{if(!A(e).isDirectory())return!1;let t=w(u(e,"Contents","Info.plist"),"utf8");return k.some((n)=>t.includes(`<string>${n}</string>`))&&(t.includes(`<string>${ue}</string>`)||t.includes("<string>Ara</string>"))&&D(e)!==null}catch{return!1}}function Kr(e=a()){let t=le(e);if(!d(t))return null;try{let n=w(u(t,"Contents","Info.plist"),"utf8");return/<key>CFBundleVersion<\/key>\s*<string>(\d+\.\d+\.\d+)<\/string>/.exec(n)?.[1]??null}catch{return null}}function pe(e,t=a()){let n=Kr(t);return n===null||j(N(n.split(".")),N(e.split(/[.-]/).slice(0,3)))}var ge=1e4;function K(e,t){return b(e,[...t],{stdio:"ignore",timeout:ge}).status??1}var W=new Set;function H(e){if(process.env.REASON_TEST_REFUSE_REAL_IDENTITY!=="1")return;let t=(n)=>{try{return T(n)}catch{return ce(n)}};if(e!==void 0&&t(e)!==t(a()))return;throw Error("A test tried to change this computer's real Reason background identity; pass a temporary home. Refused by scripts/test-env.ts.")}var V=/\/(?:runtime|CLI)\/versions\/(\d+)\.(\d+)\.(\d+)[^/]*\/[^/]+$|\/\.(?:ara|reason)(?:-staging)?-worker-(\d+)\.(\d+)\.(\d+)[^/]*\/[^/]+$/,J=new Set(["ara","ara.exe","reason","reason.exe"]);function N(e){return e.map((t)=>Number(t))}function j(e,t){for(let n=0;n<3;n+=1)if(e[n]!==t[n])return e[n]<t[n];return!1}var ye=[0,2,161];function me(e){if(e===null)return!0;let t=ye,n=null;try{n=T(process.execPath)}catch{}return e.some((r)=>{let i=V.exec(r);if(i){let f=i[1]===void 0?i.slice(4,7):i.slice(1,4);return j(N(f),t)}let o=r.slice(r.lastIndexOf("/")+1);return J.has(o)&&r!==n&&r!==process.execPath})}function Ee(){let e=b("/bin/ps",["-xo","pid=,comm="],{encoding:"utf8",timeout:5000});if(e.status!==0)return null;let t=[];for(let n of e.stdout.split(`
|
|
3
3
|
`)){let r=/^\s*(\d+)\s+(\S.*)$/.exec(n);if(!r||Number(r[1])===process.pid)continue;let i=r[2].trimEnd(),o=i.slice(i.lastIndexOf("/")+1);if(!V.test(i)&&J.has(o)){let c=b("/usr/sbin/lsof",["-a","-p",r[1],"-d","txt","-Fn"],{encoding:"utf8",timeout:5000}).stdout?.split(`
|
|
4
4
|
`).find((l)=>l.startsWith("n/"));if(c)i=c.slice(1)}t.push(i)}return t}function _e(e){if(H(e.home),!d(e.sourceApp))throw new h("identity_invalid","The packaged Reason background identity is missing or invalid.");let t=e.command??K,n=le(e.home),r=I(n);Y(r,{recursive:!0,mode:448}),ee(r,448);let i=T(e.sourceApp),o=null;try{o=T(n)}catch{}if(i!==o){let f=`${process.pid}.${L()}`,c=u(r,`.Reason.app.${f}.tmp`),l=u(r,`.Reason.app.${f}.old`),y=!1;try{if(te(i,c,{recursive:!0,errorOnExist:!0,preserveTimestamps:!0}),!d(c))throw new h("identity_invalid","The copied Reason background identity is invalid.");let _=e.releaseSigned?["--test-requirement",`=${de}`]:[];if(t("/usr/bin/codesign",["--verify","--strict",..._,c])!==0)throw new h("identity_invalid_signature","The installed Reason background identity has an invalid signature.");let S=!1;for(let p=0;p<4;p+=1){let m=!1;try{E(n,l),m=!0,y=!0}catch(s){if(s.code!=="ENOENT")throw s}if(p===0)e.beforePublish?.();try{E(c,n),S=!0}catch(s){let Z=s.code;if(!["EEXIST","ENOTEMPTY"].includes(Z??""))throw s;if(m)g(l,{recursive:!0,force:!0}),y=!1;if(p===3)throw s;continue}if(m)g(l,{recursive:!0,force:!0}),y=!1;break}if(!S)throw Error("Could not publish Reason's background identity.")}catch(_){if(y&&!x(n)&&x(l))E(l,n);throw _}finally{g(c,{recursive:!0,force:!0}),g(l,{recursive:!0,force:!0})}}return z(n,e,{verified:i!==o}),n}function X(e){return u(I(e),".Reason.app.registered")}function q(e){try{let t=A(e);return t.isDirectory()?`${t.ino}:${t.birthtimeMs}`:null}catch{return null}}function C(e){let t=q(e);try{return t!==null&&w(X(e),"utf8")===t}catch{return!1}}function Q(e){if(d(e))return"bundle";try{if(A(u(e,"Contents","Info.plist"),{throwIfNoEntry:!1}))return null;return A(u(e,"Contents","MacOS",v)).isSymbolicLink()?"retired":null}catch{return null}}function z(e,t,n={}){let r=t.command??K;if(!n.verified&&r("/usr/bin/codesign",["--verify","--strict",e])!==0)throw new h("identity_invalid_signature","The installed Reason background identity has an invalid signature.");if(r(R,["-f",e])!==0)throw new h("identity_register_failed","Could not register Reason's macOS background identity.");let i=q(e);try{if(i)oe(X(e),i,{mode:384})}catch{}try{Se(e,t.home,r,t.runningExecutables??Ee)}catch(o){let f=o.code??"unknown";process.stderr.write(`Reason background identity: legacy_identity_retire_failed (${f})
|
|
5
5
|
`)}}function Se(e,t,n,r){let i=D(e);if(!i)return;let o=O(t),f=I(o),c=(s)=>u(s,"Contents","MacOS",v),l=se(I(c(o)),i),y=`${process.pid}.${L()}`,_=Q(o);if(_===null)return;let S=_==="bundle";if(S)n(R,["-u",o]);let p=u(f,`.Ara.app.${y}.old`);if(!W.has(o)&&!me(r())){if(!S)n(R,["-u",o]);try{E(o,p)}catch(s){if(s.code==="ENOENT")return;throw s}g(p,{recursive:!0,force:!0}),Ie(f);return}if(!S){if(re(c(o))===l)return;let s=`${c(o)}.${y}`;M(l,s);try{E(s,c(o))}finally{g(s,{force:!0})}return}let m=u(f,`.Ara.app.${y}.shim`);Y(I(c(m)),{recursive:!0}),M(l,c(m));try{try{E(o,p)}catch(s){if(s.code==="ENOENT")return;throw s}try{E(m,o)}catch(s){if(x(o))return;throw E(p,o),s}}finally{g(m,{recursive:!0,force:!0}),g(p,{recursive:!0,force:!0})}}function Ie(e){try{if(ne(e).some((n)=>n!==".DS_Store"))return;g(u(e,".DS_Store"),{force:!0}),ie(e)}catch{}}var B=new Map;function Xn(e=a()){let t=B.get(e);if(t)return t;if(process.platform!=="darwin")return[];let n=U(e);if(n===null&&x(I(le(e))))Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,100),n=U(e);if(n===null)return[];return B.set(e,n),n}function U(e){let t=le(e),n=O(e);if(!d(t)||!C(t))try{he({home:e,skipWhenSettled:!0})}catch{}let r=d(t)&&(C(t)||!d(n))?t:d(n)?n:null,i=r?D(r):null;if(!i)return null;if(r===n)W.add(n);let o=b(i,["--can-spawn"],{env:{},timeout:2000,encoding:"utf8"});return o.status===0&&o.stdout===`spawn
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{T}from"./vm-hands-entry-lite-fcvf8md1.js";import{Mo}from"./vm-hands-entry-lite-wp0d65yx.js";import{Fe,un,It,dn}from"./vm-hands-entry-lite-pwmvq53c.js";import{Yn}from"./vm-hands-entry-lite-42117xc5.js";import{t,o,d,u,i,hs,W,g,s,n}from"./vm-hands-entry-lite-qzcac2mf.js";var q=/^(0|[1-9][0-9]{0,5})\.(0|[1-9][0-9]{0,5})$/;function k(e){let r=typeof e==="string"?q.exec(e):null;return r?{major:Number(r[1]),minor:Number(r[2])}:null}var j=25,v=1e5,L=/^[0-9a-f]{64}$/,N=i({day:t().regex(/^\d{4}-\d{2}-\d{2}$/),sent:o().int().min(0).max(v),received:o().int().min(0).max(v)}),Te=i({machine:t().min(1).max(200),person:t().min(1).max(200),team:t().min(1).max(200),team_id:t().min(1).max(200).optional(),workspace:d().optional(),version:t().max(64).optional(),wait_seconds:o().int().min(0).max(j).optional(),message_counts:u(N).max(14).optional().catch(void 0),endpoint:t().regex(L).optional().catch(void 0)}),D=g("kind",[i({id:t(),kind:n("who"),all:d().optional()}),i({id:t(),kind:n("send"),to:t(),body:t(),from_name:t(),from_agent:t(),wake:d(),reply_to:t().max(100).optional(),notify:d().optional()})]),x=i({job:D.nullable(),retry_after_seconds:o().optional()}),H=i({address:t(),person:t(),machine:t(),agent:t(),repo:t().nullable(),branch:t().nullable(),status:t(),since:o().nullable(),doing:t().nullable(),worker:d(),tier:t().max(10).optional()}),F=i({person:t(),machine:t(),online:d()}),B=i({team:t().nullable(),sessions:u(H).max(2000),machines:u(F).max(500),all:d().optional()}),G=i({address:t().max(300),state:t().max(40),note:t().max(500)}),$e=W([i({who:B}),i({sent:i({ids:u(t().max(100)).max(500),recipients:u(t().max(300)).max(500),from:t().max(300),deliveries:u(G).max(500).optional()})}),i({error:t().min(1).max(2000)})]),J=i({id:t().max(100),from:t().max(300),from_agent:t().max(100).nullable(),to:t().max(300),reply_to:t().max(100).nullable(),body:t().max(64000),sent_at:o()}),Ue=i({messages:u(J).max(100),team:t().min(1).max(200).optional(),team_id:t().min(1).max(200).optional(),workspace:d().optional()});var P=["run","mcp:read","mcp:write","secrets:read","secrets:write","sessions:read","sessions:debug","devices:read","devices:write","devices:use","ssh:write","knowledge:read","memory:read","memory:write","skills:read","skills:write","repos:read","repos:write","reviews:read","reviews:write","deployment:read","analytics:read","org:read","org:write","attachments:read","attachments:write","guardrails:read","guardrails:write","network:read","network:write","automations:read","automations:write","agent_auth:read"];var We=P.filter((e)=>e!=="network:read"&&e!=="network:write");class R extends Error{oauthCode;constructor(e,r=null){super(e);this.oauthCode=r;this.name="LoginError"}}function Q(e,r){let a=typeof e.error==="string"?e.error:null,l=typeof e.error_description==="string"?e.error_description:a?a:r;return new R(l,a)}async function K(e,r,a,l){let c=await a(`${e}/mcp/oauth/token`,{method:"POST",redirect:"error",headers:{"content-type":"application/x-www-form-urlencoded"},body:r,signal:l}),m=await c.json().catch(()=>({}));if(!c.ok)throw Q(m,`OAuth token request failed (${c.status})`);return m}var V=1e4;async function Y(e,r={}){let a=r.fetchImpl??fetch,l=await K(e.apiOrigin,new URLSearchParams({grant_type:"refresh_token",client_id:e.clientId,refresh_token:e.refreshToken}),a,AbortSignal.timeout(V)).catch((m)=>{if(m instanceof Error&&m.name==="TimeoutError")throw new R("Reason did not answer the login refresh in time. Check the network and retry.");throw m});if(typeof l.access_token!=="string"||typeof l.refresh_token!=="string"||typeof l.expires_in!=="number")throw new R("Reason returned an incomplete refreshed login.");let c={...e,accessToken:l.access_token,refreshToken:l.refresh_token,expiresAt:new Date(Date.now()+l.expires_in*1000).toISOString(),scopes:typeof l.scope==="string"?l.scope.split(/\s+/).filter(Boolean):e.scopes};return un(c,r.path??Fe()),c}var b=new Map,X=2000,Z=100;function C(e,r){if(!r)return e;if(r.aborted)return Promise.reject(r.reason);return new Promise((a,l)=>{let c=()=>l(r.reason);r.addEventListener("abort",c,{once:!0}),e.then(a,l).finally(()=>r.removeEventListener("abort",c))})}async function Ot(e={}){let r=e.path??Fe(),a=It(r);if(!a)return null;let l=e.apiOrigin??T(process.env,"REASON_API_URL")?.trim();if(l&&!Mo(a.apiOrigin,new URL(l).origin))return null;if(!(Date.parse(a.expiresAt)<=Date.now()+60000)&&(!e.forceRefresh||e.refused!==void 0&&a.accessToken!==e.refused))return a;let m=[r,a.apiOrigin,a.clientId,a.refreshToken].join("\x00"),p=b.get(m);if(p)return C(p,e.signal);let f;return f=Y(a,{fetchImpl:e.fetchImpl,path:r}).catch(async(y)=>{if(!(y instanceof R)||y.oauthCode!=="invalid_grant"&&y.oauthCode!=="invalid_client")throw y;let S=(_)=>_!==null&&(y.oauthCode==="invalid_client"?_.clientId!==a.clientId:_.refreshToken!==a.refreshToken),E=Date.now()+X;while(!S(It(r))&&Date.now()<E)await new Promise((_)=>setTimeout(_,Z));if(S(It(r)))return Ot({fetchImpl:e.fetchImpl,path:r});return dn(r),null}).finally(()=>{if(b.get(m)===f)b.delete(m)}),b.set(m,f),C(f,e.signal)}var ee=i({label:t(),used_percent:o().min(0).max(100).nullable(),resets_at:t().nullable(),exhausted:d().nullable()}),ne=i({groups:u(i({selectable:d().optional(),accounts:u(i({source_id:t().min(1),model_ids:u(t().min(1)).optional()}))}))});function te(e){let r=ne.safeParse(e);if(!r.success)return;return r.data.groups.some((a)=>a.selectable!==!1&&a.accounts.some((l)=>l.model_ids===void 0||l.model_ids.length>0))}class I extends Error{status;code;suggestedModel;retryAfterMs;resolutionReason;refusal;constructor(e,r,a,l,c,m,p){super(a);this.status=e;this.code=r;this.suggestedModel=l;this.retryAfterMs=c;this.resolutionReason=m;this.refusal=p;this.name="ApiError"}static rateLimitDelayMs(e,r){if(!(e instanceof I)||e.status!==429)return null;return Math.min(60000,Math.max(r,e.retryAfterMs??0))}}var se=["minimal","low","medium","high","xhigh","max"],oe=i({id:t().min(1),kind:t(),name:t(),custom_name:t().nullish(),status:t(),online:d(),compatible:d().optional(),compatibility_reason:t().nullish(),folder_lane_of:t().nullish(),roots:u(i({id:t().min(1),label:t()}))}),re=i({devices:u(oe),end_cursor:t().nullish(),has_next_page:d().optional()}),ie=i({id:t().min(1),name:t()}),ae=i({items:u(ie)}),le=i({id:t().min(1),name:t(),main:d(),mine:d(),session_id:t().nullish(),appearance:i({color:t().nullish()}).nullish().catch(null)}),ce=i({items:u(le)}),de=i({skill_id:t().min(1),name:t(),description:t().nullish(),activation_keywords:u(t()).default([]),is_enabled:d().default(!0)}),ue=i({items:u(de).default([])}),me=i({id:t().min(1),kind:t(),enabled:d(),schedule:i({expression:t().nullish(),every_seconds:o().nullish(),next_run_at:t().nullish()}).nullish(),github:i({event:t().nullish(),action:t().nullish(),repo:t().nullish()}).nullish(),last_fired_at:t().nullish()}),U=i({id:t().min(1),name:t().nullish(),instructions:t().nullish(),enabled:d(),triggers:u(me).default([])}),ge=i({items:u(U).default([]),end_cursor:t().nullish(),has_next_page:d().optional()}),he=i({id:t().min(1),slug:t().nullish(),name:t(),description:t().nullish(),transport:t().nullish(),url:t().nullish(),enabled:d()}),pe=i({items:u(he).default([])}),fe=i({status:t(),summary:t().nullish(),category:t().nullish(),outcome:t().nullish(),message_count:o().nullish(),pr_url:t().nullish(),cost_usd:o().nullish(),generated_at:t().nullish()}),A=i({tags:u(t()).default([])}),ye=s(["linux","macos"]),O=i({id:t().min(1),name:t().min(1),platform:ye.nullable(),workers:i({total:o().int(),online:o().int(),busy:o().int(),idle:o().int()}),sessions:i({queued:o().int(),running:o().int()})}),_e=i({machines:u(O)}),Re=i({machine:O}),be=i({deleted:n(!0),revoked_workers:o().int(),revoked_tokens:o().int()}),we=i({token:i({id:t().min(1),machine_id:t().min(1),token_prefix:t()}),secret:t().startsWith("rmt_")}),M=hs({machine_id:t().min(1),machine_name:t().min(1)}),Se=M.extend({organization_id:t().min(1)}),on=i({id:t().min(1),name:t().min(1),state:s(["waiting","placed"]),queue_position:o().int().nullable()});var rn=W([i({kind:n("cloud")}),i({kind:s(["mac","headless"]),device_id:t().min(1),root_id:t().min(1)})]);function h(e,r,a){let l=e.safeParse(r);if(!l.success)throw new I(502,a,"Reason returned an unexpected response.");return l.data}var ke=i({error:i({type:t(),message:t()})});function w(e,r,a){let l=ke.safeParse(r),c=typeof r.error==="string"?r.error:l.success?l.data.error.type:`http_${e}`,m=typeof r.detail==="string"?r.detail:typeof r.message==="string"?r.message:l.success?l.data.error.message:`Reason request failed (${e}${typeof r.error==="string"?` ${r.error}`:""})`,p=c==="github_connection_required"&&typeof r.connect_url==="string"&&/^https?:\/\//.test(r.connect_url)?` Connect it at ${r.connect_url}`:"",f=a===null||a.trim()===""?NaN:Number(a);return new I(e,c,`${m}${p}`,typeof r.suggested_model==="string"?r.suggested_model:void 0,Number.isFinite(f)&&f>=0?f*1000:void 0,typeof r.resolution_reason==="string"?r.resolution_reason:void 0,typeof r.code==="string"?{code:r.code,...typeof r.billing_path==="string"&&/^\/(?![/\\])/.test(r.billing_path)?{billingPath:r.billing_path}:{}}:void 0)}async function ks(e){let r=await(e.fetchImpl??fetch)(`${e.apiOrigin}/v3/machines/enrollment-tickets`,{method:"POST",headers:{authorization:`Bearer ${e.token}`,accept:"application/json","content-type":"application/json"},body:JSON.stringify(e.body),signal:AbortSignal.timeout(30000),redirect:"error"}),a=await r.json().catch(()=>({}));if(!r.ok)throw w(r.status,a,r.headers.get("retry-after"));return h(Se,a,"invalid_machine_ticket")}class Qo{options;credentials;constructor(e,r={}){this.options=r;this.credentials=e}trackEvent(e,r={}){}async request(e,r={}){let{status:a,headers:l,json:c}=await this.exchange(e,r);if(a<200||a>299)throw w(a,c,l.get("retry-after"));return c}async exchange(e,r={},a=!1){let l=this.options.fetchImpl??fetch,c=await l(`${this.credentials.apiOrigin}/v3${e}`,{method:r.method??"GET",headers:{authorization:`Bearer ${this.credentials.accessToken}`,accept:"application/json","user-agent":Yn,"x-reason-agent":"Reason CLI","x-client-surface":this.options.clientSurface??"direct_cli",...r.raw?{"content-type":r.raw.contentType}:r.body===void 0?{}:{"content-type":"application/json"},...r.headers,...r.ifNoneMatch?{"if-none-match":r.ifNoneMatch}:{}},body:r.raw?r.raw.bytes:r.body===void 0?void 0:JSON.stringify(r.body),signal:r.signal,redirect:r.ifNoneMatch?"manual":"error"}),m=await c.json().catch(()=>({}));if(c.status===401&&!a&&r.retryUnauthorized!==!1&&this.credentials.credentialKind!=="api_key"){let p=await Ot({fetchImpl:l,path:this.options.credentialsPath,forceRefresh:!0,refused:this.credentials.accessToken,signal:r.signal});if(p)return this.credentials=p,this.exchange(e,r,!0)}return{status:c.status,headers:c.headers,json:m}}createHeadlessDeviceEnrollmentTicket(e){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/enrollment-tickets`,{method:"POST",body:e,signal:AbortSignal.timeout(30000),retryUnauthorized:!1})}async enrollHeadlessDevice(e){try{return await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/enrollments`,{method:"POST",body:e,signal:AbortSignal.timeout(30000),retryUnauthorized:!1})}catch(r){if(r instanceof I&&(r.status===404||r.status===405||r.status===403&&r.code==="endpoint_not_available"))return null;throw r}}addDeviceRoot(e,r){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/${encodeURIComponent(e)}/roots`,{method:"POST",body:r,signal:AbortSignal.timeout(30000)})}removeDeviceRoot(e,r){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/${encodeURIComponent(e)}/roots/${encodeURIComponent(r)}`,{method:"DELETE",signal:AbortSignal.timeout(30000)})}machinePath(e,r=""){let a=`/organizations/${encodeURIComponent(this.credentials.orgId)}/machines`;return e===void 0?a:`${a}/${encodeURIComponent(e)}${r}`}async listMachines(){return h(_e,await this.request(this.machinePath()),"invalid_machine_list").machines}async createMachine(e){let r=await this.request(this.machinePath(),{method:"POST",body:{name:e.name,...e.platform?{platform:e.platform}:{}}});return h(Re,r,"invalid_machine").machine}async deleteMachine(e){let r=await this.request(this.machinePath(e),{method:"DELETE"});return h(be,r,"invalid_machine_deletion")}async createMachineToken(e){let r=await this.request(this.machinePath(e,"/tokens"),{method:"POST",body:{}});return h(we,r,"invalid_machine_token")}async createMachineEnrollmentTicket(e,r){let a=await this.request(this.machinePath(e,"/enrollment-tickets"),{method:"POST",body:r,signal:AbortSignal.timeout(30000),retryUnauthorized:!1});return h(M,a,"invalid_machine_ticket")}self(e){return this.request("/self",{signal:e})}submitFeedback(e){return this.request("/feedback",{method:"POST",body:e,signal:AbortSignal.timeout(30000)})}agentNetwork(){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network`,{signal:AbortSignal.timeout(30000)})}startAgentNetwork(e){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network`,{method:"POST",body:e,signal:AbortSignal.timeout(30000)})}rotateAgentNetwork(e){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network`,{method:"PUT",body:e,signal:AbortSignal.timeout(30000)})}async claimAgentNetworkRelayJob(e,r){let a=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network/relay/claim`,{method:"POST",body:e,signal:r});return h(x,a,"invalid_agent_network_job")}async completeAgentNetworkRelayJob(e,r){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network/relay/jobs/${encodeURIComponent(e)}`,{method:"POST",body:r,signal:AbortSignal.timeout(30000)})}async recordAgentNetworkRelayReplies(e){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network/relay/replies`,{method:"POST",body:e,signal:AbortSignal.timeout(30000)})}async workspaceMembers(){return((await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/members/users`,{signal:AbortSignal.timeout(30000)})).items??[]).flatMap((r)=>typeof r.email==="string"?[{email:r.email,role:typeof r.role==="string"?r.role:"member"}]:[])}claimExistingCliPairing(e){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/onboarding/import/pairing/claim-existing`,{method:"POST",body:{pairing_code:e}})}async claudeCodeSignIn(e){return(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/provider-credentials`,{retryUnauthorized:!1,signal:e?AbortSignal.any([e,AbortSignal.timeout(15000)]):AbortSignal.timeout(15000)})).claude_code_sign_in===!0}connectAnthropicProvider(e,r,a={}){let l=e.kind==="setup_token"?{setup_token:e.token}:{access_token:e.credential.access,refresh_token:e.credential.refresh,expires_at:new Date(e.credential.expires).toISOString()};return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/provider-credentials/anthropic`,{method:"POST",retryUnauthorized:a.retryUnauthorized,signal:a.signal,body:{...l,...r?{account_key:r}:{}}})}async listRepositories(){return((await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/repositories`)).items??[]).flatMap((r)=>{let a=typeof r.full_name==="string"?r.full_name:typeof r.repo_full_name==="string"?r.repo_full_name:null;if(!a)return[];return[{repo_id:typeof r.repo_id==="string"?r.repo_id:void 0,full_name:a,provider:r.provider==="gitlab"?"gitlab":"github",default_branch:typeof r.default_branch==="string"?r.default_branch:null,private:typeof r.private==="boolean"?r.private:void 0}]})}async listProjects(){let e=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/projects`),r=ae.safeParse(e);if(!r.success)throw new I(502,"invalid_project_list","Reason returned an unexpected project list.");return r.data.items}async listReasons(){let e=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/reasons`);return h(ce,e,"invalid_reason_list").items}async openReasonConversation(e){let r=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/reasons/${encodeURIComponent(e)}/conversation`,{method:"POST"});return h(i({session_id:t().min(1)}),r,"invalid_reason_conversation").session_id}async listSkills(){try{let e=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/skills`);return h(ue,e,"invalid_skill_list").items}catch(e){if(e instanceof I&&(e.status===403||e.status===404))return[];throw e}}async listDevices(){let e=[],r=null;for(let a=0;a<50;a+=1){let l=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices${r?`?after=${encodeURIComponent(r)}`:""}`),c=re.safeParse(l);if(!c.success)throw new I(502,"invalid_device_list","Reason returned an unexpected machine list.");if(e.push(...c.data.devices),r=c.data.has_next_page?c.data.end_cursor??null:null,!r)break}return e}async listModels(){try{let r=((await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-auth/models`)).models??[]).filter((c)=>c.hidden!==!0),a=r.filter((c)=>c.available!==!1).map(({reasoning_efforts:c,hidden:m,available:p,...f})=>({...f,...Array.isArray(c)?{reasoning_efforts:se.filter((y)=>c.includes(y))}:{}})),l=new Set(a.map((c)=>c.detail));return{models:a.length>1&&l.size===1?a.map(({detail:c,...m})=>m):a,runnable:a.length>0||r.length===0}}catch(e){if(e instanceof I&&(e.status===403||e.status===404))return{models:[],runnable:!0};throw e}}async getAgentVersion(e){try{let r=await this.request("/deployment",{signal:e,retryUnauthorized:!1});return k(r.reason_version)?r.reason_version:null}catch{return null}}async getUsageQuota(){try{let e=ee.safeParse(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/usage/quota`));if(!e.success)return null;let r;try{r=te(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-auth/models`))}catch{}return{...e.data,own_inference:r}}catch(e){if(e instanceof I&&(e.status===403||e.status===404))return null;throw e}}async listSessionFields(e){let r=new URLSearchParams({first:String(Math.min(Math.max(e.first,1),200)),status:e.status??"active"});if(e.origin)r.set("origin",e.origin);r.set("fields",e.fields.join(","));let a=`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions?${r.toString()}`,{status:l,headers:c,json:m}=await this.exchange(a,e.etag?{ifNoneMatch:e.etag}:{});if(l===304)return null;if(l<200||l>299)throw w(l,m,c.get("retry-after"));return{items:Array.isArray(m.items)?m.items:[],etag:c.get("etag")}}async listSessions(e=50,r,a={}){let l=new URLSearchParams({first:String(Math.min(Math.max(e,1),200)),status:a.status??"active"});if(r)l.set("project_id",r);if(a.origin)l.set("origin",a.origin);return(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions?${l.toString()}`)).items??[]}getSession(e,r){let a=r?.fields.length?`?fields=${encodeURIComponent(r.fields.join(","))}`:"";return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}${a}`)}async prestartSession(e){let r=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/prestart`,{method:"POST",body:{client_session_id:e}});return r?.status==="starting"||r?.status==="ready"}async createSession(e){let r=e.mode==="ephemeral"||e.workspaceOwnership==="externally-managed";if(e.attachments?.length)await this.requireSessionAttachments();if(r||e.runtimeProfile){let c=await this.request("/deployment");if(r&&(!Array.isArray(c.session_modes)||!c.session_modes.includes(e.mode??"standard")||!Array.isArray(c.workspace_ownerships)||!c.workspace_ownerships.includes(e.workspaceOwnership??"managed")))throw Error("Deployment does not support the requested Session policy; refusing to create a Session.");if(e.runtimeProfile&&(!Array.isArray(c.experimental_runtime_profiles)||!c.experimental_runtime_profiles.includes(e.runtimeProfile)))throw Error("Deployment does not support the requested runtime profile; refusing to create a Session.")}let a=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions`,{method:"POST",body:{prompt:e.prompt,...e.attachments?.length?{attachments:e.attachments}:{},...e.mode?{mode:e.mode}:{},...e.workspaceOwnership?{workspace_ownership:e.workspaceOwnership}:{},...e.target?{target:e.target}:{},...e.repo?{repo:e.repo}:{},...e.provider?{provider:e.provider}:{},...e.model?{model:e.model}:{},...e.reasoningEffort?{reasoning_effort:e.reasoningEffort}:{},...e.runtimeProfile?{experimental_runtime_profile:e.runtimeProfile}:{},...e.ref?{ref:e.ref}:{},...e.branch?{branch:e.branch}:{},...e.completionMode?{completion_mode:e.completionMode}:{},...e.env&&Object.keys(e.env).length>0?{env:e.env}:{},...e.clientSessionId?{client_session_id:e.clientSessionId}:{},...e.longRunning?{long_running:{enabled:!0}}:{},...e.spendLimitRcu?{spend_limit_rcu:e.spendLimitRcu}:{},idempotency_key:`cli-${crypto.randomUUID()}`}}),l=await this.getSession(a.session_id);if(r){let c=l.session_policy,m=["memoryRead","memoryWrite","skills","inheritedInstructions","integrations","secretInjection"];if(!c||c.version!==1||c.mode!==(e.mode??"standard")||c.workspaceOwnership!==(e.workspaceOwnership??"managed")||!c.components||m.some((p)=>c.components[p]!==!0))throw await this.cancelSession(a.session_id),Error("Server did not attest the requested Session policy; cancellation requested.")}if(e.runtimeProfile&&l.experimental_runtime_profile!==e.runtimeProfile)throw await this.cancelSession(a.session_id),Error("Server did not attest the requested runtime profile; cancellation requested.");return l}async getEvents(e,r=-1,a={}){try{return await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/events?after_seq=${r}&limit=500${a.waitMs?`&wait_ms=${a.waitMs}`:""}`,a.signal?{signal:a.signal}:{})}catch(l){if(!(l instanceof I)||l.status!==403&&l.status!==404)throw l;return{session:await this.getSession(e),items:[],next_seq:r}}}async getMessages(e,r){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/messages?first=500${r===void 0?"":`&after_seq=${r}`}`)}async getAttachments(e,r){try{return(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/attachments${r?`?view=${r}`:""}`)).items??[]}catch(a){if(a instanceof I&&(a.status===403||a.status===404))return[];throw a}}async requireSessionAttachments(){let e=await this.request("/deployment",{headers:{"cache-control":"no-cache"}});if(e.session_attachments!==!0){let r=typeof e.reason_version==="string"&&/^\d+\.\d+(?:\.\d+)?$/.test(e.reason_version)?`Agent ${e.reason_version}`:null,a=typeof e.commit_sha==="string"&&/^[a-f0-9]{40,64}$/i.test(e.commit_sha)?`server ${e.commit_sha.slice(0,12)}`:null,l=[r,a].filter(Boolean).join(", ");throw Error(`This server does not support Session image attachments: ${new URL(this.credentials.apiOrigin).host}${l?` (${l})`:""}. The API server needs an attachment-capable deployment; updating the Agent version alone is not enough. Your image was not sent; retry after the server update.`)}}async sendMessage(e,r,a={}){if(a.attachments?.length)await this.requireSessionAttachments();return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/messages`,{method:"POST",body:{message:r,...a.attachments?.length?{attachments:a.attachments}:{},...a.model?{model:a.model}:{},...a.reasoningEffort?{reasoning_effort:a.reasoningEffort}:{},...a.target?{target:a.target}:{},...a.delivery?{delivery:a.delivery}:{}}})}async steerQueuedMessage(e,r){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/messages/${encodeURIComponent(r)}/steer`,{method:"POST",body:{}})}async withdrawQueuedMessage(e,r){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/messages/${encodeURIComponent(r)}/queued`,{method:"DELETE"})}async getConversation(e){let r=[],a=null;for(let l=0;l<50;l+=1){let c=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/conversation${a?`?after=${encodeURIComponent(a)}`:""}`);if(r.push(...c.items??[]),!c.has_next_page||!c.end_cursor)break;a=c.end_cursor}return r}createSharedLink(e,r){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/shared-links`,{method:"POST",body:{url:r.url,...r.label?{label:r.label}:{},...r.expiresInSeconds!==void 0?{expires_in_seconds:r.expiresInSeconds}:{}}})}sessionAction(e,r,a={}){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/${r}`,{method:"POST",body:a})}renameSession(e,r){return this.sessionAction(e,"rename",{title:r||null})}moveSessionToProject(e,r){return this.sessionAction(e,"project",{project_id:r})}compactSession(e){return this.sessionAction(e,"compact")}retrySession(e){return this.sessionAction(e,"retry")}rewindSession(e,r){return this.sessionAction(e,"rewind",{message_id:r.messageId,content:r.content,request_id:r.requestId})}forkSession(e,r){return this.sessionAction(e,"fork",{...r.message?{message:r.message}:{},client_session_id:r.clientSessionId})}cancelSession(e,r={}){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/cancel`,{method:"POST",body:r.mode==="hard"?{mode:"hard"}:{}})}sessionPath(e,r=""){return`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}${r}`}async archiveSession(e){await this.request(this.sessionPath(e,"/archive"),{method:"POST",body:{}})}async unarchiveSession(e){await this.request(this.sessionPath(e,"/unarchive"),{method:"POST",body:{}})}async deleteSession(e){await this.request(this.sessionPath(e),{method:"DELETE"})}async listSessionTags(e){return h(A,await this.request(this.sessionPath(e,"/tags")),"invalid_session_tags").tags}async appendSessionTags(e,r){let a=await this.request(this.sessionPath(e,"/tags"),{method:"POST",body:{tags:r}});return h(A,a,"invalid_session_tags").tags}async sessionInsight(e,r=!1){let a=await this.request(this.sessionPath(e,r?"/insights/generate":"/insights"),r?{method:"POST",body:{}}:{});return h(fe,a,"invalid_session_insight")}async listAutomations(){let e=[],r=null;for(let a=0;a<20;a+=1){let l=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations?first=100${r?`&after=${encodeURIComponent(r)}`:""}`),c=h(ge,l,"invalid_automation_list");if(e.push(...c.items),r=c.has_next_page?c.end_cursor??null:null,!r)break}return e}async createScheduledAutomation(e,r){let a=`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations`,l=h(U,await this.request(a,{method:"POST",body:{name:e.name,instructions:e.instructions,...e.repo?{repo:e.repo.full_name,provider:e.repo.provider}:{}}}),"invalid_automation");try{await this.request(`${a}/${encodeURIComponent(l.id)}/triggers`,{method:"POST",body:r})}catch(c){throw await this.deleteAutomation(l.id).catch(()=>{return}),c}return l}async setAutomationEnabled(e,r){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations/${encodeURIComponent(e)}`,{method:"PATCH",body:{enabled:r}})}async deleteAutomation(e){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations/${encodeURIComponent(e)}`,{method:"DELETE"})}async transcribe(e,r){let a=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/transcribe`,{method:"POST",raw:{bytes:e,contentType:r}});return h(i({transcript:t()}),a,"invalid_transcript").transcript}async listMcpServers(){let e=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/mcp-servers`);return h(pe,e,"invalid_mcp_server_list").items}async setSkillEnabled(e,r){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/skills/${encodeURIComponent(e)}`,{method:"PUT",body:{is_enabled:r}})}}
|
|
2
|
+
import{T}from"./vm-hands-entry-lite-fcvf8md1.js";import{Mo}from"./vm-hands-entry-lite-wp0d65yx.js";import{Fe,un,It,dn}from"./vm-hands-entry-lite-pwmvq53c.js";import{Yn}from"./vm-hands-entry-lite-10txe4yb.js";import{t,o,d,u,i,hs,W,g,s,n}from"./vm-hands-entry-lite-qzcac2mf.js";var q=/^(0|[1-9][0-9]{0,5})\.(0|[1-9][0-9]{0,5})$/;function k(e){let r=typeof e==="string"?q.exec(e):null;return r?{major:Number(r[1]),minor:Number(r[2])}:null}var j=25,v=1e5,L=/^[0-9a-f]{64}$/,N=i({day:t().regex(/^\d{4}-\d{2}-\d{2}$/),sent:o().int().min(0).max(v),received:o().int().min(0).max(v)}),Te=i({machine:t().min(1).max(200),person:t().min(1).max(200),team:t().min(1).max(200),team_id:t().min(1).max(200).optional(),workspace:d().optional(),version:t().max(64).optional(),wait_seconds:o().int().min(0).max(j).optional(),message_counts:u(N).max(14).optional().catch(void 0),endpoint:t().regex(L).optional().catch(void 0)}),D=g("kind",[i({id:t(),kind:n("who"),all:d().optional()}),i({id:t(),kind:n("send"),to:t(),body:t(),from_name:t(),from_agent:t(),wake:d(),reply_to:t().max(100).optional(),notify:d().optional()})]),x=i({job:D.nullable(),retry_after_seconds:o().optional()}),H=i({address:t(),person:t(),machine:t(),agent:t(),repo:t().nullable(),branch:t().nullable(),status:t(),since:o().nullable(),doing:t().nullable(),worker:d(),tier:t().max(10).optional()}),F=i({person:t(),machine:t(),online:d()}),B=i({team:t().nullable(),sessions:u(H).max(2000),machines:u(F).max(500),all:d().optional()}),G=i({address:t().max(300),state:t().max(40),note:t().max(500)}),$e=W([i({who:B}),i({sent:i({ids:u(t().max(100)).max(500),recipients:u(t().max(300)).max(500),from:t().max(300),deliveries:u(G).max(500).optional()})}),i({error:t().min(1).max(2000)})]),J=i({id:t().max(100),from:t().max(300),from_agent:t().max(100).nullable(),to:t().max(300),reply_to:t().max(100).nullable(),body:t().max(64000),sent_at:o()}),Ue=i({messages:u(J).max(100),team:t().min(1).max(200).optional(),team_id:t().min(1).max(200).optional(),workspace:d().optional()});var P=["run","mcp:read","mcp:write","secrets:read","secrets:write","sessions:read","sessions:debug","devices:read","devices:write","devices:use","ssh:write","knowledge:read","memory:read","memory:write","skills:read","skills:write","repos:read","repos:write","reviews:read","reviews:write","deployment:read","analytics:read","org:read","org:write","attachments:read","attachments:write","guardrails:read","guardrails:write","network:read","network:write","automations:read","automations:write","agent_auth:read"];var We=P.filter((e)=>e!=="network:read"&&e!=="network:write");class R extends Error{oauthCode;constructor(e,r=null){super(e);this.oauthCode=r;this.name="LoginError"}}function Q(e,r){let a=typeof e.error==="string"?e.error:null,l=typeof e.error_description==="string"?e.error_description:a?a:r;return new R(l,a)}async function K(e,r,a,l){let c=await a(`${e}/mcp/oauth/token`,{method:"POST",redirect:"error",headers:{"content-type":"application/x-www-form-urlencoded"},body:r,signal:l}),m=await c.json().catch(()=>({}));if(!c.ok)throw Q(m,`OAuth token request failed (${c.status})`);return m}var V=1e4;async function Y(e,r={}){let a=r.fetchImpl??fetch,l=await K(e.apiOrigin,new URLSearchParams({grant_type:"refresh_token",client_id:e.clientId,refresh_token:e.refreshToken}),a,AbortSignal.timeout(V)).catch((m)=>{if(m instanceof Error&&m.name==="TimeoutError")throw new R("Reason did not answer the login refresh in time. Check the network and retry.");throw m});if(typeof l.access_token!=="string"||typeof l.refresh_token!=="string"||typeof l.expires_in!=="number")throw new R("Reason returned an incomplete refreshed login.");let c={...e,accessToken:l.access_token,refreshToken:l.refresh_token,expiresAt:new Date(Date.now()+l.expires_in*1000).toISOString(),scopes:typeof l.scope==="string"?l.scope.split(/\s+/).filter(Boolean):e.scopes};return un(c,r.path??Fe()),c}var b=new Map,X=2000,Z=100;function C(e,r){if(!r)return e;if(r.aborted)return Promise.reject(r.reason);return new Promise((a,l)=>{let c=()=>l(r.reason);r.addEventListener("abort",c,{once:!0}),e.then(a,l).finally(()=>r.removeEventListener("abort",c))})}async function Ot(e={}){let r=e.path??Fe(),a=It(r);if(!a)return null;let l=e.apiOrigin??T(process.env,"REASON_API_URL")?.trim();if(l&&!Mo(a.apiOrigin,new URL(l).origin))return null;if(!(Date.parse(a.expiresAt)<=Date.now()+60000)&&(!e.forceRefresh||e.refused!==void 0&&a.accessToken!==e.refused))return a;let m=[r,a.apiOrigin,a.clientId,a.refreshToken].join("\x00"),p=b.get(m);if(p)return C(p,e.signal);let f;return f=Y(a,{fetchImpl:e.fetchImpl,path:r}).catch(async(y)=>{if(!(y instanceof R)||y.oauthCode!=="invalid_grant"&&y.oauthCode!=="invalid_client")throw y;let S=(_)=>_!==null&&(y.oauthCode==="invalid_client"?_.clientId!==a.clientId:_.refreshToken!==a.refreshToken),E=Date.now()+X;while(!S(It(r))&&Date.now()<E)await new Promise((_)=>setTimeout(_,Z));if(S(It(r)))return Ot({fetchImpl:e.fetchImpl,path:r});return dn(r),null}).finally(()=>{if(b.get(m)===f)b.delete(m)}),b.set(m,f),C(f,e.signal)}var ee=i({label:t(),used_percent:o().min(0).max(100).nullable(),resets_at:t().nullable(),exhausted:d().nullable()}),ne=i({groups:u(i({selectable:d().optional(),accounts:u(i({source_id:t().min(1),model_ids:u(t().min(1)).optional()}))}))});function te(e){let r=ne.safeParse(e);if(!r.success)return;return r.data.groups.some((a)=>a.selectable!==!1&&a.accounts.some((l)=>l.model_ids===void 0||l.model_ids.length>0))}class I extends Error{status;code;suggestedModel;retryAfterMs;resolutionReason;refusal;constructor(e,r,a,l,c,m,p){super(a);this.status=e;this.code=r;this.suggestedModel=l;this.retryAfterMs=c;this.resolutionReason=m;this.refusal=p;this.name="ApiError"}static rateLimitDelayMs(e,r){if(!(e instanceof I)||e.status!==429)return null;return Math.min(60000,Math.max(r,e.retryAfterMs??0))}}var se=["minimal","low","medium","high","xhigh","max"],oe=i({id:t().min(1),kind:t(),name:t(),custom_name:t().nullish(),status:t(),online:d(),compatible:d().optional(),compatibility_reason:t().nullish(),folder_lane_of:t().nullish(),roots:u(i({id:t().min(1),label:t()}))}),re=i({devices:u(oe),end_cursor:t().nullish(),has_next_page:d().optional()}),ie=i({id:t().min(1),name:t()}),ae=i({items:u(ie)}),le=i({id:t().min(1),name:t(),main:d(),mine:d(),session_id:t().nullish(),appearance:i({color:t().nullish()}).nullish().catch(null)}),ce=i({items:u(le)}),de=i({skill_id:t().min(1),name:t(),description:t().nullish(),activation_keywords:u(t()).default([]),is_enabled:d().default(!0)}),ue=i({items:u(de).default([])}),me=i({id:t().min(1),kind:t(),enabled:d(),schedule:i({expression:t().nullish(),every_seconds:o().nullish(),next_run_at:t().nullish()}).nullish(),github:i({event:t().nullish(),action:t().nullish(),repo:t().nullish()}).nullish(),last_fired_at:t().nullish()}),U=i({id:t().min(1),name:t().nullish(),instructions:t().nullish(),enabled:d(),triggers:u(me).default([])}),ge=i({items:u(U).default([]),end_cursor:t().nullish(),has_next_page:d().optional()}),he=i({id:t().min(1),slug:t().nullish(),name:t(),description:t().nullish(),transport:t().nullish(),url:t().nullish(),enabled:d()}),pe=i({items:u(he).default([])}),fe=i({status:t(),summary:t().nullish(),category:t().nullish(),outcome:t().nullish(),message_count:o().nullish(),pr_url:t().nullish(),cost_usd:o().nullish(),generated_at:t().nullish()}),A=i({tags:u(t()).default([])}),ye=s(["linux","macos"]),O=i({id:t().min(1),name:t().min(1),platform:ye.nullable(),workers:i({total:o().int(),online:o().int(),busy:o().int(),idle:o().int()}),sessions:i({queued:o().int(),running:o().int()})}),_e=i({machines:u(O)}),Re=i({machine:O}),be=i({deleted:n(!0),revoked_workers:o().int(),revoked_tokens:o().int()}),we=i({token:i({id:t().min(1),machine_id:t().min(1),token_prefix:t()}),secret:t().startsWith("rmt_")}),M=hs({machine_id:t().min(1),machine_name:t().min(1)}),Se=M.extend({organization_id:t().min(1)}),on=i({id:t().min(1),name:t().min(1),state:s(["waiting","placed"]),queue_position:o().int().nullable()});var rn=W([i({kind:n("cloud")}),i({kind:s(["mac","headless"]),device_id:t().min(1),root_id:t().min(1)})]);function h(e,r,a){let l=e.safeParse(r);if(!l.success)throw new I(502,a,"Reason returned an unexpected response.");return l.data}var ke=i({error:i({type:t(),message:t()})});function w(e,r,a){let l=ke.safeParse(r),c=typeof r.error==="string"?r.error:l.success?l.data.error.type:`http_${e}`,m=typeof r.detail==="string"?r.detail:typeof r.message==="string"?r.message:l.success?l.data.error.message:`Reason request failed (${e}${typeof r.error==="string"?` ${r.error}`:""})`,p=c==="github_connection_required"&&typeof r.connect_url==="string"&&/^https?:\/\//.test(r.connect_url)?` Connect it at ${r.connect_url}`:"",f=a===null||a.trim()===""?NaN:Number(a);return new I(e,c,`${m}${p}`,typeof r.suggested_model==="string"?r.suggested_model:void 0,Number.isFinite(f)&&f>=0?f*1000:void 0,typeof r.resolution_reason==="string"?r.resolution_reason:void 0,typeof r.code==="string"?{code:r.code,...typeof r.billing_path==="string"&&/^\/(?![/\\])/.test(r.billing_path)?{billingPath:r.billing_path}:{}}:void 0)}async function ks(e){let r=await(e.fetchImpl??fetch)(`${e.apiOrigin}/v3/machines/enrollment-tickets`,{method:"POST",headers:{authorization:`Bearer ${e.token}`,accept:"application/json","content-type":"application/json"},body:JSON.stringify(e.body),signal:AbortSignal.timeout(30000),redirect:"error"}),a=await r.json().catch(()=>({}));if(!r.ok)throw w(r.status,a,r.headers.get("retry-after"));return h(Se,a,"invalid_machine_ticket")}class Qo{options;credentials;constructor(e,r={}){this.options=r;this.credentials=e}trackEvent(e,r={}){}async request(e,r={}){let{status:a,headers:l,json:c}=await this.exchange(e,r);if(a<200||a>299)throw w(a,c,l.get("retry-after"));return c}async exchange(e,r={},a=!1){let l=this.options.fetchImpl??fetch,c=await l(`${this.credentials.apiOrigin}/v3${e}`,{method:r.method??"GET",headers:{authorization:`Bearer ${this.credentials.accessToken}`,accept:"application/json","user-agent":Yn,"x-reason-agent":"Reason CLI","x-client-surface":this.options.clientSurface??"direct_cli",...r.raw?{"content-type":r.raw.contentType}:r.body===void 0?{}:{"content-type":"application/json"},...r.headers,...r.ifNoneMatch?{"if-none-match":r.ifNoneMatch}:{}},body:r.raw?r.raw.bytes:r.body===void 0?void 0:JSON.stringify(r.body),signal:r.signal,redirect:r.ifNoneMatch?"manual":"error"}),m=await c.json().catch(()=>({}));if(c.status===401&&!a&&r.retryUnauthorized!==!1&&this.credentials.credentialKind!=="api_key"){let p=await Ot({fetchImpl:l,path:this.options.credentialsPath,forceRefresh:!0,refused:this.credentials.accessToken,signal:r.signal});if(p)return this.credentials=p,this.exchange(e,r,!0)}return{status:c.status,headers:c.headers,json:m}}createHeadlessDeviceEnrollmentTicket(e){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/enrollment-tickets`,{method:"POST",body:e,signal:AbortSignal.timeout(30000),retryUnauthorized:!1})}async enrollHeadlessDevice(e){try{return await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/enrollments`,{method:"POST",body:e,signal:AbortSignal.timeout(30000),retryUnauthorized:!1})}catch(r){if(r instanceof I&&(r.status===404||r.status===405||r.status===403&&r.code==="endpoint_not_available"))return null;throw r}}addDeviceRoot(e,r){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/${encodeURIComponent(e)}/roots`,{method:"POST",body:r,signal:AbortSignal.timeout(30000)})}removeDeviceRoot(e,r){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/${encodeURIComponent(e)}/roots/${encodeURIComponent(r)}`,{method:"DELETE",signal:AbortSignal.timeout(30000)})}machinePath(e,r=""){let a=`/organizations/${encodeURIComponent(this.credentials.orgId)}/machines`;return e===void 0?a:`${a}/${encodeURIComponent(e)}${r}`}async listMachines(){return h(_e,await this.request(this.machinePath()),"invalid_machine_list").machines}async createMachine(e){let r=await this.request(this.machinePath(),{method:"POST",body:{name:e.name,...e.platform?{platform:e.platform}:{}}});return h(Re,r,"invalid_machine").machine}async deleteMachine(e){let r=await this.request(this.machinePath(e),{method:"DELETE"});return h(be,r,"invalid_machine_deletion")}async createMachineToken(e){let r=await this.request(this.machinePath(e,"/tokens"),{method:"POST",body:{}});return h(we,r,"invalid_machine_token")}async createMachineEnrollmentTicket(e,r){let a=await this.request(this.machinePath(e,"/enrollment-tickets"),{method:"POST",body:r,signal:AbortSignal.timeout(30000),retryUnauthorized:!1});return h(M,a,"invalid_machine_ticket")}self(e){return this.request("/self",{signal:e})}submitFeedback(e){return this.request("/feedback",{method:"POST",body:e,signal:AbortSignal.timeout(30000)})}agentNetwork(){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network`,{signal:AbortSignal.timeout(30000)})}startAgentNetwork(e){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network`,{method:"POST",body:e,signal:AbortSignal.timeout(30000)})}rotateAgentNetwork(e){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network`,{method:"PUT",body:e,signal:AbortSignal.timeout(30000)})}async claimAgentNetworkRelayJob(e,r){let a=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network/relay/claim`,{method:"POST",body:e,signal:r});return h(x,a,"invalid_agent_network_job")}async completeAgentNetworkRelayJob(e,r){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network/relay/jobs/${encodeURIComponent(e)}`,{method:"POST",body:r,signal:AbortSignal.timeout(30000)})}async recordAgentNetworkRelayReplies(e){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network/relay/replies`,{method:"POST",body:e,signal:AbortSignal.timeout(30000)})}async workspaceMembers(){return((await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/members/users`,{signal:AbortSignal.timeout(30000)})).items??[]).flatMap((r)=>typeof r.email==="string"?[{email:r.email,role:typeof r.role==="string"?r.role:"member"}]:[])}claimExistingCliPairing(e){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/onboarding/import/pairing/claim-existing`,{method:"POST",body:{pairing_code:e}})}async claudeCodeSignIn(e){return(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/provider-credentials`,{retryUnauthorized:!1,signal:e?AbortSignal.any([e,AbortSignal.timeout(15000)]):AbortSignal.timeout(15000)})).claude_code_sign_in===!0}connectAnthropicProvider(e,r,a={}){let l=e.kind==="setup_token"?{setup_token:e.token}:{access_token:e.credential.access,refresh_token:e.credential.refresh,expires_at:new Date(e.credential.expires).toISOString()};return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/provider-credentials/anthropic`,{method:"POST",retryUnauthorized:a.retryUnauthorized,signal:a.signal,body:{...l,...r?{account_key:r}:{}}})}async listRepositories(){return((await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/repositories`)).items??[]).flatMap((r)=>{let a=typeof r.full_name==="string"?r.full_name:typeof r.repo_full_name==="string"?r.repo_full_name:null;if(!a)return[];return[{repo_id:typeof r.repo_id==="string"?r.repo_id:void 0,full_name:a,provider:r.provider==="gitlab"?"gitlab":"github",default_branch:typeof r.default_branch==="string"?r.default_branch:null,private:typeof r.private==="boolean"?r.private:void 0}]})}async listProjects(){let e=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/projects`),r=ae.safeParse(e);if(!r.success)throw new I(502,"invalid_project_list","Reason returned an unexpected project list.");return r.data.items}async listReasons(){let e=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/reasons`);return h(ce,e,"invalid_reason_list").items}async openReasonConversation(e){let r=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/reasons/${encodeURIComponent(e)}/conversation`,{method:"POST"});return h(i({session_id:t().min(1)}),r,"invalid_reason_conversation").session_id}async listSkills(){try{let e=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/skills`);return h(ue,e,"invalid_skill_list").items}catch(e){if(e instanceof I&&(e.status===403||e.status===404))return[];throw e}}async listDevices(){let e=[],r=null;for(let a=0;a<50;a+=1){let l=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices${r?`?after=${encodeURIComponent(r)}`:""}`),c=re.safeParse(l);if(!c.success)throw new I(502,"invalid_device_list","Reason returned an unexpected machine list.");if(e.push(...c.data.devices),r=c.data.has_next_page?c.data.end_cursor??null:null,!r)break}return e}async listModels(){try{let r=((await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-auth/models`)).models??[]).filter((c)=>c.hidden!==!0),a=r.filter((c)=>c.available!==!1).map(({reasoning_efforts:c,hidden:m,available:p,...f})=>({...f,...Array.isArray(c)?{reasoning_efforts:se.filter((y)=>c.includes(y))}:{}})),l=new Set(a.map((c)=>c.detail));return{models:a.length>1&&l.size===1?a.map(({detail:c,...m})=>m):a,runnable:a.length>0||r.length===0}}catch(e){if(e instanceof I&&(e.status===403||e.status===404))return{models:[],runnable:!0};throw e}}async getAgentVersion(e){try{let r=await this.request("/deployment",{signal:e,retryUnauthorized:!1});return k(r.reason_version)?r.reason_version:null}catch{return null}}async getUsageQuota(){try{let e=ee.safeParse(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/usage/quota`));if(!e.success)return null;let r;try{r=te(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-auth/models`))}catch{}return{...e.data,own_inference:r}}catch(e){if(e instanceof I&&(e.status===403||e.status===404))return null;throw e}}async listSessionFields(e){let r=new URLSearchParams({first:String(Math.min(Math.max(e.first,1),200)),status:e.status??"active"});if(e.origin)r.set("origin",e.origin);r.set("fields",e.fields.join(","));let a=`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions?${r.toString()}`,{status:l,headers:c,json:m}=await this.exchange(a,e.etag?{ifNoneMatch:e.etag}:{});if(l===304)return null;if(l<200||l>299)throw w(l,m,c.get("retry-after"));return{items:Array.isArray(m.items)?m.items:[],etag:c.get("etag")}}async listSessions(e=50,r,a={}){let l=new URLSearchParams({first:String(Math.min(Math.max(e,1),200)),status:a.status??"active"});if(r)l.set("project_id",r);if(a.origin)l.set("origin",a.origin);return(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions?${l.toString()}`)).items??[]}getSession(e,r){let a=r?.fields.length?`?fields=${encodeURIComponent(r.fields.join(","))}`:"";return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}${a}`)}async prestartSession(e){let r=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/prestart`,{method:"POST",body:{client_session_id:e}});return r?.status==="starting"||r?.status==="ready"}async createSession(e){let r=e.mode==="ephemeral"||e.workspaceOwnership==="externally-managed";if(e.attachments?.length)await this.requireSessionAttachments();if(r||e.runtimeProfile){let c=await this.request("/deployment");if(r&&(!Array.isArray(c.session_modes)||!c.session_modes.includes(e.mode??"standard")||!Array.isArray(c.workspace_ownerships)||!c.workspace_ownerships.includes(e.workspaceOwnership??"managed")))throw Error("Deployment does not support the requested Session policy; refusing to create a Session.");if(e.runtimeProfile&&(!Array.isArray(c.experimental_runtime_profiles)||!c.experimental_runtime_profiles.includes(e.runtimeProfile)))throw Error("Deployment does not support the requested runtime profile; refusing to create a Session.")}let a=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions`,{method:"POST",body:{prompt:e.prompt,...e.attachments?.length?{attachments:e.attachments}:{},...e.mode?{mode:e.mode}:{},...e.workspaceOwnership?{workspace_ownership:e.workspaceOwnership}:{},...e.target?{target:e.target}:{},...e.repo?{repo:e.repo}:{},...e.provider?{provider:e.provider}:{},...e.model?{model:e.model}:{},...e.reasoningEffort?{reasoning_effort:e.reasoningEffort}:{},...e.runtimeProfile?{experimental_runtime_profile:e.runtimeProfile}:{},...e.ref?{ref:e.ref}:{},...e.branch?{branch:e.branch}:{},...e.completionMode?{completion_mode:e.completionMode}:{},...e.env&&Object.keys(e.env).length>0?{env:e.env}:{},...e.clientSessionId?{client_session_id:e.clientSessionId}:{},...e.longRunning?{long_running:{enabled:!0}}:{},...e.spendLimitRcu?{spend_limit_rcu:e.spendLimitRcu}:{},idempotency_key:`cli-${crypto.randomUUID()}`}}),l=await this.getSession(a.session_id);if(r){let c=l.session_policy,m=["memoryRead","memoryWrite","skills","inheritedInstructions","integrations","secretInjection"];if(!c||c.version!==1||c.mode!==(e.mode??"standard")||c.workspaceOwnership!==(e.workspaceOwnership??"managed")||!c.components||m.some((p)=>c.components[p]!==!0))throw await this.cancelSession(a.session_id),Error("Server did not attest the requested Session policy; cancellation requested.")}if(e.runtimeProfile&&l.experimental_runtime_profile!==e.runtimeProfile)throw await this.cancelSession(a.session_id),Error("Server did not attest the requested runtime profile; cancellation requested.");return l}async getEvents(e,r=-1,a={}){try{return await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/events?after_seq=${r}&limit=500${a.waitMs?`&wait_ms=${a.waitMs}`:""}`,a.signal?{signal:a.signal}:{})}catch(l){if(!(l instanceof I)||l.status!==403&&l.status!==404)throw l;return{session:await this.getSession(e),items:[],next_seq:r}}}async getMessages(e,r){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/messages?first=500${r===void 0?"":`&after_seq=${r}`}`)}async getAttachments(e,r){try{return(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/attachments${r?`?view=${r}`:""}`)).items??[]}catch(a){if(a instanceof I&&(a.status===403||a.status===404))return[];throw a}}async requireSessionAttachments(){let e=await this.request("/deployment",{headers:{"cache-control":"no-cache"}});if(e.session_attachments!==!0){let r=typeof e.reason_version==="string"&&/^\d+\.\d+(?:\.\d+)?$/.test(e.reason_version)?`Agent ${e.reason_version}`:null,a=typeof e.commit_sha==="string"&&/^[a-f0-9]{40,64}$/i.test(e.commit_sha)?`server ${e.commit_sha.slice(0,12)}`:null,l=[r,a].filter(Boolean).join(", ");throw Error(`This server does not support Session image attachments: ${new URL(this.credentials.apiOrigin).host}${l?` (${l})`:""}. The API server needs an attachment-capable deployment; updating the Agent version alone is not enough. Your image was not sent; retry after the server update.`)}}async sendMessage(e,r,a={}){if(a.attachments?.length)await this.requireSessionAttachments();return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/messages`,{method:"POST",body:{message:r,...a.attachments?.length?{attachments:a.attachments}:{},...a.model?{model:a.model}:{},...a.reasoningEffort?{reasoning_effort:a.reasoningEffort}:{},...a.target?{target:a.target}:{},...a.delivery?{delivery:a.delivery}:{}}})}async steerQueuedMessage(e,r){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/messages/${encodeURIComponent(r)}/steer`,{method:"POST",body:{}})}async withdrawQueuedMessage(e,r){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/messages/${encodeURIComponent(r)}/queued`,{method:"DELETE"})}async getConversation(e){let r=[],a=null;for(let l=0;l<50;l+=1){let c=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/conversation${a?`?after=${encodeURIComponent(a)}`:""}`);if(r.push(...c.items??[]),!c.has_next_page||!c.end_cursor)break;a=c.end_cursor}return r}createSharedLink(e,r){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/shared-links`,{method:"POST",body:{url:r.url,...r.label?{label:r.label}:{},...r.expiresInSeconds!==void 0?{expires_in_seconds:r.expiresInSeconds}:{}}})}sessionAction(e,r,a={}){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/${r}`,{method:"POST",body:a})}renameSession(e,r){return this.sessionAction(e,"rename",{title:r||null})}moveSessionToProject(e,r){return this.sessionAction(e,"project",{project_id:r})}compactSession(e){return this.sessionAction(e,"compact")}retrySession(e){return this.sessionAction(e,"retry")}rewindSession(e,r){return this.sessionAction(e,"rewind",{message_id:r.messageId,content:r.content,request_id:r.requestId})}forkSession(e,r){return this.sessionAction(e,"fork",{...r.message?{message:r.message}:{},client_session_id:r.clientSessionId})}cancelSession(e,r={}){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/cancel`,{method:"POST",body:r.mode==="hard"?{mode:"hard"}:{}})}sessionPath(e,r=""){return`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}${r}`}async archiveSession(e){await this.request(this.sessionPath(e,"/archive"),{method:"POST",body:{}})}async unarchiveSession(e){await this.request(this.sessionPath(e,"/unarchive"),{method:"POST",body:{}})}async deleteSession(e){await this.request(this.sessionPath(e),{method:"DELETE"})}async listSessionTags(e){return h(A,await this.request(this.sessionPath(e,"/tags")),"invalid_session_tags").tags}async appendSessionTags(e,r){let a=await this.request(this.sessionPath(e,"/tags"),{method:"POST",body:{tags:r}});return h(A,a,"invalid_session_tags").tags}async sessionInsight(e,r=!1){let a=await this.request(this.sessionPath(e,r?"/insights/generate":"/insights"),r?{method:"POST",body:{}}:{});return h(fe,a,"invalid_session_insight")}async listAutomations(){let e=[],r=null;for(let a=0;a<20;a+=1){let l=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations?first=100${r?`&after=${encodeURIComponent(r)}`:""}`),c=h(ge,l,"invalid_automation_list");if(e.push(...c.items),r=c.has_next_page?c.end_cursor??null:null,!r)break}return e}async createScheduledAutomation(e,r){let a=`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations`,l=h(U,await this.request(a,{method:"POST",body:{name:e.name,instructions:e.instructions,...e.repo?{repo:e.repo.full_name,provider:e.repo.provider}:{}}}),"invalid_automation");try{await this.request(`${a}/${encodeURIComponent(l.id)}/triggers`,{method:"POST",body:r})}catch(c){throw await this.deleteAutomation(l.id).catch(()=>{return}),c}return l}async setAutomationEnabled(e,r){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations/${encodeURIComponent(e)}`,{method:"PATCH",body:{enabled:r}})}async deleteAutomation(e){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations/${encodeURIComponent(e)}`,{method:"DELETE"})}async transcribe(e,r){let a=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/transcribe`,{method:"POST",raw:{bytes:e,contentType:r}});return h(i({transcript:t()}),a,"invalid_transcript").transcript}async listMcpServers(){let e=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/mcp-servers`);return h(pe,e,"invalid_mcp_server_list").items}async setSkillEnabled(e,r){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/skills/${encodeURIComponent(e)}`,{method:"PUT",body:{is_enabled:r}})}}
|
|
3
3
|
export{Ot,I,ks,Qo};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{We,fo,F,Ve,Ut,Rr,x}from"./vm-hands-entry-lite-
|
|
2
|
+
import{We,fo,F,Ve,Ut,Rr,x}from"./vm-hands-entry-lite-gdbb55w3.js";import{K}from"./vm-hands-entry-lite-wx1fmrbs.js";import{dt}from"./vm-hands-entry-lite-k1wghndy.js";import{mt}from"./vm-hands-entry-lite-mby8j0ss.js";import{Or}from"./vm-hands-entry-lite-f9ezhnqw.js";import{At,ji}from"./vm-hands-entry-lite-024t90qh.js";import{G,qe}from"./vm-hands-entry-lite-gpezb160.js";import{xe,Kn}from"./vm-hands-entry-lite-whaeqrzh.js";import{vt}from"./vm-hands-entry-lite-vwxg4fhe.js";import{a}from"./vm-hands-entry-lite-0sh835na.js";import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{C}from"./vm-hands-entry-lite-qz74j563.js";import{spawn as R,spawnSync as st}from"child_process";import{createHash as it,randomUUID as ge}from"crypto";import{closeSync as at,copyFileSync as ae,existsSync as M,fstatSync as ct,mkdirSync as ce,openSync as lt,readdirSync as U,readFileSync as X,readlinkSync as ut,renameSync as he,rmSync as pt,statSync as ft,writeFileSync as gt}from"fs";import{connect as ht}from"net";import{tmpdir as L,userInfo as we}from"os";import{basename as le,delimiter as wt,dirname as B,join as f}from"path";var z=`import { spawn, execFileSync } from "node:child_process";
|
|
3
3
|
import { createHash, randomUUID } from "node:crypto";
|
|
4
4
|
import { readFileSync, readlinkSync, lstatSync, realpathSync, statSync, mkdtempSync, mkdirSync, chmodSync, writeFileSync, readdirSync, rmSync, openSync, readSync, closeSync, renameSync } from "node:fs";
|
|
5
5
|
import { tmpdir } from "node:os";
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{nt,St,cr,on,Et,xt,Oi,sn,Ii,Di,Ni}from"./vm-hands-entry-lite-64b6nx6h.js";import{Pe,sr,ri,yt,zo,oe,qo,Wo,tt,Te,nn,ii,bt,ci,li,ui,di,pi,hi,fi,mi,gi,_i,yi,wi,bi,pe,Y,Re,q,vi,Si,Ei,xi,ki,Ci,Ai,Pi,vt,Ti}from"./vm-hands-entry-lite-vwxg4fhe.js";import{ue,Z,O}from"./vm-hands-entry-lite-39qv4sqt.js";import{P,Xt}from"./vm-hands-entry-lite-1ek3r3w9.js";import{mr,Yi,Qi,st,eo,to,ro,no,io,oo,yr,wr,br,wn,bn,vr,ao,vn,Sr,me,ge,Dt,Er,kr,Nt}from"./vm-hands-entry-lite-
|
|
2
|
+
import{nt,St,cr,on,Et,xt,Oi,sn,Ii,Di,Ni}from"./vm-hands-entry-lite-64b6nx6h.js";import{Pe,sr,ri,yt,zo,oe,qo,Wo,tt,Te,nn,ii,bt,ci,li,ui,di,pi,hi,fi,mi,gi,_i,yi,wi,bi,pe,Y,Re,q,vi,Si,Ei,xi,ki,Ci,Ai,Pi,vt,Ti}from"./vm-hands-entry-lite-vwxg4fhe.js";import{ue,Z,O}from"./vm-hands-entry-lite-39qv4sqt.js";import{P,Xt}from"./vm-hands-entry-lite-1ek3r3w9.js";import{mr,Yi,Qi,st,eo,to,ro,no,io,oo,yr,wr,br,wn,bn,vr,ao,vn,Sr,me,ge,Dt,Er,kr,Nt}from"./vm-hands-entry-lite-3r7d9pk1.js";import{D,R,b}from"./vm-hands-entry-lite-1zd088yv.js";import{Ki,Ji,_n,Zi,yn,Xi,ot,fr}from"./vm-hands-entry-lite-kean8gnh.js";import{K}from"./vm-hands-entry-lite-wx1fmrbs.js";import{He}from"./vm-hands-entry-lite-dcrz19xf.js";import{j}from"./vm-hands-entry-lite-3p7zk3yt.js";import{hr,gn,Gi}from"./vm-hands-entry-lite-5np5k3wb.js";import{wo,bo,ut,vo,So,Eo,xo,ko}from"./vm-hands-entry-lite-k1wghndy.js";import{Ir,Vt,Dr,jn,Un}from"./vm-hands-entry-lite-m7pkmatv.js";import{Ft,qe,jt}from"./vm-hands-entry-lite-gpezb160.js";import{Nn,x,go}from"./vm-hands-entry-lite-gdbb55w3.js";import{_o,yo}from"./vm-hands-entry-lite-f9ezhnqw.js";import{Bt,Pn,Tn}from"./vm-hands-entry-lite-v38e60gh.js";import{ye,uo,po}from"./vm-hands-entry-lite-psjcmgj8.js";import{be}from"./vm-hands-entry-lite-yretc2th.js";import{$t}from"./vm-hands-entry-lite-ckezse0f.js";import{ve,Ht,zt,qt,E}from"./vm-hands-entry-lite-70hq7mrs.js";import{a,ie}from"./vm-hands-entry-lite-0sh835na.js";import{t,k,o,d,u,i,W,g,ee,s,n,Ko}from"./vm-hands-entry-lite-qzcac2mf.js";import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{fe,Ne,Le,Me,ln}from"./vm-hands-entry-lite-qz74j563.js";import{$e}from"./vm-hands-entry-lite-mcjca0ez.js";import{request as Nl}from"http";import{request as Ml}from"https";import{lookup as $l}from"dns/promises";import{isIP as Bl}from"net";async function Fl(e){let l=new URL(e.url);return await new Promise((c,p)=>{let m=(l.protocol==="https:"?Ml:Nl)(l,{method:"POST",headers:{...e.headers,"accept-encoding":"identity"},signal:e.signal,timeout:Oi},(f)=>c({response:f,close:()=>{f.destroy(),m.destroy(),f.socket?.destroy()}}));m.once("error",p),m.once("timeout",()=>m.destroy(Object.assign(Error("custom_endpoint_timeout"),{code:"ETIMEDOUT"}))),m.end(e.body)})}var Wi=new Set(["ENOTFOUND","EAI_AGAIN","EAI_NONAME","EAI_NODATA","EAI_FAIL","DNSException"]),Ul=new Set(["ECONNREFUSED","ETIMEDOUT","ECONNRESET","EHOSTUNREACH","ENETUNREACH","EHOSTDOWN","ENETDOWN","EPIPE","ECONNABORTED","EADDRNOTAVAIL","ConnectionRefused","ConnectionClosed","ConnectionTimedOut","Timeout"]);function Vi(e,l=0){if(!e||typeof e!=="object"||l>3)return null;let c=e.code;if(typeof c==="string"){if(Wi.has(c))return"custom_endpoint_host_not_found";if(Ul.has(c))return"custom_endpoint_connection_failed";if(/^(?:ERR_TLS_|ERR_SSL_|CERT_|UNABLE_TO_(?:GET|VERIFY|DECRYPT)|DEPTH_ZERO_SELF_SIGNED|SELF_SIGNED_CERT|HOSTNAME_MISMATCH|EPROTO$)/.test(c))return"custom_endpoint_tls_failed"}for(let p of[...e instanceof AggregateError?e.errors:[],e.cause]){let m=Vi(p,l+1);if(m)return m}return null}async function Hl(e,l){let c=Vi(e),p=new URL(l).hostname.replace(/^\[|\]$/g,"");if(c!==null&&c!=="custom_endpoint_connection_failed"||Bl(p)!==0)return c;let m;return await Promise.race([$l(p).then(()=>!0,(h)=>!Wi.has(String(h?.code))),new Promise((h)=>{m=setTimeout(()=>h(!0),5000)})]).finally(()=>clearTimeout(m))?c:"custom_endpoint_host_not_found"}function jl(e){for(let l=42;;l++){if(l===127)l=256;let c=String.fromCodePoint(l);if(!e.includes(c))return c}}function ql(e,l){let c=Buffer.from(e),p=Buffer.from(l),m=new Uint32Array(c.length);for(let h=1,y=0;h<c.length;h++){while(y&&c[h]!==c[y])y=m[y-1];if(c[h]===c[y])y++;m[h]=y}let f=0;return(h,y=!1)=>{let S=Buffer.allocUnsafe(h.length*p.length+f),w=0;for(let _ of h){while(f&&c[f]!==_){let v=m[f-1];w+=c.copy(S,w,0,f-v),f=v}if(c[f]===_){if(f++,f===c.length)w+=p.copy(S,w),f=0}else S[w++]=_}if(y)w+=c.copy(S,w,0,f),f=0;return S.subarray(0,w)}}async function zi(e){e.signal.throwIfAborted();let l=Ii.safeParse(e.payload);if(!l.success)throw new r("custom_endpoint_invalid_request","Invalid local model request.");let c=l.data,p=Di.parse(await e.credential(e.signal));if(!sn(c,{baseUrl:c.baseUrl,api:p.api,execution:"device"}))throw new r("custom_endpoint_invalid_request","The request does not match the configured API.");e.signal.throwIfAborted();let m,f,h=0,y=0,S=0,w=jl(p.apiKey),_=ql(p.apiKey,w),v=async(I,A)=>{e.signal.throwIfAborted(),await new Promise((M,N)=>{let L=()=>{e.signal.removeEventListener("abort",L),N(e.signal.reason)};if(e.signal.addEventListener("abort",L,{once:!0}),e.signal.aborted){L();return}Promise.resolve().then(()=>(e.signal.throwIfAborted(),e.emit(I,A))).then(()=>{e.signal.removeEventListener("abort",L),M()},(B)=>{e.signal.removeEventListener("abort",L),N(B)})})},C=async(I)=>{if(h+=I.length,h>cr)throw new r("custom_endpoint_response_too_large","Local model response exceeds the transport limit.");for(let A=0;A<I.length;A+=St){if(S>=on)throw new r("custom_endpoint_response_too_large","Local model response exceeds the chunk limit.");await v(`custom_endpoint.chunk.${S++}`,{eof:!1,data:I.subarray(A,A+St).toString("base64")})}};try{let I=await Fl({url:c.url,body:c.body,signal:e.signal,headers:{...c.headers,...p.api==="anthropic-messages"?{"x-api-key":p.apiKey}:{authorization:`Bearer ${p.apiKey}`}}});m=I.response,f=I.close;let A=m.statusCode??500;if(A>=300&&A<400)throw new r("custom_endpoint_redirect_refused","Local model redirects are not followed.");if(m.headers["content-encoding"]&&m.headers["content-encoding"]!=="identity")throw new r("custom_endpoint_encoding_unsupported","The local server must honor identity encoding.");let M={};for(let N of["content-type","retry-after","x-request-id","request-id"]){let L=m.headers[N];if(typeof L==="string")M[N]=L.replaceAll(p.apiKey,w).slice(0,4096)}await v("custom_endpoint.headers",{status:A,statusText:(m.statusMessage??"").replaceAll(p.apiKey,w).slice(0,256),headers:M});for await(let N of m){e.signal.throwIfAborted();let L=Buffer.isBuffer(N)?N:Buffer.from(N);if(y+=L.length,y>cr)throw new r("custom_endpoint_response_too_large","Local model response exceeds the transport limit.");await C(_(L))}return await C(_(Buffer.alloc(0),!0)),await v(`custom_endpoint.chunk.${S}`,{eof:!0}),{bytes:h,chunks:S}}catch(I){if(e.signal.throwIfAborted(),I instanceof r)throw I;throw new r((m?null:await Hl(I,c.url))??"custom_endpoint_request_failed","The local model server could not complete the request.")}finally{f?.()}}import{join as os}from"path";function Wl(e,l){return e===os(l,".ara","workspace")||e===os(l,".reason","workspace")}function ss(e,l){let c=e.filter((p)=>Wl(p.path,l));return c.length===1?c[0].path:null}var Vl=/^[a-f0-9]{64}$/;var an=32,zl=/^\/[^\x00-\x1f\x7f\\]*$/;function Cr(e){if(typeof e!=="string"||e.length>4096||!zl.test(e))return!1;if(e==="/")return!0;return e.split("/").slice(1).every((l)=>l!==""&&l!=="."&&l!=="..")}function Pr(e,l){let c=l==="win32"?/^([A-Za-z]):[\\/]*(.*)$/.exec(e):null;if(!c)return e;let p=c[2].split(/[\\/]+/).filter(Boolean).join("/");return`/${c[1].toUpperCase()}:${p?`/${p}`:""}`}function cn(e){if(!e||typeof e!=="object"||Array.isArray(e))return;let l=e;if(!Cr(l.home)||!Array.isArray(l.roots)||l.roots.length>an)return;let c=[];for(let p of l.roots){if(!p||typeof p!=="object"||Array.isArray(p))return;let{path_fingerprint:m,path:f}=p;if(typeof m!=="string"||!Vl.test(m)||!Cr(f))return;c.push({path_fingerprint:m,path:f})}return{home:l.home,roots:c}}function Gl(e){let l=/^Reason contributor (rc_[0-9a-f]{32})$/.exec(e.name)?.[1];return e.email.toLowerCase()==="343777287+reason-contributors@users.noreply.github.com"&&l?l:void 0}function Yl(e){return Gl(e)??e.email.toLowerCase()}function un(e){let l=/^Co-authored-by:\s*([^<>\r\n]+) <([^<>\s]+)>$/i.exec(e.trim());return l?Yl({name:l[1],email:l[2]}):e.trim().toLowerCase()}var Gt=(e)=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/[a-z]/gi,(l)=>`[${l.toLowerCase()}${l.toUpperCase()}]`),Kl=[...ve.map((e)=>`/(${e.map(Gt).join("/")})(/|$)`),...Ht.map((e)=>`/(${e.map(Gt).join("/")})(/|$)`),...[...zt].map((e)=>`/(${Gt(e)})$`),`/${Gt(".env.")}[^/]*$`,...qt.map((e)=>`/[^/]*${Gt(e)}$`)],as=`function localGithubSandboxProfile(root, temporary) {
|
|
3
3
|
return ['(version 1)','(deny default)','(import "system.sb")','(allow process-exec process-fork)',
|
|
4
4
|
'(allow file-read* (subpath "/bin") (subpath "/sbin") (subpath "/usr/bin") (subpath "/usr/sbin") (subpath "/usr/libexec") (subpath "/usr/share") (subpath "/private/var/select") (literal "/private/var/db/xcode_select_link"))',
|
|
5
5
|
'(allow file-read-metadata (path-ancestors "/opt/homebrew/bin") (path-ancestors "/usr/local/bin") (path-ancestors "/Library/Developer/CommandLineTools"))',
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{T}from"./vm-hands-entry-lite-fcvf8md1.js";import{_}from"./vm-hands-entry-lite-wp0d65yx.js";import{Jr,Qn,Zr,ei}from"./vm-hands-entry-lite-vs47bs09.js";import{Zn,er,Lo}from"./vm-hands-entry-lite-
|
|
2
|
+
import{T}from"./vm-hands-entry-lite-fcvf8md1.js";import{_}from"./vm-hands-entry-lite-wp0d65yx.js";import{Jr,Qn,Zr,ei}from"./vm-hands-entry-lite-vs47bs09.js";import{Zn,er,Lo}from"./vm-hands-entry-lite-mby8j0ss.js";import{C}from"./vm-hands-entry-lite-qz74j563.js";import{spawnSync as y}from"child_process";import{createHash as ke,randomUUID as Se}from"crypto";import{chmodSync as we,existsSync as P,mkdirSync as $e,readdirSync as Ve,readFileSync as p,renameSync as ye,rmSync as u,statSync as ve,writeFileSync as be}from"fs";import{dirname as We,isAbsolute as q,join as g}from"path";import{spawnSync as de}from"child_process";import{readFileSync as me}from"fs";import{userInfo as D}from"os";import{join as fe}from"path";var ge="REASON_SCHEDULED_TASK";function H(r){return fe(r,"AppData","Local","Reason","Tasks")}function S(r){if(/[\0-\x1f\x7f"%]/.test(r))throw Error(`A background task cannot use a value with a double quote, percent sign or control character: ${r}`);return`'${r.replace(/['\u2018\u2019\u201a\u201b]/g,"$&$&")}'`}function M(r){if(!/^[A-Za-z0-9._-]+$/.test(r))throw Error(`Invalid Windows Scheduled Task name: ${r}`);return`$env:${ge}=${S(r)};`}function K(r){let e=Object.entries(r.environment).map(([t,i])=>{if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(t))throw Error(`Invalid Windows Scheduled Task environment name: ${t}`);return`$env:${t}=${S(i)};`}),n=`$global:LASTEXITCODE=1; & ${[r.program,...r.args].map(S).join(" ")} 2>&1 | ForEach-Object { Add-Content -LiteralPath ${S(r.log)} -Value $_.ToString() -Encoding UTF8 }; $c=$LASTEXITCODE;`;return[M(r.name),...e,"$ErrorActionPreference='Continue';",r.keepAlive?`do { ${n} if ($c) { Start-Sleep -Seconds 10 } } while ($c)`:`${n} exit $c`].join(" ")}function A(r){return r.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}function pe(){let r=process.env.USERDOMAIN?.trim();return r?`${r}\\${D().username}`:D().username}function U(r){let e=A(r.user??pe()),n=r.schedule==="logon",t=r.schedule==="logon"?`<LogonTrigger><Enabled>true</Enabled><UserId>${e}</UserId></LogonTrigger>`:`<TimeTrigger><Repetition><Interval>PT${r.schedule.everyMinutes}M</Interval><StopAtDurationEnd>false</StopAtDurationEnd></Repetition><StartBoundary>2026-01-01T00:00:00</StartBoundary><Enabled>true</Enabled></TimeTrigger>`,i=`-NoProfile -NonInteractive -ExecutionPolicy Bypass -WindowStyle Hidden -Command "${r.script}"`;return`<?xml version="1.0" encoding="UTF-16"?>
|
|
3
3
|
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
|
|
4
4
|
<RegistrationInfo>
|
|
5
5
|
<Description>${A(r.description)}</Description>
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
2
|
import{ni,bt,oi,si,ai,Ri}from"./vm-hands-entry-lite-vwxg4fhe.js";import"./vm-hands-entry-lite-64b6nx6h.js";import{createHash as H,randomBytes as he}from"crypto";import{closeSync as Ae,fsyncSync as xe,mkdirSync as Xe,openSync as Oe,renameSync as Qe,rmSync as Ze,statSync as De,writeSync as Me,constants as W}from"fs";import{join as se}from"path";var en=1;var oe=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function pe(e){if(e.environment!==void 0||e.payload.environment!==void 0)throw new l("vm_hands_bind_invalid","bind carries a plaintext environment");if(e.payload.vm_hands_env_deferred===!0&&e.environment_sealed!==void 0)throw new l("vm_hands_bind_invalid","split bind carries an environment");return e.environment_sealed!==void 0}function Te(e,n){let{payload:i,authority:r}=e;if(!i||typeof i!=="object"||Array.isArray(i)||!r||typeof r!=="object"||Array.isArray(r)||!n.deviceId||!n.rootId||i.run_id!==n.runId||i.device_id!==n.deviceId||r.device_id!==n.deviceId||i.root_id!==n.rootId||n.snapshotId!==void 0&&i.snapshot_id!==n.snapshotId)throw new l("vm_hands_env_invalid","environment does not match this Hands");return i}function ve(e){if(e.capability!=="hands.connect")throw new l("vm_hands_bind_invalid","not a hands.connect claim");let n=e.payload;return{kind:"vm_hands.bind",v:1,bind_id:e.attempt_id,attempt_id:e.attempt_id,attempt_token:e.attempt_token,run_id:e.run_id,session_id:typeof n.workspace_id==="string"&&oe.test(n.workspace_id)?n.workspace_id:e.run_id,brain_generation:n.target_generation,fence_id:n.target_fence_id,lease_until:e.lease_until,policy:{agent_profile:"",confinement_key:String(n.hands_confinement??""),browser_egress:n.browser_egress??null,policy_digest:n.vm_hands_policy_digest},cwd:typeof n.cwd==="string"?n.cwd:"",claim:e,env:pe(e)?e.environment_sealed:null,workspace_deferred:nn(e)}}function nn(e){let n=e.payload[oi];if(n===void 0)return!1;if(n!==!0||e.payload.vm_hands_env_deferred!==!0||e.environment_sealed!==void 0)throw new l("vm_hands_bind_invalid","a pre-bind must be environment-less");return!0}class l extends Error{code;constructor(e,n){super(n);this.code=e}}function Re(e,n){if(e instanceof l)return e;let i=e&&typeof e==="object"&&"code"in e&&typeof e.code==="string"&&/^[a-z][a-z0-9_]{2,63}$/.test(e.code)?e.code:"vm_hands_bind_failed";return new l(i,n)}var G=(e)=>Buffer.from(e instanceof Uint8Array?e:new Uint8Array(e)).toString("base64url"),K=(e)=>new Uint8Array(Buffer.from(e,"base64url"));function V(e){if(e===null||typeof e!=="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(V).join(",")}]`;return`{${Object.keys(e).sort().map((n)=>`${JSON.stringify(n)}:${V(e[n])}`).join(",")}}`}async function Hi(e){let n=await crypto.subtle.importKey("pkcs8",K(e.device_key.pkcs8),{name:"ECDSA",namedCurve:"P-256"},!1,["sign"]),i=K(e.device_key.spki),r=await crypto.subtle.generateKey({name:"ECDH",namedCurve:"P-256"},!1,["deriveKey"]),h=new Uint8Array(await crypto.subtle.exportKey("spki",r.publicKey)),m=H("sha256").update(i).digest("base64url");return{signing:{privateKey:n},agreement:r,signingSpki:i,agreementSpki:h,fingerprint:m}}var tn=16;class pn{init;keys;hooks;options;identity="identity_free";lastBrainGeneration=new Map;rebindableGeneration=new Map;bound=new Map;binding=new Map;unbinding=new Set;servedRun=!1;bootKillPending=!1;unverified=new Set;unverifiedTeardowns=new Map;grants=new Map;structural=Promise.resolve();exclusive(e){let n=this.structural.then(e,e);return this.structural=n.catch(()=>{return}),n}constructor(e,n,i,r){this.init=e;this.keys=n;this.hooks=i;this.options=r;if(!oe.test(e.workspace_id)&&!/^ws-[a-z0-9]{8,64}$/.test(e.workspace_id))throw new l("vm_hands_layout_invalid","bad workspace id");if(!Number.isSafeInteger(e.instance_generation)||e.instance_generation<1)throw new l("vm_hands_layout_invalid","bad generation")}get phase(){if(this.identity==="identity_free")return"identity_free";if(this.unbinding.size)return"unbinding";return this.bound.size||this.binding.size?"bound":"registered"}isBoundRun(e){for(let n of this.bound.values())if(n.runId===e)return!0;return!1}bindIdForRun(e){for(let n of this.bound.values())if(n.runId===e)return n.bindId;return null}get liveBindIds(){return[...new Set([...this.bound.keys(),...this.binding.keys(),...this.unbinding])]}get liveSessionIds(){return[...new Set([...this.bound.values()].map((e)=>e.sessionId.toLowerCase()))]}get settingUp(){return this.binding.size>0}async environmentInstalled(e,n,i){for(let r=Date.now()+n;;){let h=this.bound.get(e);if(!h)return!1;if(h.envInstalled)return!0;if(Date.now()>=r||i?.aborted)return!1;await new Promise((m)=>setTimeout(m,25))}}canSpawn(e){for(let n of this.bound.values())if(n.runId===e)return n.envInstalled;return!1}async registerFrame(e){if(this.identity!=="identity_free")throw new l("vm_hands_register_twice","already registered");if(typeof e!=="string"||e.length<16||e.length>256)throw new l("vm_hands_challenge_invalid","bad register challenge");let n={challenge:e,t:"register",v:en,workspace_id:this.init.workspace_id,instance_generation:this.init.instance_generation,credential:this.init.credential,device_public_key:G(this.keys.signingSpki),env_public_key:G(this.keys.agreementSpki),key_fingerprint:this.keys.fingerprint,manifest_digest:this.init.manifest_digest,nonce:G(he(32)),timestamp_ms:(this.options.now??Date.now)(),vm_hands_attest_hold:!0},i=await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},this.keys.signing.privateKey,new TextEncoder().encode(V(n)));return{...n,device_signature:G(i)}}async helloFrame(e,n){if(this.identity==="identity_free")throw new l("vm_hands_not_registered","hello before register");let i=String((this.options.now??Date.now)()),r=G(he(32)),h=Ri({method:"GET",pathAndQuery:ni,timestamp:i,nonce:r,challenge:e,bodySha256:H("sha256").update("").digest("hex")}),m=new Uint8Array(await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},this.keys.signing.privateKey,new Uint8Array(h)));return{t:"hello",timestamp:i,nonce:r,signature:G(rn(m)),...n?{vm_hands_previous_connection:n}:{}}}registered(){if(this.identity!=="identity_free")throw new l("vm_hands_register_unexpected","registered twice");this.identity="registered"}async bind(e){if(this.identity!=="registered")throw new l("vm_hands_not_registered","bind before register");if(e.kind!=="vm_hands.bind"||e.v!==1)throw new l("vm_hands_bind_invalid","bad bind");for(let r of[e.bind_id,e.attempt_id,e.run_id,e.session_id,e.fence_id])if(!oe.test(r))throw new l("vm_hands_bind_invalid","bad id");let n=this.lastBrainGeneration.get(e.run_id)??0;if(!Number.isSafeInteger(e.brain_generation)||e.brain_generation<n||e.brain_generation===n&&this.rebindableGeneration.get(e.run_id)!==n)throw new l("vm_hands_generation_stale","brain generation not strictly higher");if(e.env&&(e.env.aad!==e.bind_id||e.env.alg!=="ECDH-P256+A256GCM"))throw new l("vm_hands_bind_invalid","bad env envelope");if(!/^[0-9a-f]{64}$/.test(e.policy.policy_digest))throw new l("vm_hands_bind_invalid","bad policy or nonce");if(H("sha256").update(V({hands_confinement:e.policy.confinement_key||null,browser_egress:e.policy.browser_egress??null})).digest("hex")!==e.policy.policy_digest)throw new l("vm_hands_policy_mismatch","policy digest does not match the claim");if(this.liveBindIds.includes(e.bind_id)||[...this.bound.values()].some((r)=>r.runId===e.run_id)||[...this.binding.values()].includes(e.run_id))throw new l("vm_hands_busy","this run already holds a bind here");if(this.liveBindIds.length>=tn)throw new l("vm_hands_busy","every bind slot is held");if([...this.grants.values()].some((r)=>r.sessionId===e.session_id))throw new l("vm_hands_busy","a bind of this Session waits for its workspace beside the setup");if(this.lastBrainGeneration.set(e.run_id,e.brain_generation),this.rebindableGeneration.delete(e.run_id),this.binding.set(e.bind_id,e.run_id),e.workspace_deferred){let r,h,m=new Promise((_,k)=>{r=_,h=k});return m.catch(()=>{return}),this.grants.set(e.bind_id,{sessionId:e.session_id,promise:m,resolve:r,reject:h}),this.setUpDeferred(e)}return this.exclusive(()=>this.setUp(e))}liveCgroupBindsBut(e){return[...new Set([...this.bound.keys(),...this.binding.keys()])].filter((n)=>n!==e)}async setUpDeferred(e){let n=this.grants.get(e.bind_id);try{await this.exclusive(()=>this.prepareBind(e))}catch(v){throw this.binding.delete(e.bind_id),this.grants.delete(e.bind_id),this.rebindableGeneration.set(e.run_id,e.brain_generation),Re(v,"the bind's kill-verify failed")}let i,r=new Promise((v)=>{i=v}),h=!1,m=!1,_=()=>{m=!0,i()},k=n.promise.then(()=>new Promise((v,I)=>{this.exclusive(async()=>{if(m){I(new l("vm_hands_bind_lost","the pre-bind ended before its turn"));return}h=!0;try{if(this.unverified.size>0)await this.hooks.killAndVerifyPayload({keep:[...this.liveCgroupBindsBut(e.bind_id),e.bind_id]}),this.unverified.clear();v()}catch(w){I(w)}await r})}));k.catch(()=>{return});try{return await this.setUp(e,{workspaceGrant:k,inTurn:()=>h,leave:_})}finally{_()}}async prepareBind(e){if(this.bootKillPending&&!this.servedRun){try{await this.hooks.killProbe()}catch{throw new l("vm_hands_kill_unverified","the boot's scoped kill did not verify")}this.bootKillPending=!1}let n=this.liveCgroupBindsBut(e.bind_id);if(this.unverified.size>0)await this.hooks.killAndVerifyPayload(n.length?{keep:n}:void 0),this.unverified.clear();this.servedRun=!0}async setUp(e,n){let i=null,r=!1;try{if(!n)await this.prepareBind(e);r=!0;let{launchId:h,applied:m,readyData:_}=await this.hooks.startExecutor({bindId:e.bind_id,sessionId:e.session_id,policyDigest:e.policy.policy_digest,confinementKey:e.policy.confinement_key,browserEgress:e.policy.browser_egress,cwd:e.cwd,claim:e.claim,...n?{workspaceGrant:n.workspaceGrant}:{}}),k=this.hooks.restatLayout(e.session_id);this.hooks.verifyMounts?.(e.session_id);let v=null,I=null;if(e.env){let w=e.claim?.owner??{},E=Te(await this.openSealed(e.env,e.bind_id),{runId:e.run_id,deviceId:typeof w.device_id==="string"?w.device_id:"",rootId:e.claim?.root_id??""});v=this.hooks.installEnvironment(e.bind_id,E),I=typeof E.snapshot_id==="string"&&E.snapshot_id?E.snapshot_id:null,i=this.writeJobEnvRootOnly(e.bind_id,E)}if(this.unbinding.has(e.bind_id))throw new l("vm_hands_bind_lost","unbound while binding");return this.bound.set(e.bind_id,{bindId:e.bind_id,runId:e.run_id,sessionId:e.session_id,brainGeneration:e.brain_generation,policyDigest:e.policy.policy_digest,launchId:h,envInstalled:v!==null,rootId:e.claim?.root_id??"",envDirectory:i}),this.binding.delete(e.bind_id),this.grants.delete(e.bind_id),{bind_id:e.bind_id,attempt_id:e.attempt_id,attempt_token:e.attempt_token,launch_id:h,snapshot_revision:v,snapshot_id:I,layout:k,..._?{ready_data:_}:{},policy_digest:H("sha256").update(V({hands_confinement:m.hands_confinement??null,browser_egress:m.browser_egress??null})).digest("hex")}}catch(h){if(i)fe(i);if(r){let m=()=>this.hooks.killAndVerifyPayload({bindId:e.bind_id,keep:this.liveCgroupBindsBut(e.bind_id),own:!0}).catch(()=>{this.unverified.add(e.bind_id)});if(n&&!n.inTurn())n.leave(),await this.exclusive(m);else await m()}throw this.binding.delete(e.bind_id),this.grants.delete(e.bind_id),this.rebindableGeneration.set(e.run_id,e.brain_generation),Re(h,"executor refused the bind")}}grantWorkspace(e){let n=this.grants.get(e);if(!n)throw new l("vm_hands_not_binding","no pre-bind waits for a workspace grant");n.resolve()}abandonWorkspaceGrant(e){this.grants.get(e)?.reject(new l("vm_hands_bind_lost","the pre-bind ended before its workspace grant"))}async deliverEnvironment(e){let n=this.bound.get(e.attemptId);if(!n||this.unbinding.has(e.attemptId))throw new l("vm_hands_not_bound","environment delivered while not bound");if(!oe.test(e.attemptId)||typeof e.snapshotId!=="string"||!e.snapshotId||e.snapshotId.length>128||e.snapshotId.includes("/"))throw new l("vm_hands_env_invalid","bad snapshot id");let i=`${e.attemptId}/${e.snapshotId}`;if(e.sealed?.alg!=="ECDH-P256+A256GCM"||e.sealed.aad!==i)throw new l("vm_hands_env_invalid","bad env envelope");let r=Te(await this.openSealed(e.sealed,i),{runId:n.runId,deviceId:e.deviceId,rootId:n.rootId,snapshotId:e.snapshotId}),h=this.hooks.installEnvironment(n.bindId,r);if(n.envInstalled=!0,n.envDirectory)fe(n.envDirectory);return n.envDirectory=null,n.envDirectory=this.writeJobEnvRootOnly(`${n.bindId}-r${h}`,r),{snapshot_id:e.snapshotId,installed_revision:h,installed:!0}}async attestFrame(e,n){if(this.identity==="identity_free")throw new l("vm_hands_not_registered","attest before register");if(!e||e.length>65536)throw new l("vm_hands_attest_invalid","no probe script");return this.exclusive(async()=>{if(this.liveBindIds.length)throw new l("vm_hands_attest_invalid","attest beside a bind");let i=await this.hooks.runProbe({nonce:n,script:e});try{await this.hooks.killProbe()}catch{this.bootKillPending=!0}return{t:"attest",nonce:n,exit_code:i.exitCode,markers:i.markers,proof_dir_inode:i.proofDirInode,script_sha256:H("sha256").update(e).digest("hex")}})}executorExited(e){return this.hooks.executorExited?.(e)??new Promise(()=>{})}async boundRefused(e){await this.unbind(e)}async unbind(e){let n=this.bound.get(e)??null;if(this.unbinding.add(e),this.bound.delete(e),this.abandonWorkspaceGrant(e),n)try{this.hooks.freezeBind?.(e)}catch{}return this.exclusive(()=>this.tearDown(e,n))}async retryUnbind(e){if(!this.unverifiedTeardowns.has(e))throw new l("vm_hands_unbind_unknown","no unverified unbind of this bind");return this.exclusive(async()=>{if(!this.unverifiedTeardowns.has(e))throw new l("vm_hands_unbind_unknown","no unverified unbind of this bind");return this.tearDown(e,this.unverifiedTeardowns.get(e)??null,!0)})}async tearDown(e,n,i=!1){try{this.bound.delete(e);let r=this.liveCgroupBindsBut(e);try{await this.hooks.killAndVerifyPayload({bindId:e,keep:r})}catch(h){if(this.unverified.add(e),!this.unverifiedTeardowns.has(e))this.unverifiedTeardowns.set(e,n);throw h}if(this.unverified.delete(e),!r.length&&!i)this.unverified.clear();if(n?.envDirectory)fe(n.envDirectory);if(this.unverifiedTeardowns.delete(e),n&&this.lastBrainGeneration.get(n.runId)===n.brainGeneration)this.rebindableGeneration.set(n.runId,n.brainGeneration);return{bind_id:n?e:null,killed_verified:!0,shredded:!0,srt_fallbacks:r.length||i?null:this.hooks.takeSrtFallbacks?.()??null}}finally{this.unbinding.delete(e)}}async openSealed(e,n){let i=()=>{throw new l("vm_hands_env_invalid","env did not decrypt")},r=await crypto.subtle.importKey("spki",K(e.epk),{name:"ECDH",namedCurve:"P-256"},!1,[]).catch(i),h=await crypto.subtle.deriveKey({name:"ECDH",public:r},this.keys.agreement.privateKey,{name:"AES-GCM",length:256},!1,["decrypt"]),m=await crypto.subtle.decrypt({name:"AES-GCM",iv:K(e.iv),additionalData:new TextEncoder().encode(n)},h,K(e.ct)).catch(i),_=JSON.parse(new TextDecoder().decode(m));if(!_||typeof _!=="object"||Array.isArray(_))throw new l("vm_hands_env_invalid","env not an object");return _}writeJobEnvRootOnly(e,n){let i=se(this.options.envRoot,`bind-${e}`);Xe(i,{mode:448});let r=De(i);if(!r.isDirectory()||(r.mode&63)!==0||r.uid!==(process.getuid?.()??-1))throw new l("vm_hands_env_dir_unsafe","env directory is not root's 0700");let h=n.variables&&typeof n.variables==="object"?n.variables:{},m=Object.entries(h).filter(([v,I])=>/^[A-Za-z_][A-Za-z0-9_]*$/.test(v)&&typeof I==="string").map(([v,I])=>`export ${v}='${String(I).replaceAll("'","'\\''")}'`).join(`
|
|
3
3
|
`)+`
|
|
4
|
-
`,_=se(i,`.job.env.${he(8).toString("hex")}`),k=Oe(_,W.O_WRONLY|W.O_CREAT|W.O_EXCL|W.O_NOFOLLOW,384);try{Me(k,m),xe(k)}finally{Ae(k)}return Qe(_,se(i,"job.env")),i}}function fe(e){try{let n=se(e,"job.env"),i=De(n).size,r=Oe(n,W.O_WRONLY|W.O_NOFOLLOW);try{Me(r,Buffer.alloc(i)),xe(r)}finally{Ae(r)}}catch{}Ze(e,{recursive:!0,force:!0})}function rn(e){if(e.length!==64)throw new l("vm_hands_signature_invalid","unexpected ECDSA signature length");let n=(h)=>{let m=0;while(m<h.length-1&&h[m]===0)m++;let _=h.subarray(m),k=_[0]&128?Uint8Array.of(0,..._):_;return Uint8Array.of(2,k.length,...k)},i=n(e.subarray(0,32)),r=n(e.subarray(32));return Uint8Array.of(48,i.length+r.length,...i,...r)}import{randomUUID as sn}from"crypto";var on="/app/local-runtime/session?register=vm_hands_v1",an="/app/local-runtime",Ce=25000,we=20000,dn=1e4,Ue=5000,cn=new Set(["pty.start","jobs.control","tunnel.open","tunnel.close"]),ln="preview.serve.v1",un=60000,ye=75000,_n=2000,mn=1e4,gn=new Set(["vm_hands_no_register","vm_hands_register_failed"]),hn=3,fn=20000,vn=250,wn=2000;function $e(e){let n=Math.min(vn*2**(e-1),wn);return Math.round(n/2+Math.random()*n/2)}var yn=5000;function bn(e){return e>=500||e===408||e===429}var ae=20000;function Be(e,n){return typeof e==="string"&&/^[A-Za-z0-9._:-]{1,160}$/.test(e)?e:n}class D extends Error{}var kn=64,qe=[1000,2000,4000,8000,15000,30000,60000,120000];function je(e){let n=e&&typeof e==="object"&&"code"in e?e.code:null;return typeof n==="string"&&/^[a-z][a-z0-9_]{2,63}$/.test(n)?n:"vm_hands_unbind_failed"}function Sn(e,n,i,r,h){let m=i.turn.claim.attempt_id,_=e.healing??=new Set;if(_.has(m))return;_.add(m);let k=i.turn.claim.operation_id;(async()=>{for(let[v,I]of qe.entries()){if(r.aborted)return;if(await new Promise((w)=>{let E=setTimeout(w,I);E.unref?.(),r.addEventListener("abort",()=>{clearTimeout(E),w()},{once:!0})}),r.aborted)return;try{let w=await n.retryUnbind(m);h("vm_hands.unbind_healed",{operation_id:k,attempt:v+1}),e.receipts.push({...i,unbound:w}),e.flushReceipts?.();return}catch(w){let E=je(w);if(h("vm_hands.unbind_unverified",{operation_id:k,code:E,attempt:v+1}),E==="vm_hands_unbind_unknown")return}}h("vm_hands.unbind_heal_exhausted",{operation_id:k,attempts:qe.length})})().finally(()=>_.delete(m))}async function Ge(e,n){let i=[...e.modelOps.get(n)??[]];for(let r of i)r.abort.abort();await Promise.race([Promise.all(i.map((r)=>r.settled)),new Promise((r)=>setTimeout(r,Ue))])}async function In(e,n){let i=[...e.personTerminals].filter((r)=>r.session===null||r.session===n);for(let r of i)r.abort.abort();if(i.length)await Promise.race([Promise.all(i.map((r)=>r.settled)),new Promise((r)=>setTimeout(r,Ue))]);return i.length}function Pn(e){let n=e.payload,i=n?.workspace?.kind==="managed"?n.workspace.workspaceId:void 0;return typeof i==="string"&&/^[0-9a-f-]{36}$/i.test(i)?i.toLowerCase():null}async function L(e,n,i){return await Ge(e,i),n.unbind(i)}function de(e){for(let n of e.outbox?.splice(0)??[])n.reject(Error("vm_hands_attempt_ended"))}var Ne=15000,En=1e4,Tn=1000;async function zi(e){let n=Date.now(),i={deviceId:null,connection:null,turns:new Map,lostAt:0,receipts:[],attest:"pending",attestWaiters:[],modelOps:new Map,personTerminals:new Set,bindsStarting:new Map},r=e.log??(()=>{}),h=async(k)=>{for(let[v,I]of[...i.turns]){i.turns.delete(v),e.onTurn?.(v,null),de(I);let w=await L(i,e.agent,v).catch(()=>null);if(w)i.receipts.push({turn:I,failure:"vm_hands_bind_lost",unbound:w});r("vm_hands.bound_dropped",{reason:k})}},m=0,_=0;try{for(let k=0;!e.signal.aborted;k++){let v=await Rn(e,i).catch((w)=>{if(w instanceof l&&i.deviceId===null&&w.code==="vm_hands_no_session"&&Date.now()-n<mn)return{closeCode:0,closeReason:"vm_hands_no_session"};if(w instanceof l&&i.deviceId===null&&gn.has(w.code)&&m<hn&&Date.now()-n<fn)return m++,_=$e(m),r("vm_hands.register_retry",{attempt:m,code:w.code,delay_ms:_}),{closeCode:0,closeReason:"vm_hands_register_retry"};if(w instanceof l&&i.deviceId===null)throw w;return{closeCode:0,closeReason:w instanceof Error?w.message:String(w)}});if(r("vm_hands.session_closed",{close_code:v.closeCode,reason:v.closeReason.slice(0,120),registered:i.deviceId!==null}),v.closeCode===4401||i.attest==="refused")return;if(e.signal.aborted)return;if(i.turns.size&&Date.now()-i.lostAt>=ye)await h("reconnect_deadline");if(i.served)i.served=!1,k=0;let I=v.closeReason==="drain_reconnect"?0:v.closeReason==="vm_hands_register_retry"?_:v.closeReason==="vm_hands_no_session"?Math.min(250*2**Math.min(k,5),2000):i.turns.size?Math.min(250*2**Math.min(k,5),5000,Math.max(0,i.lostAt+ye-Date.now())):Math.min(500*2**k,30000);if(await new Promise((w)=>setTimeout(w,I)),i.turns.size&&Date.now()-i.lostAt>=ye)await h("reconnect_deadline")}}finally{await h("session_ended")}}async function Rn(e,n){let i=n.deviceId,r=e.log??(()=>{}),h=i?`/app/local-runtime/session?device_id=${encodeURIComponent(i)}`:on,m=`${e.apiOrigin.replace(/^http/,"ws")}${h}`,_=new WebSocket(m),k=0,v="",I=new Map,w=[],E=null,ce=new Promise((t)=>{_.onclose=(o)=>{k=o.code,v=o.reason;for(let s of I.values())s.reject(new D(`session closed ${o.code}`));for(let s of n.attestWaiters.splice(0))s(!1);I.clear(),t()}});_.onmessage=(t)=>{let o;try{o=JSON.parse(String(t.data))}catch{_.close(4400);return}if(o.t==="res"){let s=o;I.get(s.id)?.resolve({status:s.status,body:s.body}),I.delete(s.id);return}if(o.t==="reconnect"){let s=Math.max(0,Math.min(Number(o.after_ms)||0,Tn));r("vm_hands.drain_reconnect",{after_ms:s}),setTimeout(()=>{try{_.close(4001,"drain_reconnect")}catch{}},s).unref?.();return}if(!E?.(o))w.push(o)};let J=(t,o)=>new Promise((s,a)=>{let u=w.findIndex((p)=>t.includes(p.t));if(u>=0){s(w.splice(u,1)[0]);return}let f=setTimeout(()=>{E=null,a(new l("vm_hands_no_register",`no ${t.join("/")} in ${o} ms`))},o);E=(p)=>{if(!t.includes(p.t))return!1;return clearTimeout(f),E=null,s(p),!0}}),Y=(t)=>_.send(JSON.stringify(t)),q=(t,o)=>new Promise((s,a)=>{if(_.readyState!==WebSocket.OPEN){a(new D("session closed"));return}let u=sn(),f=typeof o.wait_ms==="number"?o.wait_ms:0,p=setTimeout(()=>{if(!I.delete(u))return;a(new D(`no answer to ${t.split("/").pop()} in ${f+Ne} ms`)),_.close(4000,"request_timeout")},f+Ne);I.set(u,{reject:(c)=>{clearTimeout(p),a(c)},resolve:({status:c,body:d})=>{clearTimeout(p);let g=null;try{g=d?JSON.parse(d):null}catch{}s({status:c,json:g})}}),Y({t:"req",id:u,path:`${an}${t}`,body:JSON.stringify(o)})}),be=()=>_.close(1001,"stopping");e.signal.addEventListener("abort",be,{once:!0});let le,X=new Map,Q=new Map,ue=!1,_e=new Set,me=Promise.resolve(),ke=()=>{ne().catch(()=>{return})},Z=!1;try{await new Promise((c,d)=>{let g=setTimeout(()=>d(Error("session open timeout")),En);_.onopen=()=>{clearTimeout(g),r("vm_hands.ws_open",{}),c()},_.onerror=()=>{clearTimeout(g),d(Error("session socket error"))}});let t=await J(["challenge"],5000);r("vm_hands.challenge",{});let o=[],s=null,a;if(i){Y(await e.agent.helloFrame(t.challenge,n.connection));let c=await J(["ready"],1e4);if(typeof c.vm_hands_connection==="string")n.connection=c.vm_hands_connection;if(a={device_id:i,...c.cadence?{cadence:c.cadence}:{}},typeof c.vm_hands_probe_script==="string"){if(s=c.vm_hands_probe_script,Z=!0,e.agent.phase==="registered"&&!n.turns.size)n.attest="pending"}n.served=!0,r("vm_hands.reconnected",{device_id:i});let d=Array.isArray(c.vm_hands_binds)?c.vm_hands_binds:c.vm_hands_bind?[c.vm_hands_bind]:[];for(let[g,S]of[...n.turns]){if(d.some((T)=>T&&T.operation_id===S.claim.operation_id&&T.attempt_id===S.claim.attempt_id)){o.push(S),r("vm_hands.bound_resumed",{operation_id:S.claim.operation_id});continue}n.turns.delete(g),e.onTurn?.(g,null),de(S);let P=await L(n,e.agent,g).catch((T)=>ee(T,S,"vm_hands_bind_lost"));if(P)n.receipts.push({turn:S,failure:"vm_hands_bind_lost",unbound:P});r("vm_hands.bound_dropped",{reason:"not_named_on_reconnect"})}}else{Y(await e.agent.registerFrame(t.challenge)),r("vm_hands.register_sent",{});let c=await Promise.race([J(["registered","register_refused"],1e4),ce.then(()=>{throw new l(v==="register_failed"?"vm_hands_register_failed":"vm_hands_register_closed","session closed before the register was answered")})]);if(c.t==="register_refused")throw new l(c.code,"register refused");e.agent.registered();let d=c;if(a=d,n.deviceId=d.device_id,typeof d.vm_hands_connection==="string")n.connection=d.vm_hands_connection;if(typeof d.vm_hands_probe_script==="string"){if(s=d.vm_hands_probe_script,Z=!0,e.agent.phase==="registered"&&!n.turns.size)n.attest="pending"}n.served=!0,r("vm_hands.registered",{device_id:a.device_id})}let u=async()=>{let c=await q("/heartbeat",await e.heartbeat());if(c.status>=300)throw Error(`heartbeat ${c.status}`)};await u();let f=a.cadence?.presence_interval_ms??30000;if(le=setInterval(()=>{u().catch(()=>_.close())},f),e.onHeartbeatNow?.(()=>{u().catch(()=>_.close())}),n.request=q,ce.then(()=>{if(n.request===q)n.request=null}),s&&n.attest!=="accepted"&&e.agent.phase==="registered"&&!n.turns.size)ze(s,t.challenge);let p=(c,d)=>{Q.set(c,d().catch(async(g)=>{if(await Se(g,c),g instanceof D)_.close();else await ne().catch(()=>{return})}).finally(()=>{Q.delete(c)}))};n.flushReceipts=ke;try{await ne();for(let c of o)c.flush=()=>Ie(c),c.flush(),p(c.claim.attempt_id,()=>Pe(c));while(!e.signal.aborted&&_.readyState===WebSocket.OPEN){let c=await q("/operations/claim",{wait_ms:Math.min(a.cadence?.claim_wait_ms??Ce,Ce)});if(c.status===204||!c.json)continue;if(c.status>=300)throw Error(`claim ${c.status}`);let d=c.json;if(d.capability==="hands.connect"){if(Q.has(d.attempt_id)){O({claim:d,eventSeq:0}).complete("failed",{error_code:"vm_hands_busy"}).catch(()=>{return});continue}p(d.attempt_id,()=>Fe(d))}else Ke(d).catch(()=>{return})}}catch(c){await Se(c,null)}}finally{if(le)clearInterval(le);e.signal.removeEventListener("abort",be);for(let t of n.turns.values())t.flush=null;if(n.flushReceipts===ke)n.flushReceipts=null;_.close(),await ce,await Promise.all([...Q.values()]);for(let t of e.agent.liveBindIds){if(n.turns.has(t))continue;let o=X.get(t),s=o?{...o,eventSeq:o.eventSeq+1}:null,a=await L(n,e.agent,t).catch((u)=>s?ee(u,s,"vm_hands_bind_lost"):null);if(a&&s)n.receipts.push({turn:s,failure:"vm_hands_bind_lost",unbound:a});r("vm_hands.bound_dropped",{reason:"bound_after_loss"})}}return{closeCode:k,closeReason:v};async function Se(t,o){if(t instanceof D){if(!ue&&n.turns.size)n.lostAt=Date.now();ue=!0}else{let s=o!==null?[o]:[...new Set([...n.turns.keys(),...e.agent.liveBindIds])];if(o===null)ue=!0;for(let a of s){let u=n.turns.get(a);if(n.turns.delete(a),u)de(u),e.onTurn?.(a,null);if(e.agent.liveBindIds.includes(a)){let f=X.get(a)??u,p=f?{...f,eventSeq:f.eventSeq+1}:null,c=await L(n,e.agent,a).catch((d)=>p?ee(d,p,"vm_hands_bind_lost"):null);if(c&&p)n.receipts.push({turn:p,failure:"vm_hands_bind_lost",unbound:c})}}}r("vm_hands.session_lost",{error:t instanceof Error?t.message:String(t),bound_kept:n.turns.size})}function O(t,o=q){let s=o,a=t.claim,u={attempt_id:a.attempt_id,attempt_token:a.attempt_token},f=encodeURIComponent(a.operation_id);return{fence:u,op:f,complete:(c,d={})=>s(`/operations/${f}/complete`,{...u,status:c,...d}),emit:(c,d)=>{let g=(t.chain??Promise.resolve()).catch(()=>{return}).then(()=>p(c,d));return t.chain=g,g}};async function p(c,d){let g=t.eventSeq,S=(R)=>s(`/operations/${f}/events`,{...u,event_seq_start:R,events:[{kind:c,payload:{sequence:R,capability:String(a.capability??"hands.connect"),data:d}}]}),P=g,T=await S(P),M=T.status===409?T.json?.expected_event_seq:void 0;if(typeof M==="number"&&M>=0&&M!==g)P=M,T=await S(P);if(T.status<300)t.eventSeq=P+1;return T}}function We(t){return(o,s)=>new Promise((a,u)=>{if(n.turns.get(t.claim.attempt_id)!==t){u(Error("vm_hands_attempt_ended"));return}if(t.outbox??=[],t.outbox.length>=kn){u(Error("vm_hands_outbox_full"));return}t.outbox.push({kind:o,data:s,resolve:a,reject:u}),t.flush?.()})}function Ie(t){if(_e.has(t))return;_e.add(t),(async()=>{try{while(t.outbox?.length&&n.turns.get(t.claim.attempt_id)===t&&_.readyState===WebSocket.OPEN){let o=t.outbox[0],s;try{s=await O(t).emit(o.kind,o.data)}catch(a){if(a instanceof D)return;s={status:500}}if(t.outbox.shift(),s.status<300)o.resolve();else o.reject(Error(`${o.kind} refused ${s.status}`))}}finally{_e.delete(t)}})()}async function ze(t,o){try{let s=await e.agent.attestFrame(t,o);if(_.readyState!==WebSocket.OPEN)return;Y(s);let a=await J(["attested","attest_refused"],15000);n.attest=a.t==="attested"?"accepted":"refused";for(let u of n.attestWaiters.splice(0))u(n.attest==="accepted");if(r("vm_hands.attest",{result:n.attest,exit_code:s.exit_code,...a.t==="attest_refused"?{code:String(a.code??"")}:{}}),n.attest==="refused")_.close(4401,"attest_refused")}catch(s){r("vm_hands.attest_failed",{code:s instanceof l?s.code:"probe_error"});for(let a of n.attestWaiters.splice(0))a(!1);if(n.attest!=="accepted")_.close(4000,"attest_unanswered")}}async function Fe(t){let o=Z&&n.attest==="pending",s=t.vm_hands_attest,a=s;if(n.attest==="refused"){r("vm_hands.claim_attest_refused",{said:typeof s==="string"?s.slice(0,16):typeof s,local:n.attest}),await O({claim:t,eventSeq:0}).complete("failed",{error_code:"vm_hands_unattested"}).catch(()=>{return});return}if(a==="accepted"){if(!o&&n.attest!=="accepted"){n.attest="accepted";for(let b of n.attestWaiters.splice(0))b(!0)}}else if(a!=="pending"||!o&&n.attest!=="accepted"){r("vm_hands.claim_attest_refused",{said:typeof s==="string"?s.slice(0,16):typeof s,local:n.attest}),await O({claim:t,eventSeq:0}).complete("failed",{error_code:"vm_hands_unattested"}).catch(()=>{return});return}if(n.attest!=="accepted"){let b=Date.parse(t.lease_until)-Date.now()-5000,B=Math.max(0,Math.min(ae,Number.isFinite(b)?b:ae));if(!await new Promise((ie)=>{let y=setTimeout(()=>ie(!1),B);n.attestWaiters.push((x)=>{clearTimeout(y),ie(x)})})){await O({claim:t,eventSeq:0}).complete("failed",{error_code:"vm_hands_unattested"}).catch(()=>{return});return}}let u={claim:t,eventSeq:0},{complete:f,emit:p}=O(u),c;try{if(t.capability!=="hands.connect")throw new l("vm_hands_bind_invalid","not hands.connect");c=!pe(t)}catch(b){r("vm_hands.bind_refused",{code:b instanceof l?b.code:"unexpected"}),await f("failed",{error_code:b instanceof l?b.code:"vm_hands_bind_invalid"});return}let d,g=null,S=!1,P=(()=>{try{return ve(t).session_id.toLowerCase()}catch{return String(t.run_id)}})();n.bindsStarting.set(P,(n.bindsStarting.get(P)??0)+1);try{let b=await In(n,P);if(b)r("vm_hands.person_terminals_closed",{count:b});let B=ve(t),j=e.agent.bind(B);if(B.workspace_deferred)S=!0,g=He(u,()=>S);d=await j}catch(b){r("vm_hands.bind_refused",{code:b instanceof l?b.code:"unexpected"}),await f("failed",{error_code:b instanceof l?b.code:"vm_hands_bind_failed"});return}finally{S=!1;let b=(n.bindsStarting.get(P)??1)-1;if(b>0)n.bindsStarting.set(P,b);else n.bindsStarting.delete(P)}let T=g?await g:-1,M={...d.ready_data??e.readyData({launchId:d.launch_id,claim:t})};if(c)delete M.environment_installed;let R=!c&&d.snapshot_revision!==null&&d.snapshot_id!==null?{environment_installed:{snapshot_id:d.snapshot_id,installed_revision:d.snapshot_revision}}:{};X.set(t.attempt_id,{claim:t,launchId:d.launch_id,readyData:M,eventSeq:u.eventSeq,ackSeq:-1});let F={...M,...R,vm_hands:{layout:d.layout,policy_digest:d.policy_digest,launch_id:d.launch_id}},te=Date.now()+yn,U=1,N=await p("hands.ready",F);while(bn(N.status)&&!e.signal.aborted){let b=$e(U);if(Date.now()+b>=te)break;await new Promise((B)=>setTimeout(B,b)),U++,N=await p("hands.ready",F)}if(U>1)r("vm_hands.ready_retried",{attempts:U,status_class:`${Math.floor(N.status/100)}xx`});if(X.delete(t.attempt_id),N.status>=300){await Ge(n,t.attempt_id),await e.agent.boundRefused(t.attempt_id),await f("failed",{error_code:Be(N.json?.error,"vm_hands_probe_failed")});return}let C={claim:t,launchId:d.launch_id,readyData:M,eventSeq:u.eventSeq,ackSeq:T};n.turns.set(t.attempt_id,C),C.flush=()=>Ie(C),e.onTurn?.(t.attempt_id,We(C)),await Pe(C)}async function He(t,o){let{fence:s,op:a}=O(t),u=t.claim.attempt_id,f=-1;try{for(;;){let p=await q(`/operations/${a}/heartbeat`,{...s,control_ack_seq:f,wait_ms:we});if(!o())return f;if(p.status>=300)return e.agent.abandonWorkspaceGrant(u),f;let c=(p.json?.controls??[]).slice().sort((d,g)=>d.seq-g.seq);for(let d of c){if(d.seq<=f)continue;if(f=d.seq,d.kind===si)return r("vm_hands.workspace_granted",{}),e.agent.grantWorkspace(u),f;return r("vm_hands.workspace_grant_abandoned",{control:/^[a-z][a-z0-9._-]{0,63}$/.test(d.kind)?d.kind:"other"}),e.agent.abandonWorkspaceGrant(u),f}}}catch{return e.agent.abandonWorkspaceGrant(u),f}}async function Pe(t){let{fence:o,op:s}=O(t),a=null,u=null,f=e.agent.executorExited(t.claim.attempt_id).then((p)=>(u=p,null));e:for(;;){let p=await Promise.race([f,q(`/operations/${s}/heartbeat`,{...o,control_ack_seq:t.ackSeq,wait_ms:we})]);if(!p){a="vm_hands_executor_exited",r("vm_hands.executor_exited",{reason:u});break}if(p.status>=300)break;let c=(p.json?.controls??[]).slice().sort((d,g)=>d.seq-g.seq);for(let d of c){if(d.seq<=t.ackSeq)continue;if(d.kind==="operation.cancel"||d.kind==="cancel"){t.ackSeq=d.seq;break e}if(d.kind===bt)try{await Le(t,d.payload??{})}catch(g){if(g instanceof D)throw g;a=g instanceof l?g.code:"environment_unavailable";let S=g&&typeof g==="object"&&"code"in g&&typeof g.code==="string"&&/^[a-z][a-z0-9_]{2,63}$/.test(g.code)?g.code:null;r("vm_hands.environment_refused",{code:a,cause:S});break e}t.ackSeq=d.seq}}await Ve(t,a)}async function ge(t,o){let s=Date.now()+un;for(;;){let a=n.request;if(a)try{return await a(t,o)}catch(u){if(!(u instanceof D))throw u}if(Date.now()>=s||e.signal.aborted)throw new D("kept operation has no live session");await new Promise((u)=>setTimeout(u,500))}}async function Ke(t){let o=t,s={claim:o,eventSeq:0},a=String(t.capability??""),u=a===ln,{complete:f,emit:p,fence:c,op:d}={...O(s,ge)},g=t.vm_hands_origin==="person"?"person":"model";if(!e.executeOp){await f("failed",{error_code:"vm_hands_op_unsupported"});return}if(t.vm_hands_attest==="accepted"&&n.attest==="pending"&&!(Z&&n.attest==="pending")){n.attest="accepted";for(let y of n.attestWaiters.splice(0))y(!0)}if(n.attest!=="accepted"){let y=Date.parse(String(t.lease_until??""))-Date.now()-5000,x=n.attest==="refused"?0:Math.max(0,Math.min(ae,Number.isFinite(y)?y:ae));if(!(x>0&&await new Promise((re)=>{let Je=setTimeout(()=>re(!1),x);n.attestWaiters.push((Ye)=>{clearTimeout(Je),re(Ye)})}))){await f("failed",{error_code:"vm_hands_unattested"});return}}let S=e.agent.bindIdForRun(o.run_id);if(g==="model"&&S===null){await f("failed",{error_code:"vm_hands_not_bound"});return}let P=a==="pty.start"&&g==="person"&&!t.authority,T=P?Pn(t):null;if(P&&((y)=>y===null?e.agent.liveBindIds.length>0||n.bindsStarting.size>0:e.agent.liveSessionIds.includes(y)||n.bindsStarting.has(y))(T)){await f("failed",{error_code:"vm_hands_bound"});return}if(cn.has(a)&&!P&&e.agent.liveBindIds.length===0){await f("failed",{error_code:"vm_hands_not_bound"});return}let R=new AbortController,F=()=>R.abort();e.signal.addEventListener("abort",F,{once:!0});let te,U=new Promise((y)=>{te=y}),N={abort:R,settled:U},C=P?{...N,session:T}:null;if(C)n.personTerminals.add(C);if(g==="model"&&S&&a!=="preview.serve.v1"){let y=n.modelOps.get(S)??new Set;y.add(N),n.modelOps.set(S,y),await e.agent.environmentInstalled(S,_n,R.signal)}let b=-1,B=!1,j=!1,ie=u?void 0:setInterval(()=>{if(j)return;j=!0,ge(`/operations/${d}/heartbeat`,{...c,control_ack_seq:b,wait_ms:0}).then((y)=>{if(y.status>=300){R.abort();return}let x=y.json?.controls??[];for(let A of x)if(b=Math.max(b,A.seq),A.kind==="operation.cancel"||A.kind==="cancel")R.abort()},()=>R.abort()).finally(()=>{j=!1})},dn);if(u)(async()=>{while(!B&&!R.signal.aborted){let y;try{y=await ge(`/operations/${d}/heartbeat`,{...c,control_ack_seq:b,wait_ms:we})}catch{R.abort();return}if(B)return;if(y.status>=300){R.abort();return}let x=(y.json?.controls??[]).slice().sort((A,re)=>A.seq-re.seq);for(let A of x){if(A.seq<=b)continue;if(A.kind==="operation.cancel"||A.kind==="cancel")R.abort();else await e.controlOp?.({claim:t,control:A}).catch(()=>!1);b=A.seq}}})();try{let y=await e.executeOp({kind:g,claim:t,...g==="model"&&S?{bindId:S}:{},signal:R.signal,emit:async(A)=>{await p(A.kind,A.data??{})}}),x=await f(y.status,{...y.result?{result:y.result}:{},...y.error_code?{error_code:Be(y.error_code,"vm_hands_op_failed")}:{}});e.opCompleted?.({claim:t,status:y.status,acknowledged:x.status<300}),r("vm_hands.op",{capability:a,kind:g,status:y.status,code:y.error_code??null,...x.status>=300?{complete_status:x.status,complete_error:String(x.json?.error??"").slice(0,64)}:{}})}finally{if(B=!0,clearInterval(ie),e.signal.removeEventListener("abort",F),S)n.modelOps.get(S)?.delete(N);if(C)n.personTerminals.delete(C);te()}}async function Ve(t,o){let s=t.claim.attempt_id;if(n.turns.get(s)===t)n.turns.delete(s);e.onTurn?.(s,null),de(t);let a=await L(n,e.agent,s).catch((u)=>ee(u,t,o));if(!a)return;n.receipts.push({turn:t,failure:o,unbound:a}),await ne()}function ee(t,o,s){let a=je(t);return r("vm_hands.unbind_unverified",{operation_id:o.claim.operation_id,code:a,attempt:0}),O(o).emit(ai,{code:a}).catch(()=>{return}),Sn(n,e.agent,{turn:o,failure:s},e.signal,r),null}function ne(){return me=me.then(Ee,Ee),me}async function Ee(){while(n.receipts.length){let{turn:t,failure:o,unbound:s}=n.receipts[0],{complete:a,emit:u}=O(t);try{if(await u("hands.stopped",{...t.readyData,reason_code:o?"failed":"cancelled",killed_verified:s.killed_verified,shredded:s.shredded,...s.srt_fallbacks?{vm_hands_srt_fallbacks:s.srt_fallbacks}:{}}),o)await a("failed",{error_code:o});else await a("cancelled",{error_code:"driver_stopped"})}catch(f){if(f instanceof D)return}n.receipts.shift()}}async function Le(t,o){let{fence:s,op:a}=O(t),u=o.snapshot_id;if(o.version!==1||typeof u!=="string"||Object.keys(o).length!==2)throw new l("vm_hands_env_invalid","invalid environment delivery");let f=await q(`/operations/${a}/environment`,{...s,snapshot_id:u}),p=f.json?.environment_sealed;if(f.status!==200||!p||f.json?.payload!==void 0)throw new l("vm_hands_env_invalid","environment not delivered sealed");let c=await e.agent.deliverEnvironment({attemptId:t.claim.attempt_id,snapshotId:u,deviceId:n.deviceId??"",sealed:p});if((await q(`/operations/${a}/environment-ack`,{...s,...c})).status>=300)throw new l("vm_hands_env_ack_refused","environment ack refused")}}import{readFileSync as xn}from"fs";var An=performance.now();delete process.env.BUN_BE_BUN;var z=(e,n={})=>console.log(JSON.stringify({stage:e,ms:Math.round(performance.now()),...n}));async function On(){if(process.argv.includes("--vm-hands-op-runner")){let{runVmHandsOpRunner:m}=await import("./vm-hands-op-runner-545vwzvp.js");await m();return}z("parsed",{t0:Math.round(An)});let e="";try{e=xn(3,"utf8")}catch{}z("fd3_read",{bytes:e.length});let n=null;if(e.trim())try{n=JSON.parse(e)}catch{n=null}if(!n||typeof n!=="object"||Array.isArray(n))z(e.trim()?"identity_invalid":"identity_free"),await new Promise(()=>{setInterval(()=>{return},1073741824)});let{parseVmHandsInit:i,runVmHands:r}=await import("./vm-hands-runtime-wr0m4gny.js"),h=i(n);if(!h)z("identity_invalid"),await new Promise(()=>{setInterval(()=>{return},1073741824)});try{await r(h,z)}catch(m){let _=m&&typeof m==="object"&&"code"in m&&typeof m.code==="string"?m.code:"error";throw z("failed",{code:_}),m}process.exit(0)}On();export{Hi,pn,zi};
|
|
4
|
+
`,_=se(i,`.job.env.${he(8).toString("hex")}`),k=Oe(_,W.O_WRONLY|W.O_CREAT|W.O_EXCL|W.O_NOFOLLOW,384);try{Me(k,m),xe(k)}finally{Ae(k)}return Qe(_,se(i,"job.env")),i}}function fe(e){try{let n=se(e,"job.env"),i=De(n).size,r=Oe(n,W.O_WRONLY|W.O_NOFOLLOW);try{Me(r,Buffer.alloc(i)),xe(r)}finally{Ae(r)}}catch{}Ze(e,{recursive:!0,force:!0})}function rn(e){if(e.length!==64)throw new l("vm_hands_signature_invalid","unexpected ECDSA signature length");let n=(h)=>{let m=0;while(m<h.length-1&&h[m]===0)m++;let _=h.subarray(m),k=_[0]&128?Uint8Array.of(0,..._):_;return Uint8Array.of(2,k.length,...k)},i=n(e.subarray(0,32)),r=n(e.subarray(32));return Uint8Array.of(48,i.length+r.length,...i,...r)}import{randomUUID as sn}from"crypto";var on="/app/local-runtime/session?register=vm_hands_v1",an="/app/local-runtime",Ce=25000,we=20000,dn=1e4,Ue=5000,cn=new Set(["pty.start","jobs.control","tunnel.open","tunnel.close"]),ln="preview.serve.v1",un=60000,ye=75000,_n=2000,mn=1e4,gn=new Set(["vm_hands_no_register","vm_hands_register_failed"]),hn=3,fn=20000,vn=250,wn=2000;function $e(e){let n=Math.min(vn*2**(e-1),wn);return Math.round(n/2+Math.random()*n/2)}var yn=5000;function bn(e){return e>=500||e===408||e===429}var ae=20000;function Be(e,n){return typeof e==="string"&&/^[A-Za-z0-9._:-]{1,160}$/.test(e)?e:n}class D extends Error{}var kn=64,qe=[1000,2000,4000,8000,15000,30000,60000,120000];function je(e){let n=e&&typeof e==="object"&&"code"in e?e.code:null;return typeof n==="string"&&/^[a-z][a-z0-9_]{2,63}$/.test(n)?n:"vm_hands_unbind_failed"}function Sn(e,n,i,r,h){let m=i.turn.claim.attempt_id,_=e.healing??=new Set;if(_.has(m))return;_.add(m);let k=i.turn.claim.operation_id;(async()=>{for(let[v,I]of qe.entries()){if(r.aborted)return;if(await new Promise((w)=>{let E=setTimeout(w,I);E.unref?.(),r.addEventListener("abort",()=>{clearTimeout(E),w()},{once:!0})}),r.aborted)return;try{let w=await n.retryUnbind(m);h("vm_hands.unbind_healed",{operation_id:k,attempt:v+1}),e.receipts.push({...i,unbound:w}),e.flushReceipts?.();return}catch(w){let E=je(w);if(h("vm_hands.unbind_unverified",{operation_id:k,code:E,attempt:v+1}),E==="vm_hands_unbind_unknown")return}}h("vm_hands.unbind_heal_exhausted",{operation_id:k,attempts:qe.length})})().finally(()=>_.delete(m))}async function Ge(e,n){let i=[...e.modelOps.get(n)??[]];for(let r of i)r.abort.abort();await Promise.race([Promise.all(i.map((r)=>r.settled)),new Promise((r)=>setTimeout(r,Ue))])}async function In(e,n){let i=[...e.personTerminals].filter((r)=>r.session===null||r.session===n);for(let r of i)r.abort.abort();if(i.length)await Promise.race([Promise.all(i.map((r)=>r.settled)),new Promise((r)=>setTimeout(r,Ue))]);return i.length}function Pn(e){let n=e.payload,i=n?.workspace?.kind==="managed"?n.workspace.workspaceId:void 0;return typeof i==="string"&&/^[0-9a-f-]{36}$/i.test(i)?i.toLowerCase():null}async function L(e,n,i){return await Ge(e,i),n.unbind(i)}function de(e){for(let n of e.outbox?.splice(0)??[])n.reject(Error("vm_hands_attempt_ended"))}var Ne=15000,En=1e4,Tn=1000;async function zi(e){let n=Date.now(),i={deviceId:null,connection:null,turns:new Map,lostAt:0,receipts:[],attest:"pending",attestWaiters:[],modelOps:new Map,personTerminals:new Set,bindsStarting:new Map},r=e.log??(()=>{}),h=async(k)=>{for(let[v,I]of[...i.turns]){i.turns.delete(v),e.onTurn?.(v,null),de(I);let w=await L(i,e.agent,v).catch(()=>null);if(w)i.receipts.push({turn:I,failure:"vm_hands_bind_lost",unbound:w});r("vm_hands.bound_dropped",{reason:k})}},m=0,_=0;try{for(let k=0;!e.signal.aborted;k++){let v=await Rn(e,i).catch((w)=>{if(w instanceof l&&i.deviceId===null&&w.code==="vm_hands_no_session"&&Date.now()-n<mn)return{closeCode:0,closeReason:"vm_hands_no_session"};if(w instanceof l&&i.deviceId===null&&gn.has(w.code)&&m<hn&&Date.now()-n<fn)return m++,_=$e(m),r("vm_hands.register_retry",{attempt:m,code:w.code,delay_ms:_}),{closeCode:0,closeReason:"vm_hands_register_retry"};if(w instanceof l&&i.deviceId===null)throw w;return{closeCode:0,closeReason:w instanceof Error?w.message:String(w)}});if(r("vm_hands.session_closed",{close_code:v.closeCode,reason:v.closeReason.slice(0,120),registered:i.deviceId!==null}),v.closeCode===4401||i.attest==="refused")return;if(e.signal.aborted)return;if(i.turns.size&&Date.now()-i.lostAt>=ye)await h("reconnect_deadline");if(i.served)i.served=!1,k=0;let I=v.closeReason==="drain_reconnect"?0:v.closeReason==="vm_hands_register_retry"?_:v.closeReason==="vm_hands_no_session"?Math.min(250*2**Math.min(k,5),2000):i.turns.size?Math.min(250*2**Math.min(k,5),5000,Math.max(0,i.lostAt+ye-Date.now())):Math.min(500*2**k,30000);if(await new Promise((w)=>setTimeout(w,I)),i.turns.size&&Date.now()-i.lostAt>=ye)await h("reconnect_deadline")}}finally{await h("session_ended")}}async function Rn(e,n){let i=n.deviceId,r=e.log??(()=>{}),h=i?`/app/local-runtime/session?device_id=${encodeURIComponent(i)}`:on,m=`${e.apiOrigin.replace(/^http/,"ws")}${h}`,_=new WebSocket(m),k=0,v="",I=new Map,w=[],E=null,ce=new Promise((t)=>{_.onclose=(o)=>{k=o.code,v=o.reason;for(let s of I.values())s.reject(new D(`session closed ${o.code}`));for(let s of n.attestWaiters.splice(0))s(!1);I.clear(),t()}});_.onmessage=(t)=>{let o;try{o=JSON.parse(String(t.data))}catch{_.close(4400);return}if(o.t==="res"){let s=o;I.get(s.id)?.resolve({status:s.status,body:s.body}),I.delete(s.id);return}if(o.t==="reconnect"){let s=Math.max(0,Math.min(Number(o.after_ms)||0,Tn));r("vm_hands.drain_reconnect",{after_ms:s}),setTimeout(()=>{try{_.close(4001,"drain_reconnect")}catch{}},s).unref?.();return}if(!E?.(o))w.push(o)};let J=(t,o)=>new Promise((s,a)=>{let u=w.findIndex((p)=>t.includes(p.t));if(u>=0){s(w.splice(u,1)[0]);return}let f=setTimeout(()=>{E=null,a(new l("vm_hands_no_register",`no ${t.join("/")} in ${o} ms`))},o);E=(p)=>{if(!t.includes(p.t))return!1;return clearTimeout(f),E=null,s(p),!0}}),Y=(t)=>_.send(JSON.stringify(t)),q=(t,o)=>new Promise((s,a)=>{if(_.readyState!==WebSocket.OPEN){a(new D("session closed"));return}let u=sn(),f=typeof o.wait_ms==="number"?o.wait_ms:0,p=setTimeout(()=>{if(!I.delete(u))return;a(new D(`no answer to ${t.split("/").pop()} in ${f+Ne} ms`)),_.close(4000,"request_timeout")},f+Ne);I.set(u,{reject:(c)=>{clearTimeout(p),a(c)},resolve:({status:c,body:d})=>{clearTimeout(p);let g=null;try{g=d?JSON.parse(d):null}catch{}s({status:c,json:g})}}),Y({t:"req",id:u,path:`${an}${t}`,body:JSON.stringify(o)})}),be=()=>_.close(1001,"stopping");e.signal.addEventListener("abort",be,{once:!0});let le,X=new Map,Q=new Map,ue=!1,_e=new Set,me=Promise.resolve(),ke=()=>{ne().catch(()=>{return})},Z=!1;try{await new Promise((c,d)=>{let g=setTimeout(()=>d(Error("session open timeout")),En);_.onopen=()=>{clearTimeout(g),r("vm_hands.ws_open",{}),c()},_.onerror=()=>{clearTimeout(g),d(Error("session socket error"))}});let t=await J(["challenge"],5000);r("vm_hands.challenge",{});let o=[],s=null,a;if(i){Y(await e.agent.helloFrame(t.challenge,n.connection));let c=await J(["ready"],1e4);if(typeof c.vm_hands_connection==="string")n.connection=c.vm_hands_connection;if(a={device_id:i,...c.cadence?{cadence:c.cadence}:{}},typeof c.vm_hands_probe_script==="string"){if(s=c.vm_hands_probe_script,Z=!0,e.agent.phase==="registered"&&!n.turns.size)n.attest="pending"}n.served=!0,r("vm_hands.reconnected",{device_id:i});let d=Array.isArray(c.vm_hands_binds)?c.vm_hands_binds:c.vm_hands_bind?[c.vm_hands_bind]:[];for(let[g,S]of[...n.turns]){if(d.some((T)=>T&&T.operation_id===S.claim.operation_id&&T.attempt_id===S.claim.attempt_id)){o.push(S),r("vm_hands.bound_resumed",{operation_id:S.claim.operation_id});continue}n.turns.delete(g),e.onTurn?.(g,null),de(S);let P=await L(n,e.agent,g).catch((T)=>ee(T,S,"vm_hands_bind_lost"));if(P)n.receipts.push({turn:S,failure:"vm_hands_bind_lost",unbound:P});r("vm_hands.bound_dropped",{reason:"not_named_on_reconnect"})}}else{Y(await e.agent.registerFrame(t.challenge)),r("vm_hands.register_sent",{});let c=await Promise.race([J(["registered","register_refused"],1e4),ce.then(()=>{throw new l(v==="register_failed"?"vm_hands_register_failed":"vm_hands_register_closed","session closed before the register was answered")})]);if(c.t==="register_refused")throw new l(c.code,"register refused");e.agent.registered();let d=c;if(a=d,n.deviceId=d.device_id,typeof d.vm_hands_connection==="string")n.connection=d.vm_hands_connection;if(typeof d.vm_hands_probe_script==="string"){if(s=d.vm_hands_probe_script,Z=!0,e.agent.phase==="registered"&&!n.turns.size)n.attest="pending"}n.served=!0,r("vm_hands.registered",{device_id:a.device_id})}let u=async()=>{let c=await q("/heartbeat",await e.heartbeat());if(c.status>=300)throw Error(`heartbeat ${c.status}`)};await u();let f=a.cadence?.presence_interval_ms??30000;if(le=setInterval(()=>{u().catch(()=>_.close())},f),e.onHeartbeatNow?.(()=>{u().catch(()=>_.close())}),n.request=q,ce.then(()=>{if(n.request===q)n.request=null}),s&&n.attest!=="accepted"&&e.agent.phase==="registered"&&!n.turns.size)ze(s,t.challenge);let p=(c,d)=>{Q.set(c,d().catch(async(g)=>{if(await Se(g,c),g instanceof D)_.close();else await ne().catch(()=>{return})}).finally(()=>{Q.delete(c)}))};n.flushReceipts=ke;try{await ne();for(let c of o)c.flush=()=>Ie(c),c.flush(),p(c.claim.attempt_id,()=>Pe(c));while(!e.signal.aborted&&_.readyState===WebSocket.OPEN){let c=await q("/operations/claim",{wait_ms:Math.min(a.cadence?.claim_wait_ms??Ce,Ce)});if(c.status===204||!c.json)continue;if(c.status>=300)throw Error(`claim ${c.status}`);let d=c.json;if(d.capability==="hands.connect"){if(Q.has(d.attempt_id)){O({claim:d,eventSeq:0}).complete("failed",{error_code:"vm_hands_busy"}).catch(()=>{return});continue}p(d.attempt_id,()=>Fe(d))}else Ke(d).catch(()=>{return})}}catch(c){await Se(c,null)}}finally{if(le)clearInterval(le);e.signal.removeEventListener("abort",be);for(let t of n.turns.values())t.flush=null;if(n.flushReceipts===ke)n.flushReceipts=null;_.close(),await ce,await Promise.all([...Q.values()]);for(let t of e.agent.liveBindIds){if(n.turns.has(t))continue;let o=X.get(t),s=o?{...o,eventSeq:o.eventSeq+1}:null,a=await L(n,e.agent,t).catch((u)=>s?ee(u,s,"vm_hands_bind_lost"):null);if(a&&s)n.receipts.push({turn:s,failure:"vm_hands_bind_lost",unbound:a});r("vm_hands.bound_dropped",{reason:"bound_after_loss"})}}return{closeCode:k,closeReason:v};async function Se(t,o){if(t instanceof D){if(!ue&&n.turns.size)n.lostAt=Date.now();ue=!0}else{let s=o!==null?[o]:[...new Set([...n.turns.keys(),...e.agent.liveBindIds])];if(o===null)ue=!0;for(let a of s){let u=n.turns.get(a);if(n.turns.delete(a),u)de(u),e.onTurn?.(a,null);if(e.agent.liveBindIds.includes(a)){let f=X.get(a)??u,p=f?{...f,eventSeq:f.eventSeq+1}:null,c=await L(n,e.agent,a).catch((d)=>p?ee(d,p,"vm_hands_bind_lost"):null);if(c&&p)n.receipts.push({turn:p,failure:"vm_hands_bind_lost",unbound:c})}}}r("vm_hands.session_lost",{error:t instanceof Error?t.message:String(t),bound_kept:n.turns.size})}function O(t,o=q){let s=o,a=t.claim,u={attempt_id:a.attempt_id,attempt_token:a.attempt_token},f=encodeURIComponent(a.operation_id);return{fence:u,op:f,complete:(c,d={})=>s(`/operations/${f}/complete`,{...u,status:c,...d}),emit:(c,d)=>{let g=(t.chain??Promise.resolve()).catch(()=>{return}).then(()=>p(c,d));return t.chain=g,g}};async function p(c,d){let g=t.eventSeq,S=(R)=>s(`/operations/${f}/events`,{...u,event_seq_start:R,events:[{kind:c,payload:{sequence:R,capability:String(a.capability??"hands.connect"),data:d}}]}),P=g,T=await S(P),M=T.status===409?T.json?.expected_event_seq:void 0;if(typeof M==="number"&&M>=0&&M!==g)P=M,T=await S(P);if(T.status<300)t.eventSeq=P+1;return T}}function We(t){return(o,s)=>new Promise((a,u)=>{if(n.turns.get(t.claim.attempt_id)!==t){u(Error("vm_hands_attempt_ended"));return}if(t.outbox??=[],t.outbox.length>=kn){u(Error("vm_hands_outbox_full"));return}t.outbox.push({kind:o,data:s,resolve:a,reject:u}),t.flush?.()})}function Ie(t){if(_e.has(t))return;_e.add(t),(async()=>{try{while(t.outbox?.length&&n.turns.get(t.claim.attempt_id)===t&&_.readyState===WebSocket.OPEN){let o=t.outbox[0],s;try{s=await O(t).emit(o.kind,o.data)}catch(a){if(a instanceof D)return;s={status:500}}if(t.outbox.shift(),s.status<300)o.resolve();else o.reject(Error(`${o.kind} refused ${s.status}`))}}finally{_e.delete(t)}})()}async function ze(t,o){try{let s=await e.agent.attestFrame(t,o);if(_.readyState!==WebSocket.OPEN)return;Y(s);let a=await J(["attested","attest_refused"],15000);n.attest=a.t==="attested"?"accepted":"refused";for(let u of n.attestWaiters.splice(0))u(n.attest==="accepted");if(r("vm_hands.attest",{result:n.attest,exit_code:s.exit_code,...a.t==="attest_refused"?{code:String(a.code??"")}:{}}),n.attest==="refused")_.close(4401,"attest_refused")}catch(s){r("vm_hands.attest_failed",{code:s instanceof l?s.code:"probe_error"});for(let a of n.attestWaiters.splice(0))a(!1);if(n.attest!=="accepted")_.close(4000,"attest_unanswered")}}async function Fe(t){let o=Z&&n.attest==="pending",s=t.vm_hands_attest,a=s;if(n.attest==="refused"){r("vm_hands.claim_attest_refused",{said:typeof s==="string"?s.slice(0,16):typeof s,local:n.attest}),await O({claim:t,eventSeq:0}).complete("failed",{error_code:"vm_hands_unattested"}).catch(()=>{return});return}if(a==="accepted"){if(!o&&n.attest!=="accepted"){n.attest="accepted";for(let b of n.attestWaiters.splice(0))b(!0)}}else if(a!=="pending"||!o&&n.attest!=="accepted"){r("vm_hands.claim_attest_refused",{said:typeof s==="string"?s.slice(0,16):typeof s,local:n.attest}),await O({claim:t,eventSeq:0}).complete("failed",{error_code:"vm_hands_unattested"}).catch(()=>{return});return}if(n.attest!=="accepted"){let b=Date.parse(t.lease_until)-Date.now()-5000,B=Math.max(0,Math.min(ae,Number.isFinite(b)?b:ae));if(!await new Promise((ie)=>{let y=setTimeout(()=>ie(!1),B);n.attestWaiters.push((x)=>{clearTimeout(y),ie(x)})})){await O({claim:t,eventSeq:0}).complete("failed",{error_code:"vm_hands_unattested"}).catch(()=>{return});return}}let u={claim:t,eventSeq:0},{complete:f,emit:p}=O(u),c;try{if(t.capability!=="hands.connect")throw new l("vm_hands_bind_invalid","not hands.connect");c=!pe(t)}catch(b){r("vm_hands.bind_refused",{code:b instanceof l?b.code:"unexpected"}),await f("failed",{error_code:b instanceof l?b.code:"vm_hands_bind_invalid"});return}let d,g=null,S=!1,P=(()=>{try{return ve(t).session_id.toLowerCase()}catch{return String(t.run_id)}})();n.bindsStarting.set(P,(n.bindsStarting.get(P)??0)+1);try{let b=await In(n,P);if(b)r("vm_hands.person_terminals_closed",{count:b});let B=ve(t),j=e.agent.bind(B);if(B.workspace_deferred)S=!0,g=He(u,()=>S);d=await j}catch(b){r("vm_hands.bind_refused",{code:b instanceof l?b.code:"unexpected"}),await f("failed",{error_code:b instanceof l?b.code:"vm_hands_bind_failed"});return}finally{S=!1;let b=(n.bindsStarting.get(P)??1)-1;if(b>0)n.bindsStarting.set(P,b);else n.bindsStarting.delete(P)}let T=g?await g:-1,M={...d.ready_data??e.readyData({launchId:d.launch_id,claim:t})};if(c)delete M.environment_installed;let R=!c&&d.snapshot_revision!==null&&d.snapshot_id!==null?{environment_installed:{snapshot_id:d.snapshot_id,installed_revision:d.snapshot_revision}}:{};X.set(t.attempt_id,{claim:t,launchId:d.launch_id,readyData:M,eventSeq:u.eventSeq,ackSeq:-1});let F={...M,...R,vm_hands:{layout:d.layout,policy_digest:d.policy_digest,launch_id:d.launch_id}},te=Date.now()+yn,U=1,N=await p("hands.ready",F);while(bn(N.status)&&!e.signal.aborted){let b=$e(U);if(Date.now()+b>=te)break;await new Promise((B)=>setTimeout(B,b)),U++,N=await p("hands.ready",F)}if(U>1)r("vm_hands.ready_retried",{attempts:U,status_class:`${Math.floor(N.status/100)}xx`});if(X.delete(t.attempt_id),N.status>=300){await Ge(n,t.attempt_id),await e.agent.boundRefused(t.attempt_id),await f("failed",{error_code:Be(N.json?.error,"vm_hands_probe_failed")});return}let C={claim:t,launchId:d.launch_id,readyData:M,eventSeq:u.eventSeq,ackSeq:T};n.turns.set(t.attempt_id,C),C.flush=()=>Ie(C),e.onTurn?.(t.attempt_id,We(C)),await Pe(C)}async function He(t,o){let{fence:s,op:a}=O(t),u=t.claim.attempt_id,f=-1;try{for(;;){let p=await q(`/operations/${a}/heartbeat`,{...s,control_ack_seq:f,wait_ms:we});if(!o())return f;if(p.status>=300)return e.agent.abandonWorkspaceGrant(u),f;let c=(p.json?.controls??[]).slice().sort((d,g)=>d.seq-g.seq);for(let d of c){if(d.seq<=f)continue;if(f=d.seq,d.kind===si)return r("vm_hands.workspace_granted",{}),e.agent.grantWorkspace(u),f;return r("vm_hands.workspace_grant_abandoned",{control:/^[a-z][a-z0-9._-]{0,63}$/.test(d.kind)?d.kind:"other"}),e.agent.abandonWorkspaceGrant(u),f}}}catch{return e.agent.abandonWorkspaceGrant(u),f}}async function Pe(t){let{fence:o,op:s}=O(t),a=null,u=null,f=e.agent.executorExited(t.claim.attempt_id).then((p)=>(u=p,null));e:for(;;){let p=await Promise.race([f,q(`/operations/${s}/heartbeat`,{...o,control_ack_seq:t.ackSeq,wait_ms:we})]);if(!p){a="vm_hands_executor_exited",r("vm_hands.executor_exited",{reason:u});break}if(p.status>=300)break;let c=(p.json?.controls??[]).slice().sort((d,g)=>d.seq-g.seq);for(let d of c){if(d.seq<=t.ackSeq)continue;if(d.kind==="operation.cancel"||d.kind==="cancel"){t.ackSeq=d.seq;break e}if(d.kind===bt)try{await Le(t,d.payload??{})}catch(g){if(g instanceof D)throw g;a=g instanceof l?g.code:"environment_unavailable";let S=g&&typeof g==="object"&&"code"in g&&typeof g.code==="string"&&/^[a-z][a-z0-9_]{2,63}$/.test(g.code)?g.code:null;r("vm_hands.environment_refused",{code:a,cause:S});break e}t.ackSeq=d.seq}}await Ve(t,a)}async function ge(t,o){let s=Date.now()+un;for(;;){let a=n.request;if(a)try{return await a(t,o)}catch(u){if(!(u instanceof D))throw u}if(Date.now()>=s||e.signal.aborted)throw new D("kept operation has no live session");await new Promise((u)=>setTimeout(u,500))}}async function Ke(t){let o=t,s={claim:o,eventSeq:0},a=String(t.capability??""),u=a===ln,{complete:f,emit:p,fence:c,op:d}={...O(s,ge)},g=t.vm_hands_origin==="person"?"person":"model";if(!e.executeOp){await f("failed",{error_code:"vm_hands_op_unsupported"});return}if(t.vm_hands_attest==="accepted"&&n.attest==="pending"&&!(Z&&n.attest==="pending")){n.attest="accepted";for(let y of n.attestWaiters.splice(0))y(!0)}if(n.attest!=="accepted"){let y=Date.parse(String(t.lease_until??""))-Date.now()-5000,x=n.attest==="refused"?0:Math.max(0,Math.min(ae,Number.isFinite(y)?y:ae));if(!(x>0&&await new Promise((re)=>{let Je=setTimeout(()=>re(!1),x);n.attestWaiters.push((Ye)=>{clearTimeout(Je),re(Ye)})}))){await f("failed",{error_code:"vm_hands_unattested"});return}}let S=e.agent.bindIdForRun(o.run_id);if(g==="model"&&S===null){await f("failed",{error_code:"vm_hands_not_bound"});return}let P=a==="pty.start"&&g==="person"&&!t.authority,T=P?Pn(t):null;if(P&&((y)=>y===null?e.agent.liveBindIds.length>0||n.bindsStarting.size>0:e.agent.liveSessionIds.includes(y)||n.bindsStarting.has(y))(T)){await f("failed",{error_code:"vm_hands_bound"});return}if(cn.has(a)&&!P&&e.agent.liveBindIds.length===0){await f("failed",{error_code:"vm_hands_not_bound"});return}let R=new AbortController,F=()=>R.abort();e.signal.addEventListener("abort",F,{once:!0});let te,U=new Promise((y)=>{te=y}),N={abort:R,settled:U},C=P?{...N,session:T}:null;if(C)n.personTerminals.add(C);if(g==="model"&&S&&a!=="preview.serve.v1"){let y=n.modelOps.get(S)??new Set;y.add(N),n.modelOps.set(S,y),await e.agent.environmentInstalled(S,_n,R.signal)}let b=-1,B=!1,j=!1,ie=u?void 0:setInterval(()=>{if(j)return;j=!0,ge(`/operations/${d}/heartbeat`,{...c,control_ack_seq:b,wait_ms:0}).then((y)=>{if(y.status>=300){R.abort();return}let x=y.json?.controls??[];for(let A of x)if(b=Math.max(b,A.seq),A.kind==="operation.cancel"||A.kind==="cancel")R.abort()},()=>R.abort()).finally(()=>{j=!1})},dn);if(u)(async()=>{while(!B&&!R.signal.aborted){let y;try{y=await ge(`/operations/${d}/heartbeat`,{...c,control_ack_seq:b,wait_ms:we})}catch{R.abort();return}if(B)return;if(y.status>=300){R.abort();return}let x=(y.json?.controls??[]).slice().sort((A,re)=>A.seq-re.seq);for(let A of x){if(A.seq<=b)continue;if(A.kind==="operation.cancel"||A.kind==="cancel")R.abort();else await e.controlOp?.({claim:t,control:A}).catch(()=>!1);b=A.seq}}})();try{let y=await e.executeOp({kind:g,claim:t,...g==="model"&&S?{bindId:S}:{},signal:R.signal,emit:async(A)=>{await p(A.kind,A.data??{})}}),x=await f(y.status,{...y.result?{result:y.result}:{},...y.error_code?{error_code:Be(y.error_code,"vm_hands_op_failed")}:{}});e.opCompleted?.({claim:t,status:y.status,acknowledged:x.status<300}),r("vm_hands.op",{capability:a,kind:g,status:y.status,code:y.error_code??null,...x.status>=300?{complete_status:x.status,complete_error:String(x.json?.error??"").slice(0,64)}:{}})}finally{if(B=!0,clearInterval(ie),e.signal.removeEventListener("abort",F),S)n.modelOps.get(S)?.delete(N);if(C)n.personTerminals.delete(C);te()}}async function Ve(t,o){let s=t.claim.attempt_id;if(n.turns.get(s)===t)n.turns.delete(s);e.onTurn?.(s,null),de(t);let a=await L(n,e.agent,s).catch((u)=>ee(u,t,o));if(!a)return;n.receipts.push({turn:t,failure:o,unbound:a}),await ne()}function ee(t,o,s){let a=je(t);return r("vm_hands.unbind_unverified",{operation_id:o.claim.operation_id,code:a,attempt:0}),O(o).emit(ai,{code:a}).catch(()=>{return}),Sn(n,e.agent,{turn:o,failure:s},e.signal,r),null}function ne(){return me=me.then(Ee,Ee),me}async function Ee(){while(n.receipts.length){let{turn:t,failure:o,unbound:s}=n.receipts[0],{complete:a,emit:u}=O(t);try{if(await u("hands.stopped",{...t.readyData,reason_code:o?"failed":"cancelled",killed_verified:s.killed_verified,shredded:s.shredded,...s.srt_fallbacks?{vm_hands_srt_fallbacks:s.srt_fallbacks}:{}}),o)await a("failed",{error_code:o});else await a("cancelled",{error_code:"driver_stopped"})}catch(f){if(f instanceof D)return}n.receipts.shift()}}async function Le(t,o){let{fence:s,op:a}=O(t),u=o.snapshot_id;if(o.version!==1||typeof u!=="string"||Object.keys(o).length!==2)throw new l("vm_hands_env_invalid","invalid environment delivery");let f=await q(`/operations/${a}/environment`,{...s,snapshot_id:u}),p=f.json?.environment_sealed;if(f.status!==200||!p||f.json?.payload!==void 0)throw new l("vm_hands_env_invalid","environment not delivered sealed");let c=await e.agent.deliverEnvironment({attemptId:t.claim.attempt_id,snapshotId:u,deviceId:n.deviceId??"",sealed:p});if((await q(`/operations/${a}/environment-ack`,{...s,...c})).status>=300)throw new l("vm_hands_env_ack_refused","environment ack refused")}}import{readFileSync as xn}from"fs";var An=performance.now();delete process.env.BUN_BE_BUN;var z=(e,n={})=>console.log(JSON.stringify({stage:e,ms:Math.round(performance.now()),...n}));async function On(){if(process.argv.includes("--vm-hands-op-runner")){let{runVmHandsOpRunner:m}=await import("./vm-hands-op-runner-8zjcz4w7.js");await m();return}z("parsed",{t0:Math.round(An)});let e="";try{e=xn(3,"utf8")}catch{}z("fd3_read",{bytes:e.length});let n=null;if(e.trim())try{n=JSON.parse(e)}catch{n=null}if(!n||typeof n!=="object"||Array.isArray(n))z(e.trim()?"identity_invalid":"identity_free"),await new Promise(()=>{setInterval(()=>{return},1073741824)});let{parseVmHandsInit:i,runVmHands:r}=await import("./vm-hands-runtime-p26hr2sr.js"),h=i(n);if(!h)z("identity_invalid"),await new Promise(()=>{setInterval(()=>{return},1073741824)});try{await r(h,z)}catch(m){let _=m&&typeof m==="object"&&"code"in m&&typeof m.code==="string"?m.code:"error";throw z("failed",{code:_}),m}process.exit(0)}On();export{Hi,pn,zi};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import"./vm-hands-entry-lite-vwxg4fhe.js";import"./vm-hands-entry-lite-39qv4sqt.js";import"./vm-hands-entry-lite-1ek3r3w9.js";import"./vm-hands-entry-lite-s85p7tqp.js";import{st,so,xr,Nt}from"./vm-hands-entry-lite-
|
|
2
|
+
import"./vm-hands-entry-lite-vwxg4fhe.js";import"./vm-hands-entry-lite-39qv4sqt.js";import"./vm-hands-entry-lite-1ek3r3w9.js";import"./vm-hands-entry-lite-s85p7tqp.js";import{st,so,xr,Nt}from"./vm-hands-entry-lite-3r7d9pk1.js";import"./vm-hands-entry-lite-wx1fmrbs.js";import"./vm-hands-entry-lite-1zd088yv.js";import"./vm-hands-entry-lite-64b6nx6h.js";import"./vm-hands-entry-lite-024t90qh.js";import"./vm-hands-entry-lite-fcvf8md1.js";import"./vm-hands-entry-lite-dcrz19xf.js";import"./vm-hands-entry-lite-wp0d65yx.js";import"./vm-hands-entry-lite-3p7zk3yt.js";import"./vm-hands-entry-lite-td73npv3.js";import{ur,dr,Pt,Tt}from"./vm-hands-entry-lite-c8r6jyj2.js";import"./vm-hands-entry-lite-psjcmgj8.js";import"./vm-hands-entry-lite-ymqb2927.js";import"./vm-hands-entry-lite-0sh835na.js";import"./vm-hands-entry-lite-qz74j563.js";import{spawn as Ae}from"child_process";import{chmodSync as Me,chownSync as Le,existsSync as G,lstatSync as q,mkdirSync as V,mkdtempSync as Te,readdirSync as Z,readFileSync as k,realpathSync as We,rmdirSync as de,rmSync as He,writeFileSync as B}from"fs";import{basename as ze,dirname as Ue,join as d}from"path";import{readFileSync as ie,readlinkSync as ae}from"fs";import{relative as Ie}from"path";var ce=16;function ue(e){return e.replace(/\\([0-7]{3})/g,(r,t)=>String.fromCharCode(Number.parseInt(t,8)))}function Ne(e){let r=[];for(let t of e.split(`
|
|
3
3
|
`)){let n=t.split(" ");if(n.length<10||!/^\d+:\d+$/.test(n[2]))continue;r.push({device:n[2],root:ue(n[3]),mountPoint:ue(n[4])})}return r}function De(e,r,t){let n=e.replace(/\/+$/,"")||"/",c=(m)=>n==="/"||m===n||m.startsWith(`${n}/`),o=(m)=>new Map(Ne(m).filter((_)=>c(_.mountPoint)).map((_)=>[`${_.mountPoint}\x00${_.device}\x00${_.root}`,_.mountPoint])),u=o(r),p=o(t),b=(m)=>Ie(n,m)||".",P=[...u].filter(([m])=>!p.has(m)).map(([,m])=>b(m)),x=[...p].filter(([m])=>!u.has(m)).map(([,m])=>b(m));return{missing:P,extra:x,referenceCount:u.size,ownCount:p.size}}function le(e,r,t,n="/proc"){let c,o,u=null;try{c=ie(`${n}/1/mountinfo`,"utf8"),o=ie(`${n}/self/mountinfo`,"utf8")}catch(_){let O=_&&typeof _==="object"&&"code"in _&&typeof _.code==="string"?_.code:"unreadable";r("vm_hands.mount_check_unavailable",{code:O});return}try{u=ae(`${n}/1/ns/mnt`)===ae(`${n}/self/ns/mnt`)}catch{}let{missing:p,extra:b,referenceCount:P,ownCount:x}=De(e,c,o),m={reference_count:P,own_count:x,missing_count:p.length,extra_count:b.length,same_namespace:u};if(b.length)r("vm_hands.mount_extra",{...m,extra:b.slice(0,ce)});if(p.length)throw r("vm_hands.mount_mismatch",{...m,missing:p.slice(0,ce)}),t(`${p.length} mount(s) under the Session root are missing from vm-hands' namespace`)}var we="/sys/fs/cgroup/reason-payload",M="vm-hands",Be="/run/ara-srt/fallbacks.jsonl",se="/reason-person",Fe="/reason-workload",Ke="surface",ee=5000,je=1e4,pe="__VM_HANDS_PROOF_DIR__",Ge="__VM_HANDS_PROBE_NONCE__";class w extends Error{code;constructor(e,r){super(r);this.code=e}}function Ee(e,r){if(!/^[0-9a-f-]{36}$/i.test(r))throw new w("vm_hands_bind_invalid","bad bind id");return d(e,M,`b-${r.toLowerCase()}`)}var Ve=5000,ve=(e)=>`'${e.replaceAll("'","'\\''")}'`;function Je(e,r){if(!r||!/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(r))return e;let t=d(Ue(e),r.toLowerCase());return ze(e).toLowerCase()===r.toLowerCase()?e:t}function gn(e){let r=e.cgroup??we,t=e.init.layout.payload_uid,n=e.init.workload_ended!==!0,c=(s)=>z(s,se)||n&&z(s,Fe),o=e.log??(()=>{}),u=(s)=>Je(e.init.layout.session_root,s),p=new Map,b=new Map,P=0,x=()=>{try{let s=k("/run/ara-srt/starts.jsonl","utf8"),i=s.slice(P>s.length?0:P).split(`
|
|
4
4
|
`).filter(Boolean);P=s.length;let l=i.map((f)=>{try{return Number(JSON.parse(f).elapsed_ms)||0}catch{return 0}});if(l.length)o("vm_hands.srt_server_starts",{count:l.length,elapsed_ms:l.slice(0,8)})}catch{}},m=null,_=!1,O=e.srtCgroup??"/sys/fs/cgroup/reason-srt",I=()=>{m??=fe()},R=0,F=()=>{try{let s=k(Be,"utf8"),i=s.slice(R>s.length?0:R);R=s.length;let l=i.split(`
|
|
5
5
|
`).filter(Boolean).slice(0,1000);if(!l.length)return null;let f={},g=0;for(let S of l)try{let h=JSON.parse(S),y=typeof h.code==="string"&&/^[a-z_]{1,40}$/.test(h.code)?h.code:"other";if(f[y]=(f[y]??0)+1,typeof h.elapsed_ms==="number")g=Math.max(g,h.elapsed_ms)}catch{f.unparsed=(f.unparsed??0)+1}return o("vm_hands.srt_fallbacks",{count:l.length,codes:f,max_elapsed_ms:g}),{count:l.length,codes:f,max_elapsed_ms:g}}catch{return null}},U=(s,i,l)=>Re(s,i,l),K=(s)=>(i,l,f)=>Ae("/bin/sh",["-c",`echo $$ > ${ve(d(s,"cgroup.procs"))} || exit 125; exec "$@"`,"vm-hands-join",i,...l],f),Re=K(d(r,M)),j=d(r,M,"probe"),T=(s)=>Ee(r,s),Ce=(s)=>{let i=T(s);try{V(i,{mode:493})}catch(l){if(!(l&&typeof l==="object"&&("code"in l)&&l.code==="EEXIST"))throw new w("vm_hands_bind_failed","bind cgroup")}return i},Oe=(s)=>{try{de(T(s))}catch{}},W=e.prespawn?so({spawnProcess:U,...e.relayDependencies?.sourceEntrypoint?{sourceEntrypoint:e.relayDependencies.sourceEntrypoint}:{},log:(s,i)=>o(s,i??{})}):null;W?.arm();let X=W?setInterval(()=>{W.arm()},Ve):null;X?.unref?.();async function Y(s){let i=p.get(s);if(p.delete(s),!i)return;i.abort.abort(),await i.done}return{bindCgroup:T,async startExecutor(s){if(I(),b.set(s.bindId,fe()),_=!0,!s.claim)throw new w("vm_hands_bind_invalid","an executor needs the claim it serves");await Y(s.bindId);let{claim:i,bindId:l}=s,f=Ce(l),g=i.owner;if(!g||typeof g.device_id!=="string"||typeof i.root_id!=="string")throw new w("vm_hands_bind_invalid","claim without its owner Device or root");let S=new AbortController,h,y,N=new Promise((a,v)=>{h=a,y=v}),D,C=new Promise((a)=>{D=a}),H=Nt({headless:!0,hostExecution:!0,runtimeDirectory:e.runtimeDirectory,managedPty:{version:1,startupVerified:!0},deviceIdentity:{deviceId:g.device_id,rootId:i.root_id,apiOrigin:e.apiOrigin},claimOwner:i.owner,root:e.root,runId:i.run_id,operationId:i.operation_id,attemptId:i.attempt_id,payload:Object.fromEntries(Object.entries(i.payload).filter(([a])=>!a.startsWith("vm_hands_"))),signal:S.signal,...s.workspaceGrant?{workspaceGrant:s.workspaceGrant}:{},emitEvent:async(a,v)=>{if(a==="hands.ready"){h(v);return}if(a==="hands.started"||a==="hands.stopped"||a==="hands.failed")return;await e.forward(l,a,v)}},{...e.relayDependencies,spawnWorker:(a)=>K(f)(a.command,a.args,a.options),...W?{takePrespawnedWorker:(a)=>{let v=W.take(a);if(!v?.pid)return v;try{return B(d(f,"cgroup.procs"),String(v.pid)),v}catch{try{v.kill("SIGKILL")}catch{}return null}},adoptSpawnedWorker:W.adopt}:{}}).then(()=>{D("executor_stopped")},(a)=>{let v=a&&typeof a==="object"&&"code"in a?String(a.code):"executor_failed";y(new w(v,a instanceof Error?a.message:String(a))),D(v)}).finally(()=>y(new w("vm_hands_executor_exited","executor ended before it was ready")));p.set(l,{abort:S,done:H,exited:C,operationId:i.operation_id,runId:i.run_id,expiresAtMs:Date.parse(String(i.payload.expires_at??""))||0});let A=await N,E=A.executor_launch_id;if(typeof E!=="string")throw new w("vm_hands_bind_failed","executor ready without a launch id");return{launchId:E,readyData:A,applied:{hands_confinement:typeof i.payload.hands_confinement==="string"?i.payload.hands_confinement:null,browser_egress:i.payload.browser_egress??null}}},takeSrtFallbacks:F,executorExited(s){return p.get(s)?.exited??new Promise(()=>{})},freezeBind(s){let i=T(s);if(G(d(i,"cgroup.freeze")))B(d(i,"cgroup.freeze"),"1")},async killAndVerifyPayload(s){let i=new Set(s?.keep??[]);if(await $e(s?.bindId??null,i,s?.own===!0),i.size)return;if((_||e.srtWarmLate?.()===!0)&&G(d(O,"cgroup.events")))x(),await te(O,Date.now()+ee,"srt"),e.onSrtReset?.();_=!1},async killProbe(){let s=Date.now()+ee;if(G(d(j,"cgroup.events"))){await te(j,s,"probe");try{de(j)}catch{}}let i=oe(process.pid);if(i===null)throw new w("vm_hands_kill_unverified","agent start time unreadable");await Ze(r,i,s);let l=(g)=>{let S=oe(g);return S!==null&&S<=i},f=he(t).filter((g)=>l(g)&&!c(g));if(f.length)throw o("vm_hands.kill_survivors",{pids:f.slice(0,16),at:"attest",...me(f)}),new w("vm_hands_kill_unverified",`${f.length} payload-uid process(es) from before this agent`);if(m!==null){let g=[r,d(r,M)].map((y)=>y.replace(/^\/sys\/fs\/cgroup/,"")),S=O.replace(/^\/sys\/fs\/cgroup/,""),h=ge(m).filter((y)=>y!==process.pid&&!c(y)&&!z(y,"/reason-vm-hands")&&!z(y,S)&&!g.some((N)=>ne(y,N)));if(h.length&&_)throw o("vm_hands.kill_strays",{strays:re(h),at:"attest"}),new w("vm_hands_kill_unverified",`${h.length} process(es) the run started survived it`);if(h.length)o("vm_hands.attest_concurrent",{processes:re(h),count:h.length});m=null}},async runProbe({nonce:s,script:i}){if(I(),!i.includes(pe))throw new w("vm_hands_probe_failed","probe names no proof directory");let l=e.proofParent??"/tmp/reason-vm-hands-proof";V(l,{mode:457,recursive:!0});let f=q(l);if(f.isSymbolicLink()||!f.isDirectory()||f.uid!==(process.getuid?.()??-1)||(f.mode&4095)!==457)throw new w("vm_hands_probe_failed","proof parent is not root's 0711 directory");let g=Te(d(l,"p-")),S=!1;try{if(!/^[A-Za-z0-9/._-]+$/.test(g)||!/^[A-Za-z0-9_-]{1,128}$/.test(s))throw new w("vm_hands_probe_failed","proof directory path or nonce");Le(g,t,t),Me(g,448);let h=q(g).ino;try{V(j,{mode:493})}catch(C){if(!(C&&typeof C==="object"&&("code"in C)&&C.code==="EEXIST"))throw new w("vm_hands_probe_failed","probe cgroup")}let y=K(j)("/bin/bash",["-c",i.replaceAll(pe,g).replaceAll(Ge,s)],{cwd:"/",env:{PATH:"/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"},stdio:["ignore","pipe","ignore"]}),N="";y.stdout?.on("data",(C)=>{if(N.length<16384)N+=C.toString("utf8").slice(0,16384-N.length)});let D=await new Promise((C)=>{let H=setTimeout(()=>{S=!0,y.kill("SIGKILL"),C(124)},je);y.once("error",()=>{clearTimeout(H),C(127)}),y.once("close",(A)=>{clearTimeout(H),C(A??1)})});return o("vm_hands.probe",{nonce_len:s.length,exit_code:D}),{exitCode:D,markers:N,proofDirInode:h}}finally{if(!S)He(g,{recursive:!0,force:!0})}},restatLayout(s){let i=u(s),l=i===e.init.layout.session_root?e.init.layout.alias:d(i,"repo"),f="invalid";try{xr(i),f="0:0:755"}catch{}let g=!1,S=-1;try{let h=q(l);S=h.uid,g=f==="0:0:755"&&l===d(i,"repo")&&!h.isSymbolicLink()&&h.isDirectory()&&We(l)===l&&h.uid===t}catch{}return{root_mode:f,alias_ok:g,owner_uid:S}},verifyMounts(s){let i=u(s);try{le(i,o,(l)=>new w("vm_hands_mount_mismatch",l))}catch(l){if(i!==e.init.layout.session_root&&l instanceof w&&l.code==="vm_hands_mount_mismatch"){o("vm_hands.member_mount_mismatch_served",{});return}throw l}},installEnvironment(s,i){let l=p.get(s);if(!l)throw new w("environment_unavailable","no executor owns an environment");return st({root:e.root,operationId:l.operationId,payload:i}).installed_revision},async stop(){if(X)clearInterval(X);W?.close(),await Promise.all([...p.keys()].map((s)=>Y(s)))}};function xe(){try{return Z(d(r,M),{withFileTypes:!0}).filter((s)=>s.isDirectory()&&/^b-[0-9a-f-]{36}$/.test(s.name)).map((s)=>s.name)}catch{return[]}}async function $e(s,i,l=!1){let f=new Set([...i].map((S)=>S.toLowerCase())),g=qe();try{await nn();let S=Date.now()+ee,h=new Set(xe().filter((a)=>!f.has(a.slice(2))).map((a)=>a.slice(2)));if(s)h.add(s.toLowerCase());let y=null;for(let a of h){let v=Y(a).catch(()=>{return}),Q=b.get(a);if(Q!==void 0)y=y===null?Q:Math.min(y,Q);if(G(d(T(a),"cgroup.events")))await te(T(a),S,"bind");await v}let N=[...f].map((a)=>T(a).replace(/^\/sys\/fs\/cgroup/,"")),D=["/",...[r,d(r,M)].map((a)=>a.replace(/^\/sys\/fs\/cgroup/,""))],C=O.replace(/^\/sys\/fs\/cgroup/,""),H=(a)=>c(a)||N.some((v)=>z(a,v))||D.some((v)=>ne(a,v)),A=l?[]:he(t).filter((a)=>!H(a));if(A.length)throw o("vm_hands.kill_survivors",{pids:A.slice(0,16),beside:f.size,...me(A)}),new w("vm_hands_kill_unverified",`${A.length} payload-uid process(es) outside a live bind`);let E=(a)=>!H(a)&&!z(a,"/reason-vm-hands")&&!z(a,C)&&!D.some((v)=>ne(a,v));if(y!==null){let a=ge(y).filter((v)=>v!==process.pid&&E(v));if(a.length)throw o("vm_hands.kill_strays",{strays:re(a),beside:f.size}),new w("vm_hands_kill_unverified",`${a.length} process(es) the run started survived it`)}for(let a of h)b.delete(a),Oe(a)}finally{g()}}}function oe(e,r="/proc"){try{let t=k(d(r,String(e),"stat"),"utf8"),n=Number(t.slice(t.lastIndexOf(")")+2).split(" ")[19]);return Number.isFinite(n)?n:null}catch{return null}}function be(e,r="/proc"){try{let t=k(d(r,String(e),"stat"),"utf8"),n=Number(t.slice(t.lastIndexOf(")")+2).split(" ")[1]);return Number.isFinite(n)?n:null}catch{return null}}async function Ze(e,r,t){try{B(d(e,"cgroup.freeze"),"1")}catch(n){throw new w("vm_hands_kill_unverified",`payload cgroup.freeze: ${n instanceof Error?n.message:String(n)}`)}try{for(;;){let n=ke(e).filter((o)=>Se(o,e)),c=new Set(n.filter((o)=>{let u=oe(o);return u!==null&&u<=r}));for(let o=!0;o;){o=!1;for(let u of n){if(c.has(u))continue;let p=be(u);if(p!==null&&c.has(p))c.add(u),o=!0}}if(c.size===0)return;if(Date.now()>t)throw new w("vm_hands_kill_unverified",`${c.size} previous-boot process(es) survived`);for(let o of c)try{process.kill(o,"SIGKILL")}catch{}await new Promise((o)=>setTimeout(o,10))}}finally{try{B(d(e,"cgroup.freeze"),"0")}catch{}}}function ne(e,r,t="/proc"){try{return k(d(t,String(e),"cgroup"),"utf8").split(`
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{ur,dr,Pt,Tt,Rt,_s}from"./vm-hands-entry-lite-
|
|
2
|
+
import{ur,dr,Pt,Tt,Rt,_s}from"./vm-hands-entry-lite-c8r6jyj2.js";export{ur as VM_HANDS_OP_RUNNER_PERSON_ARG,dr as VM_HANDS_OP_RUNNER_SURFACE_ARG,Tt as VM_HANDS_SURFACE_DIRECTORY_ARG,Rt as VM_HANDS_SURFACE_OPS,Pt as VM_HANDS_SURFACE_UID_ARG,_s as runVmHandsOpRunner};
|