@reason-machines/cli-linux-arm64-musl 0.2.343 → 0.2.345

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/bin/ara +1 -1
  2. package/bin/vm-hands/api-credentials-d34gw13p.js +2 -0
  3. package/bin/vm-hands/api-t5zxz49k.js +2 -0
  4. package/bin/vm-hands/{ask-relay-d96qx4ez.js → ask-relay-bczg32b2.js} +2 -2
  5. package/bin/vm-hands/connect-cli-789rv77k.js +2 -0
  6. package/bin/vm-hands/{custom-endpoint-device-whc0qjdv.js → custom-endpoint-device-syw4d5k4.js} +1 -1
  7. package/bin/vm-hands/desktop-account-pm3zxjjt.js +2 -0
  8. package/bin/vm-hands/{device-workspace-1abchg0z.js → device-workspace-s49yhsk7.js} +1 -1
  9. package/bin/vm-hands/{hands-worker-source-9mq68whc.js → hands-worker-source-0ca76sbd.js} +1 -1
  10. package/bin/vm-hands/{index-5a4yhzf8.js → index-t1h1wd8g.js} +1 -1
  11. package/bin/vm-hands/local-automation-ms5cgtgc.js +2 -0
  12. package/bin/vm-hands/local-capabilities-jfmzy2qt.js +2 -0
  13. package/bin/vm-hands/local-desktop-users-zxw8xxw9.js +2 -0
  14. package/bin/vm-hands/local-display-mac-jdgx19jw.js +2 -0
  15. package/bin/vm-hands/local-display-session-v8g6x39d.js +2 -0
  16. package/bin/vm-hands/local-pty-session-frp7k8fz.js +2 -0
  17. package/bin/vm-hands/{network-contract-7y9z06qs.js → network-contract-8d4bpy3e.js} +1 -1
  18. package/bin/vm-hands/package-vj1s3sye.js +2 -0
  19. package/bin/vm-hands/permissions-9vwmb8cz.js +2 -0
  20. package/bin/vm-hands/{reason-hands-protocol-mm6kwqk8.js → reason-hands-protocol-k12eme4q.js} +1 -1
  21. package/bin/vm-hands/{status-2mbhthe2.js → status-jfa65qn3.js} +2 -2
  22. package/bin/vm-hands/version-mzcyw4fg.js +2 -0
  23. package/bin/vm-hands/{vm-hands-entry-lite-0zr461f9.js → vm-hands-entry-lite-0jar357h.js} +2 -2
  24. package/bin/vm-hands/{vm-hands-entry-lite-pn6vyghh.js → vm-hands-entry-lite-0wyjnvjz.js} +1 -1
  25. package/bin/vm-hands/{vm-hands-entry-lite-va7g1e1f.js → vm-hands-entry-lite-1jhry648.js} +1 -1
  26. package/bin/vm-hands/{vm-hands-entry-lite-ckehp0dy.js → vm-hands-entry-lite-1w8tvrpq.js} +3 -3
  27. package/bin/vm-hands/{vm-hands-entry-lite-70d6f5r9.js → vm-hands-entry-lite-1xjtcxpn.js} +1 -1
  28. package/bin/vm-hands/{vm-hands-entry-lite-3s5fdvat.js → vm-hands-entry-lite-289bc9v7.js} +1 -1
  29. package/bin/vm-hands/{vm-hands-entry-lite-3c4qwk4d.js → vm-hands-entry-lite-2e50z7hj.js} +1 -1
  30. package/bin/vm-hands/{vm-hands-entry-lite-6z2g0td2.js → vm-hands-entry-lite-2xh7sjs0.js} +2 -2
  31. package/bin/vm-hands/vm-hands-entry-lite-36xzwsxn.js +42 -0
  32. package/bin/vm-hands/{vm-hands-entry-lite-p7x3vnz5.js → vm-hands-entry-lite-7ba3nhgv.js} +1 -1
  33. package/bin/vm-hands/{vm-hands-entry-lite-jjq3xq9z.js → vm-hands-entry-lite-8dvf3de9.js} +2 -2
  34. package/bin/vm-hands/{vm-hands-entry-lite-p9eyqdq7.js → vm-hands-entry-lite-9dx3at21.js} +2 -2
  35. package/bin/vm-hands/{vm-hands-entry-lite-8zencenv.js → vm-hands-entry-lite-ac6zyrj1.js} +1 -1
  36. package/bin/vm-hands/{vm-hands-entry-lite-q1ekx7k0.js → vm-hands-entry-lite-b38m8a8m.js} +2 -2
  37. package/bin/vm-hands/{vm-hands-entry-lite-60t59y3n.js → vm-hands-entry-lite-b8y45rcs.js} +1 -1
  38. package/bin/vm-hands/{vm-hands-entry-lite-ypcqvygf.js → vm-hands-entry-lite-gt5pkv4h.js} +1 -1
  39. package/bin/vm-hands/{vm-hands-entry-lite-dqqjy7kj.js → vm-hands-entry-lite-hywf6580.js} +2 -2
  40. package/bin/vm-hands/{vm-hands-entry-lite-xv868vfm.js → vm-hands-entry-lite-jy102628.js} +2 -2
  41. package/bin/vm-hands/{vm-hands-entry-lite-3gf1yegq.js → vm-hands-entry-lite-k2cvr710.js} +1 -1
  42. package/bin/vm-hands/{vm-hands-entry-lite-bfh3cnh2.js → vm-hands-entry-lite-k2e3q5qj.js} +1 -1
  43. package/bin/vm-hands/{vm-hands-entry-lite-2mhzfg6b.js → vm-hands-entry-lite-knfh7w3j.js} +2 -2
  44. package/bin/vm-hands/{vm-hands-entry-lite-vn0r1e8c.js → vm-hands-entry-lite-kt418g2w.js} +2 -2
  45. package/bin/vm-hands/{vm-hands-entry-lite-tt4zgt64.js → vm-hands-entry-lite-m16qf0yy.js} +1 -1
  46. package/bin/vm-hands/{vm-hands-entry-lite-45cnnd8e.js → vm-hands-entry-lite-mhsv58hw.js} +1 -1
  47. package/bin/vm-hands/{vm-hands-entry-lite-2c8m8m7v.js → vm-hands-entry-lite-pa111vpq.js} +2 -2
  48. package/bin/vm-hands/{vm-hands-entry-lite-5qe562gn.js → vm-hands-entry-lite-pnkfgnqz.js} +1 -1
  49. package/bin/vm-hands/{vm-hands-entry-lite-21sg3fyz.js → vm-hands-entry-lite-tfpebnar.js} +1 -1
  50. package/bin/vm-hands/{vm-hands-entry-lite-qezqtm4g.js → vm-hands-entry-lite-x6jqyxkx.js} +2 -2
  51. package/bin/vm-hands/vm-hands-entry-lite-y16b538h.js +529 -0
  52. package/bin/vm-hands/{vm-hands-entry-lite-xazz63m6.js → vm-hands-entry-lite-y4mtveeb.js} +2 -2
  53. package/bin/vm-hands/{vm-hands-entry-lite-bs1mbk81.js → vm-hands-entry-lite-yeahy7rk.js} +2 -2
  54. package/bin/vm-hands/vm-hands-entry-lite.js +1 -1
  55. package/bin/vm-hands/{vm-hands-executor-wqn9mnsj.js → vm-hands-executor-tyxvq0j1.js} +1 -1
  56. package/bin/vm-hands/vm-hands-op-runner-k79jadt5.js +2 -0
  57. package/bin/vm-hands/{vm-hands-runtime-bwvpt55d.js → vm-hands-runtime-dq1t8vee.js} +3 -3
  58. package/bin/vm-hands/worker-sandbox-1kpm6af4.js +2 -0
  59. package/package.json +1 -1
  60. package/bin/vm-hands/api-credentials-7wdzy9by.js +0 -2
  61. package/bin/vm-hands/api-jq1fd10n.js +0 -2
  62. package/bin/vm-hands/connect-cli-cp0zh5f8.js +0 -2
  63. package/bin/vm-hands/desktop-account-j9pxgjn0.js +0 -2
  64. package/bin/vm-hands/local-automation-v0r1k6v9.js +0 -2
  65. package/bin/vm-hands/local-capabilities-9y6jj12c.js +0 -2
  66. package/bin/vm-hands/local-desktop-users-gxkmx7rv.js +0 -2
  67. package/bin/vm-hands/local-display-mac-6ktqrbas.js +0 -2
  68. package/bin/vm-hands/local-display-session-ab79qr64.js +0 -2
  69. package/bin/vm-hands/local-pty-session-3592ene9.js +0 -2
  70. package/bin/vm-hands/package-ffnz28tt.js +0 -2
  71. package/bin/vm-hands/permissions-ddm9as7j.js +0 -2
  72. package/bin/vm-hands/version-xdgmrx9d.js +0 -2
  73. package/bin/vm-hands/vm-hands-entry-lite-1sq7jgg0.js +0 -529
  74. package/bin/vm-hands/vm-hands-entry-lite-bbc5r4y1.js +0 -42
  75. package/bin/vm-hands/vm-hands-op-runner-8nw0g7v3.js +0 -2
  76. package/bin/vm-hands/worker-sandbox-4mraqzsg.js +0 -2
