@reason-machines/cli-linux-arm64-musl 0.2.388 → 0.2.389
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/ara +1 -1
- package/bin/vm-hands/api-2edgrjpe.js +2 -0
- package/bin/vm-hands/api-credentials-1bfy2pqp.js +2 -0
- package/bin/vm-hands/{ask-relay-rpekz0vc.js → ask-relay-72awrbwx.js} +3 -3
- package/bin/vm-hands/connect-cli-rss8z5bk.js +2 -0
- package/bin/vm-hands/{custom-endpoint-device-baqm3872.js → custom-endpoint-device-3g0rc3wp.js} +1 -1
- package/bin/vm-hands/desktop-account-8yf4aqgb.js +2 -0
- package/bin/vm-hands/{device-workspace-0kk5ef85.js → device-workspace-35hjc1ff.js} +1 -1
- package/bin/vm-hands/{hands-worker-source-mshf7c6v.js → hands-worker-source-msdkfx9x.js} +1 -1
- package/bin/vm-hands/{index-cvnymkkb.js → index-m32pjcjr.js} +1 -1
- package/bin/vm-hands/{install-receipt-352cy8vj.js → install-receipt-7qanbz38.js} +1 -1
- package/bin/vm-hands/local-automation-gb4jmhmg.js +2 -0
- package/bin/vm-hands/local-capabilities-gtdp4pz0.js +2 -0
- package/bin/vm-hands/local-desktop-users-p6n48895.js +2 -0
- package/bin/vm-hands/local-display-mac-7havkbhd.js +2 -0
- package/bin/vm-hands/local-display-session-yz5szy3t.js +2 -0
- package/bin/vm-hands/local-pty-session-8ny1n2fv.js +2 -0
- package/bin/vm-hands/{managed-runtime-wzk0q157.js → managed-runtime-gyd32324.js} +1 -1
- package/bin/vm-hands/network-contract-3h853c6e.js +2 -0
- package/bin/vm-hands/package-04cf0m62.js +2 -0
- package/bin/vm-hands/permissions-6pfayzkx.js +2 -0
- package/bin/vm-hands/{reason-hands-protocol-z95pxxbh.js → reason-hands-protocol-mw7ba8vz.js} +1 -1
- package/bin/vm-hands/{serve-service-d2q1pdxh.js → serve-service-mcnkk9hs.js} +1 -1
- package/bin/vm-hands/{status-x8g58cxm.js → status-s1g9gt1e.js} +2 -2
- package/bin/vm-hands/version-cta9ffcc.js +2 -0
- package/bin/vm-hands/{vm-hands-entry-lite-jx3w1z5q.js → vm-hands-entry-lite-00800vjk.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-v2ptg6br.js → vm-hands-entry-lite-02zaqpgh.js} +5 -5
- package/bin/vm-hands/{vm-hands-entry-lite-zr8gf6nd.js → vm-hands-entry-lite-0seprnh3.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-qnnfvm5r.js → vm-hands-entry-lite-0z73amf7.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-y55f8dyw.js → vm-hands-entry-lite-180h5amj.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-sv8bb7jq.js → vm-hands-entry-lite-2yx44ayr.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-pk3q774c.js → vm-hands-entry-lite-3nr9q3nf.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-b1ygrkbq.js → vm-hands-entry-lite-3ptq7p60.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-fyvgav60.js → vm-hands-entry-lite-5x04hakp.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-6shgavn0.js → vm-hands-entry-lite-73akm1q1.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-stbfyev7.js → vm-hands-entry-lite-88h9vwrv.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-f89wk20p.js → vm-hands-entry-lite-8e932j3c.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-e05sgnwe.js → vm-hands-entry-lite-8pgggvbb.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-d7cvwy3k.js → vm-hands-entry-lite-8q63t2c0.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-ammr3xbc.js → vm-hands-entry-lite-a1yy1yp3.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-9fc26f9c.js → vm-hands-entry-lite-a8pdf1yx.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-289qftes.js → vm-hands-entry-lite-adpzn7fe.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-mbs7d7ye.js → vm-hands-entry-lite-atg4z1vg.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-y2s2w174.js → vm-hands-entry-lite-bwpay74g.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-e2mjbqmr.js → vm-hands-entry-lite-csecgmaa.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-yzaz1e8r.js → vm-hands-entry-lite-dbcsvq0f.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-spccx392.js → vm-hands-entry-lite-e73s63fb.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-p6g561rq.js → vm-hands-entry-lite-ebgackey.js} +2 -2
- package/bin/vm-hands/vm-hands-entry-lite-ezahexcb.js +5 -0
- package/bin/vm-hands/{vm-hands-entry-lite-nf0avf46.js → vm-hands-entry-lite-f5v3wap5.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-grjkhbf2.js → vm-hands-entry-lite-f78n4wqt.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-te0p47ak.js → vm-hands-entry-lite-fb02h1zm.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-fw5ztpwn.js → vm-hands-entry-lite-g87z5eb6.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-s7k376cz.js → vm-hands-entry-lite-h0keewxv.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-fb5dzy9x.js → vm-hands-entry-lite-hfv2tsm9.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-r7czqrtj.js → vm-hands-entry-lite-jt9fmk7y.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-ma001vzh.js → vm-hands-entry-lite-ksz1k1dh.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-kb981w39.js → vm-hands-entry-lite-mc3pkj0q.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-sex82vb1.js → vm-hands-entry-lite-mft9ke08.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-3vb4he21.js → vm-hands-entry-lite-nq5np26e.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-sb7n76g7.js → vm-hands-entry-lite-p1s0xyc2.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-n25efwqt.js → vm-hands-entry-lite-r166b92s.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-30rnhzfj.js → vm-hands-entry-lite-trm3dn8c.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-jjgqsan6.js → vm-hands-entry-lite-vvv3m6wy.js} +3 -3
- package/bin/vm-hands/{vm-hands-entry-lite-zs3jsffv.js → vm-hands-entry-lite-w4tyr264.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-axe84b1n.js → vm-hands-entry-lite-w844s03h.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-2e18tm6w.js → vm-hands-entry-lite-wpcagqfw.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-6tv7j3ej.js → vm-hands-entry-lite-wxzh22y4.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-nr1narzb.js → vm-hands-entry-lite-y99g8x7f.js} +1 -1
- package/bin/vm-hands/vm-hands-entry-lite.js +1 -1
- package/bin/vm-hands/{vm-hands-executor-j4q5snaz.js → vm-hands-executor-22jnr9y7.js} +1 -1
- package/bin/vm-hands/vm-hands-op-runner-dcweybjn.js +2 -0
- package/bin/vm-hands/vm-hands-runtime-bt8pe8cm.js +4 -0
- package/bin/vm-hands/worker-sandbox-nnk7fq89.js +2 -0
- package/package.json +1 -1
- package/bin/vm-hands/api-9jsc2wk3.js +0 -2
- package/bin/vm-hands/api-credentials-jhaxk9e6.js +0 -2
- package/bin/vm-hands/connect-cli-xk4wx40j.js +0 -2
- package/bin/vm-hands/desktop-account-374pyd2h.js +0 -2
- package/bin/vm-hands/local-automation-fqf1yxn8.js +0 -2
- package/bin/vm-hands/local-capabilities-0xqv6w37.js +0 -2
- package/bin/vm-hands/local-desktop-users-39d8h875.js +0 -2
- package/bin/vm-hands/local-display-mac-yt4tpb96.js +0 -2
- package/bin/vm-hands/local-display-session-12q3s3p1.js +0 -2
- package/bin/vm-hands/local-pty-session-142rrpf9.js +0 -2
- package/bin/vm-hands/network-contract-m55ndrgk.js +0 -2
- package/bin/vm-hands/package-k4xz7vcr.js +0 -2
- package/bin/vm-hands/permissions-zajmtjzs.js +0 -2
- package/bin/vm-hands/version-55234k7v.js +0 -2
- package/bin/vm-hands/vm-hands-entry-lite-wzqzjd6f.js +0 -5
- package/bin/vm-hands/vm-hands-op-runner-btwvjt4p.js +0 -2
- package/bin/vm-hands/vm-hands-runtime-gw2wdm13.js +0 -4
- package/bin/vm-hands/worker-sandbox-r41yz175.js +0 -2
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
2
|
+
import{jk as W}from"./vm-hands-entry-lite-8pgggvbb.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
3
|
repository(owner: $owner, name: $repo) {
|
|
4
4
|
nameWithOwner
|
|
5
5
|
pullRequest(number: $number) {
|
|
@@ -34,9 +34,9 @@ import{ik as W}from"./vm-hands-entry-lite-e05sgnwe.js";var T=W.string().max(201)
|
|
|
34
34
|
}
|
|
35
35
|
}
|
|
36
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="vm_hands_workspace_deferred",SQ="vm_hands.workspace_grant",IQ="
|
|
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="vm_hands_workspace_deferred",SQ="vm_hands.workspace_grant",IQ="hands.unbind_unverified",PQ="claim_v1",TQ="environment_at_claim",CQ="rebind_v1",AQ="resident_rebind",bQ="hands.rebind",EQ="snapshot_v1",kQ="cloud_access",LQ="playwright_v1",fQ="headless_browser",_Q="v1",cQ="job_env_large_values",yQ="srt_root_v1",dQ="hands_confinement",OQ="gid_v1",hQ="model_jobs_egress",RQ="setpriv_v1",rQ="jobs_user",pQ="spawning_attempt_v1",nQ="hands_session_group",oQ="session_cap",sQ="none",iQ="same_launch_v1",tQ="exit_v1",vQ="start_wait",lQ="user_chrome",uQ="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 aQ=["lock_acquired","enrollment_started","enrollment_completed","readiness_started","readiness_completed","inventory_completed","control_ready"],eQ=86400000,QW=["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",WW="ARA-DEVICE-V1";function ZW(Q,Z=i){let $=Q.method.toUpperCase();if(!/^[A-Z]+$/.test($)||!Q.pathAndQuery.startsWith(`${I}/`)||Q.pathAndQuery.includes(`
|
|
38
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
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
|
|
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
|
|
42
|
-
export{d as ye,R as ze,ZQ as Ae,x as Be,$Q as Ce,m as De,KQ as Ee,DQ as Fe,zQ as Ge,b as He,j as Ie,I as Je,n as Ke,HQ as Le,XQ as Me,GQ as Ne,BQ as Oe,MQ as Pe,gQ as Qe,qQ as Re,NQ as Se,mQ as Te,UQ as Ue,jQ as Ve,xQ as We,JQ as Xe,SQ as Ye,IQ as Ze,PQ as _e,TQ as $e,CQ as af,AQ as bf,bQ as cf,EQ as df,kQ as ef,LQ as ff,fQ as gf,_Q as hf,cQ as if,yQ as jf,dQ as kf,OQ as lf,hQ as mf,RQ as nf,rQ as of,pQ as pf,nQ as qf,oQ as rf,sQ as sf,iQ as tf,tQ as uf,vQ as vf,lQ as wf,uQ as xf,aQ as yf,eQ as zf,
|
|
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 $W(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 KW(Q){return L(Q,!1)}function DW(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 zW(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 FW(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 wW(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 VW(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 YW(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 HW(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 XW(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 GW(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 BW(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 MW(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 qW(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 ye,R as ze,ZQ as Ae,x as Be,$Q as Ce,m as De,KQ as Ee,DQ as Fe,zQ as Ge,b as He,j as Ie,I as Je,n as Ke,HQ as Le,XQ as Me,GQ as Ne,BQ as Oe,MQ as Pe,gQ as Qe,qQ as Re,NQ as Se,mQ as Te,UQ as Ue,jQ as Ve,xQ as We,JQ as Xe,SQ as Ye,IQ as Ze,PQ as _e,TQ as $e,CQ as af,AQ as bf,bQ as cf,EQ as df,kQ as ef,LQ as ff,fQ as gf,_Q as hf,cQ as if,yQ as jf,dQ as kf,OQ as lf,hQ as mf,RQ as nf,rQ as of,pQ as pf,nQ as qf,oQ as rf,sQ as sf,iQ as tf,tQ as uf,vQ as vf,lQ as wf,uQ as xf,aQ as yf,eQ as zf,QW as Af,i as Bf,WW as Cf,ZW as Df,$W as Ef,l as Ff,KW as Gf,DW as Hf,zW as If,FW as Jf,wW as Kf,VW as Lf,YW as Mf,HW as Nf,XW as Of,GW as Pf,BW as Qf,MW as Rf,gW as Sf,qW as Tf};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Cc as v,xc as q}from"./vm-hands-entry-lite-
|
|
2
|
+
import{Cc as v,xc as q}from"./vm-hands-entry-lite-mc3pkj0q.js";function A(j=process.platform){if(q(),j==="linux"||j==="win32")v("strict")}
|
|
3
3
|
export{A as r};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
2
|
+
import{mi as A,ni as x,oi as u,xi as y}from"./vm-hands-entry-lite-csecgmaa.js";import{Di as c}from"./vm-hands-entry-lite-ksz1k1dh.js";import{randomUUID as m}from"crypto";import{chmodSync as l,existsSync as p,mkdirSync as jJ,readlinkSync as YJ,readFileSync as GJ,renameSync as OJ,unlinkSync as VJ,writeFileSync as FJ}from"fs";import{homedir as d}from"os";import{basename as P,dirname as H,isAbsolute as v,join as I,normalize as n,relative as HJ,resolve as LJ}from"path";import{unlinkSync as WJ}from"fs";import{dirname as XJ,join as ZJ}from"path";function $J(J){return ZJ(XJ(J),"future-device-grant.json")}function o(J){try{WJ($J(J))}catch(Q){if(!(Q instanceof Error&&("code"in Q)&&Q.code==="ENOENT"))throw Q}}var N=3,NJ=1,TJ=2,D=1,a=1,r="Reason may read and write files and run commands in this signed-in OS account, subject to saved restrictions and operating system permissions.",b="Reason may later execute on this computer inside a Reason sandbox, limited to folders explicitly attached by the user.",zJ=[b,"Ara may later execute on this computer inside an Ara sandbox, limited to folders explicitly attached by the user."];function i(J){return typeof J==="string"&&zJ.includes(J)}var BJ=["future_device","updates_only","cli_only"];function h(J){return typeof J==="string"&&BJ.some((Q)=>Q===J)}function SJ(J=process.env,Q=d()){return J.XDG_CONFIG_HOME?.trim()||I(Q,".config")}function K(J=process.env,Q=d()){let U=x({env:J}),W=SJ(J,Q);return I(W,y(W).state==="kept"?"ara":"reason",...U==="staging"?["staging"]:[],"installation.json")}function G(J){return typeof J==="string"&&J.trim().length>0}var _J=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function IJ(J){return typeof J==="string"&&_J.test(J)}function C(J){return G(J)&&v(J)&&n(J)===J}function t(J){if(!J||typeof J!=="object"||Array.isArray(J))return!1;let Q=J;return C(Q.path)&&(Q.role==="launcher"&&(Q.kind==="file"||Q.kind==="symlink")||Q.role==="worker_root"&&Q.kind==="directory"||Q.role==="alias"&&Q.kind==="symlink"&&C(Q.target))}function g(J){return J.owned_paths?.every((Q)=>Q.role!=="alias"||J.installer==="shell"&&Q.path===I(J.install_dir,J.channel==="staging"?"reason-staging":"reason")&&Q.target===I(J.install_dir,J.channel==="staging"?"ara-staging":"ara")&&J.owned_paths?.some((U)=>U.role==="launcher"&&U.path===Q.target))??!1}function e(J,Q){try{return LJ(H(J),YJ(J))===Q}catch{return!1}}function vJ(J){let Q=P(J),U=Q==="ara"?"reason":Q==="ara-staging"?"reason-staging":null;if(!U)return J;let W=I(H(J),U);return e(W,J)?W:J}function M(J,Q){let U=HJ(J,Q);return U.length>0&&!U.startsWith("..")&&!v(U)}function JJ(J){if(J===null)return!0;if(!J||typeof J!=="object"||Array.isArray(J))return!1;let Q=J;return(Q.kind==="shell_profile"||Q.kind==="windows_user_path")&&G(Q.location)&&G(Q.value)&&(typeof Q.added_by_installer==="boolean"||typeof Q.added_by_ara==="boolean")&&(Q.added_by_installer===void 0||typeof Q.added_by_installer==="boolean")&&(Q.added_by_ara===void 0||typeof Q.added_by_ara==="boolean")}function q(J){return J.added_by_installer??J.added_by_ara??!1}function QJ(J,Q){if(Q===null)return J==="cli_only";if(!Q||typeof Q!=="object"||Array.isArray(Q))return!1;let U=Q;if(U.version!==D||!G(U.recorded_at))return!1;if(J==="future_device")return U.decision==="authorized"&&i(U.scope);return U.scope===null&&U.decision===(J==="updates_only"?"ask":"disabled")}function AJ(J){if(!J||typeof J!=="object"||Array.isArray(J))return null;let Q=J;if(Q.schema_version!==NJ||!A.includes(Q.channel)||Q.install_method!=="curl"||Q.installer!=="shell"&&Q.installer!=="powershell"||!G(Q.installed_at)||!G(Q.version)||!G(Q.target)||!C(Q.install_dir)||!Array.isArray(Q.owned_paths)||!Q.owned_paths.every(t)||!Q.owned_paths.every((U)=>M(Q.install_dir,U.path))||!g(Q)||!JJ(Q.path_entry))return null;return{...Q,schema_version:N,installation_id:null,background_mode:"cli_only",device_consent:null}}function DJ(J){if(!J||typeof J!=="object"||Array.isArray(J))return null;let Q=J;if(Q.schema_version!==TJ||!UJ(Q)||!h(Q.background_mode)||!QJ(Q.background_mode,Q.device_consent))return null;return{...Q,schema_version:N,installation_id:null}}function UJ(J){return A.includes(J.channel)&&(J.install_method==="curl"&&(J.installer==="shell"||J.installer==="powershell")||J.install_method==="desktop"&&J.installer==="desktop"&&Array.isArray(J.owned_paths)&&J.owned_paths.length===0&&J.path_entry===null)&&G(J.installed_at)&&G(J.version)&&G(J.target)&&C(J.install_dir)&&Array.isArray(J.owned_paths)&&J.owned_paths.every(t)&&J.owned_paths.every((Q)=>M(J.install_dir,Q.path))&&g(J)&&JJ(J.path_entry)}function KJ(J){let Q=AJ(J);if(Q)return Q;let U=DJ(J);if(U)return U;if(!J||typeof J!=="object"||Array.isArray(J))return null;let W=J;if(W.schema_version!==N||!IJ(W.installation_id)||!UJ(W)||!h(W.background_mode)||!QJ(W.background_mode,W.device_consent)||W.desktop_account_access!==void 0&&(W.desktop_account_access===null||typeof W.desktop_account_access!=="object"||Array.isArray(W.desktop_account_access)||W.desktop_account_access.version!==a||W.desktop_account_access.scope!==r||!G(W.desktop_account_access.recorded_at)||!Number.isFinite(Date.parse(W.desktop_account_access.recorded_at))))return null;return W}function E(J=K()){if(!p(J))return null;try{return KJ(JSON.parse(GJ(J,"utf8")))}catch{return null}}function f(J){return Boolean(J?.installation_id&&J.background_mode==="future_device"&&J.device_consent?.version===D&&J.device_consent.decision==="authorized"&&i(J.device_consent.scope))}function s(J,Q){let U=E(Q);if(!(f(U)&&f(J)&&U.installation_id===J.installation_id&&U.channel===J.channel))o(Q);jJ(H(Q),{recursive:!0,mode:448}),l(H(Q),448);let X=`${Q}.${process.pid}.${m()}.tmp`;try{FJ(X,`${JSON.stringify(J,null,2)}
|
|
3
3
|
`,{mode:384,flag:"wx"}),l(X,384),OJ(X,Q)}finally{if(p(X))VJ(X)}let Y=H(Q),$=P(Y)==="staging"?H(Y):Y;if(P($)==="reason")y(H($));return J}function RJ(J=K(),Q=new Date){let U=E(J);if(!U?.installation_id)throw Error("Reason installation ownership is missing; reinstall the current CLI before enabling Device execution");if(f(U))return U;let W={...U,background_mode:"future_device",device_consent:{version:D,decision:"authorized",scope:b,recorded_at:Q.toISOString()}};return delete W.desktop_account_access,s(W,J)}function hJ(J,Q=K(),U=new Date){if(!A.includes(J.channel))throw Error("invalid installation channel");if(!J.version.trim())throw Error("installation version is required");if(!J.target.trim())throw Error("installation target is required");let W=_(J.installDir,"install directory"),X=E(Q);if(X?.installation_id&&!J.accountAccess)return RJ(Q,U);return s({...X??{schema_version:N,channel:J.channel,install_method:"desktop",installer:"desktop",installed_at:U.toISOString(),version:J.version.trim(),target:J.target.trim(),install_dir:W,owned_paths:[],path_entry:null},schema_version:N,installation_id:X?.installation_id??m(),background_mode:"future_device",...J.accountAccess?{desktop_account_access:{version:a,scope:r,recorded_at:U.toISOString()}}:{},device_consent:{version:D,decision:"authorized",scope:b,recorded_at:U.toISOString()}},Q)}function qJ(J,Q){return J.kind===Q.kind&&J.location===Q.location&&J.value===Q.value}function _(J,Q){let U=n(J);if(!v(U))throw Error(`${Q} must be an absolute path`);return U}function CJ(J,Q=K(),U=new Date){if(!A.includes(J.channel))throw Error("invalid installation channel");if(!J.version.trim())throw Error("installation version is required");if(!J.target.trim())throw Error("installation target is required");let W=_(J.install_dir,"install directory"),X=E(Q),Y=J.backgroundMode??"preserve",$=Y==="preserve"?X?.background_mode??"cli_only":Y,L=X?.channel===J.channel&&f(X)&&$==="future_device",T=Y==="preserve"&&!X||X?.channel===J.channel&&(Y==="preserve"||L),O={path:_(J.launcherPath,"launcher path"),kind:J.launcherKind,role:"launcher"};if(!M(W,O.path))throw Error("launcher path must be inside the install directory");let z=(J.workerRoots??[]).map((j)=>_(j,"worker root"));if(z.some((j)=>!M(W,j)))throw Error("worker root must be inside the install directory");let B=[];if(J.aliasPath){let j={path:_(J.aliasPath,"alias path"),kind:"symlink",role:"alias",target:O.path};if(!g({installer:J.installer,channel:J.channel,install_dir:W,owned_paths:[O,j]})||!e(j.path,j.target))throw Error("alias must be the channel's symlink to its canonical launcher");B.push(j)}let R=[...X?.channel===J.channel&&X.install_dir===W?X.owned_paths:[],O,...B,...z.map((j)=>({path:j,kind:"directory",role:"worker_root"}))],k=Array.from(new Map(R.map((j)=>[j.path,j])).values()),Z=J.pathEntry??null,F=Z?X?.path_entry&&qJ(Z,X.path_entry)?{...Z,added_by_installer:q(Z)||q(X.path_entry),added_by_ara:q(Z)||q(X.path_entry)}:Z:X?.path_entry??null,S={schema_version:N,installation_id:X?.installation_id??m(),channel:J.channel,install_method:"curl",installer:J.installer,installed_at:U.toISOString(),version:J.version.trim(),target:J.target.trim(),install_dir:W,owned_paths:k,path_entry:F,background_mode:$,device_consent:T?X?.device_consent??null:{version:D,decision:$==="future_device"?"authorized":$==="updates_only"?"ask":"disabled",scope:$==="future_device"?b:null,recorded_at:U.toISOString()},...L&&X.desktop_account_access?{desktop_account_access:X.desktop_account_access}:{}};return s(S,Q)}function w(J,Q){let U=J.indexOf(Q);if(U===-1)return;let W=J[U+1];if(!W||W.startsWith("--"))throw Error(`${Q} needs a value`);return W}function V(J,Q){let U=w(J,Q);if(!U)throw Error(`${Q} is required`);return U}function gJ(J,Q={}){let U=Q.io??{stdout:process.stdout,stderr:process.stderr};try{let W=new Set(["--channel","--installer","--version","--target","--install-dir","--launcher-path","--launcher-kind","--worker-root","--path-kind","--path-location","--path-value","--background-mode"]);for(let Z=0;Z<J.length;Z+=1){let F=J[Z];if(F==="--path-added")continue;if(!W.has(F))throw Error(`unknown option: ${F}`);if(Z+=1,Z>=J.length)throw Error(`${F} needs a value`)}let X=Q.env??process.env,Y=V(J,"--channel"),$=x({env:X,executablePath:Q.executablePath});if(Y!==$)throw Error(`installer channel ${Y} does not match running ${$} CLI`);let L=V(J,"--installer");if(L!=="shell"&&L!=="powershell")throw Error("--installer must be shell or powershell");let T=V(J,"--launcher-kind");if(T!=="file"&&T!=="symlink")throw Error("--launcher-kind must be file or symlink");let O=w(J,"--path-kind"),z=null;if(O){if(O!=="shell_profile"&&O!=="windows_user_path")throw Error("--path-kind must be shell_profile or windows_user_path");z={kind:O,location:V(J,"--path-location"),value:V(J,"--path-value"),added_by_installer:J.includes("--path-added"),added_by_ara:J.includes("--path-added")}}else if(J.includes("--path-location")||J.includes("--path-value")||J.includes("--path-added"))throw Error("path entry flags require --path-kind");let B={channel:$,install_method:"curl",installer:L,version:V(J,"--version"),target:V(J,"--target"),install_dir:V(J,"--install-dir"),launcherPath:V(J,"--launcher-path"),launcherKind:T,workerRoots:J.flatMap((Z,F)=>{if(Z!=="--worker-root")return[];let S=J[F+1];if(!S||S.startsWith("--"))throw Error("--worker-root needs a value");return[S]}),pathEntry:z,backgroundMode:(()=>{let Z=w(J,"--background-mode")??"preserve";if(Z!=="preserve"&&!h(Z))throw Error("--background-mode must be future_device, updates_only, cli_only, or preserve");return Z})()},R=c(X,"REASON_INSTALL_ALIAS_PATH");if(R)B.aliasPath=R;let k=K(u(X,$),Q.home??d());return(Q.writeReceipt??CJ)(B,k,Q.now?.()??new Date),0}catch(W){return U.stderr.write(`Reason installer receipt: ${W instanceof Error?W.message:String(W)}
|
|
4
4
|
`),1}}
|
|
5
5
|
export{N as ge,D as he,a as ie,r as je,b as ke,BJ as le,SJ as me,K as ne,e as oe,vJ as pe,q as qe,KJ as re,E as se,f as te,RJ as ue,hJ as ve,CJ as we,gJ as xe};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
2
|
+
import{Ck as N}from"./vm-hands-entry-lite-fb02h1zm.js";import{randomUUID as K}from"crypto";import{closeSync as L,constants as V,fstatSync as M,lstatSync as Z,mkdirSync as $,openSync as O,readFileSync as T,realpathSync as b,renameSync as U,unlinkSync as X,writeFileSync as Y}from"fs";import{dirname as g,resolve as z}from"path";var A=65536;function J(j){try{return Z(j),!0}catch(q){if(q instanceof Error&&"code"in q&&q.code==="ENOENT")return!1;throw q}}function I(j,q=!1){if(!J(j)){if(!q)throw Error("worker_state_missing");D(j),$(j,{mode:448})}let C=Z(j);if(!C.isDirectory()||C.isSymbolicLink()||!N(C)||b(j)!==z(j))throw Error("worker_state_directory_not_private_or_canonical")}function D(j){let q=g(j);if(!J(q))D(q),$(q,{mode:448});if(b(q)!==z(q))throw Error("worker_parent_not_canonical")}function u(j,q=A){let C=O(j,V.O_RDONLY|V.O_NOFOLLOW);try{let G=M(C);if(!G.isFile()||G.nlink!==1||!N(G)||G.size>q)throw Error("worker_file_not_private");return T(C,"utf8")}finally{L(C)}}function f(j,q,C=A){let G=JSON.stringify(q);if(G===void 0)throw Error("worker_file_invalid");let Q=G+`
|
|
3
3
|
`;if(Buffer.byteLength(Q,"utf8")>C)throw Error("worker_file_too_large");if(I(g(j)),J(j))u(j,C);let H=`${j}.${K()}`;try{Y(H,Q,{mode:384,flag:"wx"}),U(H,j)}finally{if(J(H))X(H)}}
|
|
4
4
|
export{J as $c,I as ad,u as bd,f as cd};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Ab as P7,Bb as o4,Cb as T7,Db as R7,Kb as q7,Ob as E7,Pb as k7,Zb as J8,bc as f7,cc as b7,dc as Y8,ec as W8,gc as x7,ib as m4,ic as h8,jc as v0,kb as q2,kc as p0,lb as v4,lc as F2,mb as u4,nb as C7,ob as D7,oc as y7,pb as w7,rb as p4,rc as m8,sb as M7,sc as Z8,tb as L7,tc as Q8,ub as i4,uc as k1,vb as O7,wb as a3,wc as h7,xb as I7,yb as A7,zb as _7}from"./vm-hands-entry-lite-
|
|
2
|
+
import{Ab as P7,Bb as o4,Cb as T7,Db as R7,Kb as q7,Ob as E7,Pb as k7,Zb as J8,bc as f7,cc as b7,dc as Y8,ec as W8,gc as x7,ib as m4,ic as h8,jc as v0,kb as q2,kc as p0,lb as v4,lc as F2,mb as u4,nb as C7,ob as D7,oc as y7,pb as w7,rb as p4,rc as m8,sb as M7,sc as Z8,tb as L7,tc as Q8,ub as i4,uc as k1,vb as O7,wb as a3,wc as h7,xb as I7,yb as A7,zb as _7}from"./vm-hands-entry-lite-dbcsvq0f.js";import{Dc as p7,Fc as d7,Gc as l7}from"./vm-hands-entry-lite-mc3pkj0q.js";import{Lc as g7}from"./vm-hands-entry-lite-h0keewxv.js";import{Rc as e0,Sc as $1,Zc as g0}from"./vm-hands-entry-lite-r166b92s.js";import{_c as X1}from"./vm-hands-entry-lite-rtt2w6c6.js";import{ad as t4,bd as e4}from"./vm-hands-entry-lite-180h5amj.js";import{dd as m7}from"./vm-hands-entry-lite-g7h6wjqy.js";import{hd as H2,id as C2,jd as B4,ld as V4,nd as G4,od as X4,sd as U4,ud as Y7}from"./vm-hands-entry-lite-e73s63fb.js";import{Cd as W2,Fd as K9,Od as B9}from"./vm-hands-entry-lite-f5v3wap5.js";import{$e as u6,Ae as n3,Be as O2,Ce as y6,De as r3,Df as i8,Ee as _4,Ef as o8,Fe as P4,Ff as t8,Ge as j0,Gf as e8,Hf as $5,If as J5,Ke as C0,Kf as Z5,Lf as Q5,Mf as K5,Ne as s,Nf as B5,Oe as c1,Of as V5,Pf as G5,Qf as X5,Re as a8,Rf as U5,Sf as F5,Te as n1,Tf as Y5,Ve as h6,We as m6,_e as v6,af as p6,bf as d6,cf as l6,df as s6,ef as c6,ff as n6,gf as r6,hf as a6,if as i6,jf as o6,kf as t6,lf as e6,mf as $7,nf as J7,of as Z7,pf as Q7,rf as K7,sf as B7,tf as V7,uf as G7,vf as X7,wf as U7,xf as F7,ye as g1,ze as E1}from"./vm-hands-entry-lite-02zaqpgh.js";import{Zf as _6,bg as m5,cg as X6,ig as V9,lg as v5,mg as X2}from"./vm-hands-entry-lite-w844s03h.js";import{og as e7,pg as $9,qg as J9,ug as Z9,xg as Q9}from"./vm-hands-entry-lite-adpzn7fe.js";import{Gg as $8,Ng as S7}from"./vm-hands-entry-lite-00800vjk.js";import{Sg as Y2}from"./vm-hands-entry-lite-hfv2tsm9.js";import{Yg as u3,jh as W7}from"./vm-hands-entry-lite-a1yy1yp3.js";import{Fi as v7,Gi as u7}from"./vm-hands-entry-lite-vvv3m6wy.js";import{Si as A1,Ti as _1,Ui as P1,Vi as T1,Wi as k0}from"./vm-hands-entry-lite-mft9ke08.js";import{mj as b1,nj as j7,oj as r4,pj as a4}from"./vm-hands-entry-lite-5x04hakp.js";import{Aj as k4,rj as v3,tj as B1,zj as y8}from"./vm-hands-entry-lite-3nr9q3nf.js";import{Rj as s7,Sj as c7,Tj as n7,Uj as r7,Wj as a7,Xj as i7,Zj as o7,_j as t7}from"./vm-hands-entry-lite-ebgackey.js";import{jk as V}from"./vm-hands-entry-lite-8pgggvbb.js";import{Ak as N7,Bk as H7,Ck as n4,Dk as l1,tk as z5,uk as c4,zk as z7}from"./vm-hands-entry-lite-fb02h1zm.js";import{Ek as T4}from"./vm-hands-entry-lite-8e932j3c.js";import{Gk as H}from"./vm-hands-entry-lite-g87z5eb6.js";import{Mk as g8}from"./vm-hands-entry-lite-f78n4wqt.js";import{request as _9}from"http";import{request as P9}from"https";import{lookup as T9}from"dns/promises";import{isIP as R9}from"net";async function q9($){let J=new URL($.url);return await new Promise((Z,Q)=>{let K=(J.protocol==="https:"?P9:_9)(J,{method:"POST",headers:{...$.headers,"accept-encoding":"identity"},signal:$.signal,timeout:V4},(B)=>Z({response:B,close:()=>{B.destroy(),K.destroy(),B.socket?.destroy()}}));K.once("error",Q),K.once("timeout",()=>K.destroy(Object.assign(Error("custom_endpoint_timeout"),{code:"ETIMEDOUT"}))),K.end($.body)})}var F4=new Set(["ENOTFOUND","EAI_AGAIN","EAI_NONAME","EAI_NODATA","EAI_FAIL","DNSException"]),g9=new Set(["ECONNREFUSED","ETIMEDOUT","ECONNRESET","EHOSTUNREACH","ENETUNREACH","EHOSTDOWN","ENETDOWN","EPIPE","ECONNABORTED","EADDRNOTAVAIL","ConnectionRefused","ConnectionClosed","ConnectionTimedOut","Timeout"]);function Y4($,J=0){if(!$||typeof $!=="object"||J>3)return null;let Z=$.code;if(typeof Z==="string"){if(F4.has(Z))return"custom_endpoint_host_not_found";if(g9.has(Z))return"custom_endpoint_connection_failed";if(/^(?:ERR_TLS_|ERR_SSL_|CERT_|UNABLE_TO_(?:GET|VERIFY|DECRYPT)|DEPTH_ZERO_SELF_SIGNED|SELF_SIGNED_CERT|HOSTNAME_MISMATCH|EPROTO$)/.test(Z))return"custom_endpoint_tls_failed"}for(let Q of[...$ instanceof AggregateError?$.errors:[],$.cause]){let K=Y4(Q,J+1);if(K)return K}return null}async function E9($,J){let Z=Y4($),Q=new URL(J).hostname.replace(/^\[|\]$/g,"");if(Z!==null&&Z!=="custom_endpoint_connection_failed"||R9(Q)!==0)return Z;let K;return await Promise.race([T9(Q).then(()=>!0,(G)=>!F4.has(String(G?.code))),new Promise((G)=>{K=setTimeout(()=>G(!0),5000)})]).finally(()=>clearTimeout(K))?Z:"custom_endpoint_host_not_found"}function k9($){for(let J=42;;J++){if(J===127)J=256;let Z=String.fromCodePoint(J);if(!$.includes(Z))return Z}}function S9($,J){let Z=Buffer.from($),Q=Buffer.from(J),K=new Uint32Array(Z.length);for(let G=1,U=0;G<Z.length;G++){while(U&&Z[G]!==Z[U])U=K[U-1];if(Z[G]===Z[U])U++;K[G]=U}let B=0;return(G,U=!1)=>{let Y=Buffer.allocUnsafe(G.length*Q.length+B),F=0;for(let X of G){while(B&&Z[B]!==X){let W=K[B-1];F+=Z.copy(Y,F,0,B-W),B=W}if(Z[B]===X){if(B++,B===Z.length)F+=Q.copy(Y,F),B=0}else Y[F++]=X}if(U)F+=Z.copy(Y,F,0,B),B=0;return Y.subarray(0,F)}}async function W4($){$.signal.throwIfAborted();let J=X4.safeParse($.payload);if(!J.success)throw new H("custom_endpoint_invalid_request","Invalid local model request.");let Z=J.data,Q=U4.parse(await $.credential($.signal));if(!G4(Z,{baseUrl:Z.baseUrl,api:Q.api,execution:"device"}))throw new H("custom_endpoint_invalid_request","The request does not match the configured API.");$.signal.throwIfAborted();let K,B,G=0,U=0,Y=0,F=k9(Q.apiKey),X=S9(Q.apiKey,F),W=async(N,C)=>{$.signal.throwIfAborted(),await new Promise((M,w)=>{let D=()=>{$.signal.removeEventListener("abort",D),w($.signal.reason)};if($.signal.addEventListener("abort",D,{once:!0}),$.signal.aborted){D();return}Promise.resolve().then(()=>{return $.signal.throwIfAborted(),$.emit(N,C)}).then(()=>{$.signal.removeEventListener("abort",D),M()},(j)=>{$.signal.removeEventListener("abort",D),w(j)})})},z=async(N)=>{if(G+=N.length,G>C2)throw new H("custom_endpoint_response_too_large","Local model response exceeds the transport limit.");for(let C=0;C<N.length;C+=H2){if(Y>=B4)throw new H("custom_endpoint_response_too_large","Local model response exceeds the chunk limit.");await W(`custom_endpoint.chunk.${Y++}`,{eof:!1,data:N.subarray(C,C+H2).toString("base64")})}};try{let N=await q9({url:Z.url,body:Z.body,signal:$.signal,headers:{...Z.headers,...Q.api==="anthropic-messages"?{"x-api-key":Q.apiKey}:{authorization:`Bearer ${Q.apiKey}`}}});K=N.response,B=N.close;let C=K.statusCode??500;if(C>=300&&C<400)throw new H("custom_endpoint_redirect_refused","Local model redirects are not followed.");if(K.headers["content-encoding"]&&K.headers["content-encoding"]!=="identity")throw new H("custom_endpoint_encoding_unsupported","The local server must honor identity encoding.");let M={};for(let w of["content-type","retry-after","x-request-id","request-id"]){let D=K.headers[w];if(typeof D==="string")M[w]=D.replaceAll(Q.apiKey,F).slice(0,4096)}await W("custom_endpoint.headers",{status:C,statusText:(K.statusMessage??"").replaceAll(Q.apiKey,F).slice(0,256),headers:M});for await(let w of K){$.signal.throwIfAborted();let D=Buffer.isBuffer(w)?w:Buffer.from(w);if(U+=D.length,U>C2)throw new H("custom_endpoint_response_too_large","Local model response exceeds the transport limit.");await z(X(D))}return await z(X(Buffer.alloc(0),!0)),await W(`custom_endpoint.chunk.${Y}`,{eof:!0}),{bytes:G,chunks:Y}}catch(N){if($.signal.throwIfAborted(),N instanceof H)throw N;throw new H((K?null:await E9(N,Z.url))??"custom_endpoint_request_failed","The local model server could not complete the request.")}finally{B?.()}}import{join as z4}from"path";function f9($,J){return $===z4(J,".ara","workspace")||$===z4(J,".reason","workspace")}function N4($,J){let Z=$.filter((Q)=>f9(Q.path,J));return Z.length===1?Z[0].path:null}var b9=/^[a-f0-9]{64}$/;var D2=32,x9=/^\/[^\x00-\x1f\x7f\\]*$/;function L1($){if(typeof $!=="string"||$.length>4096||!x9.test($))return!1;if($==="/")return!0;return $.split("/").slice(1).every((J)=>J!==""&&J!=="."&&J!=="..")}function O1($,J){let Z=J==="win32"?/^([A-Za-z]):[\\/]*(.*)$/.exec($):null;if(!Z)return $;let Q=Z[2].split(/[\\/]+/).filter(Boolean).join("/");return`/${Z[1].toUpperCase()}:${Q?`/${Q}`:""}`}function I1($){if(!$||typeof $!=="object"||Array.isArray($))return;let J=$;if(!L1(J.home)||!Array.isArray(J.roots)||J.roots.length>D2)return;let Z=[];for(let Q of J.roots){if(!Q||typeof Q!=="object"||Array.isArray(Q))return;let{path_fingerprint:K,path:B}=Q;if(typeof K!=="string"||!b9.test(K)||!L1(B))return;Z.push({path_fingerprint:K,path:B})}return{home:J.home,roots:Z}}function y9($){let J=/^Reason contributor (rc_[0-9a-f]{32})$/.exec($.name)?.[1];return $.email.toLowerCase()==="343777287+reason-contributors@users.noreply.github.com"&&J?J:void 0}function h9($){return y9($)??$.email.toLowerCase()}function w2($){let J=/^Co-authored-by:\s*([^<>\r\n]+) <([^<>\s]+)>$/i.exec($.trim());return J?h9({name:J[1],email:J[2]}):$.trim().toLowerCase()}var r0=($)=>$.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/[a-z]/gi,(J)=>`[${J.toLowerCase()}${J.toUpperCase()}]`),m9=[...A1.map(($)=>`/(${$.map(r0).join("/")})(/|$)`),..._1.map(($)=>`/(${$.map(r0).join("/")})(/|$)`),...[...P1].map(($)=>`/(${r0($)})$`),`/${r0(".env.")}[^/]*$`,...T1.map(($)=>`/[^/]*${r0($)}$`)],H4=`function localGithubSandboxProfile(root, temporary) {
|
|
3
3
|
return ['(version 1)','(deny default)','(import "system.sb")','(allow process-exec process-fork)',
|
|
4
4
|
'(allow file-read* (subpath "/bin") (subpath "/sbin") (subpath "/usr/bin") (subpath "/usr/sbin") (subpath "/usr/libexec") (subpath "/usr/share") (subpath "/private/var/select") (literal "/private/var/db/xcode_select_link"))',
|
|
5
5
|
'(allow file-read-metadata (path-ancestors "/opt/homebrew/bin") (path-ancestors "/usr/local/bin") (path-ancestors "/Library/Developer/CommandLineTools"))',
|
|
@@ -34,7 +34,7 @@ Content-Length: 0\r
|
|
|
34
34
|
\r
|
|
35
35
|
`),U8(Y,N,F)})().catch(()=>Y.destroy())}),await new Promise((U,Y)=>{B.once("error",Y),B.listen(0,"127.0.0.1",()=>U())});let{port:G}=B.address();return{url:`http://127.0.0.1:${G}`,close(){B.close();for(let U of Q)U.destroy()}}}import{createHash as l2,randomUUID as k$}from"crypto";import{closeSync as p1,constants as J0,fchownSync as S$,fstatSync as L0,fsyncSync as f$,linkSync as P8,lstatSync as v2,mkdirSync as T8,openSync as v1,readSync as E8,realpathSync as u2,unlinkSync as R8,writeSync as b$}from"fs";import{isAbsolute as x$,join as y$,relative as h$,sep as m$}from"path";import{platform as p2}from"os";import{getSystemErrorName as v$}from"util";var H8={type:"string",format:"uuid"},M8=String.raw`^(?![\\/])(?![A-Za-z]:[\\/])(?!.*(?:^|[\\/])\.\.(?:[\\/]|$))(?!.*\u0000)(?=.*\S)[\s\S]+$`,x1={type:"string",minLength:1,maxLength:4096,pattern:M8},b2=V.string().min(1).max(4096).regex(new RegExp(M8)),y1={device_id:V.string().uuid(),root_id:V.string().uuid(),timeout_ms:V.number().int().min(1000).max(60000).optional()},h1={device_id:H8,root_id:H8,timeout_ms:{type:"integer",minimum:1000,maximum:60000}},iB={read:{schema:V.object({...y1,path:b2,offset:V.number().int().min(0).optional(),max_bytes:V.number().int().min(1).max(131072).optional()}).strict(),inputSchema:{type:"object",required:["device_id","root_id","path"],properties:{...h1,path:x1,offset:{type:"integer",minimum:0},max_bytes:{type:"integer",minimum:1,maximum:131072}},additionalProperties:!1}},write:{schema:V.object({...y1,path:b2,content:V.string().max(131072),mode:V.enum(["overwrite","append"]).optional(),create_parents:V.boolean().optional()}).strict(),inputSchema:{type:"object",required:["device_id","root_id","path","content"],properties:{...h1,path:x1,content:{type:"string",maxLength:131072},mode:{type:"string",enum:["overwrite","append"]},create_parents:{type:"boolean"}},additionalProperties:!1}},exec:{schema:V.object({...y1,command:V.string().min(1).max(16000),cwd:b2.optional(),mode:V.enum(["confined","host"]).optional()}).strict(),inputSchema:{type:"object",required:["device_id","root_id","command"],properties:{...h1,command:{type:"string",minLength:1,maxLength:16000},cwd:x1,mode:{type:"string",enum:["confined","host"],description:"Defaults to host: the existing permitted login shell with OS/account access, requiring execute and environment-discovery permission. Request confined explicitly for a scrubbed shell without network."}},additionalProperties:!1}}},z0=1073741824,Z1=600000,C8=String.raw`(?!\.{1,2}(?:/|(?![\s\S])))[^/\\\u0000]+`,j8=String.raw`^(?![A-Za-z]:/)(?=[\s\S]*\S)${C8}(?:/${C8})*(?![\s\S])`,L8=new RegExp(j8);function O8($){return typeof $==="string"&&$.length>0&&$.length<=4096&&L8.test($)}var x2=V.string().min(1).max(4096).regex(L8),y2={...x1,pattern:j8},I8=V.string().regex(/^[a-f0-9]{64}$/),A8=V.object({kind:V.literal("workspace"),path:x2}).strict(),q$=V.discriminatedUnion("kind",[A8,V.object({kind:V.literal("attachment"),attachment_id:V.string().min(1).max(120),sha256:I8}).strict()]),m1=1,Q1="cloud_workspace_id",h2="cloud_workspace",m2=1,g$=V.discriminatedUnion("kind",[A8,V.object({kind:V.literal("attachment"),download_url:V.string().min(1).max(16384),size_bytes:V.number().int().min(0).max(z0),sha256:I8}).strict()]),_8=V.object({source_version:V.literal(m1),source:g$,url:V.string().min(1).max(16384),transfer_cloud_scope:V.object({sandboxId:V.string().min(1).max(256),revision:V.number().int().nonnegative(),brainFence:V.string().uuid()}).strict().optional(),[Q1]:V.string().min(1).max(160).optional()}).strict(),oB=V.object({ready:V.literal(!0),cloud_source_version:V.literal(m1),source_kinds:V.array(V.enum(["workspace","attachment"]))});var D8=V.object({...y1,timeout_ms:V.number().int().min(1000).max(Z1).optional(),source_path:x2,destination_path:x2,idempotency_key:V.string().min(1).max(160).regex(/^[A-Za-z0-9._:-]+$/).optional()}).strict(),w8={type:"object",required:["device_id","root_id","source_path","destination_path"],properties:{...h1,timeout_ms:{type:"integer",minimum:1000,maximum:Z1},source_path:y2,destination_path:y2,idempotency_key:{type:"string",minLength:1,maxLength:160,pattern:"^[A-Za-z0-9._:-]+$"}},additionalProperties:!1},E$={oneOf:[{type:"object",required:["kind","path"],properties:{kind:{type:"string",const:"workspace"},path:y2},additionalProperties:!1},{type:"object",required:["kind","attachment_id","sha256"],properties:{kind:{type:"string",const:"attachment"},attachment_id:{type:"string",minLength:1,maxLength:120},sha256:{type:"string",pattern:"^[a-f0-9]{64}$"}},additionalProperties:!1}]},tB=V.union([D8,D8.omit({source_path:!0}).extend({source:q$}).strict()]),eB={...w8,required:["device_id","root_id","destination_path"],properties:{...w8.properties,source:E$},oneOf:[{required:["source_path"],not:{required:["source"]}},{required:["source"],not:{required:["source_path"]}}]};var s2=65536;function l($){throw new H($,$)}function d1($){return typeof $==="object"&&$!==null&&"code"in $&&typeof $.code==="string"?$.code:void 0}function u1($,J,Z){if(J.throwIfAborted(),$ instanceof H||$ instanceof Error&&$.name==="AbortError")throw $;return l(Z)}function u$($,J,Z){let Q;switch(d1($)){case"ENOENT":Q=Z==="export"?"transfer_source_missing":"transfer_path_unavailable";break;case"EACCES":case"EPERM":case"EROFS":Q="transfer_permission_denied";break;case"ELOOP":case"ENOTDIR":Q="transfer_path_unsafe";break;case"EEXIST":Q="transfer_destination_exists";break;default:Q="transfer_path_unavailable"}return u1($,J,Q)}function p$($){if(typeof $!=="string"||$.length>16384)return l("transfer_url_invalid");let J;try{J=new URL($)}catch{return l("transfer_url_invalid")}if(J.protocol!=="https:"||J.username||J.password||J.hash)return l("transfer_url_invalid");return J.href}var d2=J0.O_RDONLY|J0.O_DIRECTORY|J0.O_NOFOLLOW;async function d$(){if(p2()==="win32"){let F=new Map,X,W=-1,z=()=>Object.assign(Error("transfer_path_unsafe"),{code:"ELOOP"}),N=(D)=>{let j=h$(X,D);return j===""||j!==".."&&!j.startsWith(`..${m$}`)&&!x$(j)},C=(D)=>{let j=v2(D);if(j.isSymbolicLink())throw z();if(!j.isDirectory())throw Object.assign(Error("transfer_path_unsafe"),{code:"ENOTDIR"});let O=u2(D);if(X??=O,!N(O))throw z();return F.set(W,{path:D,real:O}),W--},M=(D)=>{let j=F.get(D);if(u2(j.path)!==j.real)throw z();return j.path},w=(D,j)=>{if(l1(j))throw Object.assign(Error("transfer_path_invalid"),{code:"ENOTDIR"});return y$(F.get(D).path,j)};return{root:C,openDirectory:(D,j)=>C(w(D,j)),open:(D,j,O,A=384)=>{let b=w(D,j);if(v2(b,{throwIfNoEntry:!1})?.isSymbolicLink())throw z();M(D);let I=v1(b,O,A);try{let R=L0(I),P=v2(b);if(P.isSymbolicLink()||R.ino!==P.ino||R.dev!==P.dev||!N(u2(b)))throw z()}catch(R){throw p1(I),R}return I},mkdir:(D,j)=>{let O=w(D,j);M(D),T8(O)},link:(D,j,O)=>{let A=w(D,j),b=w(D,O);M(D),P8(A,b)},unlink:(D,j)=>R8(w(D,j)),closeDirectory:(D)=>{F.delete(D)},inherit:()=>{},close:()=>{}}}let $={root:(F)=>v1(F,d2),closeDirectory:p1,inherit:l$};if(p2()==="linux")return{...$,openDirectory:(F,X)=>v1(`/proc/self/fd/${F}/${X}`,d2),open:(F,X,W,z=384)=>v1(`/proc/self/fd/${F}/${X}`,W,z),mkdir:(F,X)=>T8(`/proc/self/fd/${F}/${X}`,{mode:448}),link:(F,X,W)=>P8(`/proc/self/fd/${F}/${X}`,`/proc/self/fd/${F}/${W}`),unlink:(F,X)=>R8(`/proc/self/fd/${F}/${X}`),close:()=>{}};if(p2()!=="darwin")return l("transfer_platform_unsupported");let{dlopen:J,FFIType:Z,ptr:Q,read:K}=await import("bun:ffi"),B=J("/usr/lib/libSystem.B.dylib",{__error:{args:[],returns:Z.ptr},openat:{args:[Z.i32,Z.ptr,Z.i32,Z.i32,Z.i32,Z.i32,Z.i32,Z.i32,Z.i32],returns:Z.i32},mkdirat:{args:[Z.i32,Z.ptr,Z.i32],returns:Z.i32},linkat:{args:[Z.i32,Z.ptr,Z.i32,Z.ptr,Z.i32],returns:Z.i32},unlinkat:{args:[Z.i32,Z.ptr,Z.i32],returns:Z.i32}}),G=B.symbols.__error();if(G===null)return B.close(),l("transfer_path_unavailable");let U=(F)=>{if(F<0){let X=v$(-K.i32(G));throw Object.assign(Error("transfer_path_unavailable"),{code:X})}return F},Y=(F,X,W,z=384)=>U(B.symbols.openat(F,Q(Buffer.from(`${X}\x00`)),W,z,0,0,0,0,z));return{...$,openDirectory:(F,X)=>Y(F,X,d2),open:Y,mkdir:(F,X)=>{U(B.symbols.mkdirat(F,Q(Buffer.from(`${X}\x00`)),448))},link:(F,X,W)=>{U(B.symbols.linkat(F,Q(Buffer.from(`${X}\x00`)),F,Q(Buffer.from(`${W}\x00`)),0))},unlink:(F,X)=>{U(B.symbols.unlinkat(F,Q(Buffer.from(`${X}\x00`)),0))},close:()=>B.close()}}function l$($,J){let Z=L0($),Q=L0(J);if(Q.uid!==Z.uid||Q.gid!==Z.gid)S$(J,Z.uid,Z.gid)}function s$($,J,Z,Q){if(!O8(Z))return l("transfer_path_invalid");let K=Z.split("/"),B=$.root(J);try{for(let G of K.slice(0,-1)){let U;try{U=$.openDirectory(B,G)}catch(Y){if(!Q||d1(Y)!=="ENOENT")throw Y;try{$.mkdir(B,G)}catch(F){if(d1(F)!=="EEXIST")throw F}U=$.openDirectory(B,G),$.inherit(B,U)}$.closeDirectory(B),B=U}return{fd:B,leaf:K.at(-1)}}catch(G){throw $.closeDirectory(B),G}}function q8($,J){let Z=L0($,{bigint:!0});if(!Z.isFile()||Z.size>z0)return l("transfer_file_invalid");let Q=l2("sha256"),K=Buffer.alloc(s2),B=0;while(!0){J.throwIfAborted();let U=E8($,K,0,K.length,B);if(!U)break;if(B+=U,B>z0)return l("transfer_size_exceeded");Q.update(K.subarray(0,U))}let G=L0($,{bigint:!0});if(BigInt(B)!==Z.size||G.size!==Z.size||G.mtimeNs!==Z.mtimeNs||G.ctimeNs!==Z.ctimeNs)return l("transfer_source_changed");return{size_bytes:B,sha256:Q.digest("hex")}}async function E0($){$.signal.throwIfAborted();try{let J=p$($.payload.url),Z=await d$(),Q,K,B;try{if(Q=s$(Z,$.root,$.path,$.direction==="import"),$.direction==="export"){K=Z.open(Q.fd,Q.leaf,J0.O_RDONLY|J0.O_NOFOLLOW|J0.O_NONBLOCK);let z=L0(K,{bigint:!0});if(!z.isFile()||z.size>z0)return l("transfer_file_invalid");let N=l2("sha256"),C=0,M=K,w,D=new ReadableStream({pull(b){try{$.signal.throwIfAborted();let I=Buffer.alloc(s2),R=E8(M,I,0,I.length,C);if(!R){b.close();return}if(C+=R,C>z.size)return l("transfer_source_changed");N.update(I.subarray(0,R)),b.enqueue(I.subarray(0,R))}catch(I){throw w=I,I}}});try{let b=await($.fetchImpl??fetch)(J,Object.assign({method:"PUT",body:D,redirect:"error",signal:$.signal,headers:{"content-type":"application/octet-stream","content-length":String(z.size)}},{duplex:"half"}));if(w!==void 0)throw w;if(!b.ok)return l("transfer_upload_failed");await b.body?.cancel()}catch(b){if(w!==void 0)throw w;return u1(b,$.signal,"transfer_upload_failed")}let j=L0(K,{bigint:!0});if(BigInt(C)!==z.size||j.size!==z.size||j.mtimeNs!==z.mtimeNs||j.ctimeNs!==z.ctimeNs)return l("transfer_source_changed");let O=N.digest("hex"),A=q8(K,$.signal);if(A.size_bytes!==C||A.sha256!==O)return l("transfer_source_changed");return{size_bytes:C,sha256:O,outcome:"copied"}}let G=$.payload.size_bytes,U=$.payload.sha256;if(typeof G!=="number"||!Number.isSafeInteger(G)||G<0||G>z0||typeof U!=="string"||!/^[a-f0-9]{64}$/.test(U))return l("transfer_receipt_invalid");let Y;try{Y=Z.open(Q.fd,Q.leaf,J0.O_RDONLY|J0.O_NOFOLLOW|J0.O_NONBLOCK)}catch(z){if(d1(z)!=="ENOENT")throw z}if(Y!==void 0){try{let z=q8(Y,$.signal);if(z.size_bytes===G&&z.sha256===U)return{...z,outcome:"already_present"}}finally{p1(Y)}return l("transfer_destination_exists")}B=`.reason-copy-${k$()}`,K=Z.open(Q.fd,B,J0.O_CREAT|J0.O_EXCL|J0.O_WRONLY|J0.O_NOFOLLOW,384),Z.inherit(Q.fd,K);let F;try{let z=await($.fetchImpl??fetch)(J,{redirect:"error",signal:$.signal});if(!z.ok||!z.body)return l("transfer_download_failed");F=z.body.getReader()}catch(z){return u1(z,$.signal,"transfer_download_failed")}let X=l2("sha256"),W=0;try{while(!0){$.signal.throwIfAborted();let z=await F.read().catch((N)=>u1(N,$.signal,"transfer_download_failed"));if(z.done)break;if(W+=z.value.length,W>G)return l("transfer_size_mismatch");X.update(z.value);for(let N=0;N<z.value.length;)$.signal.throwIfAborted(),N+=b$(K,z.value,N,Math.min(s2,z.value.length-N))}}finally{await F.cancel().catch(()=>{})}if(W!==G||X.digest("hex")!==U)return l("transfer_hash_mismatch");return f$(K),await $.beforeCommit?.(),$.signal.throwIfAborted(),Z.link(Q.fd,B,Q.leaf),{size_bytes:G,sha256:U,outcome:"copied"}}finally{try{if(K!==void 0)p1(K)}finally{try{if(Q){if(B)try{Z.unlink(Q.fd,B)}catch{}Z.closeDirectory(Q.fd)}}finally{Z.close()}}}}catch(J){return u$(J,$.signal,$.direction)}}import{spawn as n$}from"child_process";import{mkdtempSync as r$,rmSync as a$,writeFileSync as i$}from"fs";import{constants as o$,platform as t$,tmpdir as e$}from"os";import{join as b8}from"path";import{gunzipSync as c$,gzipSync as YV}from"zlib";var S8=900000,zV=S8+60000,K1=49152,k8=($)=>V.string().min(1).max($).regex(/^[A-Za-z0-9+/]+=*$/),f8=V.object({version:V.literal(1),script_gzip:k8(163840),stdin_gzip:k8(65536),cwd:V.string().min(1).max(4096).startsWith("/"),env:V.record(V.string().regex(/^[A-Z_][A-Z0-9_]{0,63}$/),V.string().max(4096)).refine(($)=>Object.keys($).length<=16,"too many variables"),timeout_ms:V.number().int().min(1000).max(S8)}).strict(),c2=V.string().max(K1+256),NV=V.object({exit_code:V.number().int().min(0).max(255),stdout:c2,stderr:c2,combined:c2.optional()}).strict();function n2($){return c$(Buffer.from($,"base64")).toString("utf8")}var $J="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",JJ=["RUSTUP_HOME","TZ","LC_ALL"],ZJ=2000,QJ=100;function a2(){return t$()==="linux"&&process.geteuid?.()===0}function r2($){let J=Math.floor($/2),Z=[],Q=0,K=Buffer.alloc(0),B=0;return{push(G){B+=G.length;let U=G;if(Q<J){let Y=U.subarray(0,J-Q);Z.push(Y),Q+=Y.length,U=U.subarray(Y.length)}if(U.length)K=Buffer.concat([K,U]).subarray(-J)},text(){let G=B-Q-K.length;return Buffer.concat(Z).toString("utf8")+(G>0?`
|
|
36
36
|
[reason: ${G} bytes of output omitted]
|
|
37
|
-
`:"")+K.toString("utf8")}}}async function x8($,J){if(!a2())throw new H("workspace_setup_requires_root","Workspace setup runs only on a root Linux worker.");let Z=f8.safeParse($);if(!Z.success)throw new H("invalid_request","Reason sent an invalid workspace setup.");let Q=Z.data,K,B;try{K=n2(Q.script_gzip),B=n2(Q.stdin_gzip)}catch{throw new H("invalid_request","Reason sent an unreadable workspace setup.")}J.throwIfAborted();let G=r$(b8(e$(),"reason-workspace-setup-"));try{let U=b8(G,"setup.sh");i$(U,K,{mode:384});let Y={PATH:$J,LANG:"C.UTF-8",HOME:"/root",USER:"root",LOGNAME:"root",SHELL:"/bin/bash",TMPDIR:"/tmp"};for(let A of JJ)if(process.env[A])Y[A]=process.env[A];Object.assign(Y,Q.env);let F=n$("/bin/bash",[U],{cwd:Q.cwd,env:Y,detached:!0,stdio:["pipe","pipe","pipe"]}),X=r2(K1),W=r2(K1),z=r2(K1);F.stdout.on("data",(A)=>{X.push(A),z.push(A)}),F.stderr.on("data",(A)=>{W.push(A),z.push(A)}),F.stdin.on("error",()=>{}),F.stdin.end(B);let N=(A)=>{try{if(F.pid)process.kill(-F.pid,A)}catch{}},C=!1,M,w=()=>{N("SIGTERM"),M??=setTimeout(()=>N("SIGKILL"),ZJ)},D=setTimeout(()=>{C=!0,w()},Q.timeout_ms);J.addEventListener("abort",w,{once:!0});let j=await new Promise((A,b)=>{F.once("error",()=>b(new H("workspace_setup_start_failed","The workspace setup did not start."))),F.once("exit",(I,R)=>A({code:I,signal:R}))}).finally(()=>{clearTimeout(D),clearTimeout(M),J.removeEventListener("abort",w)});await new Promise((A)=>{let b=setTimeout(A,QJ);F.once("close",()=>{clearTimeout(b),A()})}),F.stdout.destroy(),F.stderr.destroy(),J.throwIfAborted();let O=C?124:j.signal?128+(o$.signals[j.signal]??0):j.code??1;return{exit_code:Math.min(255,O),stdout:X.text(),stderr:W.text(),...O!==0?{combined:z.text()}:{}}}finally{a$(G,{recursive:!0,force:!0})}}import{chmodSync as KJ,mkdtempSync as BJ,realpathSync as v8,rmSync as VJ}from"fs";import{tmpdir as GJ}from"os";import{dirname as XJ,join as i2,sep as UJ}from"path";function o2($){return m8($,h8($)!==null).repoPath}function u8($,J){let Z;try{if(typeof J!=="string")throw Error("invalid");Z=[B1,void 0].map((K)=>XJ(y8({kind:"managed",workspaceId:J,...K?{layout:K}:{}})))}catch{throw new H("cloud_copy_workspace_invalid","The Cloud copy workspace is invalid.")}let Q;for(let K of Z)try{Q=v8(i2($,K));break}catch{}if(Q===void 0)throw new H("cloud_copy_workspace_unavailable","The Session workspace is not on this computer.");if(!Q.startsWith(`${$}${UJ}`))throw new H("cloud_copy_workspace_invalid","The Cloud copy workspace is outside this worker's root.");return Q}async function p8($){$.signal.throwIfAborted();let J=$.source;if(J.kind==="workspace"){let Q=o2($.runtimeRoot);if(k0(Q)||k0(i2(Q,J.path)))throw new H("protected_path","Credential and secret paths are unavailable to local tasks.");return E0({direction:"export",root:Q,path:J.path,payload:{url:$.url},signal:$.signal,fetchImpl:$.fetchImpl})}let Z=BJ(i2(GJ(),`reason-cloud-copy-${process.pid}-`));try{KJ(Z,448);let Q=v8(Z);await E0({direction:"import",root:Q,path:"source",payload:{url:J.download_url,size_bytes:J.size_bytes,sha256:J.sha256},signal:$.signal,fetchImpl:$.fetchImpl});let K=await E0({direction:"export",root:Q,path:"source",payload:{url:$.url},signal:$.signal,fetchImpl:$.fetchImpl});if(K.size_bytes!==J.size_bytes||K.sha256!==J.sha256)throw new H("transfer_source_changed","The verified attachment changed before export.");return K}finally{VJ(Z,{recursive:!0,force:!0})}}import{constants as K0}from"fs";import{closeSync as G9,existsSync as F0,fstatSync as X9,ftruncateSync as lQ,lstatSync as p3,mkdirSync as sQ,mkdtempSync as cQ,openSync as U9,readSync as nQ,realpathSync as X0,rmSync as rQ,statSync as w1,writeSync as aQ}from"fs";import{homedir as H1,platform as E,tmpdir as iQ}from"os";import{dirname as C1,isAbsolute as oQ,join as F9,relative as d3,resolve as tQ,sep as eQ}from"path";import{spawn as $K}from"child_process";import{createHash as NJ,randomBytes as HJ}from"crypto";var t2=30000,FJ=1800000,YJ=5000,s1=30000,WJ=n1+15000,d8=/^\/app\/local-runtime\/operations\/[0-9a-fA-F-]{36}\/heartbeat$/,zJ=[/^\/app\/local-runtime\/operations\/claim$/,d8];class e2{options;current=null;connecting=null;retryAt=0;failures=0;nextId=0;closed=!1;reconnectTimer=null;constructor($){this.options=$}now(){return(this.options.now??Date.now)()}jitter($){return Math.floor((this.options.random??Math.random)()*$)}async request($,J,Z){Z?.throwIfAborted();let Q=this.current;if(!Q)return this.connect(),null;if(Q.pending.size>=Q.maxInFlight)return null;let K=String(++this.nextId),B=new Promise((Y)=>Q.pending.set(K,{path:$,resolve:Y}));if(!this.send(Q,{t:"req",id:K,path:$,body:J}))return Q.pending.delete(K),null;let G;if(zJ.some((Y)=>Y.test($)))G=setTimeout(()=>{if(Q.pending.has(K))this.drop(Q)},WJ);else{let Y=()=>{if(!Q.pending.has(K))return;let F=this.now()-Q.lastFrameAt;if(F>=s1)this.drop(Q);else G=setTimeout(Y,s1-F)};G=setTimeout(Y,s1)}if(B.finally(()=>clearTimeout(G)),!Z)return await B;let U=new Promise((Y,F)=>{let X=()=>{if(Q.pending.delete(K),clearTimeout(G),this.send(Q,{t:"abort",id:K}),this.now()-Q.lastFrameAt>s1)this.drop(Q);F(Z.reason)};if(Z.aborted)X();else Z.addEventListener("abort",X,{once:!0}),B.finally(()=>Z.removeEventListener("abort",X))});return await Promise.race([B,U])}cadence(){return this.current?.cadence??null}close(){if(this.closed=!0,this.reconnectTimer)clearTimeout(this.reconnectTimer);for(let $ of[this.current,this.connecting])if($)this.drop($)}send($,J){try{return $.socket.send(JSON.stringify(J)),!0}catch{return this.drop($),!1}}drop($){if($.dropped)return;$.dropped=!0,this.settle($);try{$.socket.close()}catch{}}settle($){for(let J of $.pending.values())J.resolve(null);if($.pending.clear(),this.current===$)this.current=null,this.retryAt=Math.max(this.retryAt,this.now()+this.jitter(YJ));if(this.connecting===$){this.connecting=null,this.failures+=1;let J=Math.min(FJ,t2*2**Math.min(this.failures-1,10));this.retryAt=Math.max(this.retryAt,this.now()+J/2+this.jitter(J/2))}}connect(){if(this.closed||this.connecting||this.now()<this.retryAt)return;let $=this.options.WebSocket??globalThis.WebSocket;if(!$){this.retryAt=Number.POSITIVE_INFINITY;return}let J=new URL(c1,this.options.apiOrigin);J.protocol=J.protocol==="https:"?"wss:":"ws:",J.searchParams.set("device_id",this.options.deviceId);let Z;try{Z=new $(J.toString())}catch{this.failures+=1,this.retryAt=this.now()+t2;return}let Q={socket:Z,pending:new Map,maxInFlight:0,cadence:null,lastFrameAt:this.now(),dropped:!1};this.connecting=Q,Z.onmessage=(K)=>this.receive(Q,K.data),Z.onclose=()=>this.settle(Q),Z.onerror=()=>this.settle(Q)}receive($,J){if(typeof J!=="string")return;let Z;try{Z=JSON.parse(J)}catch{return}if($.lastFrameAt=this.now(),Z.t==="res"){let Q=$.pending.get(Z.id);$.pending.delete(Z.id),Q?.resolve({status:Z.status,body:Z.body,retryAfter:Z.retry_after??null});return}if(Z.t==="challenge"&&this.connecting===$){let Q;try{Q=this.options.signHello(Z.challenge)}catch{this.drop($);return}this.send($,{t:"hello",...Q});return}if(Z.t==="ready"&&this.connecting===$){this.connecting=null,this.failures=0,$.maxInFlight=Math.max(1,Math.min(Z.max_in_flight,1000)),$.cadence=Z.cadence??null;let Q=this.current;if(this.current=$,Q){for(let[K,B]of Q.pending){if(!d8.test(B.path))continue;Q.pending.delete(K),this.send(Q,{t:"abort",id:K}),B.resolve(null)}if(Q.pending.size===0)this.drop(Q)}return}if(Z.t==="fallback"){this.retryAt=this.now()+Math.max(t2,Math.min(Z.retry_after_ms,86400000)),this.drop($);return}if(Z.t==="reconnect"&&this.current===$&&!this.reconnectTimer)this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.retryAt=0,this.connect()},Math.max(0,Math.min(Z.after_ms,60000)))}}var J3=["fs.read","fs.write","fs.export","fs.import","exec.run","exec.full","process.run.v1","process.full.v1","preview.serve.v1","pty.start","git.run","process.list","ports.list","computer.use","browser.use","browser.recording.v1","browser.pr-proof.v1","hands.connect","jobs.control","environment.install","github.local.v1","inference.custom.v1","display.stream.v1","automation.call.v1","simulator.call.v1","simulator.stream.v1","tunnel.open","tunnel.close","workspace.setup.v1"];function vV($,J={}){let Z=CJ($),Q=J.rootPathsSupported===!0?I1($.root_paths):void 0;return{supported_operations:[...$.supported_operations],...J.accountRootMetadataSupported===!0&&typeof $.account_root_fingerprint==="string"&&/^[a-f0-9]{64}$/.test($.account_root_fingerprint)?{account_root_fingerprint:$.account_root_fingerprint}:{},...J.workspaceRootMetadataSupported===!0&&typeof $.workspace_root_fingerprint==="string"&&/^[a-f0-9]{64}$/.test($.workspace_root_fingerprint)?{workspace_root_fingerprint:$.workspace_root_fingerprint}:{},...J.accountRootPathSupported===!0&&typeof $.account_root_path==="string"&&$.account_root_path.startsWith("/")&&$.account_root_path.length<=4096?{account_root_path:$.account_root_path}:{},...J.homeContainedRootsSupported===!0&&Array.isArray($.home_contained_root_fingerprints)&&$.home_contained_root_fingerprints.length<=32&&$.home_contained_root_fingerprints.every((K)=>/^[a-f0-9]{64}$/.test(K))?{home_contained_root_fingerprints:[...$.home_contained_root_fingerprints]}:{},...Q?{root_paths:Q}:{},...Object.keys(Z).length?{operation_constraints:Z}:{},...$.hands_worker_artifact_sha256&&$.hands_worker_entrypoint?{hands_worker_artifact_sha256:$.hands_worker_artifact_sha256,hands_worker_entrypoint:$.hands_worker_entrypoint}:{},...$.hands_slots!==void 0?{hands_slots:$.hands_slots}:{}}}function CJ($){let J=(Q)=>Q===null||typeof Q==="boolean"||typeof Q==="number"&&Number.isFinite(Q)||typeof Q==="string"&&Q.length<=512,Z={};for(let Q of $.supported_operations){let K=$.operation_constraints?.[Q];if(!K||typeof K!=="object"||Array.isArray(K))continue;if(!("ready"in K)||typeof K.ready!=="boolean")continue;let B={};for(let[G,U]of Object.entries(K).slice(0,32)){if(!G.length||G.length>64||["__proto__","constructor","prototype"].includes(G))continue;if(J(U)||Array.isArray(U)&&U.length<=64&&U.every(J))B[G]=U}if(Object.keys(B).length)Z[Q]=B}return Z}class N0 extends Error{status;code;retryAfter;constructor($,J,Z,Q=null){super(Z);this.status=$;this.code=J;this.retryAfter=Q;this.name="LocalRuntimeHttpError"}}class r1 extends Error{timeoutMs;constructor($){super(`Reason Device request did not answer within ${$}ms.`);this.timeoutMs=$;this.name="LocalRuntimeRequestTimeoutError"}}function DJ($){return $===408||$===429||$===500||$===502||$===503||$===504}function wJ($){if($ instanceof N0)return!1;if($ instanceof r1)return!0;if(!($ instanceof Error))return!1;if($.name==="AbortError")return!1;if($ instanceof TypeError&&$.message.toLowerCase().includes("fetch failed"))return!0;for(let J of[$,$.cause])if(J&&typeof J==="object"&&"code"in J){let Z=String(J.code);if(["ECONNRESET","ECONNREFUSED","ETIMEDOUT","EHOSTUNREACH","ENOTFOUND","EAI_AGAIN","ConnectionClosed","ConnectionRefused","UND_ERR_SOCKET","UND_ERR_CONNECT_TIMEOUT"].includes(Z))return!0}return!1}function MJ($,J,Z=500){if(J instanceof N0&&J.retryAfter){let B=parseFloat(J.retryAfter);if(Number.isFinite(B)&&B>0)return Math.min(B*1000,1e4)}let Q=Z*2**$,K=Math.floor(Math.random()*200);return Math.min(Q+K,5000)}async function jJ($,J){if(J?.aborted)throw J.reason??new DOMException("The operation was aborted.","AbortError");await new Promise((Z,Q)=>{let K=()=>{clearTimeout(B),Q(J?.reason??new DOMException("The operation was aborted.","AbortError"))},B=setTimeout(()=>{J?.removeEventListener("abort",K),Z()},$);J?.addEventListener("abort",K,{once:!0})})}function uV($){return $ instanceof N0&&$.status===401&&($.code==="device_revoked"||$.code==="invalid_device_credential")}function l8($){return Buffer.byteLength(JSON.stringify($)??"null","utf8")}function s8($){return NJ("sha256").update($??"").digest("hex")}function LJ($){return i8({method:$.method,pathAndQuery:$.route,timestamp:$.timestamp,nonce:$.nonce,challenge:$.challenge,bodySha256:$.bodySha256})}function c8($){return Boolean($)&&typeof $==="object"&&!Array.isArray($)}var OJ=20000,IJ=1e4,n8=[2000,4000],AJ=30000,_J=15000;function r8($){return $?{keepalive:!1}:{}}class $3 extends Error{constructor($){super(`Reason Device proof challenge did not answer within ${$}ms.`)}}class PJ{fetchImpl;proofStore;proofOptions;apiOrigin;spareChallenge=null;sessions=new Map;sessionsClosed=!1;constructor($,J=fetch,Z,Q={}){this.fetchImpl=J;this.proofStore=Z;this.proofOptions=Q;let K=new URL($);if(K.protocol!=="https:"&&K.hostname!=="127.0.0.1"&&K.hostname!=="localhost"&&K.hostname!=="[::1]"&&K.hostname!=="::1")throw Error("Reason Device API must use HTTPS, except for localhost development.");this.apiOrigin=K.origin}async parseResponse($){if($.status===204)return null;let J=await $.json().catch(()=>({}));if(!$.ok){let{code:Z,message:Q}=o8(J,$.status),K=$.headers?.get?.("retry-after")??null;throw new N0($.status,Z,Q,K)}return J}async challenge($,J,Z={fresh:!1}){let Q=this.proofOptions.challengeAttemptTimeoutsMs??n8;for(let K of Q)try{return await this.challengeAttempt($,J,K,Z.fresh)}catch(B){if(J?.aborted||!(B instanceof $3))throw B;Z.fresh=!0}return await this.challengeAttempt($,J,null,Z.fresh)}async challengeAttempt($,J,Z,Q=!1){let K=JSON.stringify({device_id:$}),B=Z===null?null:new AbortController,G=B&&Z!==null?setTimeout(()=>B.abort(new $3(Z)),Z):null;try{let U=await this.fetchImpl(`${this.apiOrigin}${s.authChallenge.path}`,{method:"POST",redirect:"error",headers:{accept:"application/json","content-type":"application/json"},body:K,...r8(Q),signal:B?J?AbortSignal.any([J,B.signal]):B.signal:J});return t8(await this.parseResponse(U))}catch(U){if(!J?.aborted&&B?.signal.aborted)throw B.signal.reason;throw U}finally{if(G)clearTimeout(G)}}async takeSpareChallenge($){let J=this.spareChallenge;if(this.spareChallenge=null,!J||J.deviceId!==$)return null;let Z=await J.challenge,Q=(this.proofOptions.now??Date.now)();return Z&&Date.parse(Z.expires_at)-Q>=OJ?Z:null}refillSpareChallenge($){let J=this.challengeAttempt($,void 0,n8[0]??2000).catch(()=>null);this.spareChallenge={deviceId:$,challenge:J}}async proofHeaders($,J,Z,Q,K=!1,B,G){let U=B&&Date.parse(B.expires_at)-(this.proofOptions.now??Date.now)()>=IJ?B:null,Y=!U&&K?await this.takeSpareChallenge(Z.deviceId):null,F=U??Y??await this.challenge(Z.deviceId,Q,G);if(K)this.refillSpareChallenge(Z.deviceId);let X=s8(J),W=this.signProof("POST",$,F.challenge,X);return{"x-device-id":Z.deviceId,"x-device-timestamp":W.timestamp,"x-device-nonce":W.nonce,"x-device-challenge":F.challenge,"x-device-body-sha256":X,"x-device-signature":W.signature}}signProof($,J,Z,Q){let K=String(Math.trunc((this.proofOptions.now??Date.now)())),B=(this.proofOptions.nonce??(()=>HJ(24)))();if(B.byteLength<16||B.byteLength>32)throw Error("Invalid Reason Device proof nonce.");let G=Buffer.from(B).toString("base64url"),U=this.proofStore.sign(LJ({method:$,route:J,timestamp:K,nonce:G,challenge:Z,bodySha256:Q}));if(!/^[A-Za-z0-9_-]{8,128}$/.test(U))throw Error("Reason Device proof boundary returned an invalid signature.");return{timestamp:K,nonce:G,signature:U}}sessionFor($,J){if(!this.proofOptions.deviceSession||this.sessionsClosed||!J||!a8($.path))return null;let Z=this.sessions.get(J.deviceId);if(!Z)Z=new e2({apiOrigin:this.apiOrigin,deviceId:J.deviceId,signHello:(Q)=>this.signProof("GET",c1,Q,s8("")),...this.proofOptions.webSocket?{WebSocket:this.proofOptions.webSocket}:{},...this.proofOptions.now?{now:this.proofOptions.now}:{}}),this.sessions.set(J.deviceId,Z);return Z}sessionCadence($){let J=this.proofOptions.deviceSession&&!this.sessionsClosed?this.sessions.get($.deviceId)?.cadence()??null:null;return J?{presenceIntervalMs:J.presence_interval_ms,claimWaitMs:J.claim_wait_ms}:null}close(){this.sessionsClosed=!0;for(let $ of this.sessions.values())$.close();this.sessions.clear()}async request($,J){if(J.body!==void 0&&l8(J.body)>C0)throw Error("Reason Device request exceeds the 256 KB protocol limit.");if(J.authorization!==void 0&&J.device!==void 0)throw Error("Reason Device request cannot combine bearer and proof authentication.");let Z=J.authorization!==void 0,Q=J.device!==void 0;if(!($.auth==="none"?!Z&&!Q:$.auth==="registration_bearer"?Z&&!Q:Z!==Q))throw Error(`Reason Device request used invalid authentication for ${$.path}.`);let B=J.body===void 0?void 0:JSON.stringify(J.body),G=this.proofOptions.maxAttempts??4,U=this.proofOptions.sleep??jJ,Y=this.sessionFor($,J.device),F=Math.max(AJ,(J.holdMs??0)+_J),X={fresh:!1},W;for(let z=0;z<G;z+=1)try{let N=await Y?.request($.path,J.sessionBody===void 0?B??"":JSON.stringify(J.sessionBody),J.signal)??null;if(N)return await this.parseResponse(new Response(N.status===204?null:N.body,{status:N.status,headers:N.retryAfter===null?{}:{"retry-after":N.retryAfter}}));let C=new AbortController,M=setTimeout(()=>C.abort(new r1(F)),F),w=J.signal?AbortSignal.any([J.signal,C.signal]):C.signal;try{let D=J.device===void 0?{}:await this.proofHeaders($.path,B,J.device,w,J.useSpareChallenge===!0&&z===0,z===0?J.issuedChallenge:void 0,X),j=await this.fetchImpl(`${this.apiOrigin}${$.path}`,{method:"POST",redirect:"error",headers:{...J.authorization===void 0?{}:{authorization:`Bearer ${J.authorization}`},...D,accept:"application/json",...J.body===void 0?{}:{"content-type":"application/json"}},body:B,...r8(X.fresh),signal:w});return await this.parseResponse(j)}catch(D){if(!J.signal?.aborted&&C.signal.aborted)throw C.signal.reason;throw D}finally{clearTimeout(M)}}catch(N){if(W=N,N instanceof r1)X.fresh=!0;if(J.signal?.aborted)throw N;let C=J.device!==void 0&&N instanceof N0&&N.status===401&&["invalid_device_proof","device_proof_replayed"].includes(N.code),M=N instanceof N0&&DJ(N.status),w=wJ(N),D=J.transientRetryOwner!=="caller"&&(M||w);if((C||D)&&z+1<G){let j=C?0:MJ(z,N,this.proofOptions.retryBaseDelayMs??500);if(j>0)await U(j,J.signal);continue}if(C&&z+1>=G)throw Error("Reason Device proof retry was exhausted.");throw N}throw W??Error("Reason Device request failed.")}async register($,J,Z){let Q=await this.request(s.register,{authorization:$,body:J,signal:Z});return e8(Q)}async enroll($,J,Z,Q){let K=await this.request(s.enroll,{body:{...Z,enrollment_ticket:$,code_verifier:J},signal:Q});return $5(K)}async heartbeat($,J,Z,Q){let K=await this.request(s.heartbeat,{device:$,body:J,signal:Z,...Q?{issuedChallenge:Q}:{}});return J5(K)}async syncRoots($,J,Z){let Q=await this.request(s.rootsSync,{device:$,body:{roots:J},signal:Z});return Z5(Q)}async identity($,J){let Z=await this.request(s.identity,{device:$,signal:J});return Q5(Z)}async disconnect($,J,Z,Q=[]){let K=await this.request(s.disconnect,{device:$,body:Z?{successor_device_id:Z,...Q.length?{successor_roots:Q}:{}}:{},signal:J});return K5(K)}async deviceLifecycle($,J,Z){let Q=await this.request(s.lifecycle,{device:$,body:J,signal:Z});V5(Q)}async localSubscription($,J,Z){return B5(await this.request(s.localSubscription,{device:$,body:J,signal:Z}))}async ownerWorkspaces($,J){let Q=(await this.request(s.ownerWorkspaces,{device:$,body:{},signal:J}))?.organizations;if(!Array.isArray(Q))throw Error("Reason returned an invalid workspace list.");return Q.flatMap((K)=>{let B=K;return typeof B?.id==="string"?[{id:B.id,...typeof B.name==="string"&&B.name.trim()?{name:B.name.trim()}:{},blocked:B.blocked===!0}]:[]})}async ownerWorkspaceEnrollment($,J,Z){return this.request(s.ownerWorkspaceEnrollment,{device:$,body:J,signal:Z})}async liveSessionWorktrees($,J,Z){let Q=await this.request(s.sessionWorktrees,{device:$,body:{worktree_ids:[...J]},signal:Z}).catch((K)=>{if(K instanceof N0&&K.status===404)return null;throw K});if(Q===null)return null;if(!c8(Q)||!Array.isArray(Q.live)||!Q.live.every((K)=>typeof K==="string"&&J.includes(K)))throw Error("Reason returned an invalid Session worktree answer.");return Q.live}async claimOperation($,J={}){let Z=Math.max(J.waitMs??25000,0),Q=(G)=>({wait_ms:Math.min(Z,G),...J.instanceGeneration===void 0?{}:{instance_generation:J.instanceGeneration}}),K=this.sessionCadence($)?.claimWaitMs,B=await this.request(s.operationClaim,{device:$,body:Q(30000),holdMs:Math.min(Z,30000),...K===void 0?{}:{sessionBody:Q(Math.min(K,n1))},signal:J.signal});if(B===null)return null;return G5(B,J3)}async operationHeartbeat($,J,Z={}){let Q=(G)=>this.request(s.operationHeartbeat.forOperation(J.operation_id),{device:$,body:{attempt_id:J.attempt_id,attempt_token:J.attempt_token,...Z.controlAckSeq===void 0?{}:{control_ack_seq:Z.controlAckSeq},...G?{client_retry_count:Z.clientRetryCount}:{},...G&&Z.waitMs!==void 0?{wait_ms:Math.min(Math.max(Z.waitMs,0),30000)}:{}},signal:Z.signal,transientRetryOwner:Z.transientRetryOwner,...G&&Z.waitMs!==void 0?{holdMs:Math.min(Math.max(Z.waitMs,0),30000)}:{}}),K=(Z.clientRetryCount??0)>0||Z.waitMs!==void 0,B;try{B=await Q(K)}catch(G){if(!K||!(G instanceof N0)||G.status!==400||G.code!=="invalid_operation_heartbeat")throw G;B=await Q(!1)}return X5(B)}async operationEvents($,J,Z){if(!Number.isInteger(Z.eventSeqStart)||Z.eventSeqStart<0||Z.events.length<1||Z.events.length>100||Z.events.some((K)=>!/^[A-Za-z0-9._:-]{1,64}$/.test(K.kind)||!c8(K.payload)))throw Error("Invalid Reason Device operation event batch.");let Q=await this.request(s.operationEvents.forOperation(J.operation_id),{device:$,body:{attempt_id:J.attempt_id,attempt_token:J.attempt_token,event_seq_start:Z.eventSeqStart,events:Z.events},signal:Z.signal,transientRetryOwner:Z.transientRetryOwner,...this.proofOptions.prefetchEventChallenges===!0?{useSpareChallenge:!0}:{}});return U5(Q)}async completeOperation($,J,Z,Q){let K={attempt_id:J.attempt_id,attempt_token:J.attempt_token,status:Z.status,...Z.result===void 0?{}:{result:Z.result},...Z.error_code?{error_code:Z.error_code}:{}};if(l8(K)>C0)throw Error("Reason Device operation result exceeds the 256 KB protocol limit.");let B=await this.request(s.operationComplete.forOperation(J.operation_id),{device:$,body:K,signal:Q});return Y5(B)}async operationCustomEndpointCredential($,J,Z){let{CustomEndpointDeviceCredentialSchema:Q}=await import("./custom-endpoint-device-baqm3872.js");return Q.parse(await this.request(s.operationCustomEndpointCredential.forOperation(J.operation_id),{device:$,body:{attempt_id:J.attempt_id,attempt_token:J.attempt_token},signal:Z}))}async operationEnvironment($,J,Z,Q){let K=await this.request(s.operationEnvironment.forOperation(J.operation_id),{device:$,body:{attempt_id:J.attempt_id,attempt_token:J.attempt_token,snapshot_id:Z},signal:Q,...this.proofOptions.prefetchEventChallenges===!0?{useSpareChallenge:!0}:{}});return F5(K)}async acknowledgeOperationEnvironment($,J,Z,Q){await this.request(s.operationEnvironmentAck.forOperation(J.operation_id),{device:$,body:{attempt_id:J.attempt_id,attempt_token:J.attempt_token,...Z},signal:Q,...this.proofOptions.prefetchEventChallenges===!0?{useSpareChallenge:!0}:{}})}}var TJ=new Set(["process.run.v1","process.full.v1","computer.use","browser.use"]),V1=new Set(["jobs.control","environment.install","tunnel.open","tunnel.close","display.stream.v1","automation.call.v1","workspace.setup.v1","simulator.call.v1","simulator.stream.v1"]);function a1($,J){if(TJ.has($))return!1;if(V1.has($)&&!J.runtimeDirectory)return!1;if(($==="inference.custom.v1"||$==="preview.serve.v1"||$==="simulator.call.v1"||$==="simulator.stream.v1")&&(J.executionMode!=="unsandboxed"||!J.runtimeDirectory))return!1;if(J.executionMode!=="unsandboxed"&&(["exec.full","hands.connect","pty.start","browser.pr-proof.v1"].includes($)||V1.has($)))return!1;return!0}import{accessSync as RJ,constants as qJ,existsSync as gJ,statSync as EJ}from"fs";import{basename as kJ,isAbsolute as SJ}from"path";var G1=["-lic"],W5="/bin/zsh",fJ=new Set(["zsh","bash"]),N5=20000,Z3=60000,bJ=65536,xJ=64,yJ=8192,hJ=new Set(["NODE_OPTIONS","PATH","ZDOTDIR","BASH_ENV","ENV"]),mJ=["DYLD_","LD_"];function vJ($){let J=$.toUpperCase();return hJ.has(J)||mJ.some((Z)=>J.startsWith(Z))}function H5($=process.env){return!0}function uJ($){if(!SJ($)||$.includes("\x00"))return!1;if(!fJ.has(kJ($)))return!1;try{if(!EJ($).isFile())return!1;return RJ($,qJ.X_OK),!0}catch{return!1}}function S0($=process.env){if(process.platform==="win32")return z5()??W5;let J=$.SHELL?.trim();if(J&&uJ(J))return J;return W5}function Q3($=process.env){return H5($)&&gJ(S0($))}function K3($=process.env){if(!H5($))throw new H("full_control_disabled","Full-control execution is unavailable on this Reason Device.")}function B3($){if(typeof $!=="string"||$.length===0||$.includes("\x00")||Buffer.byteLength($,"utf8")>bJ)throw new H("invalid_payload","command is missing or too large.");return $}function V3($){if($===void 0||$===null)return{forwarded:{},ignored:[]};if(typeof $!=="object"||Array.isArray($))throw new H("invalid_payload","env must be an object of strings.");let J=Object.entries($);if(J.length>xJ)throw new H("invalid_payload","env has too many entries.");let Z={},Q=[];for(let[K,B]of J){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(K)||typeof B!=="string"||B.includes("\x00")||Buffer.byteLength(B,"utf8")>yJ)throw new H("invalid_payload","env entry is invalid or too large.");if(vJ(K)){Q.push(K);continue}Z[K]=B}return{forwarded:Z,ignored:Q}}async function C5($){let J=$.processEnv??process.env;if(K3(J),$.signal.aborted)throw new H("cancelled","Operation was cancelled.");let Z=B3($.command),Q=S0(J),{forwarded:K,ignored:B}=V3($.requestEnv),G=await $.spawn(Q,[...G1,Z],{cwd:$.cwd,timeoutMs:$.timeoutMs,signal:$.signal,env:{...J,...K}});return{exit_code:G.exitCode,signal:G.signal,stdout:G.stdout,stderr:G.stderr,timed_out:G.timedOut,truncated:G.truncated,shell:Q,shell_flags:[...G1],login:!0,interactive:!0,sandbox:"none",ignored_env:B}}function D5($=process.env){return{transport:"shell",shell:`${S0($)} ${G1.join(" ")}`,login_shell:!0,interactive_shell:!0,rc_files_loaded:!0,sandbox:"none",network:!0,environment:"inherited",privilege:"user",sudo:"argv_exact_nopasswd_only",activation:"explicit_device_grant",max_timeout_ms:Z3}}import{readFile as pJ,readdir as dJ,readlink as lJ,realpath as sJ}from"fs/promises";import{basename as cJ,relative as nJ,sep as rJ}from"path";var O0="/proc",aJ=250,w5=500,iJ=50,oJ=250,tJ=1024,M5=4096,eJ=1,$Z=3,j5=9,JZ="0A",ZZ=/^socket:\[(\d+)\]$/,G3={readDirectory:($)=>dJ($),readLink:($)=>lJ($),readTextFile:($)=>pJ($,"utf8"),realPath:($)=>sJ($)};function O5($,J){return J===$||J.startsWith(`${$}${rJ}`)}function QZ($,J){return nJ($,J)||"."}async function I5($){let J;try{J=await $.readDirectory(O0)}catch{return[]}return J.filter((Z)=>/^[0-9]+$/.test(Z)).map((Z)=>Number(Z)).filter((Z)=>Number.isSafeInteger(Z)&&Z>0).sort((Z,Q)=>Z-Q)}async function A5($,J){try{let Q=(await J.readTextFile(`${O0}/${$}/comm`)).slice(0,M5).split(`
|
|
37
|
+
`:"")+K.toString("utf8")}}}async function x8($,J){if(!a2())throw new H("workspace_setup_requires_root","Workspace setup runs only on a root Linux worker.");let Z=f8.safeParse($);if(!Z.success)throw new H("invalid_request","Reason sent an invalid workspace setup.");let Q=Z.data,K,B;try{K=n2(Q.script_gzip),B=n2(Q.stdin_gzip)}catch{throw new H("invalid_request","Reason sent an unreadable workspace setup.")}J.throwIfAborted();let G=r$(b8(e$(),"reason-workspace-setup-"));try{let U=b8(G,"setup.sh");i$(U,K,{mode:384});let Y={PATH:$J,LANG:"C.UTF-8",HOME:"/root",USER:"root",LOGNAME:"root",SHELL:"/bin/bash",TMPDIR:"/tmp"};for(let A of JJ)if(process.env[A])Y[A]=process.env[A];Object.assign(Y,Q.env);let F=n$("/bin/bash",[U],{cwd:Q.cwd,env:Y,detached:!0,stdio:["pipe","pipe","pipe"]}),X=r2(K1),W=r2(K1),z=r2(K1);F.stdout.on("data",(A)=>{X.push(A),z.push(A)}),F.stderr.on("data",(A)=>{W.push(A),z.push(A)}),F.stdin.on("error",()=>{}),F.stdin.end(B);let N=(A)=>{try{if(F.pid)process.kill(-F.pid,A)}catch{}},C=!1,M,w=()=>{N("SIGTERM"),M??=setTimeout(()=>N("SIGKILL"),ZJ)},D=setTimeout(()=>{C=!0,w()},Q.timeout_ms);J.addEventListener("abort",w,{once:!0});let j=await new Promise((A,b)=>{F.once("error",()=>b(new H("workspace_setup_start_failed","The workspace setup did not start."))),F.once("exit",(I,R)=>A({code:I,signal:R}))}).finally(()=>{clearTimeout(D),clearTimeout(M),J.removeEventListener("abort",w)});await new Promise((A)=>{let b=setTimeout(A,QJ);F.once("close",()=>{clearTimeout(b),A()})}),F.stdout.destroy(),F.stderr.destroy(),J.throwIfAborted();let O=C?124:j.signal?128+(o$.signals[j.signal]??0):j.code??1;return{exit_code:Math.min(255,O),stdout:X.text(),stderr:W.text(),...O!==0?{combined:z.text()}:{}}}finally{a$(G,{recursive:!0,force:!0})}}import{chmodSync as KJ,mkdtempSync as BJ,realpathSync as v8,rmSync as VJ}from"fs";import{tmpdir as GJ}from"os";import{dirname as XJ,join as i2,sep as UJ}from"path";function o2($){return m8($,h8($)!==null).repoPath}function u8($,J){let Z;try{if(typeof J!=="string")throw Error("invalid");Z=[B1,void 0].map((K)=>XJ(y8({kind:"managed",workspaceId:J,...K?{layout:K}:{}})))}catch{throw new H("cloud_copy_workspace_invalid","The Cloud copy workspace is invalid.")}let Q;for(let K of Z)try{Q=v8(i2($,K));break}catch{}if(Q===void 0)throw new H("cloud_copy_workspace_unavailable","The Session workspace is not on this computer.");if(!Q.startsWith(`${$}${UJ}`))throw new H("cloud_copy_workspace_invalid","The Cloud copy workspace is outside this worker's root.");return Q}async function p8($){$.signal.throwIfAborted();let J=$.source;if(J.kind==="workspace"){let Q=o2($.runtimeRoot);if(k0(Q)||k0(i2(Q,J.path)))throw new H("protected_path","Credential and secret paths are unavailable to local tasks.");return E0({direction:"export",root:Q,path:J.path,payload:{url:$.url},signal:$.signal,fetchImpl:$.fetchImpl})}let Z=BJ(i2(GJ(),`reason-cloud-copy-${process.pid}-`));try{KJ(Z,448);let Q=v8(Z);await E0({direction:"import",root:Q,path:"source",payload:{url:J.download_url,size_bytes:J.size_bytes,sha256:J.sha256},signal:$.signal,fetchImpl:$.fetchImpl});let K=await E0({direction:"export",root:Q,path:"source",payload:{url:$.url},signal:$.signal,fetchImpl:$.fetchImpl});if(K.size_bytes!==J.size_bytes||K.sha256!==J.sha256)throw new H("transfer_source_changed","The verified attachment changed before export.");return K}finally{VJ(Z,{recursive:!0,force:!0})}}import{constants as K0}from"fs";import{closeSync as G9,existsSync as F0,fstatSync as X9,ftruncateSync as lQ,lstatSync as p3,mkdirSync as sQ,mkdtempSync as cQ,openSync as U9,readSync as nQ,realpathSync as X0,rmSync as rQ,statSync as w1,writeSync as aQ}from"fs";import{homedir as H1,platform as E,tmpdir as iQ}from"os";import{dirname as C1,isAbsolute as oQ,join as F9,relative as d3,resolve as tQ,sep as eQ}from"path";import{spawn as $K}from"child_process";import{createHash as NJ,randomBytes as HJ}from"crypto";var t2=30000,FJ=1800000,YJ=5000,s1=30000,WJ=n1+15000,d8=/^\/app\/local-runtime\/operations\/[0-9a-fA-F-]{36}\/heartbeat$/,zJ=[/^\/app\/local-runtime\/operations\/claim$/,d8];class e2{options;current=null;connecting=null;retryAt=0;failures=0;nextId=0;closed=!1;reconnectTimer=null;constructor($){this.options=$}now(){return(this.options.now??Date.now)()}jitter($){return Math.floor((this.options.random??Math.random)()*$)}async request($,J,Z){Z?.throwIfAborted();let Q=this.current;if(!Q)return this.connect(),null;if(Q.pending.size>=Q.maxInFlight)return null;let K=String(++this.nextId),B=new Promise((Y)=>Q.pending.set(K,{path:$,resolve:Y}));if(!this.send(Q,{t:"req",id:K,path:$,body:J}))return Q.pending.delete(K),null;let G;if(zJ.some((Y)=>Y.test($)))G=setTimeout(()=>{if(Q.pending.has(K))this.drop(Q)},WJ);else{let Y=()=>{if(!Q.pending.has(K))return;let F=this.now()-Q.lastFrameAt;if(F>=s1)this.drop(Q);else G=setTimeout(Y,s1-F)};G=setTimeout(Y,s1)}if(B.finally(()=>clearTimeout(G)),!Z)return await B;let U=new Promise((Y,F)=>{let X=()=>{if(Q.pending.delete(K),clearTimeout(G),this.send(Q,{t:"abort",id:K}),this.now()-Q.lastFrameAt>s1)this.drop(Q);F(Z.reason)};if(Z.aborted)X();else Z.addEventListener("abort",X,{once:!0}),B.finally(()=>Z.removeEventListener("abort",X))});return await Promise.race([B,U])}cadence(){return this.current?.cadence??null}close(){if(this.closed=!0,this.reconnectTimer)clearTimeout(this.reconnectTimer);for(let $ of[this.current,this.connecting])if($)this.drop($)}send($,J){try{return $.socket.send(JSON.stringify(J)),!0}catch{return this.drop($),!1}}drop($){if($.dropped)return;$.dropped=!0,this.settle($);try{$.socket.close()}catch{}}settle($){for(let J of $.pending.values())J.resolve(null);if($.pending.clear(),this.current===$)this.current=null,this.retryAt=Math.max(this.retryAt,this.now()+this.jitter(YJ));if(this.connecting===$){this.connecting=null,this.failures+=1;let J=Math.min(FJ,t2*2**Math.min(this.failures-1,10));this.retryAt=Math.max(this.retryAt,this.now()+J/2+this.jitter(J/2))}}connect(){if(this.closed||this.connecting||this.now()<this.retryAt)return;let $=this.options.WebSocket??globalThis.WebSocket;if(!$){this.retryAt=Number.POSITIVE_INFINITY;return}let J=new URL(c1,this.options.apiOrigin);J.protocol=J.protocol==="https:"?"wss:":"ws:",J.searchParams.set("device_id",this.options.deviceId);let Z;try{Z=new $(J.toString())}catch{this.failures+=1,this.retryAt=this.now()+t2;return}let Q={socket:Z,pending:new Map,maxInFlight:0,cadence:null,lastFrameAt:this.now(),dropped:!1};this.connecting=Q,Z.onmessage=(K)=>this.receive(Q,K.data),Z.onclose=()=>this.settle(Q),Z.onerror=()=>this.settle(Q)}receive($,J){if(typeof J!=="string")return;let Z;try{Z=JSON.parse(J)}catch{return}if($.lastFrameAt=this.now(),Z.t==="res"){let Q=$.pending.get(Z.id);$.pending.delete(Z.id),Q?.resolve({status:Z.status,body:Z.body,retryAfter:Z.retry_after??null});return}if(Z.t==="challenge"&&this.connecting===$){let Q;try{Q=this.options.signHello(Z.challenge)}catch{this.drop($);return}this.send($,{t:"hello",...Q});return}if(Z.t==="ready"&&this.connecting===$){this.connecting=null,this.failures=0,$.maxInFlight=Math.max(1,Math.min(Z.max_in_flight,1000)),$.cadence=Z.cadence??null;let Q=this.current;if(this.current=$,Q){for(let[K,B]of Q.pending){if(!d8.test(B.path))continue;Q.pending.delete(K),this.send(Q,{t:"abort",id:K}),B.resolve(null)}if(Q.pending.size===0)this.drop(Q)}return}if(Z.t==="fallback"){this.retryAt=this.now()+Math.max(t2,Math.min(Z.retry_after_ms,86400000)),this.drop($);return}if(Z.t==="reconnect"&&this.current===$&&!this.reconnectTimer)this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.retryAt=0,this.connect()},Math.max(0,Math.min(Z.after_ms,60000)))}}var J3=["fs.read","fs.write","fs.export","fs.import","exec.run","exec.full","process.run.v1","process.full.v1","preview.serve.v1","pty.start","git.run","process.list","ports.list","computer.use","browser.use","browser.recording.v1","browser.pr-proof.v1","hands.connect","jobs.control","environment.install","github.local.v1","inference.custom.v1","display.stream.v1","automation.call.v1","simulator.call.v1","simulator.stream.v1","tunnel.open","tunnel.close","workspace.setup.v1"];function vV($,J={}){let Z=CJ($),Q=J.rootPathsSupported===!0?I1($.root_paths):void 0;return{supported_operations:[...$.supported_operations],...J.accountRootMetadataSupported===!0&&typeof $.account_root_fingerprint==="string"&&/^[a-f0-9]{64}$/.test($.account_root_fingerprint)?{account_root_fingerprint:$.account_root_fingerprint}:{},...J.workspaceRootMetadataSupported===!0&&typeof $.workspace_root_fingerprint==="string"&&/^[a-f0-9]{64}$/.test($.workspace_root_fingerprint)?{workspace_root_fingerprint:$.workspace_root_fingerprint}:{},...J.accountRootPathSupported===!0&&typeof $.account_root_path==="string"&&$.account_root_path.startsWith("/")&&$.account_root_path.length<=4096?{account_root_path:$.account_root_path}:{},...J.homeContainedRootsSupported===!0&&Array.isArray($.home_contained_root_fingerprints)&&$.home_contained_root_fingerprints.length<=32&&$.home_contained_root_fingerprints.every((K)=>/^[a-f0-9]{64}$/.test(K))?{home_contained_root_fingerprints:[...$.home_contained_root_fingerprints]}:{},...Q?{root_paths:Q}:{},...Object.keys(Z).length?{operation_constraints:Z}:{},...$.hands_worker_artifact_sha256&&$.hands_worker_entrypoint?{hands_worker_artifact_sha256:$.hands_worker_artifact_sha256,hands_worker_entrypoint:$.hands_worker_entrypoint}:{},...$.hands_slots!==void 0?{hands_slots:$.hands_slots}:{}}}function CJ($){let J=(Q)=>Q===null||typeof Q==="boolean"||typeof Q==="number"&&Number.isFinite(Q)||typeof Q==="string"&&Q.length<=512,Z={};for(let Q of $.supported_operations){let K=$.operation_constraints?.[Q];if(!K||typeof K!=="object"||Array.isArray(K))continue;if(!("ready"in K)||typeof K.ready!=="boolean")continue;let B={};for(let[G,U]of Object.entries(K).slice(0,32)){if(!G.length||G.length>64||["__proto__","constructor","prototype"].includes(G))continue;if(J(U)||Array.isArray(U)&&U.length<=64&&U.every(J))B[G]=U}if(Object.keys(B).length)Z[Q]=B}return Z}class N0 extends Error{status;code;retryAfter;constructor($,J,Z,Q=null){super(Z);this.status=$;this.code=J;this.retryAfter=Q;this.name="LocalRuntimeHttpError"}}class r1 extends Error{timeoutMs;constructor($){super(`Reason Device request did not answer within ${$}ms.`);this.timeoutMs=$;this.name="LocalRuntimeRequestTimeoutError"}}function DJ($){return $===408||$===429||$===500||$===502||$===503||$===504}function wJ($){if($ instanceof N0)return!1;if($ instanceof r1)return!0;if(!($ instanceof Error))return!1;if($.name==="AbortError")return!1;if($ instanceof TypeError&&$.message.toLowerCase().includes("fetch failed"))return!0;for(let J of[$,$.cause])if(J&&typeof J==="object"&&"code"in J){let Z=String(J.code);if(["ECONNRESET","ECONNREFUSED","ETIMEDOUT","EHOSTUNREACH","ENOTFOUND","EAI_AGAIN","ConnectionClosed","ConnectionRefused","UND_ERR_SOCKET","UND_ERR_CONNECT_TIMEOUT"].includes(Z))return!0}return!1}function MJ($,J,Z=500){if(J instanceof N0&&J.retryAfter){let B=parseFloat(J.retryAfter);if(Number.isFinite(B)&&B>0)return Math.min(B*1000,1e4)}let Q=Z*2**$,K=Math.floor(Math.random()*200);return Math.min(Q+K,5000)}async function jJ($,J){if(J?.aborted)throw J.reason??new DOMException("The operation was aborted.","AbortError");await new Promise((Z,Q)=>{let K=()=>{clearTimeout(B),Q(J?.reason??new DOMException("The operation was aborted.","AbortError"))},B=setTimeout(()=>{J?.removeEventListener("abort",K),Z()},$);J?.addEventListener("abort",K,{once:!0})})}function uV($){return $ instanceof N0&&$.status===401&&($.code==="device_revoked"||$.code==="invalid_device_credential")}function l8($){return Buffer.byteLength(JSON.stringify($)??"null","utf8")}function s8($){return NJ("sha256").update($??"").digest("hex")}function LJ($){return i8({method:$.method,pathAndQuery:$.route,timestamp:$.timestamp,nonce:$.nonce,challenge:$.challenge,bodySha256:$.bodySha256})}function c8($){return Boolean($)&&typeof $==="object"&&!Array.isArray($)}var OJ=20000,IJ=1e4,n8=[2000,4000],AJ=30000,_J=15000;function r8($){return $?{keepalive:!1}:{}}class $3 extends Error{constructor($){super(`Reason Device proof challenge did not answer within ${$}ms.`)}}class PJ{fetchImpl;proofStore;proofOptions;apiOrigin;spareChallenge=null;sessions=new Map;sessionsClosed=!1;constructor($,J=fetch,Z,Q={}){this.fetchImpl=J;this.proofStore=Z;this.proofOptions=Q;let K=new URL($);if(K.protocol!=="https:"&&K.hostname!=="127.0.0.1"&&K.hostname!=="localhost"&&K.hostname!=="[::1]"&&K.hostname!=="::1")throw Error("Reason Device API must use HTTPS, except for localhost development.");this.apiOrigin=K.origin}async parseResponse($){if($.status===204)return null;let J=await $.json().catch(()=>({}));if(!$.ok){let{code:Z,message:Q}=o8(J,$.status),K=$.headers?.get?.("retry-after")??null;throw new N0($.status,Z,Q,K)}return J}async challenge($,J,Z={fresh:!1}){let Q=this.proofOptions.challengeAttemptTimeoutsMs??n8;for(let K of Q)try{return await this.challengeAttempt($,J,K,Z.fresh)}catch(B){if(J?.aborted||!(B instanceof $3))throw B;Z.fresh=!0}return await this.challengeAttempt($,J,null,Z.fresh)}async challengeAttempt($,J,Z,Q=!1){let K=JSON.stringify({device_id:$}),B=Z===null?null:new AbortController,G=B&&Z!==null?setTimeout(()=>B.abort(new $3(Z)),Z):null;try{let U=await this.fetchImpl(`${this.apiOrigin}${s.authChallenge.path}`,{method:"POST",redirect:"error",headers:{accept:"application/json","content-type":"application/json"},body:K,...r8(Q),signal:B?J?AbortSignal.any([J,B.signal]):B.signal:J});return t8(await this.parseResponse(U))}catch(U){if(!J?.aborted&&B?.signal.aborted)throw B.signal.reason;throw U}finally{if(G)clearTimeout(G)}}async takeSpareChallenge($){let J=this.spareChallenge;if(this.spareChallenge=null,!J||J.deviceId!==$)return null;let Z=await J.challenge,Q=(this.proofOptions.now??Date.now)();return Z&&Date.parse(Z.expires_at)-Q>=OJ?Z:null}refillSpareChallenge($){let J=this.challengeAttempt($,void 0,n8[0]??2000).catch(()=>null);this.spareChallenge={deviceId:$,challenge:J}}async proofHeaders($,J,Z,Q,K=!1,B,G){let U=B&&Date.parse(B.expires_at)-(this.proofOptions.now??Date.now)()>=IJ?B:null,Y=!U&&K?await this.takeSpareChallenge(Z.deviceId):null,F=U??Y??await this.challenge(Z.deviceId,Q,G);if(K)this.refillSpareChallenge(Z.deviceId);let X=s8(J),W=this.signProof("POST",$,F.challenge,X);return{"x-device-id":Z.deviceId,"x-device-timestamp":W.timestamp,"x-device-nonce":W.nonce,"x-device-challenge":F.challenge,"x-device-body-sha256":X,"x-device-signature":W.signature}}signProof($,J,Z,Q){let K=String(Math.trunc((this.proofOptions.now??Date.now)())),B=(this.proofOptions.nonce??(()=>HJ(24)))();if(B.byteLength<16||B.byteLength>32)throw Error("Invalid Reason Device proof nonce.");let G=Buffer.from(B).toString("base64url"),U=this.proofStore.sign(LJ({method:$,route:J,timestamp:K,nonce:G,challenge:Z,bodySha256:Q}));if(!/^[A-Za-z0-9_-]{8,128}$/.test(U))throw Error("Reason Device proof boundary returned an invalid signature.");return{timestamp:K,nonce:G,signature:U}}sessionFor($,J){if(!this.proofOptions.deviceSession||this.sessionsClosed||!J||!a8($.path))return null;let Z=this.sessions.get(J.deviceId);if(!Z)Z=new e2({apiOrigin:this.apiOrigin,deviceId:J.deviceId,signHello:(Q)=>this.signProof("GET",c1,Q,s8("")),...this.proofOptions.webSocket?{WebSocket:this.proofOptions.webSocket}:{},...this.proofOptions.now?{now:this.proofOptions.now}:{}}),this.sessions.set(J.deviceId,Z);return Z}sessionCadence($){let J=this.proofOptions.deviceSession&&!this.sessionsClosed?this.sessions.get($.deviceId)?.cadence()??null:null;return J?{presenceIntervalMs:J.presence_interval_ms,claimWaitMs:J.claim_wait_ms}:null}close(){this.sessionsClosed=!0;for(let $ of this.sessions.values())$.close();this.sessions.clear()}async request($,J){if(J.body!==void 0&&l8(J.body)>C0)throw Error("Reason Device request exceeds the 256 KB protocol limit.");if(J.authorization!==void 0&&J.device!==void 0)throw Error("Reason Device request cannot combine bearer and proof authentication.");let Z=J.authorization!==void 0,Q=J.device!==void 0;if(!($.auth==="none"?!Z&&!Q:$.auth==="registration_bearer"?Z&&!Q:Z!==Q))throw Error(`Reason Device request used invalid authentication for ${$.path}.`);let B=J.body===void 0?void 0:JSON.stringify(J.body),G=this.proofOptions.maxAttempts??4,U=this.proofOptions.sleep??jJ,Y=this.sessionFor($,J.device),F=Math.max(AJ,(J.holdMs??0)+_J),X={fresh:!1},W;for(let z=0;z<G;z+=1)try{let N=await Y?.request($.path,J.sessionBody===void 0?B??"":JSON.stringify(J.sessionBody),J.signal)??null;if(N)return await this.parseResponse(new Response(N.status===204?null:N.body,{status:N.status,headers:N.retryAfter===null?{}:{"retry-after":N.retryAfter}}));let C=new AbortController,M=setTimeout(()=>C.abort(new r1(F)),F),w=J.signal?AbortSignal.any([J.signal,C.signal]):C.signal;try{let D=J.device===void 0?{}:await this.proofHeaders($.path,B,J.device,w,J.useSpareChallenge===!0&&z===0,z===0?J.issuedChallenge:void 0,X),j=await this.fetchImpl(`${this.apiOrigin}${$.path}`,{method:"POST",redirect:"error",headers:{...J.authorization===void 0?{}:{authorization:`Bearer ${J.authorization}`},...D,accept:"application/json",...J.body===void 0?{}:{"content-type":"application/json"}},body:B,...r8(X.fresh),signal:w});return await this.parseResponse(j)}catch(D){if(!J.signal?.aborted&&C.signal.aborted)throw C.signal.reason;throw D}finally{clearTimeout(M)}}catch(N){if(W=N,N instanceof r1)X.fresh=!0;if(J.signal?.aborted)throw N;let C=J.device!==void 0&&N instanceof N0&&N.status===401&&["invalid_device_proof","device_proof_replayed"].includes(N.code),M=N instanceof N0&&DJ(N.status),w=wJ(N),D=J.transientRetryOwner!=="caller"&&(M||w);if((C||D)&&z+1<G){let j=C?0:MJ(z,N,this.proofOptions.retryBaseDelayMs??500);if(j>0)await U(j,J.signal);continue}if(C&&z+1>=G)throw Error("Reason Device proof retry was exhausted.");throw N}throw W??Error("Reason Device request failed.")}async register($,J,Z){let Q=await this.request(s.register,{authorization:$,body:J,signal:Z});return e8(Q)}async enroll($,J,Z,Q){let K=await this.request(s.enroll,{body:{...Z,enrollment_ticket:$,code_verifier:J},signal:Q});return $5(K)}async heartbeat($,J,Z,Q){let K=await this.request(s.heartbeat,{device:$,body:J,signal:Z,...Q?{issuedChallenge:Q}:{}});return J5(K)}async syncRoots($,J,Z){let Q=await this.request(s.rootsSync,{device:$,body:{roots:J},signal:Z});return Z5(Q)}async identity($,J){let Z=await this.request(s.identity,{device:$,signal:J});return Q5(Z)}async disconnect($,J,Z,Q=[]){let K=await this.request(s.disconnect,{device:$,body:Z?{successor_device_id:Z,...Q.length?{successor_roots:Q}:{}}:{},signal:J});return K5(K)}async deviceLifecycle($,J,Z){let Q=await this.request(s.lifecycle,{device:$,body:J,signal:Z});V5(Q)}async localSubscription($,J,Z){return B5(await this.request(s.localSubscription,{device:$,body:J,signal:Z}))}async ownerWorkspaces($,J){let Q=(await this.request(s.ownerWorkspaces,{device:$,body:{},signal:J}))?.organizations;if(!Array.isArray(Q))throw Error("Reason returned an invalid workspace list.");return Q.flatMap((K)=>{let B=K;return typeof B?.id==="string"?[{id:B.id,...typeof B.name==="string"&&B.name.trim()?{name:B.name.trim()}:{},blocked:B.blocked===!0}]:[]})}async ownerWorkspaceEnrollment($,J,Z){return this.request(s.ownerWorkspaceEnrollment,{device:$,body:J,signal:Z})}async liveSessionWorktrees($,J,Z){let Q=await this.request(s.sessionWorktrees,{device:$,body:{worktree_ids:[...J]},signal:Z}).catch((K)=>{if(K instanceof N0&&K.status===404)return null;throw K});if(Q===null)return null;if(!c8(Q)||!Array.isArray(Q.live)||!Q.live.every((K)=>typeof K==="string"&&J.includes(K)))throw Error("Reason returned an invalid Session worktree answer.");return Q.live}async claimOperation($,J={}){let Z=Math.max(J.waitMs??25000,0),Q=(G)=>({wait_ms:Math.min(Z,G),...J.instanceGeneration===void 0?{}:{instance_generation:J.instanceGeneration}}),K=this.sessionCadence($)?.claimWaitMs,B=await this.request(s.operationClaim,{device:$,body:Q(30000),holdMs:Math.min(Z,30000),...K===void 0?{}:{sessionBody:Q(Math.min(K,n1))},signal:J.signal});if(B===null)return null;return G5(B,J3)}async operationHeartbeat($,J,Z={}){let Q=(G)=>this.request(s.operationHeartbeat.forOperation(J.operation_id),{device:$,body:{attempt_id:J.attempt_id,attempt_token:J.attempt_token,...Z.controlAckSeq===void 0?{}:{control_ack_seq:Z.controlAckSeq},...G?{client_retry_count:Z.clientRetryCount}:{},...G&&Z.waitMs!==void 0?{wait_ms:Math.min(Math.max(Z.waitMs,0),30000)}:{}},signal:Z.signal,transientRetryOwner:Z.transientRetryOwner,...G&&Z.waitMs!==void 0?{holdMs:Math.min(Math.max(Z.waitMs,0),30000)}:{}}),K=(Z.clientRetryCount??0)>0||Z.waitMs!==void 0,B;try{B=await Q(K)}catch(G){if(!K||!(G instanceof N0)||G.status!==400||G.code!=="invalid_operation_heartbeat")throw G;B=await Q(!1)}return X5(B)}async operationEvents($,J,Z){if(!Number.isInteger(Z.eventSeqStart)||Z.eventSeqStart<0||Z.events.length<1||Z.events.length>100||Z.events.some((K)=>!/^[A-Za-z0-9._:-]{1,64}$/.test(K.kind)||!c8(K.payload)))throw Error("Invalid Reason Device operation event batch.");let Q=await this.request(s.operationEvents.forOperation(J.operation_id),{device:$,body:{attempt_id:J.attempt_id,attempt_token:J.attempt_token,event_seq_start:Z.eventSeqStart,events:Z.events},signal:Z.signal,transientRetryOwner:Z.transientRetryOwner,...this.proofOptions.prefetchEventChallenges===!0?{useSpareChallenge:!0}:{}});return U5(Q)}async completeOperation($,J,Z,Q){let K={attempt_id:J.attempt_id,attempt_token:J.attempt_token,status:Z.status,...Z.result===void 0?{}:{result:Z.result},...Z.error_code?{error_code:Z.error_code}:{}};if(l8(K)>C0)throw Error("Reason Device operation result exceeds the 256 KB protocol limit.");let B=await this.request(s.operationComplete.forOperation(J.operation_id),{device:$,body:K,signal:Q});return Y5(B)}async operationCustomEndpointCredential($,J,Z){let{CustomEndpointDeviceCredentialSchema:Q}=await import("./custom-endpoint-device-3g0rc3wp.js");return Q.parse(await this.request(s.operationCustomEndpointCredential.forOperation(J.operation_id),{device:$,body:{attempt_id:J.attempt_id,attempt_token:J.attempt_token},signal:Z}))}async operationEnvironment($,J,Z,Q){let K=await this.request(s.operationEnvironment.forOperation(J.operation_id),{device:$,body:{attempt_id:J.attempt_id,attempt_token:J.attempt_token,snapshot_id:Z},signal:Q,...this.proofOptions.prefetchEventChallenges===!0?{useSpareChallenge:!0}:{}});return F5(K)}async acknowledgeOperationEnvironment($,J,Z,Q){await this.request(s.operationEnvironmentAck.forOperation(J.operation_id),{device:$,body:{attempt_id:J.attempt_id,attempt_token:J.attempt_token,...Z},signal:Q,...this.proofOptions.prefetchEventChallenges===!0?{useSpareChallenge:!0}:{}})}}var TJ=new Set(["process.run.v1","process.full.v1","computer.use","browser.use"]),V1=new Set(["jobs.control","environment.install","tunnel.open","tunnel.close","display.stream.v1","automation.call.v1","workspace.setup.v1","simulator.call.v1","simulator.stream.v1"]);function a1($,J){if(TJ.has($))return!1;if(V1.has($)&&!J.runtimeDirectory)return!1;if(($==="inference.custom.v1"||$==="preview.serve.v1"||$==="simulator.call.v1"||$==="simulator.stream.v1")&&(J.executionMode!=="unsandboxed"||!J.runtimeDirectory))return!1;if(J.executionMode!=="unsandboxed"&&(["exec.full","hands.connect","pty.start","browser.pr-proof.v1"].includes($)||V1.has($)))return!1;return!0}import{accessSync as RJ,constants as qJ,existsSync as gJ,statSync as EJ}from"fs";import{basename as kJ,isAbsolute as SJ}from"path";var G1=["-lic"],W5="/bin/zsh",fJ=new Set(["zsh","bash"]),N5=20000,Z3=60000,bJ=65536,xJ=64,yJ=8192,hJ=new Set(["NODE_OPTIONS","PATH","ZDOTDIR","BASH_ENV","ENV"]),mJ=["DYLD_","LD_"];function vJ($){let J=$.toUpperCase();return hJ.has(J)||mJ.some((Z)=>J.startsWith(Z))}function H5($=process.env){return!0}function uJ($){if(!SJ($)||$.includes("\x00"))return!1;if(!fJ.has(kJ($)))return!1;try{if(!EJ($).isFile())return!1;return RJ($,qJ.X_OK),!0}catch{return!1}}function S0($=process.env){if(process.platform==="win32")return z5()??W5;let J=$.SHELL?.trim();if(J&&uJ(J))return J;return W5}function Q3($=process.env){return H5($)&&gJ(S0($))}function K3($=process.env){if(!H5($))throw new H("full_control_disabled","Full-control execution is unavailable on this Reason Device.")}function B3($){if(typeof $!=="string"||$.length===0||$.includes("\x00")||Buffer.byteLength($,"utf8")>bJ)throw new H("invalid_payload","command is missing or too large.");return $}function V3($){if($===void 0||$===null)return{forwarded:{},ignored:[]};if(typeof $!=="object"||Array.isArray($))throw new H("invalid_payload","env must be an object of strings.");let J=Object.entries($);if(J.length>xJ)throw new H("invalid_payload","env has too many entries.");let Z={},Q=[];for(let[K,B]of J){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(K)||typeof B!=="string"||B.includes("\x00")||Buffer.byteLength(B,"utf8")>yJ)throw new H("invalid_payload","env entry is invalid or too large.");if(vJ(K)){Q.push(K);continue}Z[K]=B}return{forwarded:Z,ignored:Q}}async function C5($){let J=$.processEnv??process.env;if(K3(J),$.signal.aborted)throw new H("cancelled","Operation was cancelled.");let Z=B3($.command),Q=S0(J),{forwarded:K,ignored:B}=V3($.requestEnv),G=await $.spawn(Q,[...G1,Z],{cwd:$.cwd,timeoutMs:$.timeoutMs,signal:$.signal,env:{...J,...K}});return{exit_code:G.exitCode,signal:G.signal,stdout:G.stdout,stderr:G.stderr,timed_out:G.timedOut,truncated:G.truncated,shell:Q,shell_flags:[...G1],login:!0,interactive:!0,sandbox:"none",ignored_env:B}}function D5($=process.env){return{transport:"shell",shell:`${S0($)} ${G1.join(" ")}`,login_shell:!0,interactive_shell:!0,rc_files_loaded:!0,sandbox:"none",network:!0,environment:"inherited",privilege:"user",sudo:"argv_exact_nopasswd_only",activation:"explicit_device_grant",max_timeout_ms:Z3}}import{readFile as pJ,readdir as dJ,readlink as lJ,realpath as sJ}from"fs/promises";import{basename as cJ,relative as nJ,sep as rJ}from"path";var O0="/proc",aJ=250,w5=500,iJ=50,oJ=250,tJ=1024,M5=4096,eJ=1,$Z=3,j5=9,JZ="0A",ZZ=/^socket:\[(\d+)\]$/,G3={readDirectory:($)=>dJ($),readLink:($)=>lJ($),readTextFile:($)=>pJ($,"utf8"),realPath:($)=>sJ($)};function O5($,J){return J===$||J.startsWith(`${$}${rJ}`)}function QZ($,J){return nJ($,J)||"."}async function I5($){let J;try{J=await $.readDirectory(O0)}catch{return[]}return J.filter((Z)=>/^[0-9]+$/.test(Z)).map((Z)=>Number(Z)).filter((Z)=>Number.isSafeInteger(Z)&&Z>0).sort((Z,Q)=>Z-Q)}async function A5($,J){try{let Q=(await J.readTextFile(`${O0}/${$}/comm`)).slice(0,M5).split(`
|
|
38
38
|
`,1)[0]?.trim();if(Q)return Q}catch{}try{let Q=(await J.readTextFile(`${O0}/${$}/cmdline`)).slice(0,M5).split("\x00",1)[0]?.trim();return Q?cJ(Q):null}catch{return null}}async function _5($,J=G3){let Z;try{Z=await J.readLink(`${O0}/${$}/cwd`)}catch{return null}if(!Z)return null;try{return await J.realPath(Z)}catch{return null}}async function P5($,J=G3){let Z=[];for(let Q of await I5(J)){if(Z.length>=aJ)break;let K=await _5(Q,J);if(!K||!O5($,K))continue;Z.push({pid:Q,command:await A5(Q,J),cwd:QZ($,K)})}return{processes:Z}}function L5($){let J=[];for(let Z=0;Z<8;Z+=2)J.unshift(Number.parseInt($.slice(Z,Z+2),16));return J}function KZ($){let J=[];for(let Y=0;Y<16;Y+=2)J.push($[Y]<<8|$[Y+1]);if(J.slice(0,5).every((Y)=>Y===0)&&J[5]===65535)return`::ffff:${$.slice(12).join(".")}`;let Z=-1,Q=0,K=-1;for(let Y=0;Y<=J.length;Y+=1){if(Y<J.length&&J[Y]===0){if(K<0)K=Y;continue}if(K>=0){let F=Y-K;if(F>Q)Z=K,Q=F;K=-1}}let B=J.map((Y)=>Y.toString(16));if(Q<2)return B.join(":");let G=B.slice(0,Z).join(":"),U=B.slice(Z+Q).join(":");return`${G}::${U}`}function BZ($,J){if(/^[0-9A-Fa-f]{8}$/.test($)){let Z=L5($);if(Z.every((Q)=>Q===0))return`*:${J}`;return`${Z.join(".")}:${J}`}if(/^[0-9A-Fa-f]{32}$/.test($)){let Z=[];for(let Q=0;Q<4;Q+=1)Z.push(...L5($.slice(Q*8,Q*8+8)));if(Z.every((Q)=>Q===0))return`*:${J}`;return`[${KZ(Z)}]:${J}`}return null}function VZ($,J){let Z=[];for(let Q of $.split(`
|
|
39
39
|
`).slice(1)){if(Z.length>=J)break;let K=Q.trim().split(/\s+/);if(K.length<=j5)continue;if(K[$Z]?.toUpperCase()!==JZ)continue;let B=K[eJ]??"",G=B.lastIndexOf(":");if(G<0)continue;let U=Number.parseInt(B.slice(G+1),16);if(!Number.isInteger(U)||U<=0||U>65535)continue;let Y=BZ(B.slice(0,G),U),F=K[j5];if(!Y||!F||!/^[0-9]+$/.test(F))continue;Z.push({inode:F,port:U,address:Y})}return Z}async function GZ($){let J=[];for(let Z of["tcp","tcp6"]){if(J.length>=w5)break;let Q;try{Q=await $.readTextFile(`${O0}/net/${Z}`)}catch{continue}J.push(...VZ(Q,w5-J.length))}return J}async function XZ($,J){let Z=new Map;if($.size===0)return Z;for(let Q of await I5(J)){if(Z.size>=$.size)break;let K;try{K=await J.readDirectory(`${O0}/${Q}/fd`)}catch{continue}for(let B of K.slice(0,tJ)){let G;try{G=await J.readLink(`${O0}/${Q}/fd/${B}`)}catch{continue}let U=G.match(ZZ)?.[1];if(!U||!$.has(U)||Z.has(U))continue;Z.set(U,Q)}}return Z}async function T5($,J=G3){let Z=await GZ(J),Q=await XZ(new Set(Z.map((X)=>X.inode)),J),K=[];for(let X of Z){let W=Q.get(X.inode);if(W===void 0)continue;K.push({pid:W,port:X.port,address:X.address})}K.sort((X,W)=>X.pid-W.pid||X.port-W.port||(X.address<W.address?-1:X.address>W.address?1:0));let B=[...new Set(K.map((X)=>X.pid))].slice(0,iJ),G=await Promise.all(B.map(async(X)=>[X,await _5(X,J)])),U=new Map(G),Y=K.filter((X)=>{let W=U.get(X.pid);return Boolean(W&&O5($,W))}),F=new Map(await Promise.all([...new Set(Y.map((X)=>X.pid))].map(async(X)=>[X,await A5(X,J)])));return{ports:Y.slice(0,oJ).map((X)=>({pid:X.pid,command:F.get(X.pid)??null,address:X.address}))}}import{posix as U3}from"path";var i1=200,UZ=250,FZ=250;async function o1($,J){let Z=await $(J);if(Z.timedOut||Z.truncated||Z.exitCode!==0&&Z.exitCode!==1)throw new H("process_inspection_failed","Reading this Mac's processes did not complete.");let Q=[],K=null;for(let B of Z.stdout.split(/\r?\n/))if(B.startsWith("p")){let G=Number(B.slice(1));if(K=Number.isInteger(G)&&G>0?{pid:G,command:null,names:[]}:null,K)Q.push(K)}else if(K&&B.startsWith("c"))K.command=B.slice(1)||null;else if(K&&B.startsWith("n"))K.names.push(B.slice(1));return Q}function X3($,J){return J===$||J.startsWith($==="/"?$:`${$}/`)}var R5="/System/Volumes/Data",YZ=["/tmp","/var","/etc"];function F3($){let J=U3.normalize($);if(J.startsWith(`${R5}/`))J=J.slice(R5.length);return YZ.find((Q)=>J===Q||J.startsWith(`${Q}/`))?`/private${J}`:J}function q5($){return $&&U3.isAbsolute($)?F3($):null}async function g5($,J){let Z=new Map;for(let Q=0;Q<J.length;Q+=i1){let K=J.slice(Q,Q+i1).join(",");for(let B of await o1($,["-a","-p",K,"-d","cwd","-Fpcn"]))Z.set(B.pid,{command:B.command,cwd:q5(B.names[0])})}return Z}async function E5($,J){let Z=F3($),Q=(await o1(J,["-d","cwd","-Fpn"])).filter((B)=>{let G=q5(B.names[0]);return G!==null&&X3(Z,G)}).map((B)=>B.pid).slice(0,UZ),K=await g5(J,Q);return{processes:Q.flatMap((B)=>{let G=K.get(B);return G?.cwd&&X3(Z,G.cwd)?[{pid:B,command:G.command,cwd:U3.relative(Z,G.cwd)||"."}]:[]})}}async function k5($,J){let Z=F3($),Q=["-nP","-iTCP","-sTCP:LISTEN","-Fpcn"],K=await o1(J,Q),B=await g5(J,K.map((F)=>F.pid)),G=K.map((F)=>F.pid).filter((F)=>{let X=B.get(F)?.cwd;return Boolean(X&&X3(Z,X))});if(G.length===0)return{ports:[]};let U=new Set(K.flatMap((F)=>F.names.map((X)=>`${F.pid} ${X}`))),Y=[];for(let F=0;F<G.length;F+=i1){let X=G.slice(F,F+i1).join(",");for(let W of await o1(J,["-a","-p",X,...Q]))for(let z of W.names)if(U.has(`${W.pid} ${z}`))Y.push({pid:W.pid,command:W.command,address:z})}return{ports:Y.slice(0,FZ)}}import{join as AZ}from"path";import{spawn as wZ}from"child_process";import{randomUUID as MZ}from"crypto";import{chmodSync as b5,lstatSync as x5,mkdirSync as jZ,readdirSync as LZ,statSync as OZ,unlinkSync as IZ}from"fs";import{join as W3}from"path";var Y3={targets:24,assets:128,sourceFiles:2000,sourceBytes:20000000,outputBytes:20000000};var t1=($,J=0,Z=1e6)=>typeof $==="number"&&Number.isFinite($)&&$>=J&&$<=Z;var I0=()=>{throw Error("proof_visual_contract_invalid")};class S5 extends Error{constructor(){super("proof_visual_contract_invalid")}}function zZ($){if(!X1($)||$.version!==1)return I0();if(typeof $.route!=="string"||!$.route.startsWith("/")||$.route.length>512||/[\x00-\x20\x7f\\?#%]/.test($.route)||$.route.startsWith("//"))throw new S5;if(!X1($.viewport)||!t1($.viewport.width,1,4096)||!t1($.viewport.height,1,4096)||!Array.isArray($.targets)||$.targets.length<1||$.targets.length>Y3.targets||Object.keys($).some((Q)=>!["version","route","viewport","targets","additionalViewports"].includes(Q)))return I0();let J=$.targets.map((Q)=>{if(!X1(Q)||typeof Q.id!=="string"||!/^[a-zA-Z0-9_-]{1,64}$/.test(Q.id)||typeof Q.selector!=="string"||!Q.selector.trim()||Q.selector.length>256||/[\x00-\x1f\x7f]/.test(Q.selector)||Object.keys(Q).some((K)=>!["id","selector"].includes(K)))return I0();return{id:Q.id,selector:Q.selector}});if(new Set(J.map((Q)=>Q.id)).size!==J.length)return I0();let Z;if($.additionalViewports!==void 0){if(!Array.isArray($.additionalViewports)||$.additionalViewports.length<1||$.additionalViewports.length>3)return I0();Z=$.additionalViewports.map((K)=>{if(!X1(K)||!t1(K.width,1,4096)||!Number.isInteger(K.width)||!t1(K.height,1,4096)||!Number.isInteger(K.height)||Object.keys(K).some((B)=>!["width","height"].includes(B)))return I0();return{width:K.width,height:K.height}});let Q=[$.viewport,...Z].map((K)=>`${K.width}x${K.height}`);if(new Set(Q).size!==Q.length)return I0()}return{version:1,route:$.route,viewport:{width:$.viewport.width,height:$.viewport.height},targets:J,...Z?{additionalViewports:Z}:{}}}var HZ=["organizationId","userId","sessionId","runId"],CZ=[...HZ,"prUrl","headSha","skillDigest","evidenceKind"],GG=[...CZ,"contextId","preparedAt","captureId","startedAt","finishedAt","sha256","kind","visualPlan","visualObservation"];var DZ={"image/png":{kind:"image",directory:"/tmp/ara-public-screenshots",extension:"png",maxBytes:8388608},"video/webm":{kind:"video",directory:"/tmp/ara-public-recordings",extension:"webm",maxBytes:10551296}};function f5($){return DZ[$].directory}var y5=10485760;function h5($={}){let J=$.directory??f5("video/webm"),Z=null;return{async start(Q){if(Z)throw Error("cloud_browser_recording_active");let K=Q?.seconds;if(!Number.isInteger(K)||Number(K)<1||Number(K)>15||!Q||Object.keys(Q).some((w)=>w!=="seconds"))throw Error("cloud_browser_recording_seconds_1_to_15_required");jZ(J,{recursive:!0,mode:457});let B=x5(J);if(!B.isDirectory()||B.isSymbolicLink()||B.uid!==process.getuid?.())throw Error("cloud_browser_recording_directory_invalid");b5(J,457);let G=LZ(J).filter((w)=>/^[a-f0-9-]{36}\.webm$/.test(w)).map((w)=>({name:w,time:OZ(W3(J,w)).mtimeMs})).sort((w,D)=>D.time-w.time);for(let w of G.slice(9))IZ(W3(J,w.name));let U=W3(J,`${MZ()}.webm`),Y=["-f","x11grab","-framerate","12","-i",$.display??":99"],F=($.spawn??wZ)($.ffmpeg??"ffmpeg",["-nostdin","-hide_banner","-loglevel","error","-y",...Y,"-t",String(K),"-vf","scale=1280:-2","-c:v","libvpx","-deadline","realtime","-b:v","700k","-an","-fs",String(y5),"-progress","pipe:1",U],{stdio:["ignore","pipe","ignore"],...$.env?{env:$.env}:{}}),X,W,z=!1,N=new Promise((w,D)=>{X=w,W=D});F.stdout.on("data",(w)=>{if(/frame=\s*[1-9]/.test(String(w)))z=!0,X()});let C=new Promise((w,D)=>{F.once("error",()=>{W(Error("cloud_browser_recording_unavailable")),D(Error("cloud_browser_recording_unavailable"))}),F.once("exit",(j)=>{try{if(j!==0&&j!==255)throw Error();let O=x5(U);if(!z||!O.isFile()||O.isSymbolicLink()||O.uid!==process.getuid?.()||O.size<128||O.size>y5+65536)throw Error();b5(U,420),X(),w({path:U,mimeType:"video/webm"})}catch{W(Error("cloud_browser_recording_failed")),D(Error("cloud_browser_recording_failed"))}})});C.catch(()=>{});let M=setTimeout(()=>F.kill("SIGKILL"),(Number(K)+5)*1000);C.finally(()=>clearTimeout(M)).catch(()=>{}),Z={done:C,stop:()=>{return F.kill("SIGINT"),C}};try{await N}catch(w){throw Z=null,w}return{recording:!0,seconds:Number(K)}},async stop(){if(!Z)throw Error("cloud_browser_recording_not_started");let Q=Z;return Z=null,Q.stop()},async close(){if(Z)await this.stop().catch(()=>{})}}}function u5($,J={}){if($.executionMode!=="unsandboxed"||!$.runtimeDirectory||(J.platform??process.platform)!=="linux")return null;let Z=(J.components??m5)(),Q=Z?.features.display?Z.ffmpeg:null;if(!Q)return null;let K=AZ($.runtimeDirectory,"recordings"),B=null;return{async start(G){let U=await(J.desktop??v5)();return B??=h5({directory:K,display:U.display,ffmpeg:Q,env:{HOME:b1(),PATH:"/usr/local/bin:/usr/bin:/bin",XAUTHORITY:U.xauthority},...J.spawn?{spawn:J.spawn}:{}}),B.start(G)},async stop(){if(!B)throw Error("cloud_browser_recording_not_started");return B.stop()},async close(){await B?.close()}}}import{spawn as E3}from"child_process";import{createHash as lZ,randomUUID as sZ}from"crypto";import{existsSync as Q0,mkdirSync as P3,mkdtempSync as k3,readdirSync as G2,readFileSync as S3,renameSync as cZ,rmSync as Y1,statSync as Q2,writeFileSync as nZ}from"fs";import{homedir as f3,tmpdir as U6}from"os";import{basename as F6,dirname as T3,join as k,relative as Y6,resolve as R3,sep as W6}from"path";var a=V.string().min(1).max(200),Z0=V.number().finite().min(0).max(1e4),e1=V.string().min(1).max(4096).refine(($)=>!$.includes("\x00")),p5=V.string().regex(/^[A-Za-z0-9][A-Za-z0-9.-]{0,254}$/),N3=V.object({id:V.string().min(1).max(500).optional(),label:V.string().min(1).max(500).optional()}).strict(),H3=["home","lock","side_button","siri","apple_pay"],_Z=V.enum(["tree","screenshot","both","none"]),PZ=V.object({...N3.shape,gone:V.boolean().optional()}).strict().refine(($)=>Boolean($.id||$.label),"wait_for needs an id or label"),D0={observe:_Z.optional(),wait_for:PZ.optional(),timeout:V.number().min(0).max(20).optional()},z3=V.discriminatedUnion("action",[V.object({action:V.literal("tap"),x:Z0.optional(),y:Z0.optional(),...N3.shape,duration:V.number().min(0).max(10).optional()}).strict().refine(($)=>$.x!==void 0&&$.y!==void 0||Boolean($.id||$.label),"pass x and y, or an id or label"),V.object({action:V.literal("swipe"),x:Z0,y:Z0,x2:Z0,y2:Z0,duration:V.number().min(0.05).max(5).optional()}).strict(),V.object({action:V.literal("type"),text:V.string().min(1).max(4000)}).strict(),V.object({action:V.literal("button"),name:V.enum(H3)}).strict(),V.object({action:V.literal("sleep"),seconds:V.number().min(0).max(10)}).strict()]),C3=V.discriminatedUnion("action",[V.object({action:V.literal("devices")}).strict(),V.object({action:V.literal("boot"),device:a}).strict(),V.object({action:V.literal("shutdown"),device:a}).strict(),V.object({action:V.literal("build"),path:e1.optional(),scheme:V.string().min(1).max(200).optional(),configuration:V.string().min(1).max(100).optional(),device:a.optional(),wait:V.boolean().optional()}).strict(),V.object({action:V.literal("run"),path:e1.optional(),scheme:V.string().min(1).max(200).optional(),configuration:V.string().min(1).max(100).optional(),device:a.optional(),steps:V.array(V.lazy(()=>z3)).max(30).optional(),...D0}).strict(),V.object({action:V.literal("build_status"),build_id:V.string().regex(/^build-[0-9a-z-]{4,64}$/),device:a.optional(),wait:V.boolean().optional()}).strict(),V.object({action:V.literal("launch"),device:a.optional(),app_path:e1.optional(),bundle_id:p5.optional(),steps:V.array(V.lazy(()=>z3)).max(30).optional(),...D0}).strict().refine(($)=>Boolean($.app_path)!==Boolean($.bundle_id),"pass exactly one of app_path or bundle_id"),V.object({action:V.literal("terminate"),device:a.optional(),bundle_id:p5}).strict(),V.object({action:V.literal("logs"),device:a.optional(),after:V.number().int().min(0).optional()}).strict(),V.object({action:V.literal("screenshot"),device:a.optional(),scale:V.union([V.literal(1),V.literal(2)]).optional(),save_path:e1.optional()}).strict(),V.object({action:V.literal("chrome"),device:a.optional()}).strict(),V.object({action:V.literal("inspect"),device:a.optional()}).strict(),V.object({action:V.literal("tap"),device:a.optional(),x:Z0.optional(),y:Z0.optional(),...N3.shape,duration:V.number().min(0).max(10).optional(),...D0}).strict().refine(($)=>$.x!==void 0&&$.y!==void 0||Boolean($.id||$.label),"pass x and y, or an id or label"),V.object({action:V.literal("swipe"),device:a.optional(),x:Z0,y:Z0,x2:Z0,y2:Z0,duration:V.number().min(0.05).max(5).optional(),...D0}).strict(),V.object({action:V.literal("type"),device:a.optional(),text:V.string().min(1).max(4000),...D0}).strict(),V.object({action:V.literal("button"),device:a.optional(),name:V.enum(H3),...D0}).strict(),V.object({action:V.literal("open_url"),device:a.optional(),url:V.string().min(1).max(4000),...D0}).strict(),V.object({action:V.literal("steps"),device:a.optional(),steps:V.array(z3).min(1).max(30),...D0}).strict(),V.object({action:V.literal("appearance"),device:a.optional(),mode:V.enum(["light","dark"])}).strict()]),d5=V.object({udid:V.string(),name:V.string(),runtime:V.string(),state:V.enum(["booted","shutdown","booting","shutting_down"]),kind:V.enum(["iphone","ipad","other"])}).strict(),PG=V.object({text:V.string(),error:V.string().optional(),device:d5.optional(),devices:V.array(d5).optional(),image:V.object({mime:V.literal("image/jpeg"),data:V.string(),width:V.number(),height:V.number()}).strict().optional(),build:V.object({id:V.string(),status:V.enum(["running","succeeded","failed"]),app_path:V.string().optional(),bundle_id:V.string().optional(),errors:V.array(V.string()),log_tail:V.string(),elapsed_ms:V.number()}).strict().optional(),logs:V.object({lines:V.array(V.string()),next:V.number()}).strict().optional(),screen:V.string().optional(),chrome:V.object({identifier:V.string(),screen:V.object({width:V.number(),height:V.number()}).strict(),inset:V.object({top:V.number(),left:V.number(),bottom:V.number(),right:V.number()}).strict(),padding:V.object({top:V.number(),left:V.number(),bottom:V.number(),right:V.number()}).strict(),screen_mask:V.string().optional(),pieces:V.record(V.enum(["topLeft","top","topRight","right","bottomRight","bottom","bottomLeft","left"]),V.object({image:V.string(),width:V.number(),height:V.number()}).strict()),buttons:V.array(V.object({name:V.string(),image:V.string(),x:V.number(),y:V.number(),width:V.number(),height:V.number()}).strict())}).strict().optional()}).strict();var TG=V.object({device_id:V.uuid().optional(),root_id:V.uuid().optional()}),$2={device_id:{type:"string",format:"uuid",description:"Reason machine id from devices.list; omit for the machine this Session runs on."},root_id:{type:"string",format:"uuid"},device:{type:"string",description:"Simulator UDID or exact name. Required for boot and shutdown; for other actions omit it for the booted one."},path:{type:"string",description:"build or run: a .xcodeproj, .xcworkspace, or a folder holding one (project.yml is generated with XcodeGen), absolute or relative to the Session's folder. Omit it when the folder holds one app project."},scheme:{type:"string"},configuration:{type:"string"},build_id:{type:"string",description:"build_status (required): the build_id a build or run returned."},app_path:{type:"string",description:"launch: the built .app from build_status (or pass bundle_id instead)."},bundle_id:{type:"string",description:"terminate (required); launch: an installed app's bundle id instead of app_path."},after:{type:"integer",minimum:0,description:"logs: only lines after this sequence number."},x:{type:"number",description:"tap (with y, unless id or label is given) or swipe (required): start point in device points."},y:{type:"number"},x2:{type:"number",description:"swipe (required, with y2): end point in device points."},y2:{type:"number"},id:{type:"string",description:"tap: accessibility identifier from inspect (instead of x and y)."},label:{type:"string",description:"tap: accessibility label from inspect (instead of x and y)."},duration:{type:"number",description:"tap: seconds held (above 0.5 is a long press); swipe: seconds."},text:{type:"string",description:"type (required): the text to type."},name:{type:"string",enum:[...H3],description:"button (required)."},url:{type:"string",description:"open_url (required): the URL or deep link."},mode:{type:"string",enum:["light","dark"],description:"appearance (required)."},steps:{type:"array",maxItems:30,description:"steps (required, at least one) or launch and run: run in order in one call (after launch, once the app is up). Each item is {action:'tap', id|label|x,y} | {action:'swipe', x,y,x2,y2} | {action:'type', text} | {action:'button', name} | {action:'sleep', seconds}. Taps by id or label wait for their element to appear.",items:{type:"object"}},observe:{type:"string",enum:["tree","screenshot","both","none"],description:"After tap, swipe, type, button, open_url, launch or steps: what to return about the settled screen. Default tree (the accessibility tree, so no separate inspect is needed); screenshot or both to see it."},wait_for:{type:"object",description:"After the action, wait until this element is on screen: {id} or {label}; add gone:true to wait for it to disappear.",properties:{id:{type:"string"},label:{type:"string"},gone:{type:"boolean"}},additionalProperties:!1},timeout:{type:"number",description:"Seconds to wait for wait_for (default 5, max 20)."},wait:{type:"boolean",description:"build or build_status: wait for the build to finish (up to ~45 s) instead of returning at once."},save_path:{type:"string",description:"screenshot: also save the full-resolution PNG at this path (absolute or relative to the Session's folder), for example to show the user."}},s5=C3.options.map(($)=>$.shape).filter(($)=>$.action.value!=="chrome"),TZ={tap:[{required:["x","y"]},{required:["id"]},{required:["label"]}],launch:[{required:["app_path"],without:["bundle_id"]},{required:["bundle_id"],without:["app_path"]}]},l5=new Set;function RZ($,J){let{description:Z,...Q}=$==="steps"&&J==="steps"?{...$2.steps,minItems:1}:$2[$];if(Z===void 0||l5.has($))return Q;return l5.add($),{...Q,description:Z}}var qZ=s5.flatMap(($)=>{let J=$.action.value,Z=Object.keys($).filter((K)=>Object.hasOwn($2,K)),Q=Z.filter((K)=>!$[K].safeParse(void 0).success);return(TZ[J]??[{required:[]}]).map((K)=>({type:"object",properties:Object.fromEntries([["action",{type:"string",const:J}],...["device_id","root_id",...Z].filter((B)=>!K.without?.includes(B)).map((B)=>[B,RZ(B,J)])]),required:["action",...Q,...K.required],additionalProperties:!1}))}),gZ={type:"object",properties:{action:{type:"string",enum:s5.map(($)=>$.action.value)},...$2},required:["action"],additionalProperties:!1},RG={...gZ,anyOf:qZ};import{spawn as j3}from"child_process";import{createHash as kZ}from"crypto";import{existsSync as w3,mkdirSync as J2,mkdtempSync as SZ,readdirSync as c5,readFileSync as n5,renameSync as fZ,rmSync as r5,symlinkSync as M3,writeFileSync as U1}from"fs";import{homedir as bZ}from"os";import{dirname as t5,join as x}from"path";import{createInterface as xZ}from"readline";var D3=`// Reason's simulator host: one warm process per booted iOS Simulator.
|
|
40
40
|
//
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
2
|
var U=".reason/workspace",T="workspace_base",y="sessions",W="workspace_layout",g=".reason/workspace/sessions",B=/^[0-9a-f]{8}$/;function C(j){if(!J(j))return!1;let q=".reason/workspace/sessions/";if(!j.startsWith(q))return!1;let z=j.slice(q.length).split("/");return z.length===2&&B.test(z[0])}var G=4096,X="workspaces/pi";function J(j){if(typeof j!=="string"||!j||j.length>G)return!1;if(j.startsWith("/")||j.includes("\x00")||j.includes("\\"))return!1;return j.split("/").every((q)=>q!==""&&q!=="."&&q!=="..")}function Z(j){if(j.kind==="root"){if(j.path===void 0)return".";if(!J(j.path))throw Error("invalid_device_workspace_identity");return j.path}if(!/^[A-Za-z0-9][A-Za-z0-9._:-]{0,159}$/.test(j.workspaceId)||j.workspaceId==="."||j.workspaceId==="..")throw Error("invalid_device_workspace_identity");let q=j.layout==="sessions"?"sessions":X;return`${j.base?`${j.base}/`:""}${q}/${j.workspaceId}/repo`}function L(j){if(!j||typeof j!=="object"||Array.isArray(j))return null;let q=j;if(q.kind==="root"&&Object.keys(q).length===1)return{kind:"root"};if(q.kind==="root"&&Object.keys(q).length===2&&J(q.path))return{kind:"root",path:q.path};if(q.kind!=="managed"||typeof q.workspaceId!=="string"||Object.keys(q).length!==2+(q.base===void 0?0:1)+(q.layout===void 0?0:1)||q.base!==void 0&&q.base!==".reason/workspace"||q.layout!==void 0&&q.layout!=="sessions")return null;let z={kind:"managed",workspaceId:q.workspaceId,...q.base===".reason/workspace"?{base:".reason/workspace"}:{},...q.layout==="sessions"?{layout:"sessions"}:{}};try{return Z(z),z}catch{return null}}var b="/home/runner",P=10001,x="/run/reason/sessions",f=/^(?:\/[A-Za-z0-9._-]+)+$/,M=/-sidechat-([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/,H=/^(.+)-repository-[a-z0-9][a-z0-9._-]*-[0-9a-f]{12}$/;function K(j){return M.exec(j)?.[1]??H.exec(j)?.[1]??j}var $=/^((?:\/[A-Za-z0-9._-]+)+)\/\.reason\/workspace\/(workspaces\/pi|sessions)\/([^/]+)$/,A="*/.reason/workspace/workspaces/pi/*|*/.reason/workspace/sessions/*";function N(j,q=b,z="sessions"){if(!f.test(q)||q.split("/").some((V)=>V==="."||V===".."))throw Error("invalid_cloud_payload_home");let Q=`${q}/${Z({kind:"managed",workspaceId:j,base:".reason/workspace",...z?{layout:z}:{}})}`,F=`${x}/${K(j)}`;return{home:q,root:Q.slice(0,-5),checkout:Q,control:F,jobEnv:`${F}/job.env`,cloudAccess:`${F}/cloud-access`,logs:`${F}/logs`,pin:`${F}/ws`}}function Y(j){return $.exec(j.replace(/\/+$/,""))?.[2]==="sessions"?"sessions":null}function D(j){return{kind:"managed",workspaceId:j,layout:"sessions"}}function R(j){let q=$.exec(j.replace(/\/+$/,""));if(!q)return null;try{let z=N(q[3],q[1],Y(j));return z.root===j.replace(/\/+$/,"")?z:null}catch{return null}}
|
|
3
|
-
export{U as
|
|
3
|
+
export{U as rj,T as sj,y as tj,W as uj,g as vj,B as wj,C as xj,J as yj,Z as zj,L as Aj,b as Bj,P as Cj,x as Dj,M as Ej,H as Fj,$ as Gj,A as Hj,N as Ij,Y as Jj,D as Kj,R as Lj};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
2
|
+
import{jk as q}from"./vm-hands-entry-lite-8pgggvbb.js";var u=25,U=q.object({machine:q.string().min(1).max(200),person:q.string().min(1).max(200),team:q.string().min(1).max(200),version:q.string().max(64).optional(),wait_seconds:q.number().int().min(0).max(u).optional()}),x=q.discriminatedUnion("kind",[q.object({id:q.string(),kind:q.literal("who"),all:q.boolean().optional()}),q.object({id:q.string(),kind:q.literal("send"),to:q.string(),body:q.string(),from_name:q.string(),from_agent:q.string(),wake:q.boolean(),reply_to:q.string().max(100).optional(),notify:q.boolean().optional()})]),V=q.object({job:x.nullable(),retry_after_seconds:q.number().optional()}),B=q.object({address:q.string(),person:q.string(),machine:q.string(),agent:q.string(),repo:q.string().nullable(),branch:q.string().nullable(),status:q.string(),since:q.number().nullable(),doing:q.string().nullable(),worker:q.boolean(),tier:q.string().max(10).optional()}),F=q.object({person:q.string(),machine:q.string(),online:q.boolean()}),G=q.object({team:q.string().nullable(),sessions:q.array(B).max(2000),machines:q.array(F).max(500),all:q.boolean().optional()}),H=q.object({address:q.string().max(300),state:q.string().max(40),note:q.string().max(500)}),X=q.union([q.object({who:G}),q.object({sent:q.object({ids:q.array(q.string().max(100)).max(500),recipients:q.array(q.string().max(300)).max(500),from:q.string().max(300),deliveries:q.array(H).max(500).optional()})}),q.object({error:q.string().min(1).max(2000)})]),K=q.object({id:q.string().max(100),from:q.string().max(300),from_agent:q.string().max(100).nullable(),to:q.string().max(300),reply_to:q.string().max(100).nullable(),body:q.string().max(64000),sent_at:q.number()}),Z=q.object({messages:q.array(K).max(100)});
|
|
3
3
|
export{u as va,V as wa};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
3
|
-
export{Q as
|
|
2
|
+
import{vj as X,xj as Y,zj as Z}from"./vm-hands-entry-lite-3nr9q3nf.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 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 mj,O as nj,_ as oj,b as pj,g as qj};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{ne as Qz,pe as R,se as Zz}from"./vm-hands-entry-lite-
|
|
2
|
+
import{ne as Qz,pe as R,se as Zz}from"./vm-hands-entry-lite-0z73amf7.js";import{ni as zz}from"./vm-hands-entry-lite-csecgmaa.js";import{Di as e}from"./vm-hands-entry-lite-ksz1k1dh.js";import{Xi as Hz,jj as V,lj as Jz}from"./vm-hands-entry-lite-wxzh22y4.js";import{xk as X}from"./vm-hands-entry-lite-fb02h1zm.js";import{spawnSync as C}from"child_process";import{createHash as Pz,randomUUID as Iz}from"crypto";import{chmodSync as Wz,existsSync as y,mkdirSync as bz,readdirSync as Sz,readFileSync as L,renameSync as wz,rmSync as Y,statSync as _z,writeFileSync as xz}from"fs";import{dirname as Rz,isAbsolute as $z,join as N}from"path";import{spawnSync as Az}from"child_process";import{readFileSync as Oz}from"fs";import{userInfo as v}from"os";import{join as Cz}from"path";var Kz="REASON_SCHEDULED_TASK";function l(H){return Cz(H,"AppData","Local","Reason","Tasks")}function A(H){if(/[\0-\x1f\x7f"%]/.test(H))throw Error(`A background task cannot use a value with a double quote, percent sign or control character: ${H}`);return`'${H.replace(/['\u2018\u2019\u201a\u201b]/g,"$&$&")}'`}function a(H){if(!/^[A-Za-z0-9._-]+$/.test(H))throw Error(`Invalid Windows Scheduled Task name: ${H}`);return`$env:${Kz}=${A(H)};`}function c(H){let z=Object.entries(H.environment).map(([Q,Z])=>{if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(Q))throw Error(`Invalid Windows Scheduled Task environment name: ${Q}`);return`$env:${Q}=${A(Z)};`}),J=`$global:LASTEXITCODE=1; & ${[H.program,...H.args].map(A).join(" ")} 2>&1 | ForEach-Object { Add-Content -LiteralPath ${A(H.log)} -Value $_.ToString() -Encoding UTF8 }; $c=$LASTEXITCODE;`;return[a(H.name),...z,"$ErrorActionPreference='Continue';",H.keepAlive?`do { ${J} if ($c) { Start-Sleep -Seconds 10 } } while ($c)`:`${J} exit $c`].join(" ")}function S(H){return H.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}function Vz(){let H=process.env.USERDOMAIN?.trim();return H?`${H}\\${v().username}`:v().username}function h(H){let z=S(H.user??Vz()),J=H.schedule==="logon",Q=H.schedule==="logon"?`<LogonTrigger><Enabled>true</Enabled><UserId>${z}</UserId></LogonTrigger>`:`<TimeTrigger><Repetition><Interval>PT${H.schedule.everyMinutes}M</Interval><StopAtDurationEnd>false</StopAtDurationEnd></Repetition><StartBoundary>2026-01-01T00:00:00</StartBoundary><Enabled>true</Enabled></TimeTrigger>`,Z=`-NoProfile -NonInteractive -ExecutionPolicy Bypass -WindowStyle Hidden -Command "${H.script}"`;return`<?xml version="1.0" encoding="UTF-16"?>
|
|
3
3
|
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
|
|
4
4
|
<RegistrationInfo>
|
|
5
5
|
<Description>${S(H.description)}</Description>
|