@@ -0,0 +1,42 @@
1
+ // @bun
2
+ import{mi as W}from"./vm-hands-entry-lite-2xh7sjs0.js";var T=W.string().max(201).regex(/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/).refine((Q)=>Q.split("/").every((Z)=>Z!=="."&&Z!=="..")),G=W.string().min(1).max(255).regex(/^[A-Za-z0-9_][A-Za-z0-9_./-]*$/).refine((Q)=>!Q.includes("..")&&!Q.includes("//")&&!Q.endsWith("/")&&!Q.endsWith(".lock")),M=W.string().regex(/^[a-f0-9]{40}$/),q=W.number().int().positive(),C=W.string().min(1).max(256),A=W.string().max(60000),B={version:W.literal(1),repoFullName:T},J=W.array(W.string().max(1024).regex(/^(?:Co-authored-by: [^<>\r\n\x00]+ <[^<>\s]+@[^<>\s]+>|Reason-Contributor-ID: rc_[a-f0-9]{32})$/)).max(1000),c=W.strictObject({expectedTrailers:J,missingFromHead:J}),y=W.discriminatedUnion("action",[W.strictObject({action:W.literal("edit"),title:C.optional(),body:A.optional(),base:G.optional()}),W.strictObject({action:W.enum(["ready","draft","close"])}),W.strictObject({action:W.literal("metadata"),field:W.enum(["reviewer","assignee","label"]),change:W.enum(["add","remove"]),value:W.string().min(1).max(100).refine((Q)=>!/[\r\n\0]/.test(Q))})]),d=W.discriminatedUnion("kind",[W.strictObject({...B,kind:W.literal("read"),path:W.string().min(1).max(2048),accept:W.enum(["application/vnd.github+json","application/vnd.github.full+json","application/vnd.github.v3.diff"]).optional()}),W.strictObject({...B,kind:W.literal("pr_review_context"),number:q,after:W.string().min(1).max(1024).optional()}),W.strictObject({...B,kind:W.literal("prepare"),branch:G,baseSha:M,defaultBranch:G,diagnosticsVersion:W.literal(1).optional()}),W.strictObject({...B,kind:W.literal("publish"),branch:G,defaultBranch:G,baseSha:M,remoteHeadSha:M.nullable(),contributorTrailers:J.optional()}),W.strictObject({...B,kind:W.literal("pr_create"),head:G,base:G,title:C,body:A,draft:W.boolean()}),W.strictObject({...B,kind:W.literal("pr_mutation"),number:q,mutation:y}),W.strictObject({...B,kind:W.literal("pr_merge"),number:q,expectedHeadSha:M,expectedBaseRef:G,method:W.enum(["merge","squash","rebase"]),commitBody:W.string().max(65536).optional()})]),O=["local_device_gh_prepare_setup","local_device_gh_prepare_metadata","local_device_gh_prepare_private_init","local_device_gh_prepare_fetch","local_device_gh_prepare_base_mismatch","local_device_gh_prepare_checkout_validation","local_device_gh_prepare_checkout_init","local_device_gh_prepare_materialization"];function h(Q){return O.some((Z)=>Z===Q)}class R extends Error{code;constructor(Q){super(Q);this.code=Q}}function ZQ(Q,Z,$){let z=d.safeParse(Q);return Z==="failed"&&z.success&&z.data.kind==="prepare"&&z.data.diagnosticsVersion===1&&h($)}var x=245760,$Q=W.discriminatedUnion("kind",[W.strictObject({kind:W.literal("pr_review_context"),body:W.string().max(x)}),W.strictObject({kind:W.literal("prepare"),headSha:M}),W.strictObject({kind:W.literal("read"),status:W.number().int().min(200).max(599),headers:W.record(W.string(),W.string().max(8192)).refine((Q)=>Object.keys(Q).every((Z)=>Z==="link"||Z==="content-type")),body:W.string().max(x)}),W.strictObject({kind:W.literal("publish"),headSha:M,scannedObjectCount:W.number().int().min(0).max(5000),attribution:c.optional()}),W.strictObject({kind:W.literal("pr_create"),url:W.string().max(1024).regex(/^https:\/\/github\.com\/[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+\/pull\/[1-9][0-9]*$/)}),W.strictObject({kind:W.literal("pr_mutation"),number:q,applied:W.literal(!0)}),W.strictObject({kind:W.literal("pr_merge"),number:q,merged:W.literal(!0)})]).refine((Q)=>new TextEncoder().encode(JSON.stringify(Q)).byteLength<=x,"local_device_gh_result_too_large"),r=W.strictObject({source:W.enum(["agent","human"]),operationId:W.uuid()}),m=W.strictObject({version:W.literal(1),userId:W.guid(),deviceId:W.guid(),rootId:W.guid(),runId:W.guid(),merge:r.optional(),contributorRefresh:W.guid().optional(),repoFullName:T.nullable(),rootRevision:W.string().regex(/^[1-9][0-9]*$/),readOnly:W.boolean(),generation:W.number().int().positive().nullable(),fenceId:W.guid().nullable()}).refine((Q)=>Q.generation===null===(Q.fenceId===null));function P(Q){return/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(Q)&&Q.split("/").every((Z)=>Z!=="."&&Z!=="..")}function KQ(Q,Z,$={},z="read"){if(P(Q)&&(Z==="/search/issues"||Z.startsWith("/search/issues?")))return p(Q,Z,$);if(!P(Q)||!Z.startsWith(`/repos/${Q}/`)&&Z!==`/repos/${Q}`)throw Error("local_device_gh_repository_mismatch");if(/[\\#\u0000-\u001f]/.test(Z)||/%(?:2e|5c|00)/i.test(Z))throw Error("local_device_gh_path_denied");let V=new URL(Z,"https://api.github.com");if(V.pathname!==Z.split("?")[0]||V.username||V.password)throw Error("local_device_gh_path_denied");let Y;try{Y=decodeURIComponent(V.pathname.slice(`/repos/${Q}`.length))}catch{throw Error("local_device_gh_path_denied")}if(Y.includes("%")||Y.split("/").some((D)=>D==="."||D===".."))throw Error("local_device_gh_path_denied");if(($.method??"GET").toUpperCase()!=="GET"||$.body!=null)throw Error("local_device_gh_mutation_not_admitted");if(![/^$/,/^\/commits$/,/^\/pulls$/,/^\/pulls\/[1-9][0-9]*(?:\/(?:commits|files|reviews|comments))?$/,/^\/issues\/[1-9][0-9]*(?:\/comments)?$/,/^\/issues\/comments\/[1-9][0-9]*\/reactions$/,/^\/commits\/[A-Za-z0-9_./-]+(?:\/(?:check-runs|status))?$/,/^\/check-runs\/[1-9][0-9]*(?:\/annotations)?$/,/^\/branches\/[A-Za-z0-9_./-]+$/,/^\/git\/ref\/heads\/[A-Za-z0-9_./-]+$/,/^\/compare\/[A-Za-z0-9_./-]+\.\.\.[A-Za-z0-9_./-]+$/].some((D)=>D.test(Y)))throw Error("local_device_gh_path_denied");if(V.searchParams.forEach((D,X)=>{if(X==="per_page"&&/^[1-9][0-9]*$/.test(D)&&Number(D)<=100)return;if(X==="page"&&/^[1-9][0-9]*$/.test(D)&&Number(D)<=100)return;if(Y==="/pulls"&&X==="state"&&["open","closed","all"].includes(D))return;if(Y==="/pulls"&&X==="sort"&&D==="updated")return;if(Y==="/pulls"&&X==="direction"&&D==="desc")return;if(Y==="/pulls"&&["head","base"].includes(X)&&/^[A-Za-z0-9_./:-]{1,255}$/.test(D))return;throw Error("local_device_gh_query_denied")}),$.headers)new Headers($.headers).forEach((X,_)=>{if(_!=="accept"||!["application/vnd.github+json","application/vnd.github.full+json","application/vnd.github.v3.diff"].includes(X))throw Error("local_device_gh_header_denied")})}function p(Q,Z,$){if(/[\\#\u0000-\u001f]/.test(Z))throw Error("local_device_gh_path_denied");let z=new URL(Z,"https://api.github.com");if(z.pathname!=="/search/issues"||z.username||z.password)throw Error("local_device_gh_path_denied");if(($.method??"GET").toUpperCase()!=="GET"||$.body!=null)throw Error("local_device_gh_mutation_not_admitted");let V=null;z.searchParams.forEach((H,D)=>{if(D==="q"&&V===null){V=H;return}if(D==="per_page"&&/^[1-9][0-9]*$/.test(H)&&Number(H)<=100)return;if(D==="page"&&/^[1-9][0-9]*$/.test(H)&&Number(H)<=100)return;throw Error("local_device_gh_query_denied")});let Y=`repo:${Q.toLowerCase()} `,N=V?.toLowerCase()??"";if(N.length>512||!(N+" ").startsWith(Y)||/(?:^|\s)(?:repo|org|user):/.test(N.slice(Y.length)))throw Error("local_device_gh_query_denied");if($.headers)new Headers($.headers).forEach((H,D)=>{if(D!=="accept"||H!=="application/vnd.github+json")throw Error("local_device_gh_header_denied")})}var DQ=`query PullRequestReviewContext($owner: String!, $repo: String!, $number: Int!, $after: String) {
3
+ repository(owner: $owner, name: $repo) {
4
+ nameWithOwner
5
+ pullRequest(number: $number) {
6
+ number
7
+ reviewDecision
8
+ headRefOid
9
+ baseRefOid
10
+ baseRef {
11
+ branchProtectionRule {
12
+ requiresApprovingReviews
13
+ requiredApprovingReviewCount
14
+ requiresStatusChecks
15
+ requiredStatusCheckContexts
16
+ requiresConversationResolution
17
+ dismissesStaleReviews
18
+ }
19
+ }
20
+ reviewThreads(first: 100, after: $after) {
21
+ nodes {
22
+ id isResolved isOutdated viewerCanResolve viewerCanUnresolve
23
+ path line originalLine startLine originalStartLine diffSide startDiffSide
24
+ comments(first: 100) {
25
+ nodes {
26
+ id databaseId body createdAt updatedAt url
27
+ author { __typename login }
28
+ replyTo { databaseId }
29
+ }
30
+ pageInfo { hasNextPage }
31
+ }
32
+ }
33
+ pageInfo { hasNextPage endCursor }
34
+ }
35
+ }
36
+ }
37
+ }`;function zQ(Q){return Q.kind==="read"||Q.kind==="pr_review_context"}var b=["inspect_project","fs.read","fs.write","fs.search","fs.watch","fs.upload","fs.export","fs.import","fs.download","exec.run","exec.full","process.run.v1","process.full.v1","pty.start","pty.input","pty.resize","pty.close","git.run","process.list","process.signal","ports.list","tunnel.open","tunnel.close","env.discover","setup.run","mcp.discover","mcp.start","mcp.proxy","browser.snapshot","browser.navigate","browser.act","computer.snapshot","computer.act","computer.use","browser.use","browser.recording.v1","browser.pr-proof.v1","hands.connect","jobs.control","environment.install","github.local.v1","inference.ollama.v1","inference.custom.v1","delegate.devin.copy.v1","delegate.cursor.copy.v1","display.stream.v1","automation.call.v1","preview.serve.v1","workspace.setup.v1","simulator.call.v1","simulator.stream.v1"];var j=2,I="/app/local-runtime",n=262144,HQ="x-reason-relay-host-alias",XQ="v1";function F(Q,Z){return{path:`${I}${Q}`,routerPath:Q,auth:Z}}function g(Q,Z){return{...F(Q,"device_proof"),forOperation($){return F(`/operations/${encodeURIComponent($)}${Z}`,"device_proof")}}}var GQ={register:F("/register","registration_bearer"),enroll:F("/enroll","none"),authChallenge:F("/auth/challenge","none"),identity:F("/identity","device_proof"),heartbeat:F("/heartbeat","device_proof"),rootsSync:F("/roots/sync","device_proof"),disconnect:F("/disconnect","device_proof"),lifecycle:F("/lifecycle","device_proof"),localSubscription:F("/local-subscription","device_proof"),ownerWorkspaces:F("/owner-workspaces","device_proof"),ownerWorkspaceEnrollment:F("/owner-workspaces/enrollment","device_proof"),sessionWorktrees:F("/session-worktrees","device_proof"),operationClaim:F("/operations/claim","device_proof"),operationHeartbeat:g("/operations/:operationId/heartbeat","/heartbeat"),operationEvents:g("/operations/:operationId/events","/events"),operationComplete:g("/operations/:operationId/complete","/complete"),operationEnvironment:g("/operations/:operationId/environment","/environment"),operationEnvironmentAck:g("/operations/:operationId/environment-ack","/environment-ack"),operationCustomEndpointCredential:g("/operations/:operationId/custom-endpoint-credential","/custom-endpoint-credential")},BQ=`${I}/session`,MQ=4096,gQ=5000,o=[/^\/app\/local-runtime\/heartbeat$/,/^\/app\/local-runtime\/operations\/claim$/,/^\/app\/local-runtime\/operations\/[0-9a-fA-F-]{36}\/(?:heartbeat|events|complete|environment|environment-ack)$/];function qQ(Q){return o.some((Z)=>Z.test(Q))}var NQ="vm_hands_v1",mQ=60000,UQ={unauthenticated:4401,unavailable:4404,overloaded:4429,serviceRestart:1012},jQ="hands_control_v1",xQ="environment.deliver",JQ="claim_v1",SQ="environment_at_claim",IQ="rebind_v1",PQ="resident_rebind",TQ="hands.rebind",CQ="snapshot_v1",AQ="cloud_access",bQ="playwright_v1",EQ="headless_browser",kQ="v1",LQ="job_env_large_values",fQ="srt_root_v1",_Q="hands_confinement",cQ="gid_v1",yQ="model_jobs_egress",dQ="setpriv_v1",OQ="jobs_user",hQ="spawning_attempt_v1",RQ="hands_session_group",rQ="session_cap",pQ="none",nQ="same_launch_v1",oQ="exit_v1",sQ="start_wait",iQ="user_chrome",tQ="cloud_sessions";function S(Q){if(!K(Q)||Object.keys(Q).length!==5||Q.version!==1)return!1;let Z=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;return["boot_generation","recording_operation_id","recording_attempt_id"].every(($)=>typeof Q[$]==="string"&&Z.test(Q[$]))&&typeof Q.root_version==="string"&&/^[0-9]{1,20}(?:\.[0-9]{1,6})?$/.test(Q.root_version)}function U(Q){if(!K(Q)||Object.keys(Q).length!==6)return!1;let Z=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;return typeof Q.device_id==="string"&&Z.test(Q.device_id)&&(Q.binding==="workspace_source"||Q.binding==="mcp_control")&&Number.isSafeInteger(Q.target_revision)&&Number(Q.target_revision)>=0&&Number.isSafeInteger(Q.root_grant_revision)&&Number(Q.root_grant_revision)>0&&Number.isSafeInteger(Q.target_generation)&&Number(Q.target_generation)>0&&typeof Q.target_fence_id==="string"&&Z.test(Q.target_fence_id)}var vQ=["lock_acquired","enrollment_started","enrollment_completed","readiness_started","readiness_completed","inventory_completed","control_ready"],lQ=86400000,uQ=["service.install_started","service.install_completed","service.install_failed","service.launcher_adopted","service.launcher_conflict","service.started","service.reconnecting","service.reconnected","service.idle_sleep_held","service.idle_sleep_released","service.idle_sleep_failed","service.start_failed","service.stopped","service.exit_failed","service.singleton_rejected","credential.migration_started","credential.migration_completed","credential.migration_failed","credential.store_started","credential.store_completed","credential.store_failed","credential.delete_started","credential.delete_completed","credential.delete_failed","update.check_started","update.not_available","update.download_started","update.downloaded","update.verified","update.activated","update.rollback","update.failed","executor.update.check_started","executor.update.not_available","executor.update.download_started","executor.update.downloaded","executor.update.verified","executor.update.activated","executor.update.rollback","executor.update.failed","identity.refresh_completed","identity.refresh_failed","update.device_moved","update.components_installed","update.deferred","update.deferral_expired","worker.previous_exit","worker.capabilities_withheld","identity.computer_use_unavailable"],s=["production","staging"];function E(Q){if(!K(Q)||Object.keys(Q).length!==3)return!1;let Z=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;return["organization_id","user_id","device_id"].every(($)=>Object.hasOwn(Q,$)&&typeof Q[$]==="string"&&Z.test(Q[$])&&Q[$]!=="00000000-0000-0000-0000-000000000000")}var i="DEVICE-PROOF-V2",aQ="ARA-DEVICE-V1";function eQ(Q,Z=i){let $=Q.method.toUpperCase();if(!/^[A-Z]+$/.test($)||!Q.pathAndQuery.startsWith(`${I}/`)||Q.pathAndQuery.includes(`
38
+ `)||!/^[0-9]{1,20}$/.test(Q.timestamp)||!/^[A-Za-z0-9_-]{22,43}$/.test(Q.nonce)||Q.challenge.length<16||Q.challenge.length>1024||Q.challenge.includes(`
39
+ `)||!/^[a-f0-9]{64}$/.test(Q.bodySha256))throw Error("Invalid Reason Device proof input.");return Buffer.from([Z,$,Q.pathAndQuery,Q.timestamp,Q.nonce,Q.challenge,Q.bodySha256].join(`
40
+ `),"utf8")}function K(Q){return Boolean(Q)&&typeof Q==="object"&&!Array.isArray(Q)}function t(Q,Z){return typeof Q==="string"&&Z.some(($)=>$===Q)}function k(Q){return K(Q)&&typeof Q.id==="string"&&typeof Q.label==="string"&&typeof Q.path_fingerprint==="string"}function v(Q){return K(Q)&&Number.isInteger(Q.seq)&&Number(Q.seq)>=0&&typeof Q.kind==="string"&&/^[A-Za-z0-9._:-]{1,64}$/.test(Q.kind)&&K(Q.payload)}function w(Q){throw Error(Q)}function QW(Q,Z){let $=K(Q)?Q:{},z=typeof $.error==="string"?$.error:`http_${Z}`,V=typeof $.detail==="string"?$.detail:typeof $.message==="string"?$.message:`Reason Device request failed (${Z})`;return{code:z,message:V}}function l(Q){if(!K(Q)||typeof Q.challenge!=="string"||Q.challenge.length<16||Q.challenge.length>1024||Q.challenge.includes(`
41
+ `)||typeof Q.expires_at!=="string"||!Number.isFinite(Date.parse(Q.expires_at)))w("Reason returned an invalid Device proof challenge.");return{challenge:Q.challenge,expires_at:Q.expires_at}}function L(Q,Z){if(!K(Q)||typeof Q.device_id!=="string"||Q.auth_scheme!=="p256"||Q.organization_id!==void 0&&typeof Q.organization_id!=="string"||Q.protocol_version!==j||!Array.isArray(Q.roots)||!Q.roots.every(k)||Z&&typeof Q.organization_id!=="string"||Q.device_credential!==void 0)w(Z?"Reason returned an invalid Device enrollment.":"Reason returned an invalid Device registration.");return{...{device_id:Q.device_id,...typeof Q.organization_id==="string"?{organization_id:Q.organization_id}:{},protocol_version:j,roots:Q.roots},auth_scheme:"p256"}}function WW(Q){return L(Q,!1)}function ZW(Q){let Z=L(Q,!0);if(typeof Z.organization_id!=="string")return w("Reason returned an invalid Device enrollment.");return{...Z,organization_id:Z.organization_id}}function $W(Q){if(!K(Q)||typeof Q.server_time!=="string"||typeof Q.drain!=="boolean")return w("Reason returned an invalid Device heartbeat.");return{server_time:Q.server_time,drain:Q.drain,...f(Q),...typeof Q.update_policy==="string"||Q.update_policy===null?{update_policy:Q.update_policy}:{},...typeof Q.supported_protocol_version==="number"?{supported_protocol_version:Q.supported_protocol_version}:{},...a(Q.latest_cli_versions),...Q.hands_prespawn===!0?{hands_prespawn:!0}:{}}}var u=["account_root_metadata_supported","workspace_root_metadata_supported","account_root_path_supported","home_contained_roots_supported","root_paths_supported","startup_supported"];function f(Q){return Object.fromEntries(u.filter((Z)=>Q[Z]===!0).map((Z)=>[Z,!0]))}function KW(Q){if(!K(Q))return;try{return{...l(Q),...f(Q)}}catch{return}}function a(Q){if(!K(Q))return{};let Z={};for(let $ of s){let z=Q[$];if(typeof z==="string"&&/^(0|[1-9][0-9]{0,5})\.(0|[1-9][0-9]{0,5})\.(0|[1-9][0-9]{0,5})$/.test(z))Z[$]=z}return Object.keys(Z).length>0?{latest_cli_versions:Z}:{}}function DW(Q){if(!K(Q)||!Array.isArray(Q.roots)||!Q.roots.every(k))return w("Reason returned an invalid Device root sync.");return{roots:Q.roots}}function zW(Q){if(!K(Q)||Q.user_id!==void 0&&typeof Q.user_id!=="string"||typeof Q.organization_id!=="string"||typeof Q.organization_name!=="string"||typeof Q.organization_slug!=="string")return w("Reason returned an invalid Device identity.");return{...typeof Q.user_id==="string"?{user_id:Q.user_id}:{},organization_id:Q.organization_id,organization_name:Q.organization_name,organization_slug:Q.organization_slug}}function FW(Q){if(!K(Q)||Q.disconnected!==!0)return w("Reason did not disconnect this Device.");let Z=Q.sessions_moved;return typeof Z==="number"&&Number.isSafeInteger(Z)&&Z>=0?{disconnected:!0,sessions_moved:Z}:{disconnected:!0}}function wW(Q){if(K(Q)&&Q.ok===!0&&typeof Q.expires==="number")return{ok:!0,expires:Q.expires};if(K(Q)&&Q.ok===!1&&typeof Q.error==="string")return{ok:!1,error:Q.error};return w("Reason did not answer the local login hand-over.")}function VW(Q){if(!K(Q)||Q.accepted!==!0)return w("Reason did not accept the Device lifecycle event.");return{accepted:!0}}function e(Q){return Buffer.byteLength(JSON.stringify(Q),"utf8")}function YW(Q,Z=b){if(!K(Q)||typeof Q.operation_id!=="string"||typeof Q.attempt_id!=="string"||typeof Q.attempt_token!=="string"||!/^(?:reason|ara)_attempt_/.test(Q.attempt_token)||typeof Q.lease_until!=="string"||typeof Q.run_id!=="string"||typeof Q.root_id!=="string"||Q.owner!==void 0&&!E(Q.owner)||!t(Q.capability,Z)||!K(Q.payload)||Q.protocol_version!==j||e(Q.payload)>n||Q.authority!==void 0&&!U(Q.authority)||Q.local_github_authority!==void 0&&!m.safeParse(Q.local_github_authority).success||Q.capability==="github.local.v1"&&!m.safeParse(Q.local_github_authority).success||Q.recording_authority!==void 0&&!S(Q.recording_authority)||Q.capability==="browser.recording.v1"&&(!S(Q.recording_authority)||!E(Q.owner))||Q.capability!=="browser.recording.v1"&&Q.recording_authority!==void 0)return w("Reason returned an invalid Device operation claim.");let $={operation_id:Q.operation_id,attempt_id:Q.attempt_id,attempt_token:Q.attempt_token,lease_until:Q.lease_until,run_id:Q.run_id,root_id:Q.root_id,capability:Q.capability,payload:Q.payload,...U(Q.authority)?{authority:Q.authority}:{},...S(Q.recording_authority)?{recording_authority:Object.freeze({...Q.recording_authority})}:{},...Q.local_github_authority!==void 0?{local_github_authority:m.parse(Q.local_github_authority)}:{},...Q.capability==="hands.connect"&&K(Q.environment)&&K(Q.environment.payload)&&U(Q.environment.authority)?{environment:{payload:Q.environment.payload,authority:Q.environment.authority}}:{},protocol_version:j};if(Q.owner!==void 0)$.owner=Object.freeze({...Q.owner});return $}function HW(Q){if(!K(Q)||typeof Q.lease_until!=="string"||!Array.isArray(Q.controls)||!Q.controls.every(v)||!Number.isInteger(Q.next_control_seq)||Number(Q.next_control_seq)<0)return w("Reason returned an invalid Device operation heartbeat.");return{lease_until:Q.lease_until,controls:Q.controls,next_control_seq:Number(Q.next_control_seq)}}function XW(Q){if(!K(Q)||!Number.isInteger(Q.next_event_seq)||Number(Q.next_event_seq)<0||typeof Q.duplicate!=="boolean"||!Number.isInteger(Q.accepted_count)||Number(Q.accepted_count)<0)return w("Reason returned an invalid Device operation event result.");return{next_event_seq:Number(Q.next_event_seq),duplicate:Q.duplicate,accepted_count:Number(Q.accepted_count)}}function GW(Q){if(!K(Q)||!K(Q.payload)||!U(Q.authority))return w("Reason returned an invalid Device environment delivery.");return{payload:Q.payload,authority:Q.authority}}function QQ(Q){return Q==="succeeded"||Q==="failed"||Q==="cancelled"||Q==="expired"}function BW(Q){if(!K(Q)||!QQ(Q.status)||typeof Q.idempotent!=="boolean")return w("Reason returned an invalid Device operation completion.");return{status:Q.status,idempotent:Q.idempotent}}
42
+ export{d as ld,R as md,ZQ as nd,x as od,$Q as pd,m as qd,KQ as rd,DQ as sd,zQ as td,b as ud,j as vd,I as wd,n as xd,HQ as yd,XQ as zd,GQ as Ad,BQ as Bd,MQ as Cd,gQ as Dd,qQ as Ed,NQ as Fd,mQ as Gd,UQ as Hd,jQ as Id,xQ as Jd,JQ as Kd,SQ as Ld,IQ as Md,PQ as Nd,TQ as Od,CQ as Pd,AQ as Qd,bQ as Rd,EQ as Sd,kQ as Td,LQ as Ud,fQ as Vd,_Q as Wd,cQ as Xd,yQ as Yd,dQ as Zd,OQ as _d,hQ as $d,RQ as ae,rQ as be,pQ as ce,nQ as de,oQ as ee,sQ as fe,iQ as ge,tQ as he,vQ as ie,lQ as je,uQ as ke,i as le,aQ as me,eQ as ne,QW as oe,l as pe,WW as qe,ZW as re,$W as se,KW as te,DW as ue,zW as ve,FW as we,wW as xe,VW as ye,YW as ze,HW as Ae,XW as Be,GW as Ce,BW as De};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{Sb as D}from"./vm-hands-entry-lite-wmxksawm.js";import{si as j}from"./vm-hands-entry-lite-ypcqvygf.js";import{statSync as i}from"fs";import{delimiter as n,join as t}from"path";function _(q,z=process.env.PATH??""){if(!q||q.includes("/")||q.includes("\x00"))return!1;return z.split(n).some((G)=>{if(!G)return!1;try{let Q=i(t(G,q));return Q.isFile()&&(Q.mode&73)!==0}catch{return!1}})}import{spawn as r,spawnSync as e}from"child_process";import{existsSync as k,mkdtempSync as E,readFileSync as O,readdirSync as o,realpathSync as qq,rmSync as b,statSync as zq}from"fs";import{platform as y,tmpdir as g}from"os";import{dirname as A,join as Z}from"path";import{fileURLToPath as Gq,pathToFileURL as T}from"url";var Hq=["bwrap","socat","rg"],Jq=2000,v=20000,Qq=3,P=4000,Vq=new Set([".git",".hg",".svn","node_modules"]),Wq=["runAsHostUid","sysrq-trigger"],Yq=Z(A(A(Gq(import.meta.url))),"packages/sandbox-runtime/src/index.ts"),h=!1;function fq(){h=!0}async function u(){let z=h?Z(A(qq(process.execPath)),"runtime","srt"):void 0;if(z&&process.platform==="linux"&&!k(Z(z,"vendor","seccomp",process.arch,"apply-seccomp")))throw Error("packaged_sandbox_runtime_vendor_missing");if(z){let J=O(Z(z,"sandbox-runtime.mjs"),"utf8");for(let Y of Wq)if(!J.includes(Y))throw Error(`packaged_sandbox_runtime_fork_missing:${Y}`)}let H=(await import(z?T(Z(z,"sandbox-runtime.mjs")).href:T(Yq).href)).SandboxManager;if(!H||typeof H.initialize!=="function"||typeof H.wrapWithSandboxArgv!=="function")throw Error("sandbox-runtime does not expose the expected SandboxManager API.");return{SandboxManager:H}}function Zq(q={}){if((q.platformName??y())!=="linux")return!1;let G=q.fileExists??k,Q=q.readFile??((H)=>O(H,"utf8"));for(let H of["/.dockerenv","/run/.containerenv"])try{if(G(H))return!0}catch{}try{return/docker|containerd|kubepods|lxc|libpod/.test(Q("/proc/1/cgroup"))}catch{return!1}}function l(q){return["/bin/true","/usr/bin/true"].find((z)=>q(z))??null}function $q(q,z){return q==="strict"?["--ro-bind","/","/","--unshare-pid","--unshare-user","--cap-drop","ALL","--proc","/proc","--",z]:["--ro-bind","/","/","--unshare-pid","--unshare-user","--bind","/proc","/proc","--",z]}function jq(q,z){try{let G=e("bwrap",$q(q,z),{stdio:"ignore",timeout:Jq});return!G.error&&G.status===0}catch{return!1}}function Bq(q){let z=q.platformName??y();if(z!=="linux")return null;let G=q.hasExecutable??_;if(!Hq.every((V)=>G(V)))return null;let Q=q.fileExists??k,H=l(Q);if(!H)return null;let J=B??(q.containerized??Zq({platformName:z})?"weak":"strict");return(q.probeNamespaces??((V)=>jq(V,H)))(J)?J:null}var L=null,C=!1,K=null,S=null,f=null,B=null,F=null;function M(){throw I("sandbox_mode_conflict"),new j("sandbox_unavailable","Sandbox process policy conflicts with an existing probe or session. Restart the worker.")}function xq(q){if(B!==null&&B!==q||C&&L!==null&&L!==q||F!==null&&F!==q)M();B=q}function I(q){K=q}function c(q){if(K)return!1;if(!C){if(L=Bq(q??{}),C=!0,L&&!q)d()}return L!==null}function Lq(){return c()?L:null}var U=null,w=0;function m(q){if(K)throw new j("sandbox_unavailable","Confined execution is unavailable in this worker process.");if(B&&q.sandboxMode&&B!==q.sandboxMode)M();let z=B??q.sandboxMode??Lq();if(!z)throw new j("sandbox_unavailable","Confined command execution is unavailable on this operating system.");if(F&&F!==z)M();return F=z,U??=(async()=>{let{SandboxManager:G}=await(q.loadSandboxRuntime??u)();return await G.initialize(Iq(z)),G})().catch((G)=>{throw U=null,I(`initialize_failed: ${String(G)}`),G instanceof j?G:new j("sandbox_unavailable","The confined execution sandbox failed to start.")}),U.then((G)=>{if(K)throw new j("sandbox_unavailable","Confined execution became unavailable during sandbox initialization.");return G})}async function Kq(){let q=U;if(U=null,!q)return;try{await(await q).reset()}catch{}}async function d(q={}){if(K)return!1;if(q.loadSandboxRuntime)return x(q.loadSandboxRuntime);if(!c())return!1;return S??=x(u),S}async function x(q){try{let{SandboxManager:z}=await q(),G=z.checkDependencies().errors;if(G.length>0)return I(`dependencies_missing: ${G.join(", ")}`),!1;return!K}catch(z){return I(`load_failed: ${String(z)}`),!1}}async function Rq(q={}){if(!q.loadSandboxRuntime&&!q.sandboxMode){if(!await d())return!1;return f??=R({}),f}return R(q)}async function R(q){let z;try{z=await m(q)}catch{return!1}let G=await Xq(z);if(!G)I("confined_command_failed");if(w===0)await Kq();return G}async function Xq(q){let z=l(k);if(!z)return!1;let G=E(Z(g(),"reason-device-probe-"));try{let{argv:Q}=await q.wrapWithSandboxArgv(a([z]),p(),{filesystem:s({root:G,allowWrite:!1,temporaryDirectory:G,protectedPaths:[]})},void 0,G),[H,...J]=Q;if(!H)return!1;return await Fq(H,J,G)}catch{return!1}finally{try{q.cleanupAfterCommand()}catch{}b(G,{recursive:!0,force:!0})}}function Fq(q,z,G,Q={}){return new Promise((H)=>{let J=!1,Y,V=(X)=>{if(J)return;J=!0,clearTimeout(Y),H(X)},W;try{W=(Q.spawnChild??r)(q,z,{cwd:G,env:{PATH:D,HOME:G,TMPDIR:G},stdio:"ignore"})}catch{V(!1);return}W.once("error",()=>V(!1));let $=(X,N)=>V(X===0&&N===null);if(W.once("exit",$),W.once("close",$),W.exitCode!==null||W.signalCode!==null)$(W.exitCode,W.signalCode);if(J)return;Y=setTimeout(()=>{V(!1);try{W.kill("SIGKILL")}catch{}},Math.min(Q.timeoutMs??v,v))})}function p(q=k){return["/bin/bash","/bin/sh"].find((z)=>q(z))??"/bin/sh"}function a(q){return q.map((z)=>`'${z.replaceAll("'","'\\''")}'`).join(" ")}function Uq(q,z,G=(Q)=>o(Q,{withFileTypes:!0}).filter((H)=>H.isDirectory()||H.isFile()).map((H)=>H.name)){let Q=[],H=[{path:q,depth:0}],J=0;while(H.length>0&&J<P){let Y=H.pop(),V;try{V=G(Y.path)}catch{continue}for(let W of V){if(J+=1,J>P)break;let $=Z(Y.path,W);if(z($)){Q.push($);continue}if(Y.depth+1<Qq&&!Vq.has(W))H.push({path:$,depth:Y.depth+1})}}return Q}function s(q){let z=Z(q.root,".git"),G=[];try{if(zq(z).isDirectory())G=[Z(z,"config"),Z(z,"hooks")]}catch{}return{denyRead:["/home","/root","/tmp","/tmp/.X11-unix",...q.protectedPaths],allowRead:[q.root,q.temporaryDirectory],allowWrite:[...q.allowWrite?[q.root]:[],q.temporaryDirectory],denyWrite:[...q.protectedPaths,...G]}}function Iq(q){return{network:{allowedDomains:[],deniedDomains:[]},filesystem:{denyRead:[],allowRead:[],allowWrite:[],denyWrite:[]},...q==="weak"?{enableWeakerNestedSandbox:!0}:{}}}function Dq(q){let z=q.createTemporaryDirectory??(()=>E(Z(g(),"reason-device-"))),G=q.removeTemporaryDirectory??((Q)=>b(Q,{recursive:!0,force:!0}));return async(Q,H,J)=>{let Y=await m(q),V=z();w+=1;try{let W;try{W=await Y.wrapWithSandboxArgv(a([Q,...H]),q.shell??p(),{filesystem:s({root:J.root,allowWrite:J.allowWrite,temporaryDirectory:V,protectedPaths:Uq(J.root,q.isProtectedPath)})},J.signal,J.cwd)}catch(N){throw N instanceof j?N:new j("sandbox_unavailable","The confined execution sandbox could not wrap the command.")}let[$,...X]=W.argv;if(!$)throw new j("sandbox_unavailable","The confined execution sandbox produced no command.");return await q.spawnCaptured($,X,{cwd:J.cwd,timeoutMs:J.timeoutMs,signal:J.signal,env:q.scrubEnvironment(J.root,V)})}finally{w-=1;try{Y.cleanupAfterCommand()}catch{}G(V)}}}
2
+ import{Sb as D}from"./vm-hands-entry-lite-wmxksawm.js";import{ui as j}from"./vm-hands-entry-lite-gt5pkv4h.js";import{statSync as i}from"fs";import{delimiter as n,join as t}from"path";function _(q,z=process.env.PATH??""){if(!q||q.includes("/")||q.includes("\x00"))return!1;return z.split(n).some((G)=>{if(!G)return!1;try{let Q=i(t(G,q));return Q.isFile()&&(Q.mode&73)!==0}catch{return!1}})}import{spawn as r,spawnSync as e}from"child_process";import{existsSync as k,mkdtempSync as E,readFileSync as O,readdirSync as o,realpathSync as qq,rmSync as b,statSync as zq}from"fs";import{platform as y,tmpdir as g}from"os";import{dirname as A,join as Z}from"path";import{fileURLToPath as Gq,pathToFileURL as T}from"url";var Hq=["bwrap","socat","rg"],Jq=2000,v=20000,Qq=3,P=4000,Vq=new Set([".git",".hg",".svn","node_modules"]),Wq=["runAsHostUid","sysrq-trigger"],Yq=Z(A(A(Gq(import.meta.url))),"packages/sandbox-runtime/src/index.ts"),h=!1;function fq(){h=!0}async function u(){let z=h?Z(A(qq(process.execPath)),"runtime","srt"):void 0;if(z&&process.platform==="linux"&&!k(Z(z,"vendor","seccomp",process.arch,"apply-seccomp")))throw Error("packaged_sandbox_runtime_vendor_missing");if(z){let J=O(Z(z,"sandbox-runtime.mjs"),"utf8");for(let Y of Wq)if(!J.includes(Y))throw Error(`packaged_sandbox_runtime_fork_missing:${Y}`)}let H=(await import(z?T(Z(z,"sandbox-runtime.mjs")).href:T(Yq).href)).SandboxManager;if(!H||typeof H.initialize!=="function"||typeof H.wrapWithSandboxArgv!=="function")throw Error("sandbox-runtime does not expose the expected SandboxManager API.");return{SandboxManager:H}}function Zq(q={}){if((q.platformName??y())!=="linux")return!1;let G=q.fileExists??k,Q=q.readFile??((H)=>O(H,"utf8"));for(let H of["/.dockerenv","/run/.containerenv"])try{if(G(H))return!0}catch{}try{return/docker|containerd|kubepods|lxc|libpod/.test(Q("/proc/1/cgroup"))}catch{return!1}}function l(q){return["/bin/true","/usr/bin/true"].find((z)=>q(z))??null}function $q(q,z){return q==="strict"?["--ro-bind","/","/","--unshare-pid","--unshare-user","--cap-drop","ALL","--proc","/proc","--",z]:["--ro-bind","/","/","--unshare-pid","--unshare-user","--bind","/proc","/proc","--",z]}function jq(q,z){try{let G=e("bwrap",$q(q,z),{stdio:"ignore",timeout:Jq});return!G.error&&G.status===0}catch{return!1}}function Bq(q){let z=q.platformName??y();if(z!=="linux")return null;let G=q.hasExecutable??_;if(!Hq.every((V)=>G(V)))return null;let Q=q.fileExists??k,H=l(Q);if(!H)return null;let J=B??(q.containerized??Zq({platformName:z})?"weak":"strict");return(q.probeNamespaces??((V)=>jq(V,H)))(J)?J:null}var L=null,C=!1,K=null,S=null,f=null,B=null,F=null;function M(){throw I("sandbox_mode_conflict"),new j("sandbox_unavailable","Sandbox process policy conflicts with an existing probe or session. Restart the worker.")}function xq(q){if(B!==null&&B!==q||C&&L!==null&&L!==q||F!==null&&F!==q)M();B=q}function I(q){K=q}function c(q){if(K)return!1;if(!C){if(L=Bq(q??{}),C=!0,L&&!q)d()}return L!==null}function Lq(){return c()?L:null}var U=null,w=0;function m(q){if(K)throw new j("sandbox_unavailable","Confined execution is unavailable in this worker process.");if(B&&q.sandboxMode&&B!==q.sandboxMode)M();let z=B??q.sandboxMode??Lq();if(!z)throw new j("sandbox_unavailable","Confined command execution is unavailable on this operating system.");if(F&&F!==z)M();return F=z,U??=(async()=>{let{SandboxManager:G}=await(q.loadSandboxRuntime??u)();return await G.initialize(Iq(z)),G})().catch((G)=>{throw U=null,I(`initialize_failed: ${String(G)}`),G instanceof j?G:new j("sandbox_unavailable","The confined execution sandbox failed to start.")}),U.then((G)=>{if(K)throw new j("sandbox_unavailable","Confined execution became unavailable during sandbox initialization.");return G})}async function Kq(){let q=U;if(U=null,!q)return;try{await(await q).reset()}catch{}}async function d(q={}){if(K)return!1;if(q.loadSandboxRuntime)return x(q.loadSandboxRuntime);if(!c())return!1;return S??=x(u),S}async function x(q){try{let{SandboxManager:z}=await q(),G=z.checkDependencies().errors;if(G.length>0)return I(`dependencies_missing: ${G.join(", ")}`),!1;return!K}catch(z){return I(`load_failed: ${String(z)}`),!1}}async function Rq(q={}){if(!q.loadSandboxRuntime&&!q.sandboxMode){if(!await d())return!1;return f??=R({}),f}return R(q)}async function R(q){let z;try{z=await m(q)}catch{return!1}let G=await Xq(z);if(!G)I("confined_command_failed");if(w===0)await Kq();return G}async function Xq(q){let z=l(k);if(!z)return!1;let G=E(Z(g(),"reason-device-probe-"));try{let{argv:Q}=await q.wrapWithSandboxArgv(a([z]),p(),{filesystem:s({root:G,allowWrite:!1,temporaryDirectory:G,protectedPaths:[]})},void 0,G),[H,...J]=Q;if(!H)return!1;return await Fq(H,J,G)}catch{return!1}finally{try{q.cleanupAfterCommand()}catch{}b(G,{recursive:!0,force:!0})}}function Fq(q,z,G,Q={}){return new Promise((H)=>{let J=!1,Y,V=(X)=>{if(J)return;J=!0,clearTimeout(Y),H(X)},W;try{W=(Q.spawnChild??r)(q,z,{cwd:G,env:{PATH:D,HOME:G,TMPDIR:G},stdio:"ignore"})}catch{V(!1);return}W.once("error",()=>V(!1));let $=(X,N)=>V(X===0&&N===null);if(W.once("exit",$),W.once("close",$),W.exitCode!==null||W.signalCode!==null)$(W.exitCode,W.signalCode);if(J)return;Y=setTimeout(()=>{V(!1);try{W.kill("SIGKILL")}catch{}},Math.min(Q.timeoutMs??v,v))})}function p(q=k){return["/bin/bash","/bin/sh"].find((z)=>q(z))??"/bin/sh"}function a(q){return q.map((z)=>`'${z.replaceAll("'","'\\''")}'`).join(" ")}function Uq(q,z,G=(Q)=>o(Q,{withFileTypes:!0}).filter((H)=>H.isDirectory()||H.isFile()).map((H)=>H.name)){let Q=[],H=[{path:q,depth:0}],J=0;while(H.length>0&&J<P){let Y=H.pop(),V;try{V=G(Y.path)}catch{continue}for(let W of V){if(J+=1,J>P)break;let $=Z(Y.path,W);if(z($)){Q.push($);continue}if(Y.depth+1<Qq&&!Vq.has(W))H.push({path:$,depth:Y.depth+1})}}return Q}function s(q){let z=Z(q.root,".git"),G=[];try{if(zq(z).isDirectory())G=[Z(z,"config"),Z(z,"hooks")]}catch{}return{denyRead:["/home","/root","/tmp","/tmp/.X11-unix",...q.protectedPaths],allowRead:[q.root,q.temporaryDirectory],allowWrite:[...q.allowWrite?[q.root]:[],q.temporaryDirectory],denyWrite:[...q.protectedPaths,...G]}}function Iq(q){return{network:{allowedDomains:[],deniedDomains:[]},filesystem:{denyRead:[],allowRead:[],allowWrite:[],denyWrite:[]},...q==="weak"?{enableWeakerNestedSandbox:!0}:{}}}function Dq(q){let z=q.createTemporaryDirectory??(()=>E(Z(g(),"reason-device-"))),G=q.removeTemporaryDirectory??((Q)=>b(Q,{recursive:!0,force:!0}));return async(Q,H,J)=>{let Y=await m(q),V=z();w+=1;try{let W;try{W=await Y.wrapWithSandboxArgv(a([Q,...H]),q.shell??p(),{filesystem:s({root:J.root,allowWrite:J.allowWrite,temporaryDirectory:V,protectedPaths:Uq(J.root,q.isProtectedPath)})},J.signal,J.cwd)}catch(N){throw N instanceof j?N:new j("sandbox_unavailable","The confined execution sandbox could not wrap the command.")}let[$,...X]=W.argv;if(!$)throw new j("sandbox_unavailable","The confined execution sandbox produced no command.");return await q.spawnCaptured($,X,{cwd:J.cwd,timeoutMs:J.timeoutMs,signal:J.signal,env:q.scrubEnvironment(J.root,V)})}finally{w-=1;try{Y.cleanupAfterCommand()}catch{}G(V)}}}
3
3
  export{_ as Lb,fq as Mb,xq as Nb,c as Ob,Rq as Pb,p as Qb,Dq as Rb};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{yf as $}from"./vm-hands-entry-lite-xazz63m6.js";var O=$.version,Z=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;function S(B,D){if(!Z.test(B)||!Z.test(D))throw Error("cannot compare invalid CLI versions");let J=(q)=>{let y=q.indexOf("-");return y===-1?[q,void 0]:[q.slice(0,y),q.slice(y+1)]},[j,F]=J(B),[w,G]=J(D),K=j.split(".").map(BigInt),M=w.split(".").map(BigInt);for(let q=0;q<3;q+=1){if(K[q]===M[q])continue;return K[q]<M[q]?-1:1}if(F===void 0||G===void 0){if(F===G)return 0;return F===void 0?1:-1}let Q=F.split("."),U=G.split("."),A=Math.max(Q.length,U.length);for(let q=0;q<A;q+=1){let y=Q[q],z=U[q];if(y===void 0||z===void 0){if(y===z)return 0;return y===void 0?-1:1}if(y===z)continue;let H=/^\d+$/.test(y),W=/^\d+$/.test(z);if(H&&W){let X=BigInt(y),Y=BigInt(z);if(X===Y)continue;return X<Y?-1:1}if(H!==W)return H?-1:1;return y<z?-1:1}return 0}function k(B,D){return D?`cli ${B} \xB7 agent ${D}`:`cli ${B}`}
3
- export{O as uf,Z as vf,S as wf,k as xf};
2
+ import{Af as $}from"./vm-hands-entry-lite-y4mtveeb.js";var O=$.version,Z=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;function S(B,D){if(!Z.test(B)||!Z.test(D))throw Error("cannot compare invalid CLI versions");let J=(q)=>{let y=q.indexOf("-");return y===-1?[q,void 0]:[q.slice(0,y),q.slice(y+1)]},[j,F]=J(B),[w,G]=J(D),K=j.split(".").map(BigInt),M=w.split(".").map(BigInt);for(let q=0;q<3;q+=1){if(K[q]===M[q])continue;return K[q]<M[q]?-1:1}if(F===void 0||G===void 0){if(F===G)return 0;return F===void 0?1:-1}let Q=F.split("."),U=G.split("."),A=Math.max(Q.length,U.length);for(let q=0;q<A;q+=1){let y=Q[q],z=U[q];if(y===void 0||z===void 0){if(y===z)return 0;return y===void 0?-1:1}if(y===z)continue;let H=/^\d+$/.test(y),W=/^\d+$/.test(z);if(H&&W){let X=BigInt(y),Y=BigInt(z);if(X===Y)continue;return X<Y?-1:1}if(H!==W)return H?-1:1;return y<z?-1:1}return 0}function k(B,D){return D?`cli ${B} \xB7 agent ${D}`:`cli ${B}`}
3
+ export{O as wf,Z as xf,S as yf,k as zf};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{Vh as X,Xh as Y,Zh as Z}from"./vm-hands-entry-lite-3s5fdvat.js";import{execFileSync as z}from"child_process";import{existsSync as V,realpathSync as M}from"fs";import{userInfo as D}from"os";import{isAbsolute as $,join as C,normalize as F,parse as K}from"path";function Q(){let q=F(D().homedir);if(!$(q)||q===K(q).root)throw Error("Could not resolve the canonical macOS user home.");return q}function O(q,B,J=Q()){let L=Z(B);if(B.kind==="managed"&&B.base){let G=M(J);return{anchor:G,boundary:C(G,B.base),path:C(G,L)}}if(B.kind==="root"&&Y(B.path)){let G=M(J);return{anchor:G,boundary:C(G,X),path:C(G,L)}}return{anchor:q,boundary:q,path:C(q,L)}}function _(q=Q()){return C(q,".config")}function b(){if(process.platform!=="darwin")return null;try{let q=z("/usr/bin/getconf",["DARWIN_USER_DIR"],{encoding:"utf8",timeout:5000}).trim();return $(q)?M(q):null}catch{return null}}function g(q=Q()){let B=C(q,"Library","Application Support","Ara"),J=C(q,"Library","Application Support","Reason");return V(B)&&!V(J)?B:J}
3
- export{Q as Mh,O as Nh,_ as Oh,b as Ph,g as Qh};
2
+ import{$h as Z,Xh as X,Zh as Y}from"./vm-hands-entry-lite-289bc9v7.js";import{execFileSync as z}from"child_process";import{existsSync as V,realpathSync as M}from"fs";import{userInfo as D}from"os";import{isAbsolute as $,join as C,normalize as F,parse as K}from"path";function Q(){let q=F(D().homedir);if(!$(q)||q===K(q).root)throw Error("Could not resolve the canonical macOS user home.");return q}function O(q,B,J=Q()){let L=Z(B);if(B.kind==="managed"&&B.base){let G=M(J);return{anchor:G,boundary:C(G,B.base),path:C(G,L)}}if(B.kind==="root"&&Y(B.path)){let G=M(J);return{anchor:G,boundary:C(G,X),path:C(G,L)}}return{anchor:q,boundary:q,path:C(q,L)}}function _(q=Q()){return C(q,".config")}function b(){if(process.platform!=="darwin")return null;try{let q=z("/usr/bin/getconf",["DARWIN_USER_DIR"],{encoding:"utf8",timeout:5000}).trim();return $(q)?M(q):null}catch{return null}}function g(q=Q()){let B=C(q,"Library","Application Support","Ara"),J=C(q,"Library","Application Support","Reason");return V(B)&&!V(J)?B:J}
3
+ export{Q as Oh,O as Ph,_ as Qh,b as Rh,g as Sh};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{si as M}from"./vm-hands-entry-lite-ypcqvygf.js";import{yi as G}from"./vm-hands-entry-lite-45cnnd8e.js";import{readdirSync as D,readFileSync as I}from"fs";import{userInfo as A}from"os";var O="--vm-hands-op-runner-kind=person";function x(q){let Q=new Set([q]),K=[];try{K=D("/proc")}catch{}for(let z of K){if(!/^\d+$/.test(z))continue;try{let X=I(`/proc/${z}/stat`,"utf8");if(Number(X.slice(X.lastIndexOf(")")+2).split(" ")[3])===q)Q.add(Number(z))}catch{}}for(let z of Q)try{process.kill(z,"SIGKILL")}catch{}}var C=(q)=>{let Q=globalThis.Bun;if(!Q)throw new M("pty_unavailable","Reason terminals require the Bun runtime.");let K=Q.spawn({cmd:[q.shell,...q.args],cwd:q.cwd,env:{...q.environment,TERM:"xterm-256color"},terminal:{cols:q.cols,rows:q.rows,data:(J,Y)=>q.onData(Y)}}),z=K.terminal,X=()=>{x(K.pid);try{z?.close()}catch{}};if(!z)throw X(),new M("pty_unavailable","Reason could not allocate a pseudo-terminal.");return{write:(J)=>z.write(J),resize:(J,Y)=>z.resize(J,Y),kill:X,exited:K.exited.then((J)=>typeof J==="number"?J:null,()=>null)}};function L(){let q=(()=>{try{return A().username}catch{return}})();return{PATH:process.env.PATH,HOME:process.env.HOME,SHELL:process.env.SHELL,LANG:"C.UTF-8",...q?{USER:q,LOGNAME:q}:{}}}async function P(){let[{executeLocalOperation:q,spawnCaptured:Q},{runLocalPtySession:K},{configureDesktopAccount:z},{configureWorkerSandbox:X}]=await Promise.all([import("./local-capabilities-9y6jj12c.js"),import("./local-pty-session-3592ene9.js"),import("./desktop-account-j9pxgjn0.js"),import("./worker-sandbox-4mraqzsg.js")]);X();let T=process.argv.includes(O),J=($,j,F)=>Q($,j[0]==="-lic"?["-lc",...j.slice(1)]:j,F),Y=(process.geteuid?.()??0)!==0,H=new Map,Z=($)=>{try{process.send?.($)}catch{}};process.on("message",($)=>{let j=$;if(j?.t==="cancel"){H.get(j.id)?.abort();return}if(j?.t!=="op")return;if(!Y){Z({t:"done",id:j.id,completion:{status:"failed",error_code:"vm_hands_payload_account_unavailable"}});return}let F=j.claim.capability;if(F==="pty.start"&&!T){Z({t:"done",id:j.id,completion:{status:"failed",error_code:"capability_not_granted"}});return}let U=new AbortController;H.set(j.id,U);let V=F==="pty.start"?{runPtySession:(B)=>K(B,{spawnPty:C,environment:L(),loadProxy:()=>null})}:{worker:j.worker,...F==="exec.full"?{spawnFullControl:J}:{}};q(j.state,j.claim,{...V,signal:U.signal,emit:(B)=>{let{deliverySignal:N,...W}=B;Z({t:"event",id:j.id,event:W})}}).then((B)=>Z({t:"done",id:j.id,completion:B}),(B)=>Z({t:"done",id:j.id,completion:{status:"failed",error_code:B&&typeof B==="object"&&"code"in B&&typeof B.code==="string"?B.code:"vm_hands_op_failed"}})).finally(()=>H.delete(j.id))}),process.on("disconnect",()=>process.exit(0)),await new Promise(()=>{})}
2
+ import{ui as M}from"./vm-hands-entry-lite-gt5pkv4h.js";import{Ai as G}from"./vm-hands-entry-lite-mhsv58hw.js";import{readdirSync as D,readFileSync as I}from"fs";import{userInfo as A}from"os";var O="--vm-hands-op-runner-kind=person";function x(q){let Q=new Set([q]),K=[];try{K=D("/proc")}catch{}for(let z of K){if(!/^\d+$/.test(z))continue;try{let X=I(`/proc/${z}/stat`,"utf8");if(Number(X.slice(X.lastIndexOf(")")+2).split(" ")[3])===q)Q.add(Number(z))}catch{}}for(let z of Q)try{process.kill(z,"SIGKILL")}catch{}}var C=(q)=>{let Q=globalThis.Bun;if(!Q)throw new M("pty_unavailable","Reason terminals require the Bun runtime.");let K=Q.spawn({cmd:[q.shell,...q.args],cwd:q.cwd,env:{...q.environment,TERM:"xterm-256color"},terminal:{cols:q.cols,rows:q.rows,data:(J,Y)=>q.onData(Y)}}),z=K.terminal,X=()=>{x(K.pid);try{z?.close()}catch{}};if(!z)throw X(),new M("pty_unavailable","Reason could not allocate a pseudo-terminal.");return{write:(J)=>z.write(J),resize:(J,Y)=>z.resize(J,Y),kill:X,exited:K.exited.then((J)=>typeof J==="number"?J:null,()=>null)}};function L(){let q=(()=>{try{return A().username}catch{return}})();return{PATH:process.env.PATH,HOME:process.env.HOME,SHELL:process.env.SHELL,LANG:"C.UTF-8",...q?{USER:q,LOGNAME:q}:{}}}async function P(){let[{executeLocalOperation:q,spawnCaptured:Q},{runLocalPtySession:K},{configureDesktopAccount:z},{configureWorkerSandbox:X}]=await Promise.all([import("./local-capabilities-jfmzy2qt.js"),import("./local-pty-session-frp7k8fz.js"),import("./desktop-account-pm3zxjjt.js"),import("./worker-sandbox-1kpm6af4.js")]);X();let T=process.argv.includes(O),J=($,j,F)=>Q($,j[0]==="-lic"?["-lc",...j.slice(1)]:j,F),Y=(process.geteuid?.()??0)!==0,H=new Map,Z=($)=>{try{process.send?.($)}catch{}};process.on("message",($)=>{let j=$;if(j?.t==="cancel"){H.get(j.id)?.abort();return}if(j?.t!=="op")return;if(!Y){Z({t:"done",id:j.id,completion:{status:"failed",error_code:"vm_hands_payload_account_unavailable"}});return}let F=j.claim.capability;if(F==="pty.start"&&!T){Z({t:"done",id:j.id,completion:{status:"failed",error_code:"capability_not_granted"}});return}let U=new AbortController;H.set(j.id,U);let V=F==="pty.start"?{runPtySession:(B)=>K(B,{spawnPty:C,environment:L(),loadProxy:()=>null})}:{worker:j.worker,...F==="exec.full"?{spawnFullControl:J}:{}};q(j.state,j.claim,{...V,signal:U.signal,emit:(B)=>{let{deliverySignal:N,...W}=B;Z({t:"event",id:j.id,event:W})}}).then((B)=>Z({t:"done",id:j.id,completion:B}),(B)=>Z({t:"done",id:j.id,completion:{status:"failed",error_code:B&&typeof B==="object"&&"code"in B&&typeof B.code==="string"?B.code:"vm_hands_op_failed"}})).finally(()=>H.delete(j.id))}),process.on("disconnect",()=>process.exit(0)),await new Promise(()=>{})}
3
3
  export{O as a,C as b,P as c};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{$e as Zq}from"./vm-hands-entry-lite-2c8m8m7v.js";import{cf as Aq}from"./vm-hands-entry-lite-ckehp0dy.js";import{Df as H,Gf as L0,Jf as y0,Kf as T8,Lf as sq,Nf as $8,Qf as iq,Sf as nq}from"./vm-hands-entry-lite-bs1mbk81.js";import{$f as j0}from"./vm-hands-entry-lite-qezqtm4g.js";import{rg as U0}from"./vm-hands-entry-lite-vn0r1e8c.js";import{Mh as d}from"./vm-hands-entry-lite-p9eyqdq7.js";import{li as W0}from"./vm-hands-entry-lite-0zr461f9.js";import{si as M}from"./vm-hands-entry-lite-ypcqvygf.js";import{execFile as tx,spawn as T0}from"child_process";import{randomBytes as ex}from"crypto";import{chmodSync as q1,existsSync as B0,lstatSync as x1,mkdirSync as X1,readFileSync as Q1,rmSync as P1,writeFileSync as o8}from"fs";import{connect as b1}from"net";import{join as _}from"path";var Uq="./desktop-wallpaper-0pjhgyfk.jpg";var Lq="./dock-browser-afp005mt.png";var yq="./dock-files-rywdm96b.png";var jq="./dock-terminal-s41cj1jp.png";var Tq=`# Sets the X root window background and _XROOTPMAP_ID, as feh --bg-fill does.
2
+ import{bf as Zq}from"./vm-hands-entry-lite-pa111vpq.js";import{ef as Aq}from"./vm-hands-entry-lite-1w8tvrpq.js";import{Ff as H,If as L0,Lf as y0,Mf as T8,Nf as sq,Pf as $8,Sf as iq,Uf as nq}from"./vm-hands-entry-lite-yeahy7rk.js";import{bg as j0}from"./vm-hands-entry-lite-x6jqyxkx.js";import{tg as U0}from"./vm-hands-entry-lite-kt418g2w.js";import{Oh as d}from"./vm-hands-entry-lite-9dx3at21.js";import{ni as W0}from"./vm-hands-entry-lite-0jar357h.js";import{ui as M}from"./vm-hands-entry-lite-gt5pkv4h.js";import{execFile as tx,spawn as T0}from"child_process";import{randomBytes as ex}from"crypto";import{chmodSync as q1,existsSync as B0,lstatSync as x1,mkdirSync as X1,readFileSync as Q1,rmSync as P1,writeFileSync as o8}from"fs";import{connect as b1}from"net";import{join as _}from"path";var Uq="./desktop-wallpaper-0pjhgyfk.jpg";var Lq="./dock-browser-afp005mt.png";var yq="./dock-files-rywdm96b.png";var jq="./dock-terminal-s41cj1jp.png";var Tq=`# 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
@@ -178,4 +178,4 @@ Gtk.main()
178
178
  `).flatMap((Q)=>{let P=Q.indexOf("=");return P>0?[[Q.slice(0,P),Q.slice(P+1)]]:[]})))}catch{return{}}}var N0=new Set;async function C1(q,x,X){let Q=await R1(),P=/^:(\d+)(?:\.\d+)?$/.exec(Q.DISPLAY??"")?.[1];if(!P||`:${P}`===B8||Q.WAYLAND_DISPLAY||Q.XDG_SESSION_TYPE==="wayland")return null;let b={display:`:${P}`,xauthority:Q.XAUTHORITY??_(q,".Xauthority"),rfbSocket:_(x,`rfb-${P}.sock`)},J=`${b.display} ${b.xauthority}`;if(N0.has(J)||!await s({path:`/tmp/.X11-unix/X${P}`},!1))return null;let y={HOME:q,PATH:"/usr/local/bin:/usr/bin:/bin",DISPLAY:b.display,XAUTHORITY:b.xauthority};if(await R0(X,b,x,`x11vnc-${P}.log`,y))return{...b,sound:null};return N0.add(J),process.stderr.write(`Reason worker: your screen ${b.display} could not be served; using the virtual desktop
179
179
  `),null}function S1(q,x){let X=`chromium --no-first-run --no-default-browser-check${process.geteuid?.()===0?" --no-sandbox":""} %U`,Q=[["terminal","xterm"],["files","pcmanfm"]].filter(([,b])=>!B0(`/usr/bin/${b}`)).map(([b])=>b),P=Rq({root:q,display:x,screen:t8,browserExec:X,absent:Q});for(let b of["","openbox","tint2","picom"])D8(_(q,b));for(let[b,J]of Object.entries(P.files))o8(_(q,b),J,{mode:384});for(let[b,J]of Object.entries(Dq))o8(_(q,`ara-${b}`),Q1(J),{mode:384});return{root:q,openboxConfig:_(q,"openbox","rc.xml"),start:P.start}}async function Z1(q,x){let X=[`ROOT=${JSON.stringify(q.root)}`,...q.start,"openbox --reconfigure >/dev/null 2>&1 || true"].join(`
180
180
  `);await new Promise((Q)=>{let P=T0("/bin/sh",["-c",X],{stdio:"ignore",env:{...x,PATH:"/usr/bin:/bin"}}),b=setTimeout(()=>{P.kill(),Q()},R8);P.once("error",()=>{clearTimeout(b),Q()}),P.once("exit",()=>{clearTimeout(b),Q()})})}async function oX(q,x={}){let X=x.now??Date.now,Q=y1(q.payload,X());if(q.signal.throwIfAborted(),!Q.video)throw new M("display_video_required","Reason desktops stream as video now; this request came without it.");let P=x.platform??process.platform;if(P!=="linux"&&P!=="darwin")throw new M("display_video_unsupported","This machine does not serve desktop video.");let b=Q.video,J=(x.video?.desktop??(P==="darwin"?async()=>oq:B1))();return await A1(q.signal,Q,x,X,(y)=>Q0(y,{request:b,desktop:J,...Q.viewer?{viewer:Q.viewer}:{},viewerSameNetwork:Q.viewer_same_network===!0},x.video),(y)=>T8({type:"error",code:y}))}function A1(q,x,X,Q,P,b){let J=Q();return new Promise((y,C)=>{let W=null,j=!1,R=!1,Z,B,Y,w=!1,N=null,D=(A)=>{if(R)return;if(N)A=N;R=!0,clearTimeout(Z),clearTimeout(B),q.removeEventListener("abort",F),Y?.close();try{W?.close(1000,"display_session_over")}catch{}if("error"in A){C(A.error);return}y({reason:A.reason,...Y?.summary(),duration_ms:Math.max(0,Q()-J)})},G=()=>D({error:new M("display_relay_unavailable","Reason could not reach the desktop relay.")}),F=()=>{let A=q.reason;D({error:A instanceof M?A:new M("cancelled","Reason closed the desktop session.")})},O=()=>{if(!N||!W)return;let A=N.error;try{W.send(b(A instanceof M?A.code:"display_unavailable"))}catch{}D(N)};if(Y=P({get done(){return R||N!==null},get open(){return j&&!R&&N===null},get bufferedAmount(){return W?.bufferedAmount??0},send(A){if(R||N||!j||!W)return;try{W.send(A)}catch{D({reason:"relay_closed"})}},end:(A)=>{if(R||N)return;if(!("error"in A)){D(A);return}if(N=A,w&&j)O()}}),R){Y.close();return}if(q.aborted){F();return}q.addEventListener("abort",F,{once:!0}),Z=setTimeout(()=>D({reason:"session_expired"}),Math.max(1,Date.parse(x.expires_at)-Q())),B=setTimeout(()=>D({reason:"viewer_absent"}),X.viewerWaitMs??N1);try{W=(X.connect??j0)(x.relay_url,(X.loadProxy??U0)()?.url)}catch{G();return}W.binaryType="arraybuffer",W.onopen=()=>{if(R||!W)return;j=!0,Y?.opened()},W.onmessage=(A)=>{if(R)return;let f=A.data,I=f instanceof ArrayBuffer?new Uint8Array(f):ArrayBuffer.isView(f)?new Uint8Array(f.buffer,f.byteOffset,f.byteLength):null;if(!I||I.byteLength===0)return;if(clearTimeout(B),w=!0,N){O();return}Y?.received(I)},W.onclose=()=>{if(R)return;if(!j){G();return}D({reason:"relay_closed"})},W.onerror=()=>{if(R||j)return;G()}})}
181
- export{_8 as Ce,f1 as De,p1 as Ee,r as Fe,j8 as Ge,HX as He,J0 as Ie,Cq as Je,zq as Ke,k as Le,UX as Me,LX as Ne,yX as Oe,J1 as Pe,B8 as Qe,y1 as Re,j1 as Se,nX as Te,D8 as Ue,B1 as Ve,oX as We};
181
+ export{_8 as Ee,f1 as Fe,p1 as Ge,r as He,j8 as Ie,HX as Je,J0 as Ke,Cq as Le,zq as Me,k as Ne,UX as Oe,LX as Pe,yX as Qe,J1 as Re,B8 as Se,y1 as Te,j1 as Ue,nX as Ve,D8 as We,B1 as Xe,oX as Ye};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Hd as _J,le as CJ,zd as UJ}from"./vm-hands-entry-lite-bbc5r4y1.js";import{createHash as y,randomBytes as zJ}from"crypto";import{closeSync as LJ,fsyncSync as qJ,mkdirSync as RJ,openSync as NJ,renameSync as fJ,rmSync as mJ,statSync as DJ,writeSync as AJ,constants as V}from"fs";import{join as o}from"path";var bJ=1;var d=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function KJ(J){if(J.environment!==void 0||J.payload.environment!==void 0)throw new W("vm_hands_bind_invalid","bind carries a plaintext environment");if(J.payload.vm_hands_env_deferred===!0&&J.environment_sealed!==void 0)throw new W("vm_hands_bind_invalid","split bind carries an environment");return J.environment_sealed!==void 0}function jJ(J,Z){let{payload:z,authority:K}=J;if(!z||typeof z!=="object"||Array.isArray(z)||!K||typeof K!=="object"||Array.isArray(K)||!Z.deviceId||!Z.rootId||z.run_id!==Z.runId||z.device_id!==Z.deviceId||K.device_id!==Z.deviceId||z.root_id!==Z.rootId||Z.snapshotId!==void 0&&z.snapshot_id!==Z.snapshotId)throw new W("vm_hands_env_invalid","environment does not match this Hands");return z}function xJ(J){if(J.capability!=="hands.connect")throw new W("vm_hands_bind_invalid","not a hands.connect claim");let Z=J.payload;return{kind:"vm_hands.bind",v:1,bind_id:J.attempt_id,attempt_id:J.attempt_id,attempt_token:J.attempt_token,run_id:J.run_id,session_id:typeof Z.workspace_id==="string"&&d.test(Z.workspace_id)?Z.workspace_id:J.run_id,brain_generation:Z.target_generation,fence_id:Z.target_fence_id,lease_until:J.lease_until,policy:{agent_profile:"",confinement_key:String(Z.hands_confinement??""),browser_egress:Z.browser_egress??null,policy_digest:Z.vm_hands_policy_digest},cwd:typeof Z.cwd==="string"?Z.cwd:"",claim:J,env:KJ(J)?J.environment_sealed:null}}class W extends Error{code;constructor(J,Z){super(Z);this.code=J}}var H=(J)=>Buffer.from(J instanceof Uint8Array?J:new Uint8Array(J)).toString("base64url"),I=(J)=>new Uint8Array(Buffer.from(J,"base64url"));function R(J){if(J===null||typeof J!=="object")return JSON.stringify(J);if(Array.isArray(J))return`[${J.map(R).join(",")}]`;return`{${Object.keys(J).sort().map((Z)=>`${JSON.stringify(Z)}:${R(J[Z])}`).join(",")}}`}async function QZ(J){let Z=await crypto.subtle.importKey("pkcs8",I(J.device_key.pkcs8),{name:"ECDSA",namedCurve:"P-256"},!1,["sign"]),z=I(J.device_key.spki),K=await crypto.subtle.generateKey({name:"ECDH",namedCurve:"P-256"},!1,["deriveKey"]),U=new Uint8Array(await crypto.subtle.exportKey("spki",K.publicKey)),L=y("sha256").update(z).digest("base64url");return{signing:{privateKey:Z},agreement:K,signingSpki:z,agreementSpki:U,fingerprint:L}}var cJ=4;class pJ{init;keys;hooks;options;identity="identity_free";lastBrainGeneration=new Map;bound=new Map;binding=new Map;unbinding=new Set;servedRun=!1;verifiedSinceRun=!1;bootKillPending=!1;unverified=new Set;structural=Promise.resolve();exclusive(J){let Z=this.structural.then(J,J);return this.structural=Z.catch(()=>{return}),Z}constructor(J,Z,z,K){this.init=J;this.keys=Z;this.hooks=z;this.options=K;if(!d.test(J.workspace_id)&&!/^ws-[a-z0-9]{8,64}$/.test(J.workspace_id))throw new W("vm_hands_layout_invalid","bad workspace id");if(!Number.isSafeInteger(J.instance_generation)||J.instance_generation<1)throw new W("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(J){for(let Z of this.bound.values())if(Z.runId===J)return!0;return!1}bindIdForRun(J){for(let Z of this.bound.values())if(Z.runId===J)return Z.bindId;return null}get liveBindIds(){return[...new Set([...this.bound.keys(),...this.binding.keys(),...this.unbinding])]}async environmentInstalled(J,Z,z){for(let K=Date.now()+Z;;){let U=this.bound.get(J);if(!U)return!1;if(U.envInstalled)return!0;if(Date.now()>=K||z?.aborted)return!1;await new Promise((L)=>setTimeout(L,25))}}canSpawn(J){for(let Z of this.bound.values())if(Z.runId===J)return Z.envInstalled;return!1}async registerFrame(J){if(this.identity!=="identity_free")throw new W("vm_hands_register_twice","already registered");if(typeof J!=="string"||J.length<16||J.length>256)throw new W("vm_hands_challenge_invalid","bad register challenge");let Z={challenge:J,t:"register",v:bJ,workspace_id:this.init.workspace_id,instance_generation:this.init.instance_generation,credential:this.init.credential,device_public_key:H(this.keys.signingSpki),env_public_key:H(this.keys.agreementSpki),key_fingerprint:this.keys.fingerprint,manifest_digest:this.init.manifest_digest,nonce:H(zJ(32)),timestamp_ms:(this.options.now??Date.now)(),vm_hands_attest_hold:!0},z=await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},this.keys.signing.privateKey,new TextEncoder().encode(R(Z)));return{...Z,device_signature:H(z)}}async helloFrame(J,Z){if(this.identity==="identity_free")throw new W("vm_hands_not_registered","hello before register");let z=String((this.options.now??Date.now)()),K=H(zJ(32)),U=CJ({method:"GET",pathAndQuery:UJ,timestamp:z,nonce:K,challenge:J,bodySha256:y("sha256").update("").digest("hex")}),L=new Uint8Array(await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},this.keys.signing.privateKey,new Uint8Array(U)));return{t:"hello",timestamp:z,nonce:K,signature:H(lJ(L)),...Z?{vm_hands_previous_connection:Z}:{}}}registered(){if(this.identity!=="identity_free")throw new W("vm_hands_register_unexpected","registered twice");this.identity="registered"}async bind(J){if(this.identity!=="registered")throw new W("vm_hands_not_registered","bind before register");if(J.kind!=="vm_hands.bind"||J.v!==1)throw new W("vm_hands_bind_invalid","bad bind");for(let z of[J.bind_id,J.attempt_id,J.run_id,J.session_id,J.fence_id])if(!d.test(z))throw new W("vm_hands_bind_invalid","bad id");if(!Number.isSafeInteger(J.brain_generation)||J.brain_generation<=(this.lastBrainGeneration.get(J.run_id)??0))throw new W("vm_hands_generation_stale","brain generation not strictly higher");if(J.env&&(J.env.aad!==J.bind_id||J.env.alg!=="ECDH-P256+A256GCM"))throw new W("vm_hands_bind_invalid","bad env envelope");if(!/^[0-9a-f]{64}$/.test(J.policy.policy_digest))throw new W("vm_hands_bind_invalid","bad policy or nonce");if(y("sha256").update(R({hands_confinement:J.policy.confinement_key||null,browser_egress:J.policy.browser_egress??null})).digest("hex")!==J.policy.policy_digest)throw new W("vm_hands_policy_mismatch","policy digest does not match the claim");if(this.liveBindIds.includes(J.bind_id)||[...this.bound.values()].some((z)=>z.runId===J.run_id)||[...this.binding.values()].includes(J.run_id))throw new W("vm_hands_busy","this run already holds a bind here");if(this.liveBindIds.length>=cJ)throw new W("vm_hands_busy","every bind slot is held");return this.lastBrainGeneration.set(J.run_id,J.brain_generation),this.binding.set(J.bind_id,J.run_id),this.exclusive(()=>this.setUp(J))}async setUp(J){let Z=[...this.bound.keys()],z=null,K=!1;try{if(Z.length===0){if(this.bootKillPending&&!this.servedRun){try{await this.hooks.killProbe()}catch{throw new W("vm_hands_kill_unverified","the boot's scoped kill did not verify")}this.bootKillPending=!1}if(this.servedRun&&!this.verifiedSinceRun)await this.hooks.killAndVerifyPayload(),this.unverified.clear()}else if(this.unverified.size>0)await this.hooks.killAndVerifyPayload({keep:Z}),this.unverified.clear();this.verifiedSinceRun=!1,this.servedRun=!0,K=!0;let{launchId:U,applied:L,readyData:P}=await this.hooks.startExecutor({bindId:J.bind_id,sessionId:J.session_id,policyDigest:J.policy.policy_digest,confinementKey:J.policy.confinement_key,browserEgress:J.policy.browser_egress,cwd:J.cwd,claim:J.claim}),E=this.hooks.restatLayout(),A=null;if(J.env){let O=J.claim?.owner??{},g=jJ(await this.openSealed(J.env,J.bind_id),{runId:J.run_id,deviceId:typeof O.device_id==="string"?O.device_id:"",rootId:J.claim?.root_id??""});A=this.hooks.installEnvironment(J.bind_id,g),z=this.writeJobEnvRootOnly(J.bind_id,g)}if(this.unbinding.has(J.bind_id))throw new W("vm_hands_bind_lost","unbound while binding");return this.bound.set(J.bind_id,{bindId:J.bind_id,runId:J.run_id,sessionId:J.session_id,brainGeneration:J.brain_generation,policyDigest:J.policy.policy_digest,launchId:U,envInstalled:A!==null,rootId:J.claim?.root_id??"",envDirectory:z}),this.binding.delete(J.bind_id),{bind_id:J.bind_id,attempt_id:J.attempt_id,attempt_token:J.attempt_token,launch_id:U,snapshot_revision:A,layout:E,...P?{ready_data:P}:{},policy_digest:y("sha256").update(R({hands_confinement:L.hands_confinement??null,browser_egress:L.browser_egress??null})).digest("hex")}}catch(U){if(z)GJ(z);if(K){let P=[...this.bound.keys()];await this.hooks.killAndVerifyPayload({bindId:J.bind_id,keep:P,own:!0}).catch(()=>{this.unverified.add(J.bind_id)}),this.verifiedSinceRun=!1}this.binding.delete(J.bind_id);let L=U&&typeof U==="object"&&"code"in U&&typeof U.code==="string"&&/^[a-z][a-z0-9_]{2,63}$/.test(U.code)?U.code:"vm_hands_bind_failed";throw U instanceof W?U:new W(L,"executor refused the bind")}}async deliverEnvironment(J){let Z=this.bound.get(J.attemptId);if(!Z||this.unbinding.has(J.attemptId))throw new W("vm_hands_not_bound","environment delivered while not bound");if(!d.test(J.attemptId)||typeof J.snapshotId!=="string"||!J.snapshotId||J.snapshotId.length>128||J.snapshotId.includes("/"))throw new W("vm_hands_env_invalid","bad snapshot id");let z=`${J.attemptId}/${J.snapshotId}`;if(J.sealed?.alg!=="ECDH-P256+A256GCM"||J.sealed.aad!==z)throw new W("vm_hands_env_invalid","bad env envelope");let K=jJ(await this.openSealed(J.sealed,z),{runId:Z.runId,deviceId:J.deviceId,rootId:Z.rootId,snapshotId:J.snapshotId}),U=this.hooks.installEnvironment(Z.bindId,K);if(Z.envInstalled=!0,Z.envDirectory)GJ(Z.envDirectory);return Z.envDirectory=null,Z.envDirectory=this.writeJobEnvRootOnly(`${Z.bindId}-r${U}`,K),{snapshot_id:J.snapshotId,installed_revision:U,installed:!0}}async attestFrame(J,Z){if(this.identity==="identity_free")throw new W("vm_hands_not_registered","attest before register");if(!J||J.length>65536)throw new W("vm_hands_attest_invalid","no probe script");return this.exclusive(async()=>{if(this.liveBindIds.length)throw new W("vm_hands_attest_invalid","attest beside a bind");let z=await this.hooks.runProbe({nonce:Z,script:J});try{await this.hooks.killProbe()}catch{this.bootKillPending=!0}return{t:"attest",nonce:Z,exit_code:z.exitCode,markers:z.markers,proof_dir_inode:z.proofDirInode,script_sha256:y("sha256").update(J).digest("hex")}})}executorExited(J){return this.hooks.executorExited?.(J)??new Promise(()=>{})}async boundRefused(J){await this.unbind(J)}async unbind(J){let Z=this.bound.get(J)??null;if(this.unbinding.add(J),this.bound.delete(J),Z)try{this.hooks.freezeBind?.(J)}catch{}return this.exclusive(()=>this.tearDown(J,Z))}async tearDown(J,Z){try{this.bound.delete(J);let z=[...this.bound.keys()].filter((K)=>K!==J);try{await this.hooks.killAndVerifyPayload(z.length?{bindId:J,keep:z}:void 0)}catch(K){throw this.unverified.add(J),this.verifiedSinceRun=!1,K}if(!z.length)this.verifiedSinceRun=!0,this.unverified.clear();if(Z?.envDirectory)GJ(Z.envDirectory);return{bind_id:Z?J:null,killed_verified:!0,shredded:!0,srt_fallbacks:z.length?null:this.hooks.takeSrtFallbacks?.()??null}}finally{this.unbinding.delete(J)}}async openSealed(J,Z){let z=()=>{throw new W("vm_hands_env_invalid","env did not decrypt")},K=await crypto.subtle.importKey("spki",I(J.epk),{name:"ECDH",namedCurve:"P-256"},!1,[]).catch(z),U=await crypto.subtle.deriveKey({name:"ECDH",public:K},this.keys.agreement.privateKey,{name:"AES-GCM",length:256},!1,["decrypt"]),L=await crypto.subtle.decrypt({name:"AES-GCM",iv:I(J.iv),additionalData:new TextEncoder().encode(Z)},U,I(J.ct)).catch(z),P=JSON.parse(new TextDecoder().decode(L));if(!P||typeof P!=="object"||Array.isArray(P))throw new W("vm_hands_env_invalid","env not an object");return P}writeJobEnvRootOnly(J,Z){let z=o(this.options.envRoot,`bind-${J}`);RJ(z,{mode:448});let K=DJ(z);if(!K.isDirectory()||(K.mode&63)!==0||K.uid!==(process.getuid?.()??-1))throw new W("vm_hands_env_dir_unsafe","env directory is not root's 0700");let U=Z.variables&&typeof Z.variables==="object"?Z.variables:{},L=Object.entries(U).filter(([A,O])=>/^[A-Za-z_][A-Za-z0-9_]*$/.test(A)&&typeof O==="string").map(([A,O])=>`export ${A}='${String(O).replaceAll("'","'\\''")}'`).join(`
2
+ import{Bd as UJ,Jd as _J,ne as CJ}from"./vm-hands-entry-lite-36xzwsxn.js";import{createHash as y,randomBytes as zJ}from"crypto";import{closeSync as LJ,fsyncSync as qJ,mkdirSync as RJ,openSync as NJ,renameSync as fJ,rmSync as mJ,statSync as DJ,writeSync as AJ,constants as V}from"fs";import{join as o}from"path";var bJ=1;var d=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function KJ(J){if(J.environment!==void 0||J.payload.environment!==void 0)throw new W("vm_hands_bind_invalid","bind carries a plaintext environment");if(J.payload.vm_hands_env_deferred===!0&&J.environment_sealed!==void 0)throw new W("vm_hands_bind_invalid","split bind carries an environment");return J.environment_sealed!==void 0}function jJ(J,Z){let{payload:z,authority:K}=J;if(!z||typeof z!=="object"||Array.isArray(z)||!K||typeof K!=="object"||Array.isArray(K)||!Z.deviceId||!Z.rootId||z.run_id!==Z.runId||z.device_id!==Z.deviceId||K.device_id!==Z.deviceId||z.root_id!==Z.rootId||Z.snapshotId!==void 0&&z.snapshot_id!==Z.snapshotId)throw new W("vm_hands_env_invalid","environment does not match this Hands");return z}function xJ(J){if(J.capability!=="hands.connect")throw new W("vm_hands_bind_invalid","not a hands.connect claim");let Z=J.payload;return{kind:"vm_hands.bind",v:1,bind_id:J.attempt_id,attempt_id:J.attempt_id,attempt_token:J.attempt_token,run_id:J.run_id,session_id:typeof Z.workspace_id==="string"&&d.test(Z.workspace_id)?Z.workspace_id:J.run_id,brain_generation:Z.target_generation,fence_id:Z.target_fence_id,lease_until:J.lease_until,policy:{agent_profile:"",confinement_key:String(Z.hands_confinement??""),browser_egress:Z.browser_egress??null,policy_digest:Z.vm_hands_policy_digest},cwd:typeof Z.cwd==="string"?Z.cwd:"",claim:J,env:KJ(J)?J.environment_sealed:null}}class W extends Error{code;constructor(J,Z){super(Z);this.code=J}}var H=(J)=>Buffer.from(J instanceof Uint8Array?J:new Uint8Array(J)).toString("base64url"),I=(J)=>new Uint8Array(Buffer.from(J,"base64url"));function R(J){if(J===null||typeof J!=="object")return JSON.stringify(J);if(Array.isArray(J))return`[${J.map(R).join(",")}]`;return`{${Object.keys(J).sort().map((Z)=>`${JSON.stringify(Z)}:${R(J[Z])}`).join(",")}}`}async function QZ(J){let Z=await crypto.subtle.importKey("pkcs8",I(J.device_key.pkcs8),{name:"ECDSA",namedCurve:"P-256"},!1,["sign"]),z=I(J.device_key.spki),K=await crypto.subtle.generateKey({name:"ECDH",namedCurve:"P-256"},!1,["deriveKey"]),U=new Uint8Array(await crypto.subtle.exportKey("spki",K.publicKey)),L=y("sha256").update(z).digest("base64url");return{signing:{privateKey:Z},agreement:K,signingSpki:z,agreementSpki:U,fingerprint:L}}var cJ=4;class pJ{init;keys;hooks;options;identity="identity_free";lastBrainGeneration=new Map;bound=new Map;binding=new Map;unbinding=new Set;servedRun=!1;verifiedSinceRun=!1;bootKillPending=!1;unverified=new Set;structural=Promise.resolve();exclusive(J){let Z=this.structural.then(J,J);return this.structural=Z.catch(()=>{return}),Z}constructor(J,Z,z,K){this.init=J;this.keys=Z;this.hooks=z;this.options=K;if(!d.test(J.workspace_id)&&!/^ws-[a-z0-9]{8,64}$/.test(J.workspace_id))throw new W("vm_hands_layout_invalid","bad workspace id");if(!Number.isSafeInteger(J.instance_generation)||J.instance_generation<1)throw new W("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(J){for(let Z of this.bound.values())if(Z.runId===J)return!0;return!1}bindIdForRun(J){for(let Z of this.bound.values())if(Z.runId===J)return Z.bindId;return null}get liveBindIds(){return[...new Set([...this.bound.keys(),...this.binding.keys(),...this.unbinding])]}async environmentInstalled(J,Z,z){for(let K=Date.now()+Z;;){let U=this.bound.get(J);if(!U)return!1;if(U.envInstalled)return!0;if(Date.now()>=K||z?.aborted)return!1;await new Promise((L)=>setTimeout(L,25))}}canSpawn(J){for(let Z of this.bound.values())if(Z.runId===J)return Z.envInstalled;return!1}async registerFrame(J){if(this.identity!=="identity_free")throw new W("vm_hands_register_twice","already registered");if(typeof J!=="string"||J.length<16||J.length>256)throw new W("vm_hands_challenge_invalid","bad register challenge");let Z={challenge:J,t:"register",v:bJ,workspace_id:this.init.workspace_id,instance_generation:this.init.instance_generation,credential:this.init.credential,device_public_key:H(this.keys.signingSpki),env_public_key:H(this.keys.agreementSpki),key_fingerprint:this.keys.fingerprint,manifest_digest:this.init.manifest_digest,nonce:H(zJ(32)),timestamp_ms:(this.options.now??Date.now)(),vm_hands_attest_hold:!0},z=await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},this.keys.signing.privateKey,new TextEncoder().encode(R(Z)));return{...Z,device_signature:H(z)}}async helloFrame(J,Z){if(this.identity==="identity_free")throw new W("vm_hands_not_registered","hello before register");let z=String((this.options.now??Date.now)()),K=H(zJ(32)),U=CJ({method:"GET",pathAndQuery:UJ,timestamp:z,nonce:K,challenge:J,bodySha256:y("sha256").update("").digest("hex")}),L=new Uint8Array(await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},this.keys.signing.privateKey,new Uint8Array(U)));return{t:"hello",timestamp:z,nonce:K,signature:H(lJ(L)),...Z?{vm_hands_previous_connection:Z}:{}}}registered(){if(this.identity!=="identity_free")throw new W("vm_hands_register_unexpected","registered twice");this.identity="registered"}async bind(J){if(this.identity!=="registered")throw new W("vm_hands_not_registered","bind before register");if(J.kind!=="vm_hands.bind"||J.v!==1)throw new W("vm_hands_bind_invalid","bad bind");for(let z of[J.bind_id,J.attempt_id,J.run_id,J.session_id,J.fence_id])if(!d.test(z))throw new W("vm_hands_bind_invalid","bad id");if(!Number.isSafeInteger(J.brain_generation)||J.brain_generation<=(this.lastBrainGeneration.get(J.run_id)??0))throw new W("vm_hands_generation_stale","brain generation not strictly higher");if(J.env&&(J.env.aad!==J.bind_id||J.env.alg!=="ECDH-P256+A256GCM"))throw new W("vm_hands_bind_invalid","bad env envelope");if(!/^[0-9a-f]{64}$/.test(J.policy.policy_digest))throw new W("vm_hands_bind_invalid","bad policy or nonce");if(y("sha256").update(R({hands_confinement:J.policy.confinement_key||null,browser_egress:J.policy.browser_egress??null})).digest("hex")!==J.policy.policy_digest)throw new W("vm_hands_policy_mismatch","policy digest does not match the claim");if(this.liveBindIds.includes(J.bind_id)||[...this.bound.values()].some((z)=>z.runId===J.run_id)||[...this.binding.values()].includes(J.run_id))throw new W("vm_hands_busy","this run already holds a bind here");if(this.liveBindIds.length>=cJ)throw new W("vm_hands_busy","every bind slot is held");return this.lastBrainGeneration.set(J.run_id,J.brain_generation),this.binding.set(J.bind_id,J.run_id),this.exclusive(()=>this.setUp(J))}async setUp(J){let Z=[...this.bound.keys()],z=null,K=!1;try{if(Z.length===0){if(this.bootKillPending&&!this.servedRun){try{await this.hooks.killProbe()}catch{throw new W("vm_hands_kill_unverified","the boot's scoped kill did not verify")}this.bootKillPending=!1}if(this.servedRun&&!this.verifiedSinceRun)await this.hooks.killAndVerifyPayload(),this.unverified.clear()}else if(this.unverified.size>0)await this.hooks.killAndVerifyPayload({keep:Z}),this.unverified.clear();this.verifiedSinceRun=!1,this.servedRun=!0,K=!0;let{launchId:U,applied:L,readyData:P}=await this.hooks.startExecutor({bindId:J.bind_id,sessionId:J.session_id,policyDigest:J.policy.policy_digest,confinementKey:J.policy.confinement_key,browserEgress:J.policy.browser_egress,cwd:J.cwd,claim:J.claim}),E=this.hooks.restatLayout(),A=null;if(J.env){let O=J.claim?.owner??{},g=jJ(await this.openSealed(J.env,J.bind_id),{runId:J.run_id,deviceId:typeof O.device_id==="string"?O.device_id:"",rootId:J.claim?.root_id??""});A=this.hooks.installEnvironment(J.bind_id,g),z=this.writeJobEnvRootOnly(J.bind_id,g)}if(this.unbinding.has(J.bind_id))throw new W("vm_hands_bind_lost","unbound while binding");return this.bound.set(J.bind_id,{bindId:J.bind_id,runId:J.run_id,sessionId:J.session_id,brainGeneration:J.brain_generation,policyDigest:J.policy.policy_digest,launchId:U,envInstalled:A!==null,rootId:J.claim?.root_id??"",envDirectory:z}),this.binding.delete(J.bind_id),{bind_id:J.bind_id,attempt_id:J.attempt_id,attempt_token:J.attempt_token,launch_id:U,snapshot_revision:A,layout:E,...P?{ready_data:P}:{},policy_digest:y("sha256").update(R({hands_confinement:L.hands_confinement??null,browser_egress:L.browser_egress??null})).digest("hex")}}catch(U){if(z)GJ(z);if(K){let P=[...this.bound.keys()];await this.hooks.killAndVerifyPayload({bindId:J.bind_id,keep:P,own:!0}).catch(()=>{this.unverified.add(J.bind_id)}),this.verifiedSinceRun=!1}this.binding.delete(J.bind_id);let L=U&&typeof U==="object"&&"code"in U&&typeof U.code==="string"&&/^[a-z][a-z0-9_]{2,63}$/.test(U.code)?U.code:"vm_hands_bind_failed";throw U instanceof W?U:new W(L,"executor refused the bind")}}async deliverEnvironment(J){let Z=this.bound.get(J.attemptId);if(!Z||this.unbinding.has(J.attemptId))throw new W("vm_hands_not_bound","environment delivered while not bound");if(!d.test(J.attemptId)||typeof J.snapshotId!=="string"||!J.snapshotId||J.snapshotId.length>128||J.snapshotId.includes("/"))throw new W("vm_hands_env_invalid","bad snapshot id");let z=`${J.attemptId}/${J.snapshotId}`;if(J.sealed?.alg!=="ECDH-P256+A256GCM"||J.sealed.aad!==z)throw new W("vm_hands_env_invalid","bad env envelope");let K=jJ(await this.openSealed(J.sealed,z),{runId:Z.runId,deviceId:J.deviceId,rootId:Z.rootId,snapshotId:J.snapshotId}),U=this.hooks.installEnvironment(Z.bindId,K);if(Z.envInstalled=!0,Z.envDirectory)GJ(Z.envDirectory);return Z.envDirectory=null,Z.envDirectory=this.writeJobEnvRootOnly(`${Z.bindId}-r${U}`,K),{snapshot_id:J.snapshotId,installed_revision:U,installed:!0}}async attestFrame(J,Z){if(this.identity==="identity_free")throw new W("vm_hands_not_registered","attest before register");if(!J||J.length>65536)throw new W("vm_hands_attest_invalid","no probe script");return this.exclusive(async()=>{if(this.liveBindIds.length)throw new W("vm_hands_attest_invalid","attest beside a bind");let z=await this.hooks.runProbe({nonce:Z,script:J});try{await this.hooks.killProbe()}catch{this.bootKillPending=!0}return{t:"attest",nonce:Z,exit_code:z.exitCode,markers:z.markers,proof_dir_inode:z.proofDirInode,script_sha256:y("sha256").update(J).digest("hex")}})}executorExited(J){return this.hooks.executorExited?.(J)??new Promise(()=>{})}async boundRefused(J){await this.unbind(J)}async unbind(J){let Z=this.bound.get(J)??null;if(this.unbinding.add(J),this.bound.delete(J),Z)try{this.hooks.freezeBind?.(J)}catch{}return this.exclusive(()=>this.tearDown(J,Z))}async tearDown(J,Z){try{this.bound.delete(J);let z=[...this.bound.keys()].filter((K)=>K!==J);try{await this.hooks.killAndVerifyPayload(z.length?{bindId:J,keep:z}:void 0)}catch(K){throw this.unverified.add(J),this.verifiedSinceRun=!1,K}if(!z.length)this.verifiedSinceRun=!0,this.unverified.clear();if(Z?.envDirectory)GJ(Z.envDirectory);return{bind_id:Z?J:null,killed_verified:!0,shredded:!0,srt_fallbacks:z.length?null:this.hooks.takeSrtFallbacks?.()??null}}finally{this.unbinding.delete(J)}}async openSealed(J,Z){let z=()=>{throw new W("vm_hands_env_invalid","env did not decrypt")},K=await crypto.subtle.importKey("spki",I(J.epk),{name:"ECDH",namedCurve:"P-256"},!1,[]).catch(z),U=await crypto.subtle.deriveKey({name:"ECDH",public:K},this.keys.agreement.privateKey,{name:"AES-GCM",length:256},!1,["decrypt"]),L=await crypto.subtle.decrypt({name:"AES-GCM",iv:I(J.iv),additionalData:new TextEncoder().encode(Z)},U,I(J.ct)).catch(z),P=JSON.parse(new TextDecoder().decode(L));if(!P||typeof P!=="object"||Array.isArray(P))throw new W("vm_hands_env_invalid","env not an object");return P}writeJobEnvRootOnly(J,Z){let z=o(this.options.envRoot,`bind-${J}`);RJ(z,{mode:448});let K=DJ(z);if(!K.isDirectory()||(K.mode&63)!==0||K.uid!==(process.getuid?.()??-1))throw new W("vm_hands_env_dir_unsafe","env directory is not root's 0700");let U=Z.variables&&typeof Z.variables==="object"?Z.variables:{},L=Object.entries(U).filter(([A,O])=>/^[A-Za-z_][A-Za-z0-9_]*$/.test(A)&&typeof O==="string").map(([A,O])=>`export ${A}='${String(O).replaceAll("'","'\\''")}'`).join(`
3
3
  `)+`
4
4
  `,P=o(z,`.job.env.${zJ(8).toString("hex")}`),E=NJ(P,V.O_WRONLY|V.O_CREAT|V.O_EXCL|V.O_NOFOLLOW,384);try{AJ(E,L),qJ(E)}finally{LJ(E)}return fJ(P,o(z,"job.env")),z}}function GJ(J){try{let Z=o(J,"job.env"),z=DJ(Z).size,K=NJ(Z,V.O_WRONLY|V.O_NOFOLLOW);try{AJ(K,Buffer.alloc(z)),qJ(K)}finally{LJ(K)}}catch{}mJ(J,{recursive:!0,force:!0})}function lJ(J){if(J.length!==64)throw new W("vm_hands_signature_invalid","unexpected ECDSA signature length");let Z=(U)=>{let L=0;while(L<U.length-1&&U[L]===0)L++;let P=U.subarray(L),E=P[0]&128?Uint8Array.of(0,...P):P;return Uint8Array.of(2,E.length,...E)},z=Z(J.subarray(0,32)),K=Z(J.subarray(32));return Uint8Array.of(48,z.length+K.length,...z,...K)}import{randomUUID as uJ}from"crypto";var oJ="/app/local-runtime/session?register=vm_hands_v1",dJ="/app/local-runtime",MJ=25000,rJ=20000,iJ=1e4,TJ=5000,sJ=new Set(["pty.start","jobs.control","preview.serve.v1","display.stream.v1"]),YJ=75000,aJ=2000,nJ=1e4,r=20000;function EJ(J,Z){return typeof J==="string"&&/^[A-Za-z0-9._:-]{1,160}$/.test(J)?J:Z}class T extends Error{}var tJ=64;async function hJ(J,Z){let z=[...J.modelOps.get(Z)??[]];for(let K of z)K.abort.abort();await Promise.race([Promise.all(z.map((K)=>K.settled)),new Promise((K)=>setTimeout(K,TJ))])}async function eJ(J){let Z=[...J.personTerminals];for(let z of Z)z.abort.abort();if(Z.length)await Promise.race([Promise.all(Z.map((z)=>z.settled)),new Promise((z)=>setTimeout(z,TJ))]);return Z.length}async function f(J,Z,z){return await hJ(J,z),Z.unbind(z)}function i(J){for(let Z of J.outbox?.splice(0)??[])Z.reject(Error("vm_hands_attempt_ended"))}var OJ=15000,JZ=1e4,ZZ=1000;async function jZ(J){let Z=Date.now(),z={deviceId:null,connection:null,turns:new Map,lostAt:0,receipts:[],attest:"pending",attestWaiters:[],modelOps:new Map,personTerminals:new Set,bindsStarting:0},K=J.log??(()=>{}),U=async(L)=>{for(let[P,E]of[...z.turns]){z.turns.delete(P),J.onTurn?.(P,null),i(E);let A=await f(z,J.agent,P).catch(()=>null);if(A)z.receipts.push({turn:E,failure:"vm_hands_bind_lost",unbound:A});K("vm_hands.bound_dropped",{reason:L})}};try{for(let L=0;!J.signal.aborted;L++){let P=await $Z(J,z).catch((A)=>{if(A instanceof W&&z.deviceId===null&&A.code==="vm_hands_no_session"&&Date.now()-Z<nJ)return{closeCode:0,closeReason:"vm_hands_no_session"};if(A instanceof W&&z.deviceId===null)throw A;return{closeCode:0,closeReason:A instanceof Error?A.message:String(A)}});if(K("vm_hands.session_closed",{close_code:P.closeCode,reason:P.closeReason.slice(0,120),registered:z.deviceId!==null}),P.closeCode===4401||z.attest==="refused")return;if(J.signal.aborted)return;if(z.turns.size&&Date.now()-z.lostAt>=YJ)await U("reconnect_deadline");if(z.served)z.served=!1,L=0;let E=P.closeReason==="drain_reconnect"?0:P.closeReason==="vm_hands_no_session"?Math.min(250*2**Math.min(L,5),2000):z.turns.size?Math.min(250*2**Math.min(L,5),5000,Math.max(0,z.lostAt+YJ-Date.now())):Math.min(500*2**L,30000);if(await new Promise((A)=>setTimeout(A,E)),z.turns.size&&Date.now()-z.lostAt>=YJ)await U("reconnect_deadline")}}finally{await U("session_ended")}}async function $Z(J,Z){let z=Z.deviceId,K=J.log??(()=>{}),U=z?`/app/local-runtime/session?device_id=${encodeURIComponent(z)}`:oJ,L=`${J.apiOrigin.replace(/^http/,"ws")}${U}`,P=new WebSocket(L),E=0,A="",O=new Map,g=[],m=null,wJ=new Promise(($)=>{P.onclose=(Q)=>{E=Q.code,A=Q.reason;for(let G of O.values())G.reject(new T(`session closed ${Q.code}`));for(let G of Z.attestWaiters.splice(0))G(!1);O.clear(),$()}});P.onmessage=($)=>{let Q;try{Q=JSON.parse(String($.data))}catch{P.close(4400);return}if(Q.t==="res"){let G=Q;O.get(G.id)?.resolve({status:G.status,body:G.body}),O.delete(G.id);return}if(Q.t==="reconnect"){let G=Math.max(0,Math.min(Number(Q.after_ms)||0,ZZ));K("vm_hands.drain_reconnect",{after_ms:G}),setTimeout(()=>{try{P.close(4001,"drain_reconnect")}catch{}},G).unref?.();return}if(!m?.(Q))g.push(Q)};let b=($,Q)=>new Promise((G,X)=>{let j=g.findIndex((C)=>$.includes(C.t));if(j>=0){G(g.splice(j,1)[0]);return}let q=setTimeout(()=>{m=null,X(new W("vm_hands_no_register",`no ${$.join("/")} in ${Q} ms`))},Q);m=(C)=>{if(!$.includes(C.t))return!1;return clearTimeout(q),m=null,G(C),!0}}),c=($)=>P.send(JSON.stringify($)),h=($,Q)=>new Promise((G,X)=>{if(P.readyState!==WebSocket.OPEN){X(new T("session closed"));return}let j=uJ(),q=typeof Q.wait_ms==="number"?Q.wait_ms:0,C=setTimeout(()=>{if(!O.delete(j))return;X(new T(`no answer to ${$.split("/").pop()} in ${q+OJ} ms`)),P.close(4000,"request_timeout")},q+OJ);O.set(j,{reject:(Y)=>{clearTimeout(C),X(Y)},resolve:({status:Y,body:F})=>{clearTimeout(C);let B=null;try{B=F?JSON.parse(F):null}catch{}G({status:Y,json:B})}}),c({t:"req",id:j,path:`${dJ}${$}`,body:JSON.stringify(Q)})}),QJ=()=>P.close(1001,"stopping");J.signal.addEventListener("abort",QJ,{once:!0});let s,p=new Map,l=new Map,a=!1,n=new Set,t=new Set,e=Promise.resolve(),u=!1;try{await new Promise((Y,F)=>{let B=setTimeout(()=>F(Error("session open timeout")),JZ);P.onopen=()=>{clearTimeout(B),K("vm_hands.ws_open",{}),Y()},P.onerror=()=>{clearTimeout(B),F(Error("session socket error"))}});let $=await b(["challenge"],5000);K("vm_hands.challenge",{});let Q=[],G=null,X;if(z){c(await J.agent.helloFrame($.challenge,Z.connection));let Y=await b(["ready"],1e4);if(typeof Y.vm_hands_connection==="string")Z.connection=Y.vm_hands_connection;if(X={device_id:z,...Y.cadence?{cadence:Y.cadence}:{}},typeof Y.vm_hands_probe_script==="string"){if(G=Y.vm_hands_probe_script,u=!0,J.agent.phase==="registered"&&!Z.turns.size)Z.attest="pending"}Z.served=!0,K("vm_hands.reconnected",{device_id:z});let F=Array.isArray(Y.vm_hands_binds)?Y.vm_hands_binds:Y.vm_hands_bind?[Y.vm_hands_bind]:[];for(let[B,x]of[...Z.turns]){if(F.some((N)=>N&&N.operation_id===x.claim.operation_id&&N.attempt_id===x.claim.attempt_id)){Q.push(x),K("vm_hands.bound_resumed",{operation_id:x.claim.operation_id});continue}Z.turns.delete(B),J.onTurn?.(B,null),i(x);let D=await f(Z,J.agent,B).catch(()=>null);if(D)Z.receipts.push({turn:x,failure:"vm_hands_bind_lost",unbound:D});K("vm_hands.bound_dropped",{reason:"not_named_on_reconnect"})}}else{c(await J.agent.registerFrame($.challenge)),K("vm_hands.register_sent",{});let Y=await b(["registered","register_refused"],1e4);if(Y.t==="register_refused")throw new W(Y.code,"register refused");J.agent.registered();let F=Y;if(X=F,Z.deviceId=F.device_id,typeof F.vm_hands_connection==="string")Z.connection=F.vm_hands_connection;if(typeof F.vm_hands_probe_script==="string"){if(G=F.vm_hands_probe_script,u=!0,J.agent.phase==="registered"&&!Z.turns.size)Z.attest="pending"}Z.served=!0,K("vm_hands.registered",{device_id:X.device_id})}let j=async()=>{let Y=await h("/heartbeat",await J.heartbeat());if(Y.status>=300)throw Error(`heartbeat ${Y.status}`)};await j();let q=X.cadence?.presence_interval_ms??30000;if(s=setInterval(()=>{j().catch(()=>P.close())},q),G&&Z.attest!=="accepted"&&J.agent.phase==="registered"&&!Z.turns.size)gJ(G,$.challenge);let C=(Y,F)=>{l.set(Y,F().catch(async(B)=>{if(await XJ(B,Y),B instanceof T)P.close();else await JJ().catch(()=>{return})}).finally(()=>{l.delete(Y)}))};try{await JJ();for(let Y of Q)Y.flush=()=>FJ(Y),Y.flush(),C(Y.claim.attempt_id,()=>WJ(Y));while(!J.signal.aborted&&P.readyState===WebSocket.OPEN){let Y=await h("/operations/claim",{wait_ms:Math.min(X.cadence?.claim_wait_ms??MJ,MJ)});if(Y.status===204||!Y.json)continue;if(Y.status>=300)throw Error(`claim ${Y.status}`);let F=Y.json;if(F.capability==="hands.connect"){if(l.has(F.attempt_id)){_({claim:F,eventSeq:0}).complete("failed",{error_code:"vm_hands_busy"}).catch(()=>{return});continue}C(F.attempt_id,()=>SJ(F))}else HJ(F).catch(()=>{return})}}catch(Y){await XJ(Y,null)}}finally{if(s)clearInterval(s);J.signal.removeEventListener("abort",QJ);for(let $ of Z.turns.values())$.flush=null;P.close(),await wJ,await Promise.all([...l.values()]);for(let $ of J.agent.liveBindIds){if(Z.turns.has($))continue;let Q=await f(Z,J.agent,$).catch(()=>null),G=p.get($);if(Q&&G)Z.receipts.push({turn:{...G,eventSeq:G.eventSeq+1},failure:"vm_hands_bind_lost",unbound:Q});K("vm_hands.bound_dropped",{reason:"bound_after_loss"})}for(let $ of n)$.abort()}return{closeCode:E,closeReason:A};async function XJ($,Q){if($ instanceof T){if(!a&&Z.turns.size)Z.lostAt=Date.now();a=!0}else{let G=Q!==null?[Q]:[...new Set([...Z.turns.keys(),...J.agent.liveBindIds])];if(Q===null)a=!0;for(let X of G){let j=Z.turns.get(X);if(Z.turns.delete(X),j)i(j),J.onTurn?.(X,null);if(J.agent.liveBindIds.includes(X)){let q=await f(Z,J.agent,X).catch(()=>null),C=p.get(X)??j;if(q&&C)Z.receipts.push({turn:{...C,eventSeq:C.eventSeq+1},failure:"vm_hands_bind_lost",unbound:q})}}}K("vm_hands.session_lost",{error:$ instanceof Error?$.message:String($),bound_kept:Z.turns.size})}function _($){let Q=$.claim,G={attempt_id:Q.attempt_id,attempt_token:Q.attempt_token},X=encodeURIComponent(Q.operation_id);return{fence:G,op:X,complete:(q,C={})=>h(`/operations/${X}/complete`,{...G,status:q,...C}),emit:(q,C)=>{let Y=($.chain??Promise.resolve()).catch(()=>{return}).then(()=>j(q,C));return $.chain=Y,Y}};async function j(q,C){let Y=$.eventSeq,F=(N)=>h(`/operations/${X}/events`,{...G,event_seq_start:N,events:[{kind:q,payload:{sequence:N,capability:String(Q.capability??"hands.connect"),data:C}}]}),B=Y,x=await F(B),D=x.status===409?x.json?.expected_event_seq:void 0;if(typeof D==="number"&&D===Y+1)x={status:200,json:{duplicate:!0}};else if(typeof D==="number"&&D>=0&&D!==Y)B=D,x=await F(B);if(x.status<300)$.eventSeq=B+1;return x}}function kJ($){return(Q,G)=>new Promise((X,j)=>{if(Z.turns.get($.claim.attempt_id)!==$){j(Error("vm_hands_attempt_ended"));return}if($.outbox??=[],$.outbox.length>=tJ){j(Error("vm_hands_outbox_full"));return}$.outbox.push({kind:Q,data:G,resolve:X,reject:j}),$.flush?.()})}function FJ($){if(t.has($))return;t.add($),(async()=>{try{while($.outbox?.length&&Z.turns.get($.claim.attempt_id)===$&&P.readyState===WebSocket.OPEN){let Q=$.outbox[0],G;try{G=await _($).emit(Q.kind,Q.data)}catch(X){if(X instanceof T)return;G={status:500}}if($.outbox.shift(),G.status<300)Q.resolve();else Q.reject(Error(`${Q.kind} refused ${G.status}`))}}finally{t.delete($)}})()}async function gJ($,Q){try{let G=await J.agent.attestFrame($,Q);if(P.readyState!==WebSocket.OPEN)return;c(G);let X=await b(["attested","attest_refused"],15000);Z.attest=X.t==="attested"?"accepted":"refused";for(let j of Z.attestWaiters.splice(0))j(Z.attest==="accepted");if(K("vm_hands.attest",{result:Z.attest,exit_code:G.exit_code,...X.t==="attest_refused"?{code:String(X.code??"")}:{}}),Z.attest==="refused")P.close(4401,"attest_refused")}catch(G){K("vm_hands.attest_failed",{code:G instanceof W?G.code:"probe_error"});for(let X of Z.attestWaiters.splice(0))X(!1);if(Z.attest!=="accepted")P.close(4000,"attest_unanswered")}}async function SJ($){let Q=u&&Z.attest==="pending",G=$.vm_hands_attest,X=G;if(Z.attest==="refused"){K("vm_hands.claim_attest_refused",{said:typeof G==="string"?G.slice(0,16):typeof G,local:Z.attest}),await _({claim:$,eventSeq:0}).complete("failed",{error_code:"vm_hands_unattested"}).catch(()=>{return});return}if(X==="accepted"){if(!Q&&Z.attest!=="accepted"){Z.attest="accepted";for(let N of Z.attestWaiters.splice(0))N(!0)}}else if(X!=="pending"||!Q&&Z.attest!=="accepted"){K("vm_hands.claim_attest_refused",{said:typeof G==="string"?G.slice(0,16):typeof G,local:Z.attest}),await _({claim:$,eventSeq:0}).complete("failed",{error_code:"vm_hands_unattested"}).catch(()=>{return});return}if(Z.attest!=="accepted"){let N=Date.parse($.lease_until)-Date.now()-5000,ZJ=Math.max(0,Math.min(r,Number.isFinite(N)?N:r));if(!await new Promise((S)=>{let $J=setTimeout(()=>S(!1),ZJ);Z.attestWaiters.push((M)=>{clearTimeout($J),S(M)})})){await _({claim:$,eventSeq:0}).complete("failed",{error_code:"vm_hands_unattested"}).catch(()=>{return});return}}let j={claim:$,eventSeq:0},{complete:q,emit:C}=_(j),Y;try{if($.capability!=="hands.connect")throw new W("vm_hands_bind_invalid","not hands.connect");Y=!KJ($)}catch(N){K("vm_hands.bind_refused",{code:N instanceof W?N.code:"unexpected"}),await q("failed",{error_code:N instanceof W?N.code:"vm_hands_bind_invalid"});return}let F;Z.bindsStarting++;try{let N=await eJ(Z);if(N)K("vm_hands.person_terminals_closed",{count:N});F=await J.agent.bind(xJ($))}catch(N){K("vm_hands.bind_refused",{code:N instanceof W?N.code:"unexpected"}),await q("failed",{error_code:N instanceof W?N.code:"vm_hands_bind_failed"});return}finally{Z.bindsStarting--}let B={...F.ready_data??J.readyData({launchId:F.launch_id,claim:$})};if(Y)delete B.environment_installed;p.set($.attempt_id,{claim:$,launchId:F.launch_id,readyData:B,eventSeq:j.eventSeq,ackSeq:-1});let x=await C("hands.ready",{...B,vm_hands:{layout:F.layout,policy_digest:F.policy_digest,launch_id:F.launch_id}});if(p.delete($.attempt_id),x.status>=300){await hJ(Z,$.attempt_id),await J.agent.boundRefused($.attempt_id),await q("failed",{error_code:EJ(x.json?.error,"vm_hands_probe_failed")});return}let D={claim:$,launchId:F.launch_id,readyData:B,eventSeq:j.eventSeq,ackSeq:-1};Z.turns.set($.attempt_id,D),D.flush=()=>FJ(D),J.onTurn?.($.attempt_id,kJ(D)),await WJ(D)}async function WJ($){let{fence:Q,op:G}=_($),X=null,j=null,q=J.agent.executorExited($.claim.attempt_id).then((C)=>{return j=C,null});J:for(;;){let C=await Promise.race([q,h(`/operations/${G}/heartbeat`,{...Q,control_ack_seq:$.ackSeq,wait_ms:rJ})]);if(!C){X="vm_hands_executor_exited",K("vm_hands.executor_exited",{reason:j});break}if(C.status>=300)break;let Y=(C.json?.controls??[]).slice().sort((F,B)=>F.seq-B.seq);for(let F of Y){if(F.seq<=$.ackSeq)continue;if(F.kind==="operation.cancel"||F.kind==="cancel"){$.ackSeq=F.seq;break J}if(F.kind===_J)try{await vJ($,F.payload??{})}catch(B){if(B instanceof T)throw B;X=B instanceof W?B.code:"environment_unavailable";let x=B&&typeof B==="object"&&"code"in B&&typeof B.code==="string"&&/^[a-z][a-z0-9_]{2,63}$/.test(B.code)?B.code:null;K("vm_hands.environment_refused",{code:X,cause:x});break J}$.ackSeq=F.seq}}await VJ($,X)}async function HJ($){let Q=$,G={claim:Q,eventSeq:0},{complete:X,emit:j,fence:q,op:C}={..._(G)},Y=$.vm_hands_origin==="person"?"person":"model",F=String($.capability??"");if(!J.executeOp){await X("failed",{error_code:"vm_hands_op_unsupported"});return}if($.vm_hands_attest==="accepted"&&Z.attest==="pending"&&!(u&&Z.attest==="pending")){Z.attest="accepted";for(let M of Z.attestWaiters.splice(0))M(!0)}if(Z.attest!=="accepted"){let M=Date.parse(String($.lease_until??""))-Date.now()-5000,w=Z.attest==="refused"?0:Math.max(0,Math.min(r,Number.isFinite(M)?M:r));if(!(w>0&&await new Promise((BJ)=>{let yJ=setTimeout(()=>BJ(!1),w);Z.attestWaiters.push((IJ)=>{clearTimeout(yJ),BJ(IJ)})}))){await X("failed",{error_code:"vm_hands_unattested"});return}}let B=J.agent.bindIdForRun(Q.run_id);if(Y==="model"&&B===null){await X("failed",{error_code:"vm_hands_not_bound"});return}let x=F==="pty.start"&&Y==="person"&&!$.authority;if(x&&(J.agent.liveBindIds.length>0||Z.bindsStarting>0)){await X("failed",{error_code:"vm_hands_bound"});return}if(sJ.has(F)&&!x&&J.agent.liveBindIds.length===0){await X("failed",{error_code:"vm_hands_not_bound"});return}let D=new AbortController;n.add(D);let N,ZJ=new Promise((M)=>{N=M}),v={abort:D,settled:ZJ};if(x)Z.personTerminals.add(v);if(Y==="model"&&B){let M=Z.modelOps.get(B)??new Set;M.add(v),Z.modelOps.set(B,M),await J.agent.environmentInstalled(B,aJ,D.signal)}let S=-1,$J=setInterval(()=>{h(`/operations/${C}/heartbeat`,{...q,control_ack_seq:S,wait_ms:0}).then((M)=>{if(M.status>=300){D.abort();return}let w=M.json?.controls??[];for(let k of w)if(S=Math.max(S,k.seq),k.kind==="operation.cancel"||k.kind==="cancel")D.abort()},()=>D.abort())},iJ);try{let M=await J.executeOp({kind:Y,claim:$,...Y==="model"&&B?{bindId:B}:{},signal:D.signal,emit:async(k)=>{await j(k.kind,k.data??{})}}),w=await X(M.status,{...M.result?{result:M.result}:{},...M.error_code?{error_code:EJ(M.error_code,"vm_hands_op_failed")}:{}});K("vm_hands.op",{capability:F,kind:Y,status:M.status,code:M.error_code??null,...w.status>=300?{complete_status:w.status,complete_error:String(w.json?.error??"").slice(0,64)}:{}})}finally{if(clearInterval($J),n.delete(D),B)Z.modelOps.get(B)?.delete(v);Z.personTerminals.delete(v),N()}}async function VJ($,Q){let G=$.claim.attempt_id;if(Z.turns.get(G)===$)Z.turns.delete(G);J.onTurn?.(G,null),i($);let X=await f(Z,J.agent,G);Z.receipts.push({turn:$,failure:Q,unbound:X}),await JJ()}function JJ(){return e=e.then(PJ,PJ),e}async function PJ(){while(Z.receipts.length){let{turn:$,failure:Q,unbound:G}=Z.receipts[0],{complete:X,emit:j}=_($);try{if(await j("hands.stopped",{...$.readyData,reason_code:Q?"failed":"cancelled",killed_verified:G.killed_verified,shredded:G.shredded,...G.srt_fallbacks?{vm_hands_srt_fallbacks:G.srt_fallbacks}:{}}),Q)await X("failed",{error_code:Q});else await X("cancelled",{error_code:"driver_stopped"})}catch(q){if(q instanceof T)return}Z.receipts.shift()}}async function vJ($,Q){let{fence:G,op:X}=_($),j=Q.snapshot_id;if(Q.version!==1||typeof j!=="string"||Object.keys(Q).length!==2)throw new W("vm_hands_env_invalid","invalid environment delivery");let q=await h(`/operations/${X}/environment`,{...G,snapshot_id:j}),C=q.json?.environment_sealed;if(q.status!==200||!C||q.json?.payload!==void 0)throw new W("vm_hands_env_invalid","environment not delivered sealed");let Y=await J.agent.deliverEnvironment({attemptId:$.claim.attempt_id,snapshotId:j,deviceId:Z.deviceId??"",sealed:C});if((await h(`/operations/${X}/environment-ack`,{...G,...Y})).status>=300)throw new W("vm_hands_env_ack_refused","environment ack refused")}}
5
5
  export{QZ as N,pJ as O,jZ as P};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
2
  class o extends Error{code;constructor(a,r){super(r);this.code=a;this.name="LocalCapabilityError"}}
3
- export{o as si};
3
+ export{o as ui};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{u as g0}from"./vm-hands-entry-lite-bfh3cnh2.js";import{v as Q2,x as N7,y as Y4}from"./vm-hands-entry-lite-tt4zgt64.js";import{A as q2,B as V7,C as M4,D as T4,E as u6,F as v0,J as d6,K as I$}from"./vm-hands-entry-lite-5qe562gn.js";import{$ as h1,R as jJ,S as WJ,T as y8,U as f8,V as J6,W as Z6,X as b9,Y as A5,Z as v8,_ as _0,aa as m1,ba as P0,ca as n1,da as R5,ea as p5,fa as t3,ga as b5,ka as w5,ta as Y6,ua as G6,va as K6,wa as B6,xa as k9}from"./vm-hands-entry-lite-1sq7jgg0.js";import{$a as i8,Ab as m2,Ca as o8,Cb as z5,Da as e8,Db as B9,Fb as H5,Ga as a8,Ia as G5,Jb as $6,Kb as X9,La as K5,Qa as N5,Ra as q5,Sa as h8,Ta as m8,Ua as nJ,Va as rJ,Xa as u,Ya as e,Za as s,_a as c,ab as oJ,bb as _1,eb as G3,fb as K3,gb as G7,hb as K7,ib as B7,jb as b0,kb as J0,lb as g,mb as w9,nb as R1,ob as Z2,pb as N0,qb as eJ,vb as d5,xb as H8,za as I6}from"./vm-hands-entry-lite-xv868vfm.js";import{Pb as g8}from"./vm-hands-entry-lite-p7x3vnz5.js";import{Wb as O5}from"./vm-hands-entry-lite-wmxksawm.js";import{cc as B5,dc as U5,kc as V5}from"./vm-hands-entry-lite-3gf1yegq.js";import{qc as H$}from"./vm-hands-entry-lite-8ynztq9j.js";import{Fc as k8}from"./vm-hands-entry-lite-pn6vyghh.js";import{Lc as c$,Mc as X$,Nc as C$,Oc as F1,Pc as l6,Qc as q7,Rc as H7,Sc as L1,Tc as M7,Uc as s9,Vc as T7,Wc as Z3,Xc as T$,Yc as G8,Zc as Q3,bd as C5,ed as Q6,hd as DJ,id as OJ}from"./vm-hands-entry-lite-3c4qwk4d.js";import{_d as w8,ge as f6,he as t$,re as V2,sd as C2,wd as aJ,xd as iJ}from"./vm-hands-entry-lite-bbc5r4y1.js";import{Ee as U7,Fe as n2,Ie as X6,Le as l1,Ne as w7,Oe as k7,Te as S5}from"./vm-hands-entry-lite-q1ekx7k0.js";import{Ze as r1,_e as D5}from"./vm-hands-entry-lite-2c8m8m7v.js";import{bf as o6,ef as I5,ff as x9,hf as u8}from"./vm-hands-entry-lite-ckehp0dy.js";import{uf as t}from"./vm-hands-entry-lite-jjq3xq9z.js";import{bg as w1,cg as G0,dg as B2,eg as N6,fg as q6,gg as r$,hg as W3,ig as k2,jg as z4,lg as y2,mg as k$,ng as f0,og as o$,pg as f2,sg as y$}from"./vm-hands-entry-lite-vn0r1e8c.js";import{wg as Y5}from"./vm-hands-entry-lite-2mhzfg6b.js";import{Ah as z$,Bh as C0,Ch as B4,Dh as Q7,Eh as X7,Gh as A2,Hh as Y7,Ih as E9,Jh as X8,Kh as Y8,Lh as Q1,uh as O$,vh as E1,xh as Q$}from"./vm-hands-entry-lite-70d6f5r9.js";import{Mh as U0,Oh as vJ}from"./vm-hands-entry-lite-p9eyqdq7.js";import{ki as U}from"./vm-hands-entry-lite-6z2g0td2.js";import{ni as tJ}from"./vm-hands-entry-lite-0zr461f9.js";import{si as h0}from"./vm-hands-entry-lite-ypcqvygf.js";import{yi as JB}from"./vm-hands-entry-lite-45cnnd8e.js";import{spawn as _7,spawnSync as ZB}from"child_process";import{closeSync as F7,mkdirSync as QB,openSync as L7,readdirSync as XB,realpathSync as Y$,rmSync as W1}from"fs";import{hostname as YB}from"os";import{dirname as a9,join as F0,resolve as GB}from"path";import{createHash as f7}from"crypto";import{unlinkSync as h7}from"fs";import{platform as m7}from"os";import{join as v7}from"path";var G4=U.discriminatedUnion("store",[U.strictObject({version:U.literal(1),store:U.literal("keychain")}),U.strictObject({version:U.literal(1),store:U.literal("file"),api_key:U.string().min(1).max(4096)})]),w$=($)=>v7($,"api-key.json");function L$($){let J=f7("sha256").update(`reason-connect-api-key
2
+ import{u as g0}from"./vm-hands-entry-lite-k2e3q5qj.js";import{v as Q2,x as N7,y as Y4}from"./vm-hands-entry-lite-m16qf0yy.js";import{A as q2,B as V7,C as M4,D as T4,E as u6,F as v0,J as d6,K as I$}from"./vm-hands-entry-lite-pnkfgnqz.js";import{$ as h1,R as jJ,S as WJ,T as y8,U as f8,V as J6,W as Z6,X as b9,Y as A5,Z as v8,_ as _0,aa as m1,ba as P0,ca as n1,da as R5,ea as p5,fa as t3,ga as b5,ka as w5,ta as Y6,ua as G6,va as K6,wa as B6,xa as k9}from"./vm-hands-entry-lite-y16b538h.js";import{$a as i8,Ab as m2,Ca as o8,Cb as z5,Da as e8,Db as B9,Fb as H5,Ga as a8,Ia as G5,Jb as $6,Kb as X9,La as K5,Qa as N5,Ra as q5,Sa as h8,Ta as m8,Ua as nJ,Va as rJ,Xa as u,Ya as e,Za as s,_a as c,ab as oJ,bb as _1,eb as G3,fb as K3,gb as G7,hb as K7,ib as B7,jb as b0,kb as J0,lb as g,mb as w9,nb as R1,ob as Z2,pb as N0,qb as eJ,vb as d5,xb as H8,za as I6}from"./vm-hands-entry-lite-jy102628.js";import{Pb as g8}from"./vm-hands-entry-lite-7ba3nhgv.js";import{Wb as O5}from"./vm-hands-entry-lite-wmxksawm.js";import{cc as B5,dc as U5,kc as V5}from"./vm-hands-entry-lite-k2cvr710.js";import{qc as H$}from"./vm-hands-entry-lite-8ynztq9j.js";import{Fc as k8}from"./vm-hands-entry-lite-0wyjnvjz.js";import{Lc as c$,Mc as X$,Nc as C$,Oc as F1,Pc as l6,Qc as q7,Rc as H7,Sc as L1,Tc as M7,Uc as s9,Vc as T7,Wc as Z3,Xc as T$,Yc as G8,Zc as Q3,bd as C5,ed as Q6,hd as DJ,id as OJ}from"./vm-hands-entry-lite-2e50z7hj.js";import{ae as w8,ie as f6,je as t$,te as V2,ud as C2,yd as aJ,zd as iJ}from"./vm-hands-entry-lite-36xzwsxn.js";import{Ge as U7,He as n2,Ke as X6,Ne as l1,Pe as w7,Qe as k7,Ve as S5}from"./vm-hands-entry-lite-b38m8a8m.js";import{$e as r1,af as D5}from"./vm-hands-entry-lite-pa111vpq.js";import{df as o6,gf as I5,hf as x9,jf as u8}from"./vm-hands-entry-lite-1w8tvrpq.js";import{wf as t}from"./vm-hands-entry-lite-8dvf3de9.js";import{dg as w1,eg as G0,fg as B2,gg as N6,hg as q6,ig as r$,jg as W3,kg as k2,lg as z4,ng as y2,og as k$,pg as f0,qg as o$,rg as f2,ug as y$}from"./vm-hands-entry-lite-kt418g2w.js";import{yg as Y5}from"./vm-hands-entry-lite-knfh7w3j.js";import{Ch as z$,Dh as C0,Eh as B4,Fh as Q7,Gh as X7,Ih as A2,Jh as Y7,Kh as E9,Lh as X8,Mh as Y8,Nh as Q1,wh as O$,xh as E1,zh as Q$}from"./vm-hands-entry-lite-1xjtcxpn.js";import{Oh as U0,Qh as vJ}from"./vm-hands-entry-lite-9dx3at21.js";import{mi as U}from"./vm-hands-entry-lite-2xh7sjs0.js";import{pi as tJ}from"./vm-hands-entry-lite-0jar357h.js";import{ui as h0}from"./vm-hands-entry-lite-gt5pkv4h.js";import{Ai as JB}from"./vm-hands-entry-lite-mhsv58hw.js";import{spawn as _7,spawnSync as ZB}from"child_process";import{closeSync as F7,mkdirSync as QB,openSync as L7,readdirSync as XB,realpathSync as Y$,rmSync as W1}from"fs";import{hostname as YB}from"os";import{dirname as a9,join as F0,resolve as GB}from"path";import{createHash as f7}from"crypto";import{unlinkSync as h7}from"fs";import{platform as m7}from"os";import{join as v7}from"path";var G4=U.discriminatedUnion("store",[U.strictObject({version:U.literal(1),store:U.literal("keychain")}),U.strictObject({version:U.literal(1),store:U.literal("file"),api_key:U.string().min(1).max(4096)})]),w$=($)=>v7($,"api-key.json");function L$($){let J=f7("sha256").update(`reason-connect-api-key
3
3
  ${$}`).digest("hex");return new r$(B2(),m7(),J)}function L3($,J,Z=L$($)){try{Z.deleteBinding(),Z.createBinding(new TextEncoder().encode(J)),c(w$($),{version:1,store:"keychain"});return}catch(Q){if(!(Q instanceof G0))throw Q}c(w$($),{version:1,store:"file",api_key:J})}function l0($,J=L$($)){if(!u(w$($)))return null;let Z=G4.parse(JSON.parse(s(w$($))));if(Z.store==="file")return Z.api_key;try{let Q=J.loadBinding();return Q?new TextDecoder().decode(Q):null}catch(Q){if(!(Q instanceof G0))throw Q;throw Error("worker_api_key_unreadable")}}function K4($,J=L$($)){if(!u(w$($)))return;if(G4.parse(JSON.parse(s(w$($)))).store==="keychain")try{J.deleteBinding()}catch(Z){if(!(Z instanceof G0))throw Z}h7(w$($))}async function j3($,J){let Z;try{Z=await Y4({env:{REASON_API_KEY:J,REASON_API_URL:$.apiOrigin},fetchImpl:b0($.proxy)})}catch(Q){if(Q instanceof v0&&(Q.status===401||Q.status===403))throw Error("worker_api_key_rejected");throw Q}if(!Z)throw Error("worker_api_key_rejected");if(!Z.scopes.includes("devices:write"))throw Error("worker_api_key_devices_write_required");return Z}import{readdirSync as XZ,renameSync as YZ,rmSync as f$}from"fs";import{join as H0}from"path";import{createHash as g7}from"crypto";import{realpathSync as u7,statSync as d7,unlinkSync as U2}from"fs";import{platform as l7}from"os";import{join as w0}from"path";function d($){return{state:w0(g($),"device.json"),control:w0(g($),"control.json"),lock:w0(g($),"lifecycle.lock"),socket:w0(g($),"control.sock"),daemon:w0(g($),"daemon.json"),releaseCheck:w0(g($),"release-check.json"),updateDeferral:w0(g($),"update-deferral.json"),firstHeartbeat:w0(g($),"first-heartbeat.json")}}var p7=U.object({version:U.literal(1),device_id:U.string().min(1).max(160),offer:U.unknown().optional(),enrollment_ms:U.number().int().nonnegative().max(t$).optional()});function U4($,J,Z){e(g($),!0),c(d($).firstHeartbeat,{version:1,device_id:J,...Z.offer?{offer:Z.offer}:{},...Z.enrollmentMs!==void 0?{enrollment_ms:Z.enrollmentMs}:{}})}function D3($,J){let Z=d($).firstHeartbeat;try{if(!u(Z))return null;let Q=p7.safeParse(JSON.parse(s(Z)));if(U2(Z),!Q.success||Q.data.device_id!==J)return null;let X=V2(Q.data.offer);return{...X?{offer:X}:{},...Q.data.enrollment_ms!==void 0?{enrollmentMs:Q.data.enrollment_ms}:{}}}catch{return null}}function T0($,J=!1){e(g($),J);let Z=["local-device.key","local-device.binding","device.json"].filter((Q)=>{let X=w0(g($),Q);if(!u(X))return!1;return s(X),!0});return $.lifetime==="persistent"&&Z.join()==="device.json"?O3($):new W3(g($))}function N2($,J){T0($,!0),a7($);let Z=J??O3($),Q=new W3(g($));try{Z.deleteBinding(),Z.deleteKey(),Z.createFreshPublicKey()}catch(X){if(X instanceof G0)return Q;throw X}return Q.deleteBinding(),Q.deleteKey(),Z}function O3($){return new r$(B2(),l7(),c7($))}function c7($){let J=z3($);return g7("sha256").update(`reason-worker
4
4
  ${J?.directory??g($)}`).digest("hex")}function I1($,J){c(w0(g($),C1),{version:1,directory:z3($)?.directory??g($),devicePublicKey:J})}var C1="keychain-scope.json";function V4($){return u(w0(g($),C1))}var s7=U.strictObject({version:U.literal(1),directory:U.string().min(1),devicePublicKey:U.string().min(1)});function z3($){let J=w0(g($),C1);if(!u(J))return null;let Z=s7.safeParse(JSON.parse(s(J))),Q=d($).state;if(!Z.success||!u(Q))return null;return JSON.parse(s(Q))?.devicePublicKey===Z.data.devicePublicKey?Z.data:null}function a7($){let J=w0(g($),C1);if(!u(J))return;if(z3($))try{let Z=O3($);Z.deleteBinding(),Z.deleteKey()}catch(Z){if(!(Z instanceof G0))throw Z}U2(J)}function V$($){let J=u7($.workspaceRoot);if(J!==$.workspaceRoot||!d7(J).isDirectory()||!R1(J,$.stateDirectory))throw Error("worker_workspace_not_canonical_or_overlaps_state")}function o($){if(!u(g($)))return null;let J=k$(d($).state,{proofStore:T0($),repair:!1}),Z=J!==null&&B4($.apiOrigin,J.apiOrigin),Q=Z?[N0($),N0({...$,apiOrigin:J.apiOrigin})]:[N0($)];if(J&&(!Q.includes(J.worker?.configDigest??"")||J.worker.lifetime!==$.lifetime||J.apiOrigin!==$.apiOrigin&&!Z||J.roots.length>32||J.roots[0]?.path!==$.workspaceRoot||J.handsSlots!==$.slots))throw Error("worker_config_binding_mismatch");return J}var N4=U.strictObject({version:U.literal(1),drained:U.boolean(),revoked:U.boolean()});function $0($){let J=d($).control;return u(J)?N4.parse(JSON.parse(s(J))):{version:1,drained:!1,revoked:!1}}function I0($,J){c(d($).control,N4.parse(J))}function k0($){let J=T0($);J.deleteBinding(),J.deleteKey();let Z=w0(g($),C1);if(u(Z))U2(Z);let Q=d($).state;if(u(Q))U2(Q)}var i7=U.strictObject({read:U.boolean(),write:U.boolean(),execute:U.boolean(),discover_environment:U.boolean(),expose_mcp:U.literal(!1)}),A3=U.strictObject({version:U.literal(1),organization_id:U.string().min(1).max(160),enrollment_ticket:U.string().min(1).max(4096),code_verifier:U.string().regex(/^[A-Za-z0-9._~-]{43,128}$/),root_fingerprint_key:U.string().regex(/^[a-f0-9]{64}$/),root:U.strictObject({path_fingerprint:U.string().regex(/^[a-f0-9]{64}$/),permissions:i7,execution_mode:U.enum(["confined","host"]).default("confined")}),folders:U.array(U.strictObject({path_fingerprint:U.string().regex(/^[a-f0-9]{64}$/)})).min(1).max(31).optional()}),n7=U.object({device_id:U.string().min(1).max(160),organization_id:U.string().min(1).max(160),auth_scheme:U.literal("p256"),protocol_version:U.literal(2),roots:U.array(U.object({id:U.string().min(1),label:U.string(),path_fingerprint:U.string()})).min(1).max(32),headless:U.object({lifecycle:U.enum(["persistent","ephemeral"]),expires_at:U.iso.datetime({offset:!0})}),first_heartbeat:U.unknown().optional()}),R3=30000;class o0 extends Error{deviceRemoved;constructor($){super("worker_enrollment_rejected");this.deviceRemoved=$}}async function r7($,J,Z=fetch){let Q=await Z(`${$}/app/local-runtime/enroll`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(J),redirect:"error",signal:AbortSignal.timeout(R3)});if(!Q.ok){let X=Q.status===409?await Q.json().catch(()=>null):null;throw new o0(X?.error==="device_revoked")}return Q.json()}async function I3($,J,Z,Q){g0();let X=A3.parse(JSON.parse(s(J)));return e0($,X,Z,Q)}async function e0($,J,Z,Q=(Y,G)=>r7(Y,G,b0($.proxy)),X=performance.now()){let Y=H4($,J,Z),G=await Q($.apiOrigin,{...Y.request,enrollment_ticket:J.enrollment_ticket,code_verifier:J.code_verifier});return Y.receipt(G,X)}async function q4($,J,Z,Q,X=performance.now()){let Y=H4($,J,Z),G=await Q(Y.request,J.code_verifier);return G===null?null:Y.receipt(G,X)}function H4($,J,Z){if(g0(),J.root.execution_mode!==$.executionMode)throw Error("worker_enrollment_mode_mismatch");let Q=y$([$.workspaceRoot],J.root.permissions,Buffer.from(J.root_fingerprint_key,"hex"))[0];if(Q.path!==$.workspaceRoot||Q.pathFingerprint!==J.root.path_fingerprint)throw Error("worker_enrollment_root_mismatch");let X=($.folders??[]).map((K,N)=>{let H=y$([K],J.root.permissions,Buffer.from(J.root_fingerprint_key,"hex"))[0];if(H.path!==K||H.pathFingerprint!==J.folders?.[N]?.path_fingerprint)throw Error("worker_enrollment_root_mismatch");return H});if((J.folders?.length??0)!==X.length)throw Error("worker_enrollment_root_mismatch");let Y=[{...Q,label:"workspace"},...X],G;try{G=Z.loadPublicKey()}catch{G=Z.createFreshPublicKey()}return{request:{device_public_key:G,name:$.name,os:process.platform,architecture:process.arch,reason_runtime_version:t,bridge_version:t,protocol_version:2,capabilities:{supported_operations:[]},roots:Y.map((K)=>({label:K.label,path_fingerprint:K.pathFingerprint,permissions:J.root.permissions}))},receipt(K,N){let H=n7.parse(K);if(H.organization_id!==J.organization_id||H.roots.length!==Y.length||H.roots.some((q,M)=>q.path_fingerprint!==Y[M].pathFingerprint)||H.headless.lifecycle!==$.lifetime||Date.parse(H.headless.expires_at)<=Date.now())throw Error("worker_enrollment_receipt_mismatch");let B=V2(H.first_heartbeat);try{U4($,H.device_id,{...B?{offer:B}:{},enrollmentMs:Math.min(t$,Math.max(0,Math.round(performance.now()-N)))})}catch{}return{version:4,apiOrigin:$.apiOrigin,orgId:H.organization_id,deviceId:H.device_id,devicePublicKey:G,displayName:$.name,registeredAt:new Date().toISOString(),handsSlots:$.slots,worker:{configDigest:N0($),lifetime:$.lifetime,expiresAt:H.headless.expires_at},roots:H.roots.map((q,M)=>({id:q.id,label:q.label,path:Y[M].path,pathFingerprint:q.path_fingerprint,permissions:J.root.permissions}))}}}}import{randomBytes as t7,randomUUID as o7}from"crypto";import{unlinkSync as e7}from"fs";import{join as $Z}from"path";var _4=U.strictObject({version:U.literal(1),install_id:U.uuid(),fingerprint_key:U.string().regex(/^[a-f0-9]{64}$/)}),JZ=U.object({enrollment_ticket:U.string().min(1).max(4096),expires_at:U.iso.datetime({offset:!0}),device_kind:U.literal("headless"),lifecycle:U.enum(["persistent","ephemeral"]),device_expires_at:U.iso.datetime({offset:!0})});function C3($){return JZ.parse($)}var ZZ=U.object({credentialKind:U.enum(["oauth","api_key"]).optional(),apiOrigin:U.url(),clientId:U.string(),accessToken:U.string().min(1).max(32768),refreshToken:U.string().max(32768),expiresAt:U.iso.datetime({offset:!0}),scopes:U.array(U.string().max(128)).max(128),orgId:U.string().min(1).max(160)});function j$($){return q2(E1("REASON_CLI_CHANNEL",$.channel),U0())}async function W$($,J=j$($)){if(!u(J))return null;let Z=ZZ.parse(JSON.parse(s(J)));if(!C0(Z.apiOrigin,$.apiOrigin))throw Error("worker_session_origin_mismatch");if(Z.credentialKind==="api_key")return Date.parse(Z.expiresAt)>Date.now()?Z:null;let Q=b0($.proxy),X=Object.assign((G,V)=>Q(G,{...V,redirect:"error",signal:AbortSignal.timeout(30000)}),{preconnect:fetch.preconnect}),Y=await T4({path:J,fetchImpl:X});if(Y&&!C0(Y.apiOrigin,$.apiOrigin))throw Error("worker_session_origin_mismatch");return Y}async function F4($,J,Z){if(!C0(J.apiOrigin,$.apiOrigin))throw Error("worker_session_origin_mismatch");if(!J.scopes.includes("devices:write"))throw Error("worker_devices_write_scope_required");let Q=D$($);return Q.complete(J.orgId,await Z.createHeadlessDeviceEnrollmentTicket(Q.request))}async function L4($,J,Z,Q,X){let Y=performance.now();if(!C0(J.apiOrigin,$.apiOrigin))throw Error("worker_session_origin_mismatch");if(!J.scopes.includes("devices:write"))throw Error("worker_devices_write_scope_required");let G=D$($),V=X?void 0:Z.enrollHeadlessDevice?.bind(Z);if(V){let K=await q4($,G.direct(J.orgId),Q,(N,H)=>V({approval:G.request,code_verifier:H,registration:N}).catch((B)=>{throw QZ(B)}),Y);if(K)return K}return e0($,G.complete(J.orgId,await Z.createHeadlessDeviceEnrollmentTicket(G.request)),Q,X,Y)}function QZ($){if(!($ instanceof v0))return $;if($.status===409)return new o0($.code==="device_revoked");if($.status===410||$.status===401&&$.code==="invalid_enrollment_ticket"||$.status===403&&$.code==="grant_exceeded"||$.status===400&&$.code==="invalid_device_enrollment")return new o0(!1);return $}var P1=($)=>$Z(g($),"enrollment-install.json");function j4($){if(u(P1($)))e7(P1($))}function D$($,{stored:J=!0}={}){g0();let Z=P1($),Q=J&&u(Z)?_4.parse(JSON.parse(s(Z))):{version:1,install_id:o7(),fingerprint_key:t7(32).toString("hex")};if(J&&!u(Z))c(Z,Q);let X={read:!0,write:!0,execute:!0,discover_environment:!0,expose_mcp:!1},Y=Buffer.from(Q.fingerprint_key,"hex"),G=y$([$.workspaceRoot],X,Y)[0];if(G.path!==$.workspaceRoot)throw Error("worker_workspace_not_canonical_or_overlaps_state");let V=($.folders??[]).map((B)=>{let q=y$([B],X,Y)[0];if(q.path!==B)throw Error("worker_workspace_not_canonical_or_overlaps_state");return{path_fingerprint:q.pathFingerprint}}),K=M4(),N={install_id:Q.install_id,code_challenge:K.challenge,lifecycle:$.lifetime,roots:[G.pathFingerprint,...V.map((B)=>B.path_fingerprint)].map((B)=>({path_fingerprint:B,permissions:X,execution_mode:$.executionMode}))},H=(B)=>({version:1,organization_id:B,code_verifier:K.verifier,root_fingerprint_key:Q.fingerprint_key,root:{path_fingerprint:G.pathFingerprint,permissions:X,execution_mode:$.executionMode},...V.length?{folders:V}:{}});return{request:N,saveInstall(B){e(g(B),!0),c(P1(B),Q)},complete(B,q){let M=C3(q);if(M.lifecycle!==$.lifetime||Date.parse(M.expires_at)<=Date.now()||Date.parse(M.device_expires_at)<=Date.now())throw Error("worker_ticket_receipt_mismatch");return{...H(B),enrollment_ticket:M.enrollment_ticket}},direct:H}}function W4($,J,Z){let Q=P1($);if(!u(Q))throw Error("worker_folders_unavailable");let X=_4.parse(JSON.parse(s(Q)));return y$([J],Z,Buffer.from(X.fingerprint_key,"hex"))[0]}var H2=8,A4=600000,R4=15000,D4=new Set(["device_revoked","invalid_device_credential"]),M2=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,N$=($)=>H0(g($),"workspaces"),I4="account.json",P3=($)=>u(H0($,I4));function y0($){let J;try{J=XZ(N$($))}catch{return[]}return J.filter((Z)=>M2.test(Z)).sort().map((Z)=>{let Q=H0(N$($),Z),X=H0(Q,"worker.json"),Y=null;try{let G=J0.safeParse(JSON.parse(s(X)));if(G.success&&G.data.stateDirectory===Q)Y=G.data}catch{}return{organizationId:Z,directory:Q,configPath:X,config:Y,account:P3(Q)}})}function T2($,J){let Z=J.toLowerCase();if(!M2.test(Z))throw Error("worker_workspace_id_invalid");let Q=J0.parse({...$,stateDirectory:H0(N$($),Z)});return e(Q.stateDirectory,!0),c(H0(Q.stateDirectory,I4),{version:1}),{config:Q,configPath:H0(Q.stateDirectory,"worker.json")}}function _2($,J){try{let{config:Z,configPath:Q}=T2($,J);e(g(Z),!0),I0(Z,{version:1,drained:!0,revoked:!0}),c(Q,Z)}catch{}}function x1($,J){let Z=J.toLowerCase(),Q=null;try{Q=o($)?.orgId.toLowerCase()??null}catch{}return Q===Z||y0($).some((X)=>!X.account&&X.config!==null&&X.organizationId===Z)}var E3=["device.json","local-device.key","local-device.binding","keychain-scope.json","control.json","enrollment-install.json","first-heartbeat.json"];function O4($,J){let Z=o($);if(!Z?.worker)throw Error("worker_identity_missing");I1($,Z.devicePublicKey),e(g(J),!0);for(let Y of E3)f$(H0(g(J),Y),{force:!0});for(let Y of E3){let G=H0(g($),Y);if(u(G))YZ(G,H0(g(J),Y))}let Q=T0(J),X=k$(d(J).state,{proofStore:Q,repair:!1});if(!X?.worker)throw Error("worker_identity_missing");f0({...X,worker:{...X.worker,configDigest:N0(J)}},d(J).state,{proofStore:Q})}function x3($){for(let J of y0($)){if(J.account)continue;try{if(J.config&&u(d(J.config).state))k0(J.config)}catch{}f$(J.directory,{recursive:!0,force:!0})}f$(b3($),{force:!0})}function F2($,{prefer:J,keep:Z,live:Q=!1}){let X=Date.now(),Y=(B)=>Number(Date.parse(B.worker?.expiresAt??"")>X+60000),V=y0($).flatMap((B)=>{if(!B.account||!B.config)return[];try{if($0(B.config).revoked)return[];let q=o(B.config);return q&&q.orgId.toLowerCase()===B.organizationId&&(!Q||Y(q))?[{...B,config:B.config,state:q}]:[]}catch{return[]}}).sort((B,q)=>Number(q.organizationId===J)-Number(B.organizationId===J)||Y(q.state)-Y(B.state))[0];if(!V)return null;let K=null;try{K=$0($).revoked?null:o($)}catch{}let N=K?.orgId.toLowerCase()??"";if(Z&&K&&M2.test(N)&&N!==V.organizationId){let B=T2($,N);O4($,B.config),c(B.configPath,B.config)}else if(u(g($))){try{if(u(d($).state))k0($)}catch{}for(let B of E3)f$(H0(g($),B),{force:!0})}x3($);let H=J0.parse({...V.config,stateDirectory:$.stateDirectory});return O4(V.config,H),c(H0($.stateDirectory,"worker.json"),H),f$(V.directory,{recursive:!0,force:!0}),H}var S3={before($){for(let{config:J}of y0($))try{let Z=J?o(J):null;if(J&&Z)I1(J,Z.devicePublicKey)}catch{}},after($,J){for(let{organizationId:Z,directory:Q,configPath:X,config:Y}of y0(J)){if(Y)continue;try{let G=J0.parse(JSON.parse(s(X)));if(G.stateDirectory!==H0(N$($),Z))continue;let V=J0.parse({...G,stateDirectory:Q}),K=T0(V),N=k$(d(V).state,{proofStore:K,repair:!1});if(N?.worker?.configDigest===N0(G))f0({...N,worker:{...N.worker,configDigest:N0(V)}},d(V).state,{proofStore:K});c(X,V)}catch{}}}},b3=($)=>H0(N$($),"listed.json");function C4($){try{let J=JSON.parse(s(b3($))),Z=J.names&&typeof J.names==="object"&&!Array.isArray(J.names)?Object.fromEntries(Object.entries(J.names).filter((Q)=>typeof Q[1]==="string")):{};return{listed:J.listed===!0,reason:J.reason==="sign_in"?"sign_in":null,blocked:Array.isArray(J.blocked)?J.blocked.filter((Q)=>typeof Q==="string"):[],names:Z}}catch{return null}}function P4($,J){let Z=y0($),Q=Z.filter((K)=>K.account),X=Z.filter((K)=>!K.account),Y=C4($),G=Y&&!Y.listed?Y.reason:null,V=G||X.length===0&&Y&&!Y.listed?[]:X;if(Q.length===0&&V.length===0&&(G||Y&&!Y.listed))return{workspaces:null,off:G};return{off:G,workspaces:[...Q,...V].map(({organizationId:K,config:N,account:H})=>{let B=!1,q=null,M=!1,T=null;try{B=N?$0(N).revoked:!1,q=N&&!B?o(N):null;let _=N?o$(d(N).daemon):null;M=J&&!!q&&_?.state==="connected",T=M?z4(_,q):null}catch{}return{...T?{permission_recovery:T}:{},organization_id:K,device_id:q?.deviceId??null,name:Y?.names?.[K]??null,root:q?.roots[0]?{id:q.roots[0].id,permissions:q.roots[0].permissions}:null,state:B?"removed":M?"connected":"not_running",blocked:!H&&!B&&!M&&(Y?.blocked.includes(K)??!1),...H?{account:!0}:{}}})}}function E4($){let{config:J,state:Z,client:Q,signal:X}=$,Y=$.log??(()=>{return}),G=new Map,V=null,K=!1,N=C4(J)??{listed:!1,reason:null,blocked:[]},H=(L)=>{let{folders:W,...R}=J,E=Z.roots.slice(1).map((I)=>I.path);return J0.parse({...R,...E.length?{folders:E}:{},stateDirectory:H0(N$(J),L)})},B=async(L)=>{let W=G.get(L);if(!W)return;W.controller.abort(),await W.done},q=(L,W=!1)=>{let R=new AbortController,E=()=>R.abort();if(X.addEventListener("abort",E,{once:!0}),X.aborted)R.abort();let I={...L,controller:R,claims:0,done:Promise.resolve(),account:W};I.done=$.serve(L,R.signal,(C)=>{I.claims=C}).then(()=>{return},(C)=>{if(W&&C instanceof _0&&C.status===401&&D4.has(C.code)){try{I0(L.config,{version:1,drained:!0,revoked:!0})}catch{}Y(`Reason worker: workspace ${L.organizationId} (another account's) no longer accepts this computer (${C.code}); run \`reason connect\` signed in as that account to connect it again
5
5
  `)}else if(C instanceof _0&&C.status===401&&D4.has(C.code)){try{k0(L.config)}catch{}Y(`Reason worker: workspace ${L.organizationId} no longer accepts this computer
@@ -312,7 +312,7 @@ Usage:
312
312
  `),host:Z.host}),V=$8({...G,log:(M)=>Q.stderr.write(`${M}
313
313
  `)}),{configPath:K}=V,N=V.saved;if(!N)return Q.stderr.write("Reason: this computer has no saved connection. Run `reason connect`.\n"),0;let H=(M,T)=>{let _=q3(Z.home,Z.channel),j;try{let O=null;try{O=T.keep?null:o(N)?.orgId.toLowerCase()??null}catch{}if(j=F2(N,{prefer:X2(Z.home,Z.channel,N),...T}),j&&O)_2(j,O)}finally{_()}if(!j)return!1;N=j;let D="";try{D=` (workspace ${o(j)?.orgId??"unknown"})`}catch{}return Q.stderr.write(`Reason: ${M}; this computer goes on running Sessions for its other Reason account${D}.
314
314
  `),!0};if($0(N).revoked&&!H("this computer's connection was removed from Reason",{keep:!1}))return Q.stderr.write("Reason: this computer was removed from Reason. Run `reason connect` to connect it again.\n"),0;if(N.executionMode==="confined"||!j1(N)){let M=l0(N.stateDirectory)??void 0,T=M?null:X2(Z.home,Z.channel,N);if(!M&&!(T&&x1(N,T)))H("this computer's connection expired and its account is not signed in here",{keep:!0,live:!0})}let B=N.executionMode==="confined";if(B||!j1(N)){let M=l0(N.stateDirectory)??void 0;if(Q.stderr.write(B?O7:`Reason: this computer's connection expired; renewing it with ${M?"its API key":"your login"}\u2026
315
- `),await i9(J0.parse({...N,executionMode:"host"}),K,Q,X,M)!==0)return Q.stderr.write(M?"Reason: could not renew this computer's connection. Run `reason connect --api-key KEY` with a valid key.\n":"Reason: could not renew this computer's connection. Run `reason login`, then `reason connect`.\n"),0}let q=new AbortController;if(!X.runWorker)import("./ask-relay-d96qx4ez.js").then(({runBackgroundAskRelay:M})=>M(q.signal,(T)=>Q.stderr.write(`${T}
315
+ `),await i9(J0.parse({...N,executionMode:"host"}),K,Q,X,M)!==0)return Q.stderr.write(M?"Reason: could not renew this computer's connection. Run `reason connect --api-key KEY` with a valid key.\n":"Reason: could not renew this computer's connection. Run `reason login`, then `reason connect`.\n"),0}let q=new AbortController;if(!X.runWorker)import("./ask-relay-bczg32b2.js").then(({runBackgroundAskRelay:M})=>M(q.signal,(T)=>Q.stderr.write(`${T}
316
316
  `))).catch(()=>{});try{for(;;){let M=l0(N.stateDirectory)===null?{ownerWorkspaces:X.worker?.ownerWorkspaces??{}}:{},T=X.runWorker?null:$3({stateDirectory:N.stateDirectory}),_=!1,j;try{j=await(X.runWorker??M$)(["start","--config",K],{deferOptionalLanes:!0,...X.worker,...M,ownComputer:!0,io:{stdout:Q.stdout,stderr:Q.stderr},onDeviceRevoked:()=>{_=!0}})}finally{T?.stop()}if(!_)return j;if(!H("this computer's connection was removed from Reason",{keep:!1}))break}return U3(Z.home,Z.channel,!0),Q.stderr.write("Reason: this computer was removed from Reason. Run `reason connect` to connect it again.\n"),0}finally{q.abort()}}async function MB($,J,Z){let{io:Q,options:X,home:Y,channel:G,environment:V}=Z;if(J&&await(X.controlWorker??V0)(J,"status").catch(()=>null))throw new p("This computer is already connected in the background (see `reason status`). Run `reason disconnect` first to connect it only while a command runs.");let K=u0(Y,G,!0),N=A7({parsed:$,saved:J,stateDirectory:K,lifetime:"ephemeral",home:Y,channel:G,options:X,environment:V}),H=R7(N,Z.apiKey??(J?l0(J.stateDirectory)??void 0:void 0)),B=F0(K,"worker.json");return e(K,!0),c(B,H),Q.stdout.write(p9(`Reason: connecting "${H.name}" while this command runs`,H,Z.host.platform,["Connecting\u2026"])),(X.runWorker??M$)(["start","--config",B],{...n9(X.worker,Z.apiKey),ownComputer:!0,io:{stdout:Q.stdout,stderr:Y3(Q.stderr)},onStartup:(q)=>{if(q==="ready")Q.stdout.write(`Connected. Start Sessions on "${H.name}" from Reason. Press Ctrl-C to stop.
317
317
  `);X.worker?.onStartup?.(q)}})}function TB($,J,Z,Q){if(Z.platform!=="darwin")throw new p("--keep-awake is for macOS.");if(!J)throw new p("This computer is not connected to Reason. Run reason connect first.");e(g(J),!0),q8(d(J).daemon,$);let X=R2(d(J).daemon)==="battery_and_ac";return Q.stdout.write(`Keep awake: ${X?"on (this Mac stays awake while it runs Sessions)":"off"}
318
318
  `),0}var _B=U.object({root:U.object({id:U.string().min(1).max(160),label:U.string().max(160),path_fingerprint:U.string()})});async function I7($,J,Z,Q){let X=await(n9(Q.worker,Z).enrollmentCredentials??W$)($,j$($));if(!X)throw Error("worker_session_login_required");if(!X.scopes.includes("devices:write"))throw Error("worker_devices_write_scope_required");let Y=Q.folderApi?.(X)??new I$(X,{credentialsPath:j$($),fetchImpl:b0($.proxy)}),G=(V)=>V instanceof v0&&V.status===404&&!["device_not_found","root_not_found"].includes(V.code);return{add:async(V)=>{let K=W4($,V,{...J.roots[0].permissions,expose_mcp:!1}),N=await Y.addDeviceRoot(J.deviceId,{path_fingerprint:K.pathFingerprint,label:K.label,permissions:{...K.permissions,expose_mcp:!1}}).catch((B)=>{if(G(B))throw Error("worker_folders_unavailable");if(B instanceof v0&&B.code==="root_limit_reached")throw new p("This computer already has the most folders Reason allows (32).");throw B}),H=_B.parse(N).root;if(H.path_fingerprint!==K.pathFingerprint)throw Error("worker_enrollment_receipt_mismatch");return{...K,id:H.id,label:H.label}},remove:async(V)=>{await Y.removeDeviceRoot(J.deviceId,V).catch((K)=>{if(G(K))throw Error("worker_folders_unavailable");if(!(K instanceof v0&&K.code==="root_not_found"))throw K})}}}function C7($,J,Z){f0({...J,roots:Z,handsSlots:$.slots,worker:{...J.worker,configDigest:N0($)}},d($).state,{proofStore:T0($)})}async function P7($,J,Z,Q){let{io:X,options:Y,host:G}=Q,V=J&&!Q.apiKey&&l0(J.stateDirectory)===null?X2(Q.home,Q.channel,J):null,K=J&&V&&P$(J)&&!x1(J,V)?y0(J).find((I)=>I.account&&I.organizationId===V)??null:void 0;if(K===null)throw new p("This computer is not connected for your account. Run reason connect first.");let N=K?K.config:J,H=K?K.configPath:Z,B=N&&P$(N)&&!$0(N).revoked?o(N):null;if(!J||!N||!B||N.lifetime!=="persistent")throw new p("This computer is not connected to Reason. Run reason connect first.");let q=$.addFolder!==void 0,M=q?$.addFolder:$.removeFolder,T=Y.cwd??process.cwd(),_;try{_=X3(T,M)}catch(I){if(q)throw new p(I instanceof Error?I.message:String(I));_=GB(T,M)}if(_===N.workspaceRoot)throw new p(`${_} is this computer's main folder. To use another one, run reason connect --folder PATH.`);let j=N.folders??[],D=B.roots.slice(1).find((I)=>I.path===_);if(!q&&!D&&!j.includes(_))throw new p(`${_} is not one of this computer's folders.`);if(q&&!R1(_,N.stateDirectory))throw new p(`${_} holds Reason's own settings.`);if(q&&!D&&j.length>=31)throw new p("This computer already has the most folders Reason allows (32).");let O=Q.apiKey??l0(N.stateDirectory)??void 0,F=await I7(N,B,O,Y),z=B.roots.filter((I)=>I.path!==_);if(q)z=[...z,await F.add(_)];else if(D)await F.remove(D.id);C7(N,B,z);let L=q?[...j.filter((I)=>I!==_),_]:j.filter((I)=>I!==_),{folders:W,...R}=N;if(c(H,J0.parse({...R,...L.length?{folders:L}:{}})),!await(Y.controlWorker??V0)(J,"reload_roots").then(()=>!0,()=>!1))T$(J,G,"connect");return X.stdout.write(q?`Added ${_}. Sessions on "${N.name}" may run in it.