@reason-machines/cli-linux-x64 0.2.554 → 0.2.555
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/reason +1 -1
- package/bin/vm-hands/{api-1dsd0n4x.js → api-453kzgb3.js} +1 -1
- package/bin/vm-hands/{api-credentials-gtrz9r3n.js → api-credentials-arrtadfe.js} +1 -1
- package/bin/vm-hands/{connect-cli-jbwaswpq.js → connect-cli-33btt5ny.js} +1 -1
- package/bin/vm-hands/{local-automation-c75g446p.js → local-automation-5qwy01c7.js} +1 -1
- package/bin/vm-hands/{local-capabilities-1kcxmz0s.js → local-capabilities-mf5cm434.js} +1 -1
- package/bin/vm-hands/{local-display-session-hvbp46qx.js → local-display-session-7gvdydea.js} +1 -1
- package/bin/vm-hands/local-display-video-vg02ywcz.js +2 -0
- package/bin/vm-hands/{local-managed-process-g6vsy02z.js → local-managed-process-d02r1axd.js} +1 -1
- package/bin/vm-hands/{managed-runtime-htxs6v4q.js → managed-runtime-dyea269c.js} +1 -1
- package/bin/vm-hands/{permissions-mhd63yr2.js → permissions-4nhqq4q8.js} +1 -1
- package/bin/vm-hands/{serve-service-38k4j5rf.js → serve-service-5288h5s3.js} +1 -1
- package/bin/vm-hands/{status-m1crm0qs.js → status-zqw8s5y5.js} +1 -1
- package/bin/vm-hands/version-4nn7abs3.js +2 -0
- package/bin/vm-hands/{vm-hands-entry-lite-ggyexab2.js → vm-hands-entry-lite-2tbf0swk.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-g8md08wv.js → vm-hands-entry-lite-3apb2pjh.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-drggrrr8.js → vm-hands-entry-lite-99wrj4vv.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-h78c4zxd.js → vm-hands-entry-lite-atv6x5d3.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-x8wjxgwr.js → vm-hands-entry-lite-b23s6pvp.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-r1n9zhsm.js → vm-hands-entry-lite-b2szp9p8.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-a6brf7zp.js → vm-hands-entry-lite-bs7jaz1j.js} +1 -1
- package/bin/vm-hands/vm-hands-entry-lite-c4zazjyw.js +2 -0
- package/bin/vm-hands/{vm-hands-entry-lite-rp2twenv.js → vm-hands-entry-lite-f6b0cmq6.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-pg2czhxb.js → vm-hands-entry-lite-fde30yd5.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-8mttvhef.js → vm-hands-entry-lite-mh46pt40.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-6qq4f3v5.js → vm-hands-entry-lite-mj7yar3a.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-1pp7czc0.js → vm-hands-entry-lite-pb02nft0.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-sqzryt00.js → vm-hands-entry-lite-r2qrpjfq.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-3mn5c8wd.js → vm-hands-entry-lite-t46k8t4n.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-jha299pc.js → vm-hands-entry-lite-t87sehfe.js} +1 -1
- package/bin/vm-hands/vm-hands-entry-lite.js +1 -1
- package/bin/vm-hands/{vm-hands-executor-0b1azv5m.js → vm-hands-executor-ycprx6c1.js} +1 -1
- package/bin/vm-hands/{vm-hands-op-runner-f2pye28r.js → vm-hands-op-runner-f9m5nsa4.js} +1 -1
- package/bin/vm-hands/{vm-hands-runtime-7cwr0sys.js → vm-hands-runtime-a07nhqmd.js} +3 -3
- package/package.json +1 -1
- package/bin/vm-hands/local-display-video-yh6hfavd.js +0 -2
- package/bin/vm-hands/version-qp2wr1ds.js +0 -2
- package/bin/vm-hands/vm-hands-entry-lite-qdzbd077.js +0 -2
package/bin/reason
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{D,Ps,rs}from"./vm-hands-entry-lite-
|
|
2
|
+
import{D,Ps,rs}from"./vm-hands-entry-lite-t46k8t4n.js";import"./vm-hands-entry-lite-04x5xjt6.js";import"./vm-hands-entry-lite-c4zazjyw.js";import"./vm-hands-entry-lite-4anjdcth.js";import"./vm-hands-entry-lite-a3p6xz53.js";import"./vm-hands-entry-lite-8dfw96ym.js";import"./vm-hands-entry-lite-48rphbjm.js";import"./vm-hands-entry-lite-tyem93c1.js";import"./vm-hands-entry-lite-s85p7tqp.js";export{D as ApiError,rs as ReasonApi,Ps as createMachineEnrollmentTicketWithToken};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{zi,es,ts,As}from"./vm-hands-entry-lite-
|
|
2
|
+
import{zi,es,ts,As}from"./vm-hands-entry-lite-b23s6pvp.js";import"./vm-hands-entry-lite-t46k8t4n.js";import"./vm-hands-entry-lite-04x5xjt6.js";import"./vm-hands-entry-lite-c4zazjyw.js";import"./vm-hands-entry-lite-4anjdcth.js";import"./vm-hands-entry-lite-a3p6xz53.js";import"./vm-hands-entry-lite-8dfw96ym.js";import"./vm-hands-entry-lite-48rphbjm.js";import"./vm-hands-entry-lite-tyem93c1.js";import"./vm-hands-entry-lite-s85p7tqp.js";export{zi as apiOriginFromEnvironment,ts as environmentApiKey,es as explicitApiOrigin,As as resolveApiCredentials};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{it,Ss,Es,xs}from"./vm-hands-entry-lite-
|
|
2
|
+
import{it,Ss,Es,xs}from"./vm-hands-entry-lite-b2szp9p8.js";import"./vm-hands-entry-lite-ravxhygk.js";import"./vm-hands-entry-lite-q2h781jg.js";import"./vm-hands-entry-lite-b23s6pvp.js";import"./vm-hands-entry-lite-t46k8t4n.js";import"./vm-hands-entry-lite-04x5xjt6.js";import"./vm-hands-entry-lite-bs7jaz1j.js";import"./vm-hands-entry-lite-pb02nft0.js";import"./vm-hands-entry-lite-ak0hd94p.js";import"./vm-hands-entry-lite-3apb2pjh.js";import"./vm-hands-entry-lite-99wrj4vv.js";import"./vm-hands-entry-lite-gje7xvy9.js";import"./vm-hands-entry-lite-1yv5qqew.js";import"./vm-hands-entry-lite-bpamn7ny.js";import"./vm-hands-entry-lite-h1qjggz0.js";import"./vm-hands-entry-lite-t87sehfe.js";import"./vm-hands-entry-lite-r2qrpjfq.js";import"./vm-hands-entry-lite-0wsr8edk.js";import"./vm-hands-entry-lite-dgfx0rbn.js";import"./vm-hands-entry-lite-h2rq71rj.js";import"./vm-hands-entry-lite-n7bd44rm.js";import"./vm-hands-entry-lite-mh46pt40.js";import"./vm-hands-entry-lite-wghmyfba.js";import"./vm-hands-entry-lite-atv6x5d3.js";import"./vm-hands-entry-lite-2v4zh9ze.js";import"./vm-hands-entry-lite-mj7yar3a.js";import"./vm-hands-entry-lite-2tbf0swk.js";import"./vm-hands-entry-lite-c4zazjyw.js";import"./vm-hands-entry-lite-vj7xzb3y.js";import"./vm-hands-entry-lite-4anjdcth.js";import"./vm-hands-entry-lite-a3p6xz53.js";import"./vm-hands-entry-lite-8dfw96ym.js";import"./vm-hands-entry-lite-48rphbjm.js";import"./vm-hands-entry-lite-07apxfh8.js";import"./vm-hands-entry-lite-fxzadxz4.js";import"./vm-hands-entry-lite-qd46yhvz.js";import"./vm-hands-entry-lite-tyem93c1.js";import"./vm-hands-entry-lite-s85p7tqp.js";export{Ss as computerDisconnected,it as connectionDirectory,Es as connectionReport,xs as restartConnection};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Pn,Us,zs,qs,Ws,Rn}from"./vm-hands-entry-lite-
|
|
2
|
+
import{Pn,Us,zs,qs,Ws,Rn}from"./vm-hands-entry-lite-t87sehfe.js";import"./vm-hands-entry-lite-r2qrpjfq.js";import"./vm-hands-entry-lite-0wsr8edk.js";import"./vm-hands-entry-lite-dgfx0rbn.js";import"./vm-hands-entry-lite-h2rq71rj.js";import"./vm-hands-entry-lite-n7bd44rm.js";import"./vm-hands-entry-lite-mh46pt40.js";import"./vm-hands-entry-lite-wghmyfba.js";import"./vm-hands-entry-lite-atv6x5d3.js";import"./vm-hands-entry-lite-2v4zh9ze.js";import"./vm-hands-entry-lite-mj7yar3a.js";import"./vm-hands-entry-lite-2tbf0swk.js";import"./vm-hands-entry-lite-c4zazjyw.js";import"./vm-hands-entry-lite-vj7xzb3y.js";import"./vm-hands-entry-lite-4anjdcth.js";import"./vm-hands-entry-lite-a3p6xz53.js";import"./vm-hands-entry-lite-8dfw96ym.js";import"./vm-hands-entry-lite-48rphbjm.js";import"./vm-hands-entry-lite-07apxfh8.js";import"./vm-hands-entry-lite-fxzadxz4.js";import"./vm-hands-entry-lite-qd46yhvz.js";import"./vm-hands-entry-lite-tyem93c1.js";import"./vm-hands-entry-lite-s85p7tqp.js";export{zs as ensureLocalBrowser,Pn as localAutomationAvailable,qs as localBrowserProfile,Us as localUserChromeHost,Ws as runAutomationCallLocally,Rn as runLocalAutomation};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{ns,Vi,mn,is,os,ss,as,$s,Ms,Bs,Fs}from"./vm-hands-entry-lite-
|
|
2
|
+
import{ns,Vi,mn,is,os,ss,as,$s,Ms,Bs,Fs}from"./vm-hands-entry-lite-pb02nft0.js";import"./vm-hands-entry-lite-ak0hd94p.js";import"./vm-hands-entry-lite-3apb2pjh.js";import"./vm-hands-entry-lite-99wrj4vv.js";import"./vm-hands-entry-lite-gje7xvy9.js";import"./vm-hands-entry-lite-1yv5qqew.js";import"./vm-hands-entry-lite-bpamn7ny.js";import"./vm-hands-entry-lite-h1qjggz0.js";import"./vm-hands-entry-lite-t87sehfe.js";import"./vm-hands-entry-lite-r2qrpjfq.js";import"./vm-hands-entry-lite-0wsr8edk.js";import"./vm-hands-entry-lite-dgfx0rbn.js";import"./vm-hands-entry-lite-h2rq71rj.js";import"./vm-hands-entry-lite-n7bd44rm.js";import"./vm-hands-entry-lite-mh46pt40.js";import"./vm-hands-entry-lite-wghmyfba.js";import"./vm-hands-entry-lite-atv6x5d3.js";import"./vm-hands-entry-lite-2v4zh9ze.js";import"./vm-hands-entry-lite-mj7yar3a.js";import"./vm-hands-entry-lite-2tbf0swk.js";import"./vm-hands-entry-lite-c4zazjyw.js";import"./vm-hands-entry-lite-vj7xzb3y.js";import"./vm-hands-entry-lite-4anjdcth.js";import"./vm-hands-entry-lite-a3p6xz53.js";import"./vm-hands-entry-lite-8dfw96ym.js";import"./vm-hands-entry-lite-48rphbjm.js";import"./vm-hands-entry-lite-07apxfh8.js";import"./vm-hands-entry-lite-fxzadxz4.js";import"./vm-hands-entry-lite-qd46yhvz.js";import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import"./vm-hands-entry-lite-tyem93c1.js";import"./vm-hands-entry-lite-s85p7tqp.js";export{r as LocalCapabilityError,ns as SHORT_REQUEST_CAPABILITIES,$s as capabilityInventoryForRoots,Vi as confinedExecutionShell,is as defaultLocalCommandRunner,Ms as deliverLocalHandsEnvironment,as as enrolledRootPaths,Fs as executeLocalOperation,Bs as rebindLocalHandsControl,os as runFileCapability,ss as runTransferCapability,mn as spawnCaptured};
|
package/bin/vm-hands/{local-display-session-hvbp46qx.js → local-display-session-7gvdydea.js}
RENAMED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Ft,Vs,G,qe,jt}from"./vm-hands-entry-lite-
|
|
2
|
+
import{Ft,Vs,G,qe,jt}from"./vm-hands-entry-lite-r2qrpjfq.js";import"./vm-hands-entry-lite-0wsr8edk.js";import"./vm-hands-entry-lite-dgfx0rbn.js";import"./vm-hands-entry-lite-h2rq71rj.js";import"./vm-hands-entry-lite-n7bd44rm.js";import"./vm-hands-entry-lite-mh46pt40.js";import"./vm-hands-entry-lite-wghmyfba.js";import"./vm-hands-entry-lite-atv6x5d3.js";import"./vm-hands-entry-lite-2v4zh9ze.js";import"./vm-hands-entry-lite-2tbf0swk.js";import"./vm-hands-entry-lite-c4zazjyw.js";import"./vm-hands-entry-lite-4anjdcth.js";import"./vm-hands-entry-lite-a3p6xz53.js";import"./vm-hands-entry-lite-8dfw96ym.js";import"./vm-hands-entry-lite-48rphbjm.js";import"./vm-hands-entry-lite-qd46yhvz.js";import"./vm-hands-entry-lite-tyem93c1.js";import"./vm-hands-entry-lite-s85p7tqp.js";export{qe as ensureLinuxDesktop,Ft as localDisplayAvailable,Vs as localDisplayReady,G as privateDirectory,jt as runLocalDisplayStream};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{Fn,jn,Hn,Un,Ur}from"./vm-hands-entry-lite-mh46pt40.js";import"./vm-hands-entry-lite-wghmyfba.js";import"./vm-hands-entry-lite-atv6x5d3.js";import"./vm-hands-entry-lite-2v4zh9ze.js";import"./vm-hands-entry-lite-2tbf0swk.js";import"./vm-hands-entry-lite-c4zazjyw.js";import"./vm-hands-entry-lite-8dfw96ym.js";import"./vm-hands-entry-lite-48rphbjm.js";export{Fn as MAC_SCREEN,jn as WINDOWS_SCREEN,Hn as createDisplayVideoLane,Ur as localDisplayVideoAvailable,Un as simulatorVideoFfmpeg};
|
package/bin/vm-hands/{local-managed-process-g6vsy02z.js → local-managed-process-d02r1axd.js}
RENAMED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{st,fr,js,Hs}from"./vm-hands-entry-lite-
|
|
2
|
+
import{st,fr,js,Hs}from"./vm-hands-entry-lite-3apb2pjh.js";import"./vm-hands-entry-lite-99wrj4vv.js";import"./vm-hands-entry-lite-gje7xvy9.js";import"./vm-hands-entry-lite-1yv5qqew.js";import"./vm-hands-entry-lite-bpamn7ny.js";import"./vm-hands-entry-lite-h1qjggz0.js";import"./vm-hands-entry-lite-dgfx0rbn.js";import"./vm-hands-entry-lite-h2rq71rj.js";import"./vm-hands-entry-lite-n7bd44rm.js";import"./vm-hands-entry-lite-wghmyfba.js";import"./vm-hands-entry-lite-4anjdcth.js";import"./vm-hands-entry-lite-a3p6xz53.js";import"./vm-hands-entry-lite-8dfw96ym.js";import"./vm-hands-entry-lite-48rphbjm.js";import"./vm-hands-entry-lite-07apxfh8.js";import"./vm-hands-entry-lite-fxzadxz4.js";import"./vm-hands-entry-lite-qd46yhvz.js";import"./vm-hands-entry-lite-tyem93c1.js";import"./vm-hands-entry-lite-s85p7tqp.js";export{st as ManagedProcessStoppedError,js as controlManagedDeviceProcess,Hs as retireManagedDeviceProcess,fr as runManagedDeviceProcess};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Rs,Ts,Is,Ds,Os,Ns,Ls}from"./vm-hands-entry-lite-
|
|
2
|
+
import{Rs,Ts,Is,Ds,Os,Ns,Ls}from"./vm-hands-entry-lite-bs7jaz1j.js";import"./vm-hands-entry-lite-h1qjggz0.js";import"./vm-hands-entry-lite-2tbf0swk.js";import"./vm-hands-entry-lite-c4zazjyw.js";import"./vm-hands-entry-lite-a3p6xz53.js";import"./vm-hands-entry-lite-8dfw96ym.js";import"./vm-hands-entry-lite-48rphbjm.js";import"./vm-hands-entry-lite-tyem93c1.js";import"./vm-hands-entry-lite-s85p7tqp.js";export{Os as acquireManagedRuntimeDirectoryLock,Is as currentManagedRuntimeVersion,Ls as flushManagedRuntimeLifecycleEvents,Ds as isManagedRuntimeVersionExecutable,Ts as legacyManagedRuntimePaths,Rs as managedRuntimePaths,Ns as recordManagedRuntimeLifecycle};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{us,ds,Ks,Js}from"./vm-hands-entry-lite-
|
|
2
|
+
import{us,ds,Ks,Js}from"./vm-hands-entry-lite-atv6x5d3.js";import"./vm-hands-entry-lite-2v4zh9ze.js";import"./vm-hands-entry-lite-2tbf0swk.js";import"./vm-hands-entry-lite-c4zazjyw.js";import"./vm-hands-entry-lite-8dfw96ym.js";import"./vm-hands-entry-lite-48rphbjm.js";export{Js as allowMacPermissions,Ks as permissionsSummary,ds as readMacPermissions,us as reasonIdentity};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Wr,xe,J,Jn,Xs,No,Ys,Ze,ps,Xn,Zs,Qs,Vr,ea,ta}from"./vm-hands-entry-lite-
|
|
2
|
+
import{Wr,xe,J,Jn,Xs,No,Ys,Ze,ps,Xn,Zs,Qs,Vr,ea,ta}from"./vm-hands-entry-lite-mj7yar3a.js";import"./vm-hands-entry-lite-2tbf0swk.js";import"./vm-hands-entry-lite-c4zazjyw.js";import"./vm-hands-entry-lite-vj7xzb3y.js";import"./vm-hands-entry-lite-4anjdcth.js";import"./vm-hands-entry-lite-a3p6xz53.js";import"./vm-hands-entry-lite-8dfw96ym.js";import"./vm-hands-entry-lite-48rphbjm.js";import"./vm-hands-entry-lite-tyem93c1.js";import"./vm-hands-entry-lite-s85p7tqp.js";export{Wr as WORKER_SERVICE_ENV,J as WorkerServiceError,No as connectServiceLabel,xe as defaultWorkerServiceHost,Qs as installWorkerService,Ze as installedWorkerService,Ys as isConnectServiceLabel,ta as removeWorkerService,Vr as restartWorkerService,ea as retargetWorkerServiceLogs,ps as retireLegacyWorkerService,Zs as workerServiceDefinitionCurrent,Jn as workerServiceLauncher,Xn as workerServiceProcessRunning,Xs as workerServiceRetargetPending};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import"./vm-hands-entry-lite-
|
|
2
|
+
import"./vm-hands-entry-lite-t46k8t4n.js";import"./vm-hands-entry-lite-a3p6xz53.js";import{_}from"./vm-hands-entry-lite-4anjdcth.js";import"./vm-hands-entry-lite-48rphbjm.js";import"./vm-hands-entry-lite-04x5xjt6.js";import"./vm-hands-entry-lite-s85p7tqp.js";import"./vm-hands-entry-lite-c4zazjyw.js";import"./vm-hands-entry-lite-b23s6pvp.js";import{zt,dt}from"./vm-hands-entry-lite-dgfx0rbn.js";import{w,B,pr,Be,it}from"./vm-hands-entry-lite-b2szp9p8.js";import"./vm-hands-entry-lite-07apxfh8.js";import"./vm-hands-entry-lite-fxzadxz4.js";import"./vm-hands-entry-lite-pb02nft0.js";import"./vm-hands-entry-lite-99wrj4vv.js";import"./vm-hands-entry-lite-gje7xvy9.js";import"./vm-hands-entry-lite-ak0hd94p.js";import"./vm-hands-entry-lite-ravxhygk.js";import"./vm-hands-entry-lite-mh46pt40.js";import"./vm-hands-entry-lite-2v4zh9ze.js";import"./vm-hands-entry-lite-2tbf0swk.js";import"./vm-hands-entry-lite-atv6x5d3.js";import"./vm-hands-entry-lite-wghmyfba.js";import"./vm-hands-entry-lite-bs7jaz1j.js";import"./vm-hands-entry-lite-vj7xzb3y.js";import"./vm-hands-entry-lite-mj7yar3a.js";import"./vm-hands-entry-lite-n7bd44rm.js";import"./vm-hands-entry-lite-1yv5qqew.js";import"./vm-hands-entry-lite-h2rq71rj.js";import"./vm-hands-entry-lite-3apb2pjh.js";import"./vm-hands-entry-lite-qd46yhvz.js";import"./vm-hands-entry-lite-0wsr8edk.js";import"./vm-hands-entry-lite-r2qrpjfq.js";import"./vm-hands-entry-lite-t87sehfe.js";import"./vm-hands-entry-lite-q2h781jg.js";import"./vm-hands-entry-lite-bpamn7ny.js";import"./vm-hands-entry-lite-h1qjggz0.js";import{a}from"./vm-hands-entry-lite-8dfw96ym.js";import{t,o,u,n,s,i}from"./vm-hands-entry-lite-wzv13c8k.js";import"./vm-hands-entry-lite-tyem93c1.js";import{readFileSync as me,realpathSync as k,renameSync as fe,unlinkSync as ge,writeFileSync as he}from"fs";import{dirname as ye,join as A}from"path";function g(e){return`claude mcp add --transport http reason ${e}`}function h(e){return`codex mcp add reason --url ${e}
|
|
3
3
|
codex mcp login reason`}var j=g("https://mcp.reasonmachines.com/mcp"),F=h("https://mcp.reasonmachines.com/mcp"),z=`https://claude.ai/settings/connectors?add=custom&url=${encodeURIComponent("https://mcp.reasonmachines.com/mcp")}`,H=`https://cursor.com/install-mcp?name=reason&config=${encodeURIComponent(btoa(JSON.stringify({url:"https://mcp.reasonmachines.com/mcp"})))}`;var M="https://github.com/reason-machines/reason-plugins",X=`Connect a coding agent to Reason over MCP
|
|
4
4
|
|
|
5
5
|
Usage:
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Qe}from"./vm-hands-entry-lite-
|
|
2
|
+
import{Qe}from"./vm-hands-entry-lite-c4zazjyw.js";import{a}from"./vm-hands-entry-lite-8dfw96ym.js";import{randomUUID as L}from"crypto";import{spawnSync as b}from"child_process";import{chmodSync as ee,cpSync as te,existsSync as x,lstatSync as A,mkdirSync as Y,readdirSync as ne,readFileSync as w,readlinkSync as re,realpathSync as T,renameSync as E,rmdirSync as ie,rmSync as g,symlinkSync as M,writeFileSync as oe}from"fs";import{dirname as I,join as u,relative as se,resolve as ce}from"path";var Yn="so.ara.cli",k=[Yn,"com.reasonmachines.cli"],F="5LJFSBRY2F";function Gr(e){return`(${e.map((t)=>`identifier "${t}"`).join(" or ")}) and anchor apple generic and certificate 1[field.1.2.840.113635.100.6.2.6] exists and certificate leaf[field.1.2.840.113635.100.6.1.13] exists and certificate leaf[subject.OU] = "${F}"`}var G="ReasonBackgroundIdentity",$o="Contents/Helpers/ReasonPermissionTile",ae="so.ara.cli.permission-tile",Ne=Gr([ae,"com.reasonmachines.cli.permission-tile"]),v="AraBackgroundIdentity",ue="Reason",Ce=Gr(k),de=`anchor apple generic and (${k.map((e)=>`identifier "${e}"`).join(" or ")}) and certificate leaf[subject.OU] = "${F}"`;class h extends Error{code;constructor(e,t){super(t);this.code=e;this.name="MacOSBackgroundIdentityError"}}var R="/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister";function le(e=a()){return u(e,"Library","Application Support","Reason","Background","Reason.app")}function O(e=a()){return u(e,"Library","Application Support","Ara","Background","Ara.app")}function fe(e){try{return A(e).isFile()}catch{return!1}}function D(e){return[G,v].map((t)=>u(e,"Contents","MacOS",t)).find(fe)??null}function d(e){try{if(!A(e).isDirectory())return!1;let t=w(u(e,"Contents","Info.plist"),"utf8");return k.some((n)=>t.includes(`<string>${n}</string>`))&&(t.includes(`<string>${ue}</string>`)||t.includes("<string>Ara</string>"))&&D(e)!==null}catch{return!1}}function Kr(e=a()){let t=le(e);if(!d(t))return null;try{let n=w(u(t,"Contents","Info.plist"),"utf8");return/<key>CFBundleVersion<\/key>\s*<string>(\d+\.\d+\.\d+)<\/string>/.exec(n)?.[1]??null}catch{return null}}function pe(e,t=a()){let n=Kr(t);return n===null||j(N(n.split(".")),N(e.split(/[.-]/).slice(0,3)))}var ge=1e4;function K(e,t){return b(e,[...t],{stdio:"ignore",timeout:ge}).status??1}var W=new Set;function H(e){if(process.env.REASON_TEST_REFUSE_REAL_IDENTITY!=="1")return;let t=(n)=>{try{return T(n)}catch{return ce(n)}};if(e!==void 0&&t(e)!==t(a()))return;throw Error("A test tried to change this computer's real Reason background identity; pass a temporary home. Refused by scripts/test-env.ts.")}var V=/\/(?:runtime|CLI)\/versions\/(\d+)\.(\d+)\.(\d+)[^/]*\/[^/]+$|\/\.(?:ara|reason)(?:-staging)?-worker-(\d+)\.(\d+)\.(\d+)[^/]*\/[^/]+$/,J=new Set(["ara","ara.exe","reason","reason.exe"]);function N(e){return e.map((t)=>Number(t))}function j(e,t){for(let n=0;n<3;n+=1)if(e[n]!==t[n])return e[n]<t[n];return!1}var ye=[0,2,161];function me(e){if(e===null)return!0;let t=ye,n=null;try{n=T(process.execPath)}catch{}return e.some((r)=>{let i=V.exec(r);if(i){let f=i[1]===void 0?i.slice(4,7):i.slice(1,4);return j(N(f),t)}let o=r.slice(r.lastIndexOf("/")+1);return J.has(o)&&r!==n&&r!==process.execPath})}function Ee(){let e=b("/bin/ps",["-xo","pid=,comm="],{encoding:"utf8",timeout:5000});if(e.status!==0)return null;let t=[];for(let n of e.stdout.split(`
|
|
3
3
|
`)){let r=/^\s*(\d+)\s+(\S.*)$/.exec(n);if(!r||Number(r[1])===process.pid)continue;let i=r[2].trimEnd(),o=i.slice(i.lastIndexOf("/")+1);if(!V.test(i)&&J.has(o)){let c=b("/usr/sbin/lsof",["-a","-p",r[1],"-d","txt","-Fn"],{encoding:"utf8",timeout:5000}).stdout?.split(`
|
|
4
4
|
`).find((l)=>l.startsWith("n/"));if(c)i=c.slice(1)}t.push(i)}return t}function _e(e){if(H(e.home),!d(e.sourceApp))throw new h("identity_invalid","The packaged Reason background identity is missing or invalid.");let t=e.command??K,n=le(e.home),r=I(n);Y(r,{recursive:!0,mode:448}),ee(r,448);let i=T(e.sourceApp),o=null;try{o=T(n)}catch{}if(i!==o){let f=`${process.pid}.${L()}`,c=u(r,`.Reason.app.${f}.tmp`),l=u(r,`.Reason.app.${f}.old`),y=!1;try{if(te(i,c,{recursive:!0,errorOnExist:!0,preserveTimestamps:!0}),!d(c))throw new h("identity_invalid","The copied Reason background identity is invalid.");let _=e.releaseSigned?["--test-requirement",`=${de}`]:[];if(t("/usr/bin/codesign",["--verify","--strict",..._,c])!==0)throw new h("identity_invalid_signature","The installed Reason background identity has an invalid signature.");let S=!1;for(let p=0;p<4;p+=1){let m=!1;try{E(n,l),m=!0,y=!0}catch(s){if(s.code!=="ENOENT")throw s}if(p===0)e.beforePublish?.();try{E(c,n),S=!0}catch(s){let Z=s.code;if(!["EEXIST","ENOTEMPTY"].includes(Z??""))throw s;if(m)g(l,{recursive:!0,force:!0}),y=!1;if(p===3)throw s;continue}if(m)g(l,{recursive:!0,force:!0}),y=!1;break}if(!S)throw Error("Could not publish Reason's background identity.")}catch(_){if(y&&!x(n)&&x(l))E(l,n);throw _}finally{g(c,{recursive:!0,force:!0}),g(l,{recursive:!0,force:!0})}}return z(n,e,{verified:i!==o}),n}function X(e){return u(I(e),".Reason.app.registered")}function q(e){try{let t=A(e);return t.isDirectory()?`${t.ino}:${t.birthtimeMs}`:null}catch{return null}}function C(e){let t=q(e);try{return t!==null&&w(X(e),"utf8")===t}catch{return!1}}function Q(e){if(d(e))return"bundle";try{if(A(u(e,"Contents","Info.plist"),{throwIfNoEntry:!1}))return null;return A(u(e,"Contents","MacOS",v)).isSymbolicLink()?"retired":null}catch{return null}}function z(e,t,n={}){let r=t.command??K;if(!n.verified&&r("/usr/bin/codesign",["--verify","--strict",e])!==0)throw new h("identity_invalid_signature","The installed Reason background identity has an invalid signature.");if(r(R,["-f",e])!==0)throw new h("identity_register_failed","Could not register Reason's macOS background identity.");let i=q(e);try{if(i)oe(X(e),i,{mode:384})}catch{}try{Se(e,t.home,r,t.runningExecutables??Ee)}catch(o){let f=o.code??"unknown";process.stderr.write(`Reason background identity: legacy_identity_retire_failed (${f})
|
|
5
5
|
`)}}function Se(e,t,n,r){let i=D(e);if(!i)return;let o=O(t),f=I(o),c=(s)=>u(s,"Contents","MacOS",v),l=se(I(c(o)),i),y=`${process.pid}.${L()}`,_=Q(o);if(_===null)return;let S=_==="bundle";if(S)n(R,["-u",o]);let p=u(f,`.Ara.app.${y}.old`);if(!W.has(o)&&!me(r())){if(!S)n(R,["-u",o]);try{E(o,p)}catch(s){if(s.code==="ENOENT")return;throw s}g(p,{recursive:!0,force:!0}),Ie(f);return}if(!S){if(re(c(o))===l)return;let s=`${c(o)}.${y}`;M(l,s);try{E(s,c(o))}finally{g(s,{force:!0})}return}let m=u(f,`.Ara.app.${y}.shim`);Y(I(c(m)),{recursive:!0}),M(l,c(m));try{try{E(o,p)}catch(s){if(s.code==="ENOENT")return;throw s}try{E(m,o)}catch(s){if(x(o))return;throw E(p,o),s}}finally{g(m,{recursive:!0,force:!0}),g(p,{recursive:!0,force:!0})}}function Ie(e){try{if(ne(e).some((n)=>n!==".DS_Store"))return;g(u(e,".DS_Store"),{force:!0}),ie(e)}catch{}}var B=new Map;function Zn(e=a()){let t=B.get(e);if(t)return t;if(process.platform!=="darwin")return[];let n=U(e);if(n===null&&x(I(le(e))))Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,100),n=U(e);if(n===null)return[];return B.set(e,n),n}function U(e){let t=le(e),n=O(e);if(!d(t)||!C(t))try{he({home:e,skipWhenSettled:!0})}catch{}let r=d(t)&&(C(t)||!d(n))?t:d(n)?n:null,i=r?D(r):null;if(!i)return null;if(r===n)W.add(n);let o=b(i,["--can-spawn"],{env:{},timeout:2000,encoding:"utf8"});return o.status===0&&o.stdout===`spawn
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{N}from"./vm-hands-entry-lite-48rphbjm.js";import{O,T,b}from"./vm-hands-entry-lite-1yv5qqew.js";import{je,gr,_r,Sn,En,ct}from"./vm-hands-entry-lite-
|
|
2
|
+
import{N}from"./vm-hands-entry-lite-48rphbjm.js";import{O,T,b}from"./vm-hands-entry-lite-1yv5qqew.js";import{je,gr,_r,Sn,En,ct}from"./vm-hands-entry-lite-99wrj4vv.js";import{Or}from"./vm-hands-entry-lite-dgfx0rbn.js";import{p,ut,An,_e,we}from"./vm-hands-entry-lite-bpamn7ny.js";import{v,h}from"./vm-hands-entry-lite-h1qjggz0.js";import{a,nr,Wo}from"./vm-hands-entry-lite-8dfw96ym.js";import{an,y,t,k,o,d,ms,Ie,Bi,u,n,W,g,ee,s,i,cn}from"./vm-hands-entry-lite-wzv13c8k.js";import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{se,A}from"./vm-hands-entry-lite-tyem93c1.js";import{randomUUID as Q}from"crypto";import{spawn as Le}from"child_process";import{existsSync as Z,lstatSync as me,mkdirSync as We,readFileSync as Ne,realpathSync as G,rmSync as Ve,writeFileSync as He}from"fs";import{dirname as Ue,join as j,relative as qe,sep as Je}from"path";var Se=["process.run.v1","process.full.v1"],xe=600000,Pe=1800000,Ee=20000,ne="process.cancel.v1",ie=n({action:i("start"),request_id:t().uuid(),command:t().min(1).max(16000).refine((e)=>!e.includes("\x00")),cwd:t().min(1).max(4096).refine((e)=>!e.includes("\x00")&&!e.startsWith("/")&&!e.split(/[\\/]/).includes("..")).describe("Path relative to the granted device root; omit to use that root. Must not start with /, contain a .. path segment, or contain a NUL character.").optional(),mode:s(["host","confined"]).default("host"),timeout_ms:o().int().min(1000).max(Pe).default(xe).describe("Absolute process budget including queue and startup time. Defaults to ten minutes; longer explicit requests require the selected root's advertised max_timeout_ms. Retrying never renews the deadline.")}).strict(),K={device_id:t().uuid(),root_id:t().uuid()},Re=g("action",[ie.extend(K),n({...K,action:i("inspect"),process_id:t().uuid(),after:o().int().min(0).default(0),wait_ms:o().int().min(0).max(Ee).default(0).describe("Wait for new output or a state change, bounded by this call's wait budget. Expiring this wait does not cancel the process or extend its deadline.")}).strict(),n({...K,action:i("cancel"),process_id:t().uuid()}).strict()]),Fe=an(Re,{io:"input"}),Ke=ie.extend({process_brain_fence:t().uuid(),process_expires_at:y.datetime()}).strict(),J=n({version:i(1),process_id:t().uuid(),state:s(["starting","running","exited","cancelled","expired","uncertain"]),exit_code:o().int().nullable(),first_cursor:o().int().min(0),next_cursor:o().int().min(0),truncated:d(),observed_at:y.datetime(),output:u(n({cursor:o().int().min(1),stream:s(["stdout","stderr"]),text:t().max(32768)}).strict()).max(128)}).strict().refine((e)=>{if(Buffer.byteLength(JSON.stringify(e))>1e5||e.next_cursor<e.first_cursor-1)return!1;if((e.state==="starting"||e.state==="running"||e.state==="uncertain")&&e.exit_code!==null)return!1;if(e.state==="exited"&&(e.exit_code===null||e.exit_code<0||e.exit_code>255))return!1;if(e.state==="cancelled"&&e.exit_code!==130||e.state==="expired"&&e.exit_code!==124)return!1;let _=e.first_cursor-1;for(let l of e.output){if(l.cursor<=_||l.cursor>e.next_cursor)return!1;_=l.cursor}return!0});function ae(e){return Se.includes(e)}var Xe=n({operation_constraints:ee(t(),Ie())}),Ye=n({ready:i(!0),version:i(1),execution_mode:s(["host","confined"]),max_timeout_ms:o().int().min(1000).optional()});var De=n({version:i(1),process_id:t().uuid(),state:s(["queued","cancelled_before_start","not_started"]),exit_code:ms(),output:u(Bi()).length(0),first_cursor:i(0),next_cursor:i(0),truncated:i(!1),cancellation_requested:i(!1),reason_code:s(["cancelled_before_start","process_journal_capacity","path_not_found","process_timeout_unsupported"]).optional(),expires_at:y.datetime().optional().describe("Accepted absolute process deadline. Reading, waiting and retrying do not extend it.")}).strict(),Ce=n({...J.shape,state:s(["queued","starting","running","exited","cancelled","expired","uncertain","cancelled_before_start","not_started"]),observed_at:y.datetime().optional(),expires_at:y.datetime().optional().describe("Accepted absolute process deadline. Reading, waiting and retrying do not extend it."),cancellation_requested:d(),reason_code:t().nullable().optional(),execution_authority:i("lost").optional().describe("Historical receipt only; the current Brain cannot control this older-generation process."),recovery:n({cause:i("brain_generation_changed"),terminal_confirmed:d(),next_step:s(["inspect_until_terminal","reconcile_effects_before_new_intent"])}).strict().optional().describe("Historical process recovery only. An unconfirmed outcome forbids replay. A confirmed terminal observation proves the old process stopped, not that its command had no effects. Reconcile the result; only restart still-needed, safely repeatable work with a new request_id and current authority. Respect user cancellation."),last_observed_state:J.shape.state.or(i("cancelled_before_start")).nullable().optional().describe("Last saved observation before authority was lost; a running observation does not establish current child liveness.")}).strict(),$e=an(Ce),Qe=W([J,De.refine((e)=>e.state==="cancelled_before_start")]),X=n({version:i(1),process_id:t().uuid(),state:s(["exited","cancelled","expired"]),exit_code:o().int().min(0).max(255),observed_at:y.datetime()}).strict().refine((e)=>(e.state!=="cancelled"||e.exit_code===130)&&(e.state!=="expired"||e.exit_code===124)),Ze=n({process_terminal_observation:X}).strict();var Xi="preview.serve.v1",Yi=43200000;var ce="preview.open.v1",de=1,_n="gid_proxy_v1",Zi="egress",yn=/^(?:\*\.)?[a-z0-9](?:[a-z0-9.-]{0,251}[a-z0-9])?(?::[1-9][0-9]{0,4})?$/,Ae=n({version:i(_n),allowed_domains:u(t().max(260).regex(yn)).max(1024)}).strict(),ke=cn((e)=>N(e)!==null,"invalid workspace"),Oe=n({version:i(1),request_id:k(),session_id:k(),command:t().min(1).max(16000).refine((e)=>!e.includes("\x00")),port:o().int().min(1024).max(65535),workspace:ke,egress:Ae.optional()}).strict(),Qi=Oe.extend({expires_at:y.datetime()}).strict();var Me=4,Te=5000;function Y(e,c,_){let l=null;try{l=ut(e)}catch{}An({deviceRelayUrl:l?.deviceRelayUrl??"",binding:l?.binding??null,jobId:c,port:l?.binding.port??0,reason:l?_:"binding_invalid"})}function le(e){let c=new Map;return{open(_){let l=(x)=>Y(_,e.claim.operation_id,x),I;try{I=ut(_)}catch{return l("binding_invalid")}let{binding:w,deviceRelayUrl:z}=I,E=e.claim.owner;if(!E||w.organizationId!==E.organization_id||w.userId!==E.user_id||w.deviceId!==E.device_id||w.rootId!==e.claim.root_id||w.jobId!==e.claim.operation_id||w.fenceId!==e.claim.operation_id||w.generation!==de||w.expiresAtMs>Math.min(Date.now()+p.lifetimeMs+Te,e.expiresAtMs))return l("binding_mismatch");if(w.expiresAtMs<=Date.now())return l("binding_expired");if(c.get(w.port)?.abort(),c.delete(w.port),c.size>=Me)return l("preview_capacity");let L=new AbortController;c.set(w.port,L);let P=we({binding:w,deniedPorts:e.deniedPorts,readCurrentJob:async()=>{if(L.signal.aborted)return null;let x=await e.inspect();return x?{binding:w,executorLaunchId:e.executorLaunchId,job:x}:null}});_e({binding:w,deviceRelayUrl:z,port:P,signal:L.signal}).then((x)=>x.closed,(x)=>{let R=x instanceof Error?x.message:"preview_failed";if(R!=="preview_not_authorized")process.stderr.write(`${JSON.stringify({event:"worker_preview.open_failed",job_id:w.jobId,port:w.port,reason_code:R})}
|
|
3
3
|
`)}).finally(()=>{if(c.get(w.port)===L)c.delete(w.port)})},dispose(){for(let _ of c.values())_.abort();c.clear()}}}class st extends r{observation;constructor(e){super("process_authority_lost","Process authority was lost; the owned process group has stopped.");this.observation=e}}var fe=256,B=new Map,he="preview.serve.v1",H=new Map;function be(e){let c=H.get(e.operation_id);if(c){if(c.claim!==e)throw C("process_authority_lost");return c}if(H.size>=fe)throw C("process_journal_capacity");let _={claim:e,executing:!1,cancelRequested:!1,phase:"pending"};return H.set(e.operation_id,_),_}function pe(e){return{version:1,process_id:e,state:"cancelled_before_start",exit_code:null,output:[],first_cursor:0,next_cursor:0,truncated:!1,cancellation_requested:!1,reason_code:"cancelled_before_start"}}var ue=(e)=>new Promise((c)=>setTimeout(c,e)),C=(e="process_outcome_uncertain")=>new r(e,"The managed process outcome could not be confirmed; inspect its saved receipt before starting another intent.");function ze(e=a(),c=Ge()){let _=Ue(Or({},e)),l=qe(nr(e),_),[I,...w]=l.split(Je);return{directory:j(c,l,"processes"),previous:[j(_,"processes"),...I==="reason"?[j(c,"ara",...w,"processes")]:[]]}}function Ge(){if(process.platform!=="darwin")throw new r("process_unavailable","Managed Mac process execution is unavailable.");let e=Wo();if(!e)throw new r("process_unavailable","The private per-user process directory is unavailable.");return e}async function fr(e){if(!e.claim.owner||e.signal.aborted||e.expiresAtMs<=Date.now())throw C("process_authority_lost");let c=be(e.claim);if(c.executing)throw C("process_busy");if(c.executing=!0,c.cancelRequested)return c.phase="settling",pe(e.claim.operation_id);c.phase="starting";let _=e.journals??ze();We(_.directory,{recursive:!0,mode:448});let l=gr({runtimeDirectory:G(_.directory),previousRuntimeDirectories:(_.previous??[]).filter((m)=>Z(m)).map((m)=>G(m)),root:e.root,runId:JSON.stringify([e.claim.owner,e.claim.run_id,e.claim.root_id,e.claim.operation_id]),maxScopes:fe,folders:[e.root,e.cwd]});try{for(let m of[e.root,e.cwd])if(!je(G(m),l.journalDirectory))throw new r("process_journal_inside_workspace","The selected root contains the private process journal. Select an existing narrower granted workspace root outside the journal; no command was dispatched.")}catch(m){throw l.disposeSocket(),m}let I=me(l.journalDirectory),w=e.claim.capability===he,z=()=>B.set(e.claim.operation_id,{path:l.journalDirectory,ino:I.ino,dev:I.dev,anyCompletion:w}),E=l.launchDirectory,L=j(E,"config.json"),P={url:"",transport:"local_job_ipc",directShell:{mode:e.mode,executable:e.shell,jobId:e.claim.operation_id},workerVersion:O,protocolVersion:2,workerArtifactSha256:b,workerEntrypoint:T,targetGeneration:1,fenceId:Q(),...process.platform==="win32"?{bashExecutable:se()}:{},workRoot:e.root,workspaceAliasPath:e.root,repoPath:e.cwd,jobEnvPath:j(E,"unused.env"),replSocketPath:j(E,"unused.sock"),readyPath:j(E,"ready.json"),directTerminalReceiptPath:j(E,"terminal.json"),launchId:Q(),expiresAtMs:e.expiresAtMs+5000,bashTimeoutMs:60000,replTimeoutMs:1000,allowedTools:["bash"],managedJobs:{journalDirectory:l.journalDirectory,scopeId:l.scopeId},jobControlSocketPath:l.socketPath,...e.prefix?{bashCommandPrefix:e.prefix}:{},...e.jobsUser?{jobsUser:e.jobsUser}:{}},x;try{He(L,JSON.stringify(P),{mode:384});let m=Sn({configPath:L,root:e.cwd,grantedRoot:e.root,workRoot:e.root,temporaryDirectory:E});x=e.spawnWorker?.(L,P)??Le(m.command,m.args,{...m.options,env:e.environment,stdio:[En,"ignore","ignore"]})}catch(m){throw l.disposeSocket(),m}let R=!1,F=new Promise((m,S)=>{x.once("exit",(f)=>{R=!0,m(f)}),x.once("error",(f)=>{R=!0,S(f)})});F.catch(()=>{});let ge={root:e.root,runId:e.claim.run_id,scopeId:l.scopeId,socketPath:l.socketPath,generation:1,fenceId:P.fenceId,executorLaunchId:P.launchId,expiresAtMs:P.expiresAtMs},V=async(m)=>{let S=await _r(ge,{type:"job",version:2,generation:1,id:Q(),jobId:e.claim.operation_id,...m==="start"?{action:m,input:{script:e.command,leaseExpiresAtMs:e.expiresAtMs}}:m==="inspect"?{action:m,input:{after:0}}:m==="probe"?{action:"inspect",input:{after:Number.MAX_SAFE_INTEGER}}:{action:m,input:{}}},new AbortController().signal);if(!S.ok)throw C(S.error);return S.job},U=!1,q=!1,te,re=()=>{U=!0,ct(x,"SIGTERM")};e.signal.addEventListener("abort",re,{once:!0});let M,oe=0,ve=async(m)=>{let S=[...m.output],f={version:1,process_id:e.claim.operation_id,state:m.state,exit_code:m.exitCode,first_cursor:m.firstCursor,next_cursor:m.nextCursor,truncated:m.truncated,output:S,observed_at:new Date().toISOString()};while(Buffer.byteLength(JSON.stringify(f))>90000&&S.length)S.shift(),f.truncated=!0,f.first_cursor=S[0]?.cursor??f.next_cursor+1;M=J.parse(f),await e.emit(M),oe=Date.now()};try{let m=Math.min(Date.now()+1e4,e.expiresAtMs);while(!Z(P.readyPath)){if(R)throw new r("process_start_failed","The managed process supervisor exited before accepting a command; no command was dispatched.");if(e.signal.aborted||Date.now()>=m)throw C("process_start_unconfirmed");await ue(25)}let S=JSON.parse(Ne(P.readyPath,"utf8"));if(S.launchId!==P.launchId||S.fenceId!==P.fenceId||S.workerArtifactSha256!==b)throw C();if(e.signal.throwIfAborted(),c.cancelRequested)return pe(e.claim.operation_id);let f;try{q=!0,f=await V("start")}catch(D){if(!(D instanceof r)||D.code!=="hands_job_result_unknown")throw D;f=await V("inspect")}if(c.phase="running",c.cancel=async()=>{await V("cancel")},w&&e.preview)c.tunnels=le({claim:e.claim,executorLaunchId:P.launchId,expiresAtMs:e.expiresAtMs,deniedPorts:e.preview.deniedPorts,inspect:async()=>c.phase==="running"&&!R?await V("probe"):null});if(c.cancelRequested)await c.cancel(),f=await V("inspect");for(;;){if(!["starting","running"].includes(f.state))c.phase="settling",c.cancel=void 0;if(!M||M.state!==f.state||M.next_cursor!==f.nextCursor&&Date.now()-oe>=5000)await ve(f);if(!["starting","running"].includes(f.state))break;if(e.signal.aborted||R)throw C();await ue(1000);try{f=await V("inspect"),te=void 0}catch(D){if(!(D instanceof r)||D.code!=="hands_job_result_unknown"||e.signal.aborted||R||Date.now()-(te??=Date.now())>120000)throw D}}if(!M||M.state==="uncertain")throw C();return M}finally{if(c.phase="settling",c.cancel=void 0,c.tunnels?.dispose(),c.tunnels=void 0,await c.cancelInFlight?.catch(()=>{}),e.signal.removeEventListener("abort",re),!R&&!U)ct(x,"SIGTERM");let m,S=await Promise.race([F.then((f)=>({code:f})),new Promise((f)=>{m=setTimeout(()=>f(null),6000)})]).finally(()=>{clearTimeout(m)});if(!S){try{ct(x,"SIGKILL")}catch{}try{await F}finally{if(R)l.disposeSocket()}throw C("process_cleanup_unconfirmed")}try{if((U||e.signal.aborted)&&S.code===0&&q){v(E);let f=JSON.parse(h(P.directTerminalReceiptPath)),D=X.safeParse(f.observation);if(Object.keys(f).length===4&&f.launch_id===P.launchId&&f.fence_id===P.fenceId&&f.scope_id===l.scopeId&&D.success&&D.data.process_id===e.claim.operation_id){if(w)z();throw new st(D.data)}}}catch(f){if(f instanceof st)throw f}finally{if(R)l.disposeSocket()}if(S.code!==0&&!U&&q)throw C("process_cleanup_unconfirmed");if(!U&&S.code===0&&(M&&["exited","cancelled","expired"].includes(M.state)||!q&&c.cancelRequested)||w&&S.code===0&&!q)z()}}async function js(e,c){if(c.kind===ce&&e.capability===he){let I=H.get(e.operation_id);if(I?.claim===e&&I.tunnels)I.tunnels.open(c.payload);else Y(c.payload,e.operation_id,"server_not_running");return!0}if(c.kind!==ne||!ae(e.capability)||!e.owner||c.payload.process_id!==e.operation_id)return!1;let _=H.get(e.operation_id);if(_&&_.claim!==e)return!1;let l=be(e);if(l.cancelRequested=!0,l.phase==="running"&&l.cancel)l.cancelInFlight??=l.cancel(),await l.cancelInFlight;return!0}function Hs(e,c){H.delete(e);let _=B.get(e);if(!_||c!=="succeeded"&&!_.anyCompletion)return B.delete(e),!1;try{let l=me(_.path);if(!l.isDirectory()||l.isSymbolicLink()||l.ino!==_.ino||l.dev!==_.dev||!A(l)||G(_.path)!==_.path||Z(j(_.path,"owner.lock")))return!1;return Ve(_.path,{recursive:!0}),B.delete(e),!0}catch{return!1}}
|
|
4
4
|
export{Xi,Yi,_n,Zi,yn,Qi,st,fr,js,Hs};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{qt,j}from"./vm-hands-entry-lite-dgfx0rbn.js";import{ue,Ce,X,Ae,de,ir,et,Y,I,N,rn}from"./vm-hands-entry-lite-48rphbjm.js";import{Uo,ri}from"./vm-hands-entry-lite-4anjdcth.js";import{go,P,Ve,ve,Ge,ne,Ke,Ln,Se,Kt,ae,H,L,ce,jr,Hr,Mn}from"./vm-hands-entry-lite-n7bd44rm.js";import{Pe,oe,pe,Z,Te,q,Q}from"./vm-hands-entry-lite-07apxfh8.js";import{Lt,Pr,lt,V,O,T,b,Cn}from"./vm-hands-entry-lite-1yv5qqew.js";import{Cr,Ar,xn,uo,Ue,kn}from"./vm-hands-entry-lite-gje7xvy9.js";import{K}from"./vm-hands-entry-lite-wghmyfba.js";import{ji}from"./vm-hands-entry-lite-qd46yhvz.js";import{p,ze,$t,ut,po,_e,we}from"./vm-hands-entry-lite-bpamn7ny.js";import{v,h,mo}from"./vm-hands-entry-lite-h1qjggz0.js";import{E}from"./vm-hands-entry-lite-46pwqvpf.js";import{tr}from"./vm-hands-entry-lite-pg2czhxb.js";import{a,zo,qo,ie,Vo}from"./vm-hands-entry-lite-8dfw96ym.js";import{M,$i,Mi,Yo,y,t,k,At,o,d,u,n,c,g,ee,s,i}from"./vm-hands-entry-lite-wzv13c8k.js";import{Fi}from"./vm-hands-entry-lite-pzj5s203.js";import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{Qo,se,Ui,C,Oe,$e,A}from"./vm-hands-entry-lite-tyem93c1.js";var Oi=()=>{let e={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function l(w){return e[w]??null}let f={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"},_={nan:"NaN"};return(w)=>{switch(w.code){case"invalid_type":{let S=_[w.expected]??w.expected,x=Yo(w.input),W=_[x]??x;return`Invalid input: expected ${S}, received ${W}`}case"invalid_value":if(w.values.length===1)return`Invalid input: expected ${Mi(w.values[0])}`;return`Invalid option: expected one of ${$i(w.values,"|")}`;case"too_big":{let S=w.inclusive?"<=":"<",x=l(w.origin);if(x)return`Too big: expected ${w.origin??"value"} to have ${S}${w.maximum.toString()} ${x.unit??"elements"}`;return`Too big: expected ${w.origin??"value"} to be ${S}${w.maximum.toString()}`}case"too_small":{let S=w.inclusive?">=":">",x=l(w.origin);if(x)return`Too small: expected ${w.origin} to have ${S}${w.minimum.toString()} ${x.unit}`;return`Too small: expected ${w.origin} to be ${S}${w.minimum.toString()}`}case"invalid_format":{let S=w;if(S.format==="starts_with")return`Invalid string: must start with "${S.prefix}"`;if(S.format==="ends_with")return`Invalid string: must end with "${S.suffix}"`;if(S.format==="includes")return`Invalid string: must include "${S.includes}"`;if(S.format==="regex")return`Invalid string: must match pattern ${S.pattern}`;return`Invalid ${f[S.format]??w.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${w.divisor}`;case"unrecognized_keys":return`Unrecognized key${w.keys.length>1?"s":""}: ${$i(w.keys,", ")}`;case"invalid_key":return`Invalid key in ${w.origin}`;case"invalid_union":if(w.options&&Array.isArray(w.options)&&w.options.length>0)return`Invalid discriminator value. Expected ${w.options.map((x)=>`'${x}'`).join(" | ")}`;return"Invalid input";case"invalid_element":return`Invalid value in ${w.origin}`;default:return"Invalid input"}}};function gn(){return{localeError:Oi()}}M(gn());class mt extends Error{}function No(e){let l;try{l=new URL(e)}catch{throw new mt("The proxy must be a URL like https://proxy.example.com:3128.")}if(l.protocol!=="https:"&&l.protocol!=="http:")throw new mt("The proxy URL must use the https or http scheme.");if(!l.hostname)throw new mt("The proxy URL must name a host.");if(l.port!==""&&Number(l.port)<1)throw new mt("The proxy URL must use a port between 1 and 65535.");if(l.pathname!==""&&l.pathname!=="/"||l.search||l.hash)throw new mt("The proxy URL must not carry a path, query, or fragment.");return l.toString()}import{createHash as xi}from"crypto";import{isAbsolute as Bo,join as jo,relative as Mo,resolve as Yt,sep as Wo}from"path";var Vt=t().min(1).refine(Bo,"absolute path required"),Lo=c({version:i(1),apiOrigin:At(),channel:s(["staging","production"]),stateDirectory:Vt,workspaceRoot:Vt,lifetime:s(["persistent","ephemeral"]),executionMode:s(["confined","host"]).default("confined"),name:t().min(1).max(160).default("Reason headless worker"),slots:o().int().min(1).max(4).default(1),shutdownGraceMs:o().int().min(0).max(300000).default(30000),proxy:c({version:i(qt),url:t().refine((e)=>{try{return No(e)===e}catch{return!1}},"invalid proxy URL"),caFile:Vt.optional()}).optional(),userChrome:d().optional(),cloudSessions:i(!0).optional(),localLogins:d().optional(),folders:u(Vt).min(1).max(31).optional()}),Pi=/^https:\/\/[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.trycloudflare\.com$/,F=g("channel",[Lo,Lo.extend({channel:i("local-qa"),apiOrigin:t()})]).superRefine((e,l)=>{if(e.channel==="local-qa"){if(!Pi.test(e.apiOrigin))l.addIssue({code:"custom",message:"local QA worker requires an exact HTTPS trycloudflare.com quick-tunnel origin"})}else{let _=new URL(e.apiOrigin);if(_.origin!==e.apiOrigin||_.username||_.password||_.protocol!=="https:"&&!(_.protocol==="http:"&&ri(_.origin))||!ri(_.origin)&&!Uo(e.channel,_.origin))l.addIssue({code:"custom",message:"API origin must match channel (or loopback)"})}if(!je(e.workspaceRoot,e.stateDirectory))l.addIssue({code:"custom",message:"state and workspace must be disjoint"});let f=e.folders??[];if(new Set([e.workspaceRoot,...f]).size!==f.length+1||f.some((_)=>!je(_,e.stateDirectory)))l.addIssue({code:"custom",message:"folders must be distinct and disjoint from state"})});function m(e){return jo(e.stateDirectory,`headless-${e.channel}`)}function je(e,l){if(zr(l,e))return!1;return!zr(e,l)||E(jo(Wo,Mo(Yt(e),Yt(l))))}function zr(e,l){let f=Mo(Yt(e),Yt(l));return f===""||f!==".."&&!f.startsWith(`..${Wo}`)&&!Bo(f)}function te(e){let{proxy:l,userChrome:f,cloudSessions:_,localLogins:w,folders:S,...x}=e;return xi("sha256").update(JSON.stringify(x)).digest("hex")}var Ii=4,Ai=[2375,2376,9222,9229];function mr(e){let l=new Set(Ai);for(let f of e){let _=new URL(f);l.add(Number(_.port||(["https:","wss:"].includes(_.protocol)?443:80)))}return l}function Jr(){throw new r("preview_unavailable","The live Hands preview binding is unavailable or stale.")}var Ti=60000;function Fo(e){let l=new AbortController,f=new Map,_=(R)=>JSON.stringify([R.jobId,R.port]);function w(R){let B=e.authority.owner;if(l.signal.aborted||!e.isCurrent()||e.expiresAtMs<=Date.now()||R.organization_id!==B.organization_id||R.user_id!==B.user_id||R.device_id!==B.device_id)Jr()}function S(R){let B;try{B=e.environment.current()}catch{return null}return B.binding.target_generation===R.generation&&B.binding.target_fence_id===R.fenceId&&B.run_id===e.runId&&B.device_id===e.authority.owner.device_id&&B.root_id===e.authority.rootId?B:null}async function x(R,B,G){let U=await W(R,B,G);if(U!=="moved")return U;let D=await W(R,B,G);return D==="moved"?null:D}async function W(R,B,G){try{w(e.authority.owner);let U=e.identity();if(!U||G.aborted||R.expiresAtMs<=Date.now()||R.expiresAtMs>e.expiresAtMs)return null;let D=B.opened,re=D!==void 0&&U.generation>D.generation,J=S(U);if(re){if(J){if(J.revision<=D.revision||R.expiresAtMs>Date.parse(J.expires_at)||J.binding.target_revision!==D.attachmentRevision||J.binding.root_grant_revision!==D.grantRevision)return null;B.recoveringSinceMs=void 0}else if(Date.now()-(B.recoveringSinceMs??=Date.now())>Ti)return null}else if(!J||R.expiresAtMs>Date.parse(J.expires_at)||D&&(U.generation!==D.generation||U.fenceId!==D.fenceId))return null;let z=await e.inspect(R.jobId,G),fe=e.identity(),ke=fe&&S(fe);w(e.authority.owner);let be=J&&{generation:U.generation,fenceId:U.fenceId,snapshotId:J.snapshot_id,revision:J.revision,attachmentRevision:J.binding.target_revision,grantRevision:J.binding.root_grant_revision},Re=re?D:be;if(G.aborted||!fe)return null;if(fe.generation!==U.generation||fe.fenceId!==U.fenceId||ke?.snapshot_id!==J?.snapshot_id||ke?.revision!==J?.revision)return"moved";let Fe=z.ok&&z.job.environmentSnapshotId!==void 0&&z.job.environmentRevision!==void 0?{snapshotId:z.job.environmentSnapshotId,revision:z.job.environmentRevision}:null;if(!z.ok||z.generation!==U.generation||!Re||!Fe)return null;if((Fe.snapshotId!==Re.snapshotId||Fe.revision!==Re.revision)&&(re||!e.environment.carried(Fe.snapshotId,Fe.revision)))return null;if(!D&&U.generation===R.generation&&U.fenceId===R.fenceId)B.opened={...Re,...Fe};return{executorLaunchId:e.executorLaunchId,job:z.job,binding:{organizationId:e.authority.owner.organization_id,userId:e.authority.owner.user_id,deviceId:e.authority.owner.device_id,rootId:e.authority.rootId,runId:e.runId,attachmentRevision:Re.attachmentRevision,grantRevision:Re.grantRevision,generation:Re.generation,fenceId:Re.fenceId,jobId:z.job.jobId,port:R.port,expiresAtMs:R.expiresAtMs}}}catch{return null}}return{async open(R,B,G){w(B);let{binding:U,deviceRelayUrl:D}=ut(R);if(G.aborted||U.expiresAtMs<=Date.now()||U.expiresAtMs>Date.now()+p.lifetimeMs||new URL(D).origin!==e.authority.relayOrigin)Jr();let re=_(U),J=f.get(re);if(J){if(!ze(J.binding,U)||J.relay!==D)Jr();if(await J.opened,!await $t(()=>J.port.check())||G.aborted||J.abort.signal.aborted)Jr();return{opened:!0,binding:U}}if(f.size>=Ii)Jr();let z=new AbortController,fe={},ke=we({binding:U,deniedPorts:e.authority.deniedPorts,readCurrentJob:()=>x(U,fe,z.signal)}),be=()=>z.abort();if(G.addEventListener("abort",be,{once:!0}),l.signal.addEventListener("abort",be,{once:!0}),G.aborted||l.signal.aborted)be();let Re=_e({binding:U,deviceRelayUrl:D,port:ke,signal:z.signal}),Fe={binding:U,relay:D,abort:z,port:ke,opened:Re};f.set(re,Fe);let Xe=()=>{if(G.removeEventListener("abort",be),l.signal.removeEventListener("abort",be),f.get(re)===Fe)f.delete(re)};try{if((await Re).closed.then(Xe),G.removeEventListener("abort",be),w(B),z.signal.aborted||!await $t(()=>ke.check()))Jr();return{opened:!0,binding:U}}catch{z.abort(),Xe(),Jr()}},async close(R,B){w(B);let{binding:G}=po(R),U=f.get(_(G));if(!U||!ze(U.binding,G))Jr();return U.abort.abort(),await U.opened.then((D)=>D.closed,()=>{return}),{closed:!0,binding:G}},dispose(){l.abort();for(let R of f.values())R.abort.abort();f.clear()}}}import{WebSocket as Rn}from"ws";var $o=(e)=>("data"in e)?e.data.length:e.bytes,Ko=2*Ke;function ar(e){throw new r(e,"The bound Hands terminal is unavailable or its outcome is unconfirmed.")}var ht=(e)=>!["starting","running"].includes(e.state);function eo(e,l,f=Date.now()){let _=["relay_url","session_id","expires_at","cols","rows","pty","workspace"];if(Object.keys(e).length!==_.length||Object.keys(e).some((B)=>!_.includes(B))||!ae(l)||!ae(e.session_id)||typeof e.expires_at!=="string"||typeof e.relay_url!=="string"||e.relay_url.length>4096||![e.cols,e.rows].every((B)=>Number.isSafeInteger(B)&&Number(B)>=1&&Number(B)<=Se))ar("invalid_pty_request");let w=e.pty;if(!w||typeof w!=="object"||Array.isArray(w))ar("invalid_pty_request");let S=w;if(Object.keys(S).length!==2||S.version!==1||!ce(S.jobId))ar("invalid_pty_request");let x;try{x=new URL(e.relay_url)}catch{return ar("invalid_pty_request")}if(!["ws:","wss:"].includes(x.protocol)||x.username||x.password||x.hash||x.protocol==="ws:"&&!["127.0.0.1","[::1]","localhost"].includes(x.hostname))ar("invalid_pty_request");let W=Date.parse(e.expires_at);if(!Number.isSafeInteger(W)||W<=f)ar("invalid_pty_request");return{workspace:N(e.workspace)??ar("invalid_pty_request"),session:{jobId:S.jobId,sessionId:e.session_id,operationId:l,relayUrl:x.href,cols:Number(e.cols),rows:Number(e.rows),leaseExpiresAtMs:Math.min(W,f+43200000)}}}async function Go(e){let{session:l,binding:f}=e;if(f.assertCurrent(),e.signal.aborted||Date.now()>=l.leaseExpiresAtMs)ar("cancelled");let _=new Rn(l.relayUrl,{followRedirects:!1,perMessageDeflate:!1,maxPayload:ne}),w=new AbortController,S=()=>{},x=()=>{w.abort(),S()};e.signal.addEventListener("abort",x,{once:!0});let W=setTimeout(x,Math.max(1,l.leaseExpiresAtMs-Date.now())),R=[],B=0,G=0,U=0,D=!1,re=!1,J=!1,z,fe,ke,be=(le)=>{ke=new r(le,"Bound terminal input was refused."),x()};_.on("error",()=>be("pty_relay_unavailable")),_.on("close",x),_.on("message",(le,he)=>{if(w.signal.aborted)return;if(!re){be("pty_not_ready");return}let xe=Array.isArray(le)?Buffer.concat(le):le instanceof ArrayBuffer?Buffer.from(le):le;if(xe.length===0)return;let Je=R.at(-1),Le=he&&Je!==void 0&&"data"in Je&&Je.data.length+xe.length<=ne;if(xe.length>ne||B+xe.length>Ln){be("pty_input_backpressure");return}if(Le)Je.data=Buffer.concat([Je.data,xe]);else if(he)R.push({data:Buffer.from(xe)});else try{let Be=JSON.parse(xe.toString("utf8"));if(Be&&Be.t==="close"&&Object.keys(Be).length===1){J=!0,x();return}if(!Be||Be.t!=="resize"||Object.keys(Be).length!==3||![Be.cols,Be.rows].every((Ee)=>Number.isSafeInteger(Ee)&&Ee>=1&&Ee<=Se))throw Error("invalid_control");R.push({cols:Be.cols,rows:Be.rows,bytes:xe.length})}catch{be("invalid_pty_control");return}B+=xe.length,S()});function Re(le){return Mn(JSON.stringify({...f.scope,version:1,sessionId:l.sessionId,operationId:l.operationId,job:{...le,output:[],pty:le.pty?{...le.pty,output:[]}:void 0}}))}function Fe(le){if(!le.ok)ar(le.error);let he=le.job;if(le.generation!==f.scope.generation||he.jobId!==l.jobId||!he.pty||he.leaseExpiresAtMs>l.leaseExpiresAtMs||he.process&&he.process.executorLaunchId!==f.scope.executorLaunchId||he.process&&fe&&(he.process.pid!==fe.pid||he.process.processGroupId!==fe.processGroupId)||he.state!=="starting"&&(he.environmentRevision!==f.environment.revision||he.environmentSnapshotId!==f.environment.snapshotId))ar("pty_binding_changed");if(Re(he),he.process)fe??={...he.process};return he}async function Xe(le){f.assertCurrent();let he=await f.request(le,w.signal);if(f.assertCurrent(),w.signal.aborted)ar("cancelled");let xe=Fe(he);if(xe.inputSequence!==G)ar("job_input_sequence");if(!ht(xe)&&xe.leaseExpiresAtMs<=Date.now())ar("pty_binding_changed");return xe}function ye(le){if(f.assertCurrent(),w.signal.aborted||_.readyState!==Rn.OPEN||_.bufferedAmount+Buffer.byteLength(le)>Ko)ar("pty_output_backpressure");_.send(le)}function We(le){if(le.firstCursor>U+1)U=le.firstCursor-1;for(let he of le.pty.output){if(he.cursor<=U)continue;if(he.cursor!==U+1)ar("pty_output_gap");let xe=Buffer.from(he.dataBase64,"base64");if(_.bufferedAmount+xe.length>Ko)return!1;ye(xe),U=he.cursor}if(U!==le.nextCursor)ar("pty_output_gap");return!0}async function Ye(le,he){let xe;try{await Promise.race([e.emit(le,he),new Promise((Je,Le)=>{xe=setTimeout(()=>Le(new r("pty_event_unavailable","Terminal metadata delivery timed out.")),2000)})])}finally{clearTimeout(xe)}}async function De(){let le=AbortSignal.timeout(Kt),he=f.request({jobId:l.jobId,action:"cancel",input:{}},le),xe,Je=new Promise((Le,Be)=>{if(xe=()=>Be(new r("pty_cleanup_unconfirmed","Terminal cleanup acknowledgement was not observed within authority.")),le.addEventListener("abort",xe,{once:!0}),le.aborted)xe()});try{let Le=await Promise.race([he,Je]);if(le.aborted)ar("pty_cleanup_unconfirmed");return Fe(Le)}finally{le.removeEventListener("abort",xe)}}try{await new Promise((Le,Be)=>{let Ee=setTimeout(()=>{x(),Be(new r("pty_relay_unavailable","Terminal pairing timed out."))},5000),Me=()=>{clearTimeout(Ee),Be(new r("cancelled","Terminal pairing was cancelled."))};if(w.signal.addEventListener("abort",Me,{once:!0}),_.once("open",()=>{clearTimeout(Ee),w.signal.removeEventListener("abort",Me),Le()}),w.signal.aborted)Me()}),f.assertCurrent(),D=!0,z=await Xe({jobId:l.jobId,action:"start",input:{mode:"pty",cols:l.cols,rows:l.rows,leaseExpiresAtMs:l.leaseExpiresAtMs}});let le=Date.now()+5000;while(z.state==="starting"){if(Date.now()>=le)ar("pty_not_ready");await new Promise((Le)=>setTimeout(Le,25)),z=await Xe({jobId:l.jobId,action:"inspect",input:{after:U}})}if(z.state!=="running"||z.inputSequence!==0||z.leaseExpiresAtMs<=Date.now())ar("pty_not_ready");await Ye("pty.ready",Re(z)),re=!0,ye(JSON.stringify({t:"open",cols:z.pty.cols,rows:z.pty.rows,receipt:Re(z)}));let he=!1,xe=0,Je=!1;while(!w.signal.aborted){let Le=z.firstCursor>U+1,Be=We(z);if(ht(z)){if(Be)break}else if(Le)he=!0;else if(he&&Be&&Date.now()>=xe){he=!1,xe=Date.now()+1000;let{cols:Me,rows:rr}=z.pty;for(let or of[{cols:Me,rows:rr>1?rr-1:2},{cols:Me,rows:rr}]){if(ht(z))break;let Rr=++G;if(z=await Xe({jobId:l.jobId,action:"resize",input:{sequence:Rr,...or}}),z.inputSequence!==Rr)ar("job_input_sequence")}continue}let Ee=ht(z)||Je?void 0:R.shift();if(Ee){B-=$o(Ee);let Me=++G;try{z=await Xe("data"in Ee?{jobId:l.jobId,action:"input",input:{sequence:Me,dataBase64:Ee.data.toString("base64")}}:{jobId:l.jobId,action:"resize",input:{sequence:Me,cols:Ee.cols,rows:Ee.rows}})}catch(rr){if(!(rr instanceof r)||rr.code!=="job_input_backpressure")throw rr;G-=1,R.unshift(Ee),B+=$o(Ee),Je=!0;continue}if(z.inputSequence!==Me)ar("job_input_sequence")}else if(await new Promise((Me)=>{let rr=setTimeout(Me,Je||!Be?10:50);if(S=()=>{clearTimeout(rr),Me()},w.signal.aborted||!Je&&R.length)S()}),Je=!1,S=()=>{},!w.signal.aborted&&Be)try{z=await Xe({jobId:l.jobId,action:"inspect",input:{after:U}})}catch(Me){if(!J||!(Me instanceof r)||Me.code!=="cancelled")throw Me}}}catch(le){ke??=le}finally{if(re=!1,R.length=0,clearTimeout(W),e.signal.removeEventListener("abort",x),x(),D&&(!z||!ht(z)))try{z=await De()}catch{z=void 0}try{if(!z||!ht(z)||z.pty?.cleanup!=="confirmed")ar("pty_cleanup_unconfirmed");let le=Re(z);if(_.readyState===Rn.OPEN)await new Promise((he)=>{let xe=setTimeout(he,500);_.send(JSON.stringify({t:"exit",code:z.exitCode,receipt:le}),()=>{clearTimeout(xe),he()})});await Ye("pty.stopped",le)}catch(le){ke??=le}_.terminate()}if(ke)throw ke;if(e.signal.aborted)ar("cancelled");if(!z)ar("pty_cleanup_unconfirmed");return{receipt:Re(z)}}import{createHash as Di,randomUUID as An}from"crypto";import{spawnSync as es}from"child_process";import{closeSync as Jo,constants as On,fstatSync as Ci,fsyncSync as Hi,lstatSync as Ht,mkdirSync as Ni,mkdtempSync as rs,openSync as Xo,readFileSync as Li,readdirSync as ts,realpathSync as qr,rmSync as Pn,unlinkSync as Bi}from"fs";import{createConnection as Wi}from"net";import{dirname as zi,join as ot,sep as In}from"path";import{tmpdir as ns}from"os";var hr=new Map,Vr=new Map;function $r(e,l){return Di("sha256").update(JSON.stringify([e,l])).digest("hex")}function gt(e){try{Ni(e,{mode:448})}catch(f){if(!(f instanceof Error&&("code"in f)&&f.code==="EEXIST"))throw f}let l=Ht(e);if(!l.isDirectory()||l.isSymbolicLink()||!A(l)||qr(e)!==e)throw new r("hands_jobs_unavailable","Hands job state must be a private canonical directory.")}function Ki(e){let l;try{l=Ht(e)}catch(f){if(f instanceof Error&&"code"in f&&f.code==="ENOENT")return!1;throw f}return!l.isDirectory()||l.isSymbolicLink()||ts(e).length>0}function Gi(e){if(process.platform==="win32")return Ui();let l=e.map((f)=>{try{return qr(f)}catch{return f}});for(let f of[()=>Ui(),()=>qr("/dev/shm"),()=>qr(ns())]){let _;try{_=f()}catch{continue}if(!l.some((w)=>_===w||_.startsWith(w.endsWith(In)?w:w+In)))return _}throw new r("invalid_hands_workspace","A Session can't work in this computer's temporary folder itself; start it in a project folder inside it.")}function gr(e){let l=$r(e.root,e.runId),f=e.previousRuntimeDirectories?.find((x)=>Ki(ot(x,"jobs",l.slice(0,16))))??e.runtimeDirectory;gt(f);let _=ot(f,"jobs");gt(_);let w=ot(_,l.slice(0,16));if(e.maxScopes!==void 0){let x=ts(_);if(!Number.isSafeInteger(e.maxScopes)||e.maxScopes<1||x.length>e.maxScopes||!x.includes(l.slice(0,16))&&x.length>=e.maxScopes)throw new r("process_journal_capacity","Managed process receipt capacity is full; preserve uncertain jobs and reconcile their existing receipts before starting more work.")}gt(w);let S=rs(ot(Gi(e.folders??[]),"reason-j-"));try{return gt(S),{journalDirectory:w,scopeId:l,launchDirectory:S,socketPath:process.platform==="win32"?`\\\\.\\pipe\\reason-jobs-${An()}`:ot(S,"control.sock"),disposeSocket:()=>Pn(S,{recursive:!0,force:!0})}}catch(x){throw Pn(S,{recursive:!0,force:!0}),x}}var Ji=60000,Vi=5000;function qi(e){if(process.platform==="win32")return Yi(e);let l=es("ps",["-o","lstart=","-p",String(e)],{encoding:"utf8",timeout:2000,env:{...process.env,LC_ALL:"C",LANG:"C"}}),f=l.status===0?/^\w{3} (\w{3}) +(\d{1,2}) (\d{2}):(\d{2}):(\d{2}) (\d{4})$/.exec(l.stdout.trim()):null,_=f?"JanFebMarAprMayJunJulAugSepOctNovDec".indexOf(f[1]):-1;if(!f||_<0||_%3!==0)return null;let w=new Date(Number(f[6]),_/3,Number(f[2]),Number(f[3]),Number(f[4]),Number(f[5])).getTime();return Number.isFinite(w)?w:null}function Yi(e){let l=es(C("powershell"),["-NoProfile","-NonInteractive","-Command",`(Get-Process -Id ${e}).StartTime.ToUniversalTime().ToString('o')`],{encoding:"utf8",timeout:5000,windowsHide:!0,env:Oe()}),f=l.status===0?Date.parse(l.stdout.trim()):Number.NaN;return Number.isFinite(f)?f:null}function os(e,l={}){let f=ot(e.journalDirectory,"owner.lock"),_;try{_=Xo(f,On.O_RDONLY|On.O_NOFOLLOW)}catch{return null}try{let w=Ci(_);if(!w.isFile()||w.nlink!==1||!A(w)||w.size>4096)return null;let S=null;try{S=JSON.parse(Li(_,"utf8"))}catch{}let x;if(S===null){if((l.now??Date.now)()-w.mtimeMs<Ji)return null;x={reason:"never_written",executorLaunchId:null}}else{let{version:B,scopeId:G,pid:U,createdAtMs:D,executorLaunchId:re}=S;if(B!==1||G!==e.scopeId||typeof re!=="string"||typeof U!=="number"||!Number.isSafeInteger(U)||U<1||U===process.pid||typeof D!=="number"||!Number.isSafeInteger(D))return null;if(!(l.exists??((z)=>{try{return process.kill(z,0),!0}catch(fe){return!(fe instanceof Error&&("code"in fe)&&fe.code==="ESRCH")}}))(U))x={reason:"owner_exited",executorLaunchId:re};else{let z=(l.startedAtMs??qi)(U);if(z===null||z<=D+Vi)return null;x={reason:"pid_reused",executorLaunchId:re}}}let W=Ht(f);if(W.dev!==w.dev||W.ino!==w.ino)return null;Bi(f);let R=Xo(e.journalDirectory,On.O_RDONLY);try{Hi(R)}finally{Jo(R)}return x}catch{return null}finally{Jo(_)}}function ss(e){let l={...e,workspace:e.workspace&&Object.freeze({...e.workspace}),previewAuthority:e.previewAuthority&&Object.freeze({...e.previewAuthority,owner:Object.freeze({...e.previewAuthority.owner}),deniedPorts:new Set(e.previewAuthority.deniedPorts)})},f=$r(l.root,l.runId);if(hr.has(f)||l.operationId!==void 0&&Vr.has(l.operationId))throw new r("hands_jobs_busy","The Session already has a live Hands job supervisor.");let _={binding:l,key:f,terminals:new Map};if(l.previewAuthority&&l.environment)_.previews=Fo({authority:l.previewAuthority,runId:l.runId,expiresAtMs:l.expiresAtMs,executorLaunchId:l.executorLaunchId,environment:l.environment,isCurrent:()=>hr.get(_.key)===_,identity:()=>{try{return bt(l)}catch{return null}},inspect:(w,S)=>{if(hr.get(_.key)!==_)throw new r("preview_unavailable","The Hands supervisor is no longer current.");return is(l,{jobId:w,action:"inspect",input:{after:0}},S)}});if(hr.set(f,_),l.operationId!==void 0)Vr.set(l.operationId,_);return()=>{if(hr.get(_.key)===_)hr.delete(_.key);if(l.operationId!==void 0&&Vr.get(l.operationId)===_)Vr.delete(l.operationId);_.previews?.dispose();for(let w of _.terminals.values())w.abort()}}var Xi=5000,Zi=20;async function to(e){let l=(w)=>{throw new r("hands_rebind_unavailable",w)};if(!L(e.operationId)||!L(e.runId)||!L(e.fenceId)||!H(e.targetGeneration))l("Reason sent an invalid Hands rebind.");let f=Vr.get(e.operationId);if(!f||f.binding.root!==e.root)return l("No live Hands supervisor owns this operation.");for(let w=Date.now()+Xi;;){if(e.signal?.aborted)l("The Hands rebind was cancelled.");if(Vr.get(e.operationId)!==f)l("The Hands supervisor is no longer current.");let S=null;try{S=bt(f.binding)}catch{}if(S&&S.generation===e.targetGeneration&&S.fenceId===e.fenceId)break;if(S&&S.generation>e.targetGeneration||Date.now()>=w)l("The executor did not adopt this take.");await new Promise((x)=>setTimeout(x,Zi))}if(Vr.get(e.operationId)!==f||hr.get(f.key)!==f)l("The Hands supervisor is no longer current.");let _=$r(e.root,e.runId);if(f.key===_)return;if(hr.has(_))l("The taking run already has a live Hands job supervisor.");hr.delete(f.key);for(let w of f.terminals.values())w.abort();f.key=_,hr.set(_,f)}function at(e){let l="operationId"in e?Vr.get(e.operationId):hr.get($r(e.root,e.runId)),f=l&&l.binding.root===e.root?l.binding:void 0;if(!f?.environment||f.expiresAtMs<=Date.now())throw new r("environment_unavailable","No live Hands supervisor owns this environment.");return f.environment.install(e.payload)}async function ro(e){let l=hr.get($r(e.root,e.runId));if(!l?.previews||!e.owner)throw new r("preview_unavailable","No authenticated Hands supervisor owns this preview.");return l.previews.open(e.payload,e.owner,e.signal)}async function no(e){let l=hr.get($r(e.root,e.runId));if(!l?.previews||!e.owner||e.signal.aborted)throw new r("preview_unavailable","No authenticated Hands supervisor owns this preview.");return l.previews.close(e.payload,e.owner)}async function io(e){let l=$r(e.root,e.runId),f=hr.get(l),_=f?.binding,w=_?.runId,S=_?.previewAuthority,x=_?.environment,W=e.owner&&{...e.owner},R=e.authority&&{...e.authority},B=()=>{throw new r("pty_binding_unavailable","No current authenticated Hands scope owns this terminal.")};if(!f||!_||!S||!x||!W||!R||!_.workspace)return B();let G=Object.freeze({..._.workspace}),U=bt(_),D=x.current(),re=()=>{if(hr.get(l)!==f||W.organization_id!==S.owner.organization_id||W.user_id!==S.owner.user_id||W.device_id!==S.owner.device_id||e.deviceId!==S.owner.device_id||e.rootId!==S.rootId||I(e.workspace)!==I(G))B();let z=bt(_),fe=x.current();if(z.generation!==U.generation||z.fenceId!==U.fenceId||fe.run_id!==w||fe.device_id!==e.deviceId||fe.root_id!==e.rootId||fe.snapshot_id!==D.snapshot_id||fe.revision!==D.revision||fe.binding.target_generation!==U.generation||fe.binding.target_fence_id!==U.fenceId||R.device_id!==e.deviceId||R.binding!==fe.binding.kind||R.target_revision!==fe.binding.target_revision||R.root_grant_revision!==fe.binding.root_grant_revision||R.target_generation!==U.generation||R.target_fence_id!==U.fenceId)B()};if(re(),new URL(e.session.relayUrl).origin!==S.relayOrigin||f.terminals.has(e.session.jobId)||f.terminals.size>=4)return B();let J=new AbortController;f.terminals.set(e.session.jobId,J);try{return await Go({session:{...e.session,leaseExpiresAtMs:Math.min(e.session.leaseExpiresAtMs,U.expiresAtMs,Date.parse(D.expires_at))},signal:AbortSignal.any([e.signal,J.signal]),emit:e.emit,binding:{assertCurrent:re,environment:{revision:D.revision,snapshotId:D.snapshot_id},scope:{runId:e.runId,deviceId:e.deviceId,rootId:e.rootId,workspace:G,binding:D.binding.kind,targetRevision:D.binding.target_revision,rootGrantRevision:D.binding.root_grant_revision,generation:U.generation,fenceId:U.fenceId,executorLaunchId:U.executorLaunchId},request:(z,fe)=>_r(U,jr(JSON.stringify({...z,type:"job",version:2,generation:U.generation,id:An()})),fe)}})}finally{if(f.terminals.get(e.session.jobId)===J)f.terminals.delete(e.session.jobId)}}async function oo(e){if(ce(e.payload.jobId))throw new r("pty_binding_required","PTY jobs require the bound terminal capability.");let l=hr.get($r(e.root,e.runId))?.binding;if(!l||l.expiresAtMs<=Date.now())throw new r("hands_jobs_unavailable","No live Hands supervisor owns this Session and root.");return is(l,e.payload,e.signal)}var Qi=1e4,ea=20,ra=ve/2,ta=Ve/2,na=(e)=>e.output.reduce((l,f)=>l+f.text.length,0);async function is(e,l,f){if(Object.keys(l).some((B)=>!["jobId","action","input","waitForExitMs"].includes(B)))throw new r("invalid_payload","Unexpected job control field.");let{waitForExitMs:_,...w}=l;if(_!==void 0&&(w.action!=="start"||typeof w.input!=="object"||w.input===null||!("script"in w.input)||typeof _!=="number"||!Number.isSafeInteger(_)||_<1||_>Qi))throw new r("invalid_payload","Only a script start may wait for its job, within its bound.");let S=(B)=>{let G=bt(e);return _r(G,jr(JSON.stringify({...B,type:"job",version:2,generation:G.generation,id:An()})),f)},x=await S(w);if(_===void 0)return x;let W=Date.now()+_,R=x;while(R.ok&&["starting","running"].includes(R.job.state)&&R.job.output.length<ra&&na(R.job)<ta&&!f.aborted&&Date.now()<W){if(await new Promise((B)=>setTimeout(B,Math.min(ea,W-Date.now()))),f.aborted)break;try{let B=await S({jobId:w.jobId,action:"inspect",input:{after:0}});if(!B.ok)break;R=B}catch{break}}return R}function bt(e){if(e.expiresAtMs<=Date.now())throw new r("hands_jobs_unavailable","Hands authority expired.");let l=e.readIdentity?e.readIdentity():e;if(!l||!H(l.generation)||!L(l.fenceId)||l.generation<e.generation||l.generation===e.generation&&l.fenceId!==e.fenceId)throw new r("hands_jobs_unavailable","The live Hands fencing identity could not be verified.");return e.generation=l.generation,e.fenceId=l.fenceId,{...e}}function _r(e,l,f){if(f.aborted)return Promise.reject(new r("cancelled","Job control was cancelled."));return new Promise((_,w)=>{let S=Wi(e.socketPath),x="",W=!1,R,B=(U,D)=>{if(W)return;if(W=!0,clearTimeout(R),f.removeEventListener("abort",G),S.destroy(),U)w(U);else _(D)},G=()=>B(new r("cancelled","Job control waiter cancelled; inspect before retrying mutations."));f.addEventListener("abort",G,{once:!0}),S.setEncoding("utf8"),R=setTimeout(()=>B(new r("hands_job_result_unknown","Job control timed out; inspect before retrying mutations.")),Math.min(1e4,Math.max(1,e.expiresAtMs-Date.now()))),S.on("error",()=>B(new r("hands_job_result_unknown","Hands job control connection failed."))),S.once("connect",()=>S.write(JSON.stringify({version:1,scopeId:e.scopeId,fenceId:e.fenceId,executorLaunchId:e.executorLaunchId,request:l})+`
|
|
2
|
+
import{qt,j}from"./vm-hands-entry-lite-dgfx0rbn.js";import{ue,Ce,X,Ae,de,ir,et,Y,I,N,rn}from"./vm-hands-entry-lite-48rphbjm.js";import{Uo,ri}from"./vm-hands-entry-lite-4anjdcth.js";import{go,P,Ve,ve,Ge,ne,Ke,Ln,Se,Kt,ae,H,L,ce,jr,Hr,Mn}from"./vm-hands-entry-lite-n7bd44rm.js";import{Pe,oe,pe,Z,Te,q,Q}from"./vm-hands-entry-lite-07apxfh8.js";import{Lt,Pr,lt,V,O,T,b,Cn}from"./vm-hands-entry-lite-1yv5qqew.js";import{Cr,Ar,xn,uo,Ue,kn}from"./vm-hands-entry-lite-gje7xvy9.js";import{K}from"./vm-hands-entry-lite-wghmyfba.js";import{ji}from"./vm-hands-entry-lite-qd46yhvz.js";import{p,ze,$t,ut,po,_e,we}from"./vm-hands-entry-lite-bpamn7ny.js";import{v,h,mo}from"./vm-hands-entry-lite-h1qjggz0.js";import{E}from"./vm-hands-entry-lite-46pwqvpf.js";import{tr}from"./vm-hands-entry-lite-fde30yd5.js";import{a,zo,qo,ie,Vo}from"./vm-hands-entry-lite-8dfw96ym.js";import{M,$i,Mi,Yo,y,t,k,At,o,d,u,n,c,g,ee,s,i}from"./vm-hands-entry-lite-wzv13c8k.js";import{Fi}from"./vm-hands-entry-lite-pzj5s203.js";import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{Qo,se,Ui,C,Oe,$e,A}from"./vm-hands-entry-lite-tyem93c1.js";var Oi=()=>{let e={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function l(w){return e[w]??null}let f={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"},_={nan:"NaN"};return(w)=>{switch(w.code){case"invalid_type":{let S=_[w.expected]??w.expected,x=Yo(w.input),W=_[x]??x;return`Invalid input: expected ${S}, received ${W}`}case"invalid_value":if(w.values.length===1)return`Invalid input: expected ${Mi(w.values[0])}`;return`Invalid option: expected one of ${$i(w.values,"|")}`;case"too_big":{let S=w.inclusive?"<=":"<",x=l(w.origin);if(x)return`Too big: expected ${w.origin??"value"} to have ${S}${w.maximum.toString()} ${x.unit??"elements"}`;return`Too big: expected ${w.origin??"value"} to be ${S}${w.maximum.toString()}`}case"too_small":{let S=w.inclusive?">=":">",x=l(w.origin);if(x)return`Too small: expected ${w.origin} to have ${S}${w.minimum.toString()} ${x.unit}`;return`Too small: expected ${w.origin} to be ${S}${w.minimum.toString()}`}case"invalid_format":{let S=w;if(S.format==="starts_with")return`Invalid string: must start with "${S.prefix}"`;if(S.format==="ends_with")return`Invalid string: must end with "${S.suffix}"`;if(S.format==="includes")return`Invalid string: must include "${S.includes}"`;if(S.format==="regex")return`Invalid string: must match pattern ${S.pattern}`;return`Invalid ${f[S.format]??w.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${w.divisor}`;case"unrecognized_keys":return`Unrecognized key${w.keys.length>1?"s":""}: ${$i(w.keys,", ")}`;case"invalid_key":return`Invalid key in ${w.origin}`;case"invalid_union":if(w.options&&Array.isArray(w.options)&&w.options.length>0)return`Invalid discriminator value. Expected ${w.options.map((x)=>`'${x}'`).join(" | ")}`;return"Invalid input";case"invalid_element":return`Invalid value in ${w.origin}`;default:return"Invalid input"}}};function gn(){return{localeError:Oi()}}M(gn());class mt extends Error{}function No(e){let l;try{l=new URL(e)}catch{throw new mt("The proxy must be a URL like https://proxy.example.com:3128.")}if(l.protocol!=="https:"&&l.protocol!=="http:")throw new mt("The proxy URL must use the https or http scheme.");if(!l.hostname)throw new mt("The proxy URL must name a host.");if(l.port!==""&&Number(l.port)<1)throw new mt("The proxy URL must use a port between 1 and 65535.");if(l.pathname!==""&&l.pathname!=="/"||l.search||l.hash)throw new mt("The proxy URL must not carry a path, query, or fragment.");return l.toString()}import{createHash as xi}from"crypto";import{isAbsolute as Bo,join as jo,relative as Mo,resolve as Yt,sep as Wo}from"path";var Vt=t().min(1).refine(Bo,"absolute path required"),Lo=c({version:i(1),apiOrigin:At(),channel:s(["staging","production"]),stateDirectory:Vt,workspaceRoot:Vt,lifetime:s(["persistent","ephemeral"]),executionMode:s(["confined","host"]).default("confined"),name:t().min(1).max(160).default("Reason headless worker"),slots:o().int().min(1).max(4).default(1),shutdownGraceMs:o().int().min(0).max(300000).default(30000),proxy:c({version:i(qt),url:t().refine((e)=>{try{return No(e)===e}catch{return!1}},"invalid proxy URL"),caFile:Vt.optional()}).optional(),userChrome:d().optional(),cloudSessions:i(!0).optional(),localLogins:d().optional(),folders:u(Vt).min(1).max(31).optional()}),Pi=/^https:\/\/[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.trycloudflare\.com$/,F=g("channel",[Lo,Lo.extend({channel:i("local-qa"),apiOrigin:t()})]).superRefine((e,l)=>{if(e.channel==="local-qa"){if(!Pi.test(e.apiOrigin))l.addIssue({code:"custom",message:"local QA worker requires an exact HTTPS trycloudflare.com quick-tunnel origin"})}else{let _=new URL(e.apiOrigin);if(_.origin!==e.apiOrigin||_.username||_.password||_.protocol!=="https:"&&!(_.protocol==="http:"&&ri(_.origin))||!ri(_.origin)&&!Uo(e.channel,_.origin))l.addIssue({code:"custom",message:"API origin must match channel (or loopback)"})}if(!je(e.workspaceRoot,e.stateDirectory))l.addIssue({code:"custom",message:"state and workspace must be disjoint"});let f=e.folders??[];if(new Set([e.workspaceRoot,...f]).size!==f.length+1||f.some((_)=>!je(_,e.stateDirectory)))l.addIssue({code:"custom",message:"folders must be distinct and disjoint from state"})});function m(e){return jo(e.stateDirectory,`headless-${e.channel}`)}function je(e,l){if(zr(l,e))return!1;return!zr(e,l)||E(jo(Wo,Mo(Yt(e),Yt(l))))}function zr(e,l){let f=Mo(Yt(e),Yt(l));return f===""||f!==".."&&!f.startsWith(`..${Wo}`)&&!Bo(f)}function te(e){let{proxy:l,userChrome:f,cloudSessions:_,localLogins:w,folders:S,...x}=e;return xi("sha256").update(JSON.stringify(x)).digest("hex")}var Ii=4,Ai=[2375,2376,9222,9229];function mr(e){let l=new Set(Ai);for(let f of e){let _=new URL(f);l.add(Number(_.port||(["https:","wss:"].includes(_.protocol)?443:80)))}return l}function Jr(){throw new r("preview_unavailable","The live Hands preview binding is unavailable or stale.")}var Ti=60000;function Fo(e){let l=new AbortController,f=new Map,_=(R)=>JSON.stringify([R.jobId,R.port]);function w(R){let B=e.authority.owner;if(l.signal.aborted||!e.isCurrent()||e.expiresAtMs<=Date.now()||R.organization_id!==B.organization_id||R.user_id!==B.user_id||R.device_id!==B.device_id)Jr()}function S(R){let B;try{B=e.environment.current()}catch{return null}return B.binding.target_generation===R.generation&&B.binding.target_fence_id===R.fenceId&&B.run_id===e.runId&&B.device_id===e.authority.owner.device_id&&B.root_id===e.authority.rootId?B:null}async function x(R,B,G){let U=await W(R,B,G);if(U!=="moved")return U;let D=await W(R,B,G);return D==="moved"?null:D}async function W(R,B,G){try{w(e.authority.owner);let U=e.identity();if(!U||G.aborted||R.expiresAtMs<=Date.now()||R.expiresAtMs>e.expiresAtMs)return null;let D=B.opened,re=D!==void 0&&U.generation>D.generation,J=S(U);if(re){if(J){if(J.revision<=D.revision||R.expiresAtMs>Date.parse(J.expires_at)||J.binding.target_revision!==D.attachmentRevision||J.binding.root_grant_revision!==D.grantRevision)return null;B.recoveringSinceMs=void 0}else if(Date.now()-(B.recoveringSinceMs??=Date.now())>Ti)return null}else if(!J||R.expiresAtMs>Date.parse(J.expires_at)||D&&(U.generation!==D.generation||U.fenceId!==D.fenceId))return null;let z=await e.inspect(R.jobId,G),fe=e.identity(),ke=fe&&S(fe);w(e.authority.owner);let be=J&&{generation:U.generation,fenceId:U.fenceId,snapshotId:J.snapshot_id,revision:J.revision,attachmentRevision:J.binding.target_revision,grantRevision:J.binding.root_grant_revision},Re=re?D:be;if(G.aborted||!fe)return null;if(fe.generation!==U.generation||fe.fenceId!==U.fenceId||ke?.snapshot_id!==J?.snapshot_id||ke?.revision!==J?.revision)return"moved";let Fe=z.ok&&z.job.environmentSnapshotId!==void 0&&z.job.environmentRevision!==void 0?{snapshotId:z.job.environmentSnapshotId,revision:z.job.environmentRevision}:null;if(!z.ok||z.generation!==U.generation||!Re||!Fe)return null;if((Fe.snapshotId!==Re.snapshotId||Fe.revision!==Re.revision)&&(re||!e.environment.carried(Fe.snapshotId,Fe.revision)))return null;if(!D&&U.generation===R.generation&&U.fenceId===R.fenceId)B.opened={...Re,...Fe};return{executorLaunchId:e.executorLaunchId,job:z.job,binding:{organizationId:e.authority.owner.organization_id,userId:e.authority.owner.user_id,deviceId:e.authority.owner.device_id,rootId:e.authority.rootId,runId:e.runId,attachmentRevision:Re.attachmentRevision,grantRevision:Re.grantRevision,generation:Re.generation,fenceId:Re.fenceId,jobId:z.job.jobId,port:R.port,expiresAtMs:R.expiresAtMs}}}catch{return null}}return{async open(R,B,G){w(B);let{binding:U,deviceRelayUrl:D}=ut(R);if(G.aborted||U.expiresAtMs<=Date.now()||U.expiresAtMs>Date.now()+p.lifetimeMs||new URL(D).origin!==e.authority.relayOrigin)Jr();let re=_(U),J=f.get(re);if(J){if(!ze(J.binding,U)||J.relay!==D)Jr();if(await J.opened,!await $t(()=>J.port.check())||G.aborted||J.abort.signal.aborted)Jr();return{opened:!0,binding:U}}if(f.size>=Ii)Jr();let z=new AbortController,fe={},ke=we({binding:U,deniedPorts:e.authority.deniedPorts,readCurrentJob:()=>x(U,fe,z.signal)}),be=()=>z.abort();if(G.addEventListener("abort",be,{once:!0}),l.signal.addEventListener("abort",be,{once:!0}),G.aborted||l.signal.aborted)be();let Re=_e({binding:U,deviceRelayUrl:D,port:ke,signal:z.signal}),Fe={binding:U,relay:D,abort:z,port:ke,opened:Re};f.set(re,Fe);let Xe=()=>{if(G.removeEventListener("abort",be),l.signal.removeEventListener("abort",be),f.get(re)===Fe)f.delete(re)};try{if((await Re).closed.then(Xe),G.removeEventListener("abort",be),w(B),z.signal.aborted||!await $t(()=>ke.check()))Jr();return{opened:!0,binding:U}}catch{z.abort(),Xe(),Jr()}},async close(R,B){w(B);let{binding:G}=po(R),U=f.get(_(G));if(!U||!ze(U.binding,G))Jr();return U.abort.abort(),await U.opened.then((D)=>D.closed,()=>{return}),{closed:!0,binding:G}},dispose(){l.abort();for(let R of f.values())R.abort.abort();f.clear()}}}import{WebSocket as Rn}from"ws";var $o=(e)=>("data"in e)?e.data.length:e.bytes,Ko=2*Ke;function ar(e){throw new r(e,"The bound Hands terminal is unavailable or its outcome is unconfirmed.")}var ht=(e)=>!["starting","running"].includes(e.state);function eo(e,l,f=Date.now()){let _=["relay_url","session_id","expires_at","cols","rows","pty","workspace"];if(Object.keys(e).length!==_.length||Object.keys(e).some((B)=>!_.includes(B))||!ae(l)||!ae(e.session_id)||typeof e.expires_at!=="string"||typeof e.relay_url!=="string"||e.relay_url.length>4096||![e.cols,e.rows].every((B)=>Number.isSafeInteger(B)&&Number(B)>=1&&Number(B)<=Se))ar("invalid_pty_request");let w=e.pty;if(!w||typeof w!=="object"||Array.isArray(w))ar("invalid_pty_request");let S=w;if(Object.keys(S).length!==2||S.version!==1||!ce(S.jobId))ar("invalid_pty_request");let x;try{x=new URL(e.relay_url)}catch{return ar("invalid_pty_request")}if(!["ws:","wss:"].includes(x.protocol)||x.username||x.password||x.hash||x.protocol==="ws:"&&!["127.0.0.1","[::1]","localhost"].includes(x.hostname))ar("invalid_pty_request");let W=Date.parse(e.expires_at);if(!Number.isSafeInteger(W)||W<=f)ar("invalid_pty_request");return{workspace:N(e.workspace)??ar("invalid_pty_request"),session:{jobId:S.jobId,sessionId:e.session_id,operationId:l,relayUrl:x.href,cols:Number(e.cols),rows:Number(e.rows),leaseExpiresAtMs:Math.min(W,f+43200000)}}}async function Go(e){let{session:l,binding:f}=e;if(f.assertCurrent(),e.signal.aborted||Date.now()>=l.leaseExpiresAtMs)ar("cancelled");let _=new Rn(l.relayUrl,{followRedirects:!1,perMessageDeflate:!1,maxPayload:ne}),w=new AbortController,S=()=>{},x=()=>{w.abort(),S()};e.signal.addEventListener("abort",x,{once:!0});let W=setTimeout(x,Math.max(1,l.leaseExpiresAtMs-Date.now())),R=[],B=0,G=0,U=0,D=!1,re=!1,J=!1,z,fe,ke,be=(le)=>{ke=new r(le,"Bound terminal input was refused."),x()};_.on("error",()=>be("pty_relay_unavailable")),_.on("close",x),_.on("message",(le,he)=>{if(w.signal.aborted)return;if(!re){be("pty_not_ready");return}let xe=Array.isArray(le)?Buffer.concat(le):le instanceof ArrayBuffer?Buffer.from(le):le;if(xe.length===0)return;let Je=R.at(-1),Le=he&&Je!==void 0&&"data"in Je&&Je.data.length+xe.length<=ne;if(xe.length>ne||B+xe.length>Ln){be("pty_input_backpressure");return}if(Le)Je.data=Buffer.concat([Je.data,xe]);else if(he)R.push({data:Buffer.from(xe)});else try{let Be=JSON.parse(xe.toString("utf8"));if(Be&&Be.t==="close"&&Object.keys(Be).length===1){J=!0,x();return}if(!Be||Be.t!=="resize"||Object.keys(Be).length!==3||![Be.cols,Be.rows].every((Ee)=>Number.isSafeInteger(Ee)&&Ee>=1&&Ee<=Se))throw Error("invalid_control");R.push({cols:Be.cols,rows:Be.rows,bytes:xe.length})}catch{be("invalid_pty_control");return}B+=xe.length,S()});function Re(le){return Mn(JSON.stringify({...f.scope,version:1,sessionId:l.sessionId,operationId:l.operationId,job:{...le,output:[],pty:le.pty?{...le.pty,output:[]}:void 0}}))}function Fe(le){if(!le.ok)ar(le.error);let he=le.job;if(le.generation!==f.scope.generation||he.jobId!==l.jobId||!he.pty||he.leaseExpiresAtMs>l.leaseExpiresAtMs||he.process&&he.process.executorLaunchId!==f.scope.executorLaunchId||he.process&&fe&&(he.process.pid!==fe.pid||he.process.processGroupId!==fe.processGroupId)||he.state!=="starting"&&(he.environmentRevision!==f.environment.revision||he.environmentSnapshotId!==f.environment.snapshotId))ar("pty_binding_changed");if(Re(he),he.process)fe??={...he.process};return he}async function Xe(le){f.assertCurrent();let he=await f.request(le,w.signal);if(f.assertCurrent(),w.signal.aborted)ar("cancelled");let xe=Fe(he);if(xe.inputSequence!==G)ar("job_input_sequence");if(!ht(xe)&&xe.leaseExpiresAtMs<=Date.now())ar("pty_binding_changed");return xe}function ye(le){if(f.assertCurrent(),w.signal.aborted||_.readyState!==Rn.OPEN||_.bufferedAmount+Buffer.byteLength(le)>Ko)ar("pty_output_backpressure");_.send(le)}function We(le){if(le.firstCursor>U+1)U=le.firstCursor-1;for(let he of le.pty.output){if(he.cursor<=U)continue;if(he.cursor!==U+1)ar("pty_output_gap");let xe=Buffer.from(he.dataBase64,"base64");if(_.bufferedAmount+xe.length>Ko)return!1;ye(xe),U=he.cursor}if(U!==le.nextCursor)ar("pty_output_gap");return!0}async function Ye(le,he){let xe;try{await Promise.race([e.emit(le,he),new Promise((Je,Le)=>{xe=setTimeout(()=>Le(new r("pty_event_unavailable","Terminal metadata delivery timed out.")),2000)})])}finally{clearTimeout(xe)}}async function De(){let le=AbortSignal.timeout(Kt),he=f.request({jobId:l.jobId,action:"cancel",input:{}},le),xe,Je=new Promise((Le,Be)=>{if(xe=()=>Be(new r("pty_cleanup_unconfirmed","Terminal cleanup acknowledgement was not observed within authority.")),le.addEventListener("abort",xe,{once:!0}),le.aborted)xe()});try{let Le=await Promise.race([he,Je]);if(le.aborted)ar("pty_cleanup_unconfirmed");return Fe(Le)}finally{le.removeEventListener("abort",xe)}}try{await new Promise((Le,Be)=>{let Ee=setTimeout(()=>{x(),Be(new r("pty_relay_unavailable","Terminal pairing timed out."))},5000),Me=()=>{clearTimeout(Ee),Be(new r("cancelled","Terminal pairing was cancelled."))};if(w.signal.addEventListener("abort",Me,{once:!0}),_.once("open",()=>{clearTimeout(Ee),w.signal.removeEventListener("abort",Me),Le()}),w.signal.aborted)Me()}),f.assertCurrent(),D=!0,z=await Xe({jobId:l.jobId,action:"start",input:{mode:"pty",cols:l.cols,rows:l.rows,leaseExpiresAtMs:l.leaseExpiresAtMs}});let le=Date.now()+5000;while(z.state==="starting"){if(Date.now()>=le)ar("pty_not_ready");await new Promise((Le)=>setTimeout(Le,25)),z=await Xe({jobId:l.jobId,action:"inspect",input:{after:U}})}if(z.state!=="running"||z.inputSequence!==0||z.leaseExpiresAtMs<=Date.now())ar("pty_not_ready");await Ye("pty.ready",Re(z)),re=!0,ye(JSON.stringify({t:"open",cols:z.pty.cols,rows:z.pty.rows,receipt:Re(z)}));let he=!1,xe=0,Je=!1;while(!w.signal.aborted){let Le=z.firstCursor>U+1,Be=We(z);if(ht(z)){if(Be)break}else if(Le)he=!0;else if(he&&Be&&Date.now()>=xe){he=!1,xe=Date.now()+1000;let{cols:Me,rows:rr}=z.pty;for(let or of[{cols:Me,rows:rr>1?rr-1:2},{cols:Me,rows:rr}]){if(ht(z))break;let Rr=++G;if(z=await Xe({jobId:l.jobId,action:"resize",input:{sequence:Rr,...or}}),z.inputSequence!==Rr)ar("job_input_sequence")}continue}let Ee=ht(z)||Je?void 0:R.shift();if(Ee){B-=$o(Ee);let Me=++G;try{z=await Xe("data"in Ee?{jobId:l.jobId,action:"input",input:{sequence:Me,dataBase64:Ee.data.toString("base64")}}:{jobId:l.jobId,action:"resize",input:{sequence:Me,cols:Ee.cols,rows:Ee.rows}})}catch(rr){if(!(rr instanceof r)||rr.code!=="job_input_backpressure")throw rr;G-=1,R.unshift(Ee),B+=$o(Ee),Je=!0;continue}if(z.inputSequence!==Me)ar("job_input_sequence")}else if(await new Promise((Me)=>{let rr=setTimeout(Me,Je||!Be?10:50);if(S=()=>{clearTimeout(rr),Me()},w.signal.aborted||!Je&&R.length)S()}),Je=!1,S=()=>{},!w.signal.aborted&&Be)try{z=await Xe({jobId:l.jobId,action:"inspect",input:{after:U}})}catch(Me){if(!J||!(Me instanceof r)||Me.code!=="cancelled")throw Me}}}catch(le){ke??=le}finally{if(re=!1,R.length=0,clearTimeout(W),e.signal.removeEventListener("abort",x),x(),D&&(!z||!ht(z)))try{z=await De()}catch{z=void 0}try{if(!z||!ht(z)||z.pty?.cleanup!=="confirmed")ar("pty_cleanup_unconfirmed");let le=Re(z);if(_.readyState===Rn.OPEN)await new Promise((he)=>{let xe=setTimeout(he,500);_.send(JSON.stringify({t:"exit",code:z.exitCode,receipt:le}),()=>{clearTimeout(xe),he()})});await Ye("pty.stopped",le)}catch(le){ke??=le}_.terminate()}if(ke)throw ke;if(e.signal.aborted)ar("cancelled");if(!z)ar("pty_cleanup_unconfirmed");return{receipt:Re(z)}}import{createHash as Di,randomUUID as An}from"crypto";import{spawnSync as es}from"child_process";import{closeSync as Jo,constants as On,fstatSync as Ci,fsyncSync as Hi,lstatSync as Ht,mkdirSync as Ni,mkdtempSync as rs,openSync as Xo,readFileSync as Li,readdirSync as ts,realpathSync as qr,rmSync as Pn,unlinkSync as Bi}from"fs";import{createConnection as Wi}from"net";import{dirname as zi,join as ot,sep as In}from"path";import{tmpdir as ns}from"os";var hr=new Map,Vr=new Map;function $r(e,l){return Di("sha256").update(JSON.stringify([e,l])).digest("hex")}function gt(e){try{Ni(e,{mode:448})}catch(f){if(!(f instanceof Error&&("code"in f)&&f.code==="EEXIST"))throw f}let l=Ht(e);if(!l.isDirectory()||l.isSymbolicLink()||!A(l)||qr(e)!==e)throw new r("hands_jobs_unavailable","Hands job state must be a private canonical directory.")}function Ki(e){let l;try{l=Ht(e)}catch(f){if(f instanceof Error&&"code"in f&&f.code==="ENOENT")return!1;throw f}return!l.isDirectory()||l.isSymbolicLink()||ts(e).length>0}function Gi(e){if(process.platform==="win32")return Ui();let l=e.map((f)=>{try{return qr(f)}catch{return f}});for(let f of[()=>Ui(),()=>qr("/dev/shm"),()=>qr(ns())]){let _;try{_=f()}catch{continue}if(!l.some((w)=>_===w||_.startsWith(w.endsWith(In)?w:w+In)))return _}throw new r("invalid_hands_workspace","A Session can't work in this computer's temporary folder itself; start it in a project folder inside it.")}function gr(e){let l=$r(e.root,e.runId),f=e.previousRuntimeDirectories?.find((x)=>Ki(ot(x,"jobs",l.slice(0,16))))??e.runtimeDirectory;gt(f);let _=ot(f,"jobs");gt(_);let w=ot(_,l.slice(0,16));if(e.maxScopes!==void 0){let x=ts(_);if(!Number.isSafeInteger(e.maxScopes)||e.maxScopes<1||x.length>e.maxScopes||!x.includes(l.slice(0,16))&&x.length>=e.maxScopes)throw new r("process_journal_capacity","Managed process receipt capacity is full; preserve uncertain jobs and reconcile their existing receipts before starting more work.")}gt(w);let S=rs(ot(Gi(e.folders??[]),"reason-j-"));try{return gt(S),{journalDirectory:w,scopeId:l,launchDirectory:S,socketPath:process.platform==="win32"?`\\\\.\\pipe\\reason-jobs-${An()}`:ot(S,"control.sock"),disposeSocket:()=>Pn(S,{recursive:!0,force:!0})}}catch(x){throw Pn(S,{recursive:!0,force:!0}),x}}var Ji=60000,Vi=5000;function qi(e){if(process.platform==="win32")return Yi(e);let l=es("ps",["-o","lstart=","-p",String(e)],{encoding:"utf8",timeout:2000,env:{...process.env,LC_ALL:"C",LANG:"C"}}),f=l.status===0?/^\w{3} (\w{3}) +(\d{1,2}) (\d{2}):(\d{2}):(\d{2}) (\d{4})$/.exec(l.stdout.trim()):null,_=f?"JanFebMarAprMayJunJulAugSepOctNovDec".indexOf(f[1]):-1;if(!f||_<0||_%3!==0)return null;let w=new Date(Number(f[6]),_/3,Number(f[2]),Number(f[3]),Number(f[4]),Number(f[5])).getTime();return Number.isFinite(w)?w:null}function Yi(e){let l=es(C("powershell"),["-NoProfile","-NonInteractive","-Command",`(Get-Process -Id ${e}).StartTime.ToUniversalTime().ToString('o')`],{encoding:"utf8",timeout:5000,windowsHide:!0,env:Oe()}),f=l.status===0?Date.parse(l.stdout.trim()):Number.NaN;return Number.isFinite(f)?f:null}function os(e,l={}){let f=ot(e.journalDirectory,"owner.lock"),_;try{_=Xo(f,On.O_RDONLY|On.O_NOFOLLOW)}catch{return null}try{let w=Ci(_);if(!w.isFile()||w.nlink!==1||!A(w)||w.size>4096)return null;let S=null;try{S=JSON.parse(Li(_,"utf8"))}catch{}let x;if(S===null){if((l.now??Date.now)()-w.mtimeMs<Ji)return null;x={reason:"never_written",executorLaunchId:null}}else{let{version:B,scopeId:G,pid:U,createdAtMs:D,executorLaunchId:re}=S;if(B!==1||G!==e.scopeId||typeof re!=="string"||typeof U!=="number"||!Number.isSafeInteger(U)||U<1||U===process.pid||typeof D!=="number"||!Number.isSafeInteger(D))return null;if(!(l.exists??((z)=>{try{return process.kill(z,0),!0}catch(fe){return!(fe instanceof Error&&("code"in fe)&&fe.code==="ESRCH")}}))(U))x={reason:"owner_exited",executorLaunchId:re};else{let z=(l.startedAtMs??qi)(U);if(z===null||z<=D+Vi)return null;x={reason:"pid_reused",executorLaunchId:re}}}let W=Ht(f);if(W.dev!==w.dev||W.ino!==w.ino)return null;Bi(f);let R=Xo(e.journalDirectory,On.O_RDONLY);try{Hi(R)}finally{Jo(R)}return x}catch{return null}finally{Jo(_)}}function ss(e){let l={...e,workspace:e.workspace&&Object.freeze({...e.workspace}),previewAuthority:e.previewAuthority&&Object.freeze({...e.previewAuthority,owner:Object.freeze({...e.previewAuthority.owner}),deniedPorts:new Set(e.previewAuthority.deniedPorts)})},f=$r(l.root,l.runId);if(hr.has(f)||l.operationId!==void 0&&Vr.has(l.operationId))throw new r("hands_jobs_busy","The Session already has a live Hands job supervisor.");let _={binding:l,key:f,terminals:new Map};if(l.previewAuthority&&l.environment)_.previews=Fo({authority:l.previewAuthority,runId:l.runId,expiresAtMs:l.expiresAtMs,executorLaunchId:l.executorLaunchId,environment:l.environment,isCurrent:()=>hr.get(_.key)===_,identity:()=>{try{return bt(l)}catch{return null}},inspect:(w,S)=>{if(hr.get(_.key)!==_)throw new r("preview_unavailable","The Hands supervisor is no longer current.");return is(l,{jobId:w,action:"inspect",input:{after:0}},S)}});if(hr.set(f,_),l.operationId!==void 0)Vr.set(l.operationId,_);return()=>{if(hr.get(_.key)===_)hr.delete(_.key);if(l.operationId!==void 0&&Vr.get(l.operationId)===_)Vr.delete(l.operationId);_.previews?.dispose();for(let w of _.terminals.values())w.abort()}}var Xi=5000,Zi=20;async function to(e){let l=(w)=>{throw new r("hands_rebind_unavailable",w)};if(!L(e.operationId)||!L(e.runId)||!L(e.fenceId)||!H(e.targetGeneration))l("Reason sent an invalid Hands rebind.");let f=Vr.get(e.operationId);if(!f||f.binding.root!==e.root)return l("No live Hands supervisor owns this operation.");for(let w=Date.now()+Xi;;){if(e.signal?.aborted)l("The Hands rebind was cancelled.");if(Vr.get(e.operationId)!==f)l("The Hands supervisor is no longer current.");let S=null;try{S=bt(f.binding)}catch{}if(S&&S.generation===e.targetGeneration&&S.fenceId===e.fenceId)break;if(S&&S.generation>e.targetGeneration||Date.now()>=w)l("The executor did not adopt this take.");await new Promise((x)=>setTimeout(x,Zi))}if(Vr.get(e.operationId)!==f||hr.get(f.key)!==f)l("The Hands supervisor is no longer current.");let _=$r(e.root,e.runId);if(f.key===_)return;if(hr.has(_))l("The taking run already has a live Hands job supervisor.");hr.delete(f.key);for(let w of f.terminals.values())w.abort();f.key=_,hr.set(_,f)}function at(e){let l="operationId"in e?Vr.get(e.operationId):hr.get($r(e.root,e.runId)),f=l&&l.binding.root===e.root?l.binding:void 0;if(!f?.environment||f.expiresAtMs<=Date.now())throw new r("environment_unavailable","No live Hands supervisor owns this environment.");return f.environment.install(e.payload)}async function ro(e){let l=hr.get($r(e.root,e.runId));if(!l?.previews||!e.owner)throw new r("preview_unavailable","No authenticated Hands supervisor owns this preview.");return l.previews.open(e.payload,e.owner,e.signal)}async function no(e){let l=hr.get($r(e.root,e.runId));if(!l?.previews||!e.owner||e.signal.aborted)throw new r("preview_unavailable","No authenticated Hands supervisor owns this preview.");return l.previews.close(e.payload,e.owner)}async function io(e){let l=$r(e.root,e.runId),f=hr.get(l),_=f?.binding,w=_?.runId,S=_?.previewAuthority,x=_?.environment,W=e.owner&&{...e.owner},R=e.authority&&{...e.authority},B=()=>{throw new r("pty_binding_unavailable","No current authenticated Hands scope owns this terminal.")};if(!f||!_||!S||!x||!W||!R||!_.workspace)return B();let G=Object.freeze({..._.workspace}),U=bt(_),D=x.current(),re=()=>{if(hr.get(l)!==f||W.organization_id!==S.owner.organization_id||W.user_id!==S.owner.user_id||W.device_id!==S.owner.device_id||e.deviceId!==S.owner.device_id||e.rootId!==S.rootId||I(e.workspace)!==I(G))B();let z=bt(_),fe=x.current();if(z.generation!==U.generation||z.fenceId!==U.fenceId||fe.run_id!==w||fe.device_id!==e.deviceId||fe.root_id!==e.rootId||fe.snapshot_id!==D.snapshot_id||fe.revision!==D.revision||fe.binding.target_generation!==U.generation||fe.binding.target_fence_id!==U.fenceId||R.device_id!==e.deviceId||R.binding!==fe.binding.kind||R.target_revision!==fe.binding.target_revision||R.root_grant_revision!==fe.binding.root_grant_revision||R.target_generation!==U.generation||R.target_fence_id!==U.fenceId)B()};if(re(),new URL(e.session.relayUrl).origin!==S.relayOrigin||f.terminals.has(e.session.jobId)||f.terminals.size>=4)return B();let J=new AbortController;f.terminals.set(e.session.jobId,J);try{return await Go({session:{...e.session,leaseExpiresAtMs:Math.min(e.session.leaseExpiresAtMs,U.expiresAtMs,Date.parse(D.expires_at))},signal:AbortSignal.any([e.signal,J.signal]),emit:e.emit,binding:{assertCurrent:re,environment:{revision:D.revision,snapshotId:D.snapshot_id},scope:{runId:e.runId,deviceId:e.deviceId,rootId:e.rootId,workspace:G,binding:D.binding.kind,targetRevision:D.binding.target_revision,rootGrantRevision:D.binding.root_grant_revision,generation:U.generation,fenceId:U.fenceId,executorLaunchId:U.executorLaunchId},request:(z,fe)=>_r(U,jr(JSON.stringify({...z,type:"job",version:2,generation:U.generation,id:An()})),fe)}})}finally{if(f.terminals.get(e.session.jobId)===J)f.terminals.delete(e.session.jobId)}}async function oo(e){if(ce(e.payload.jobId))throw new r("pty_binding_required","PTY jobs require the bound terminal capability.");let l=hr.get($r(e.root,e.runId))?.binding;if(!l||l.expiresAtMs<=Date.now())throw new r("hands_jobs_unavailable","No live Hands supervisor owns this Session and root.");return is(l,e.payload,e.signal)}var Qi=1e4,ea=20,ra=ve/2,ta=Ve/2,na=(e)=>e.output.reduce((l,f)=>l+f.text.length,0);async function is(e,l,f){if(Object.keys(l).some((B)=>!["jobId","action","input","waitForExitMs"].includes(B)))throw new r("invalid_payload","Unexpected job control field.");let{waitForExitMs:_,...w}=l;if(_!==void 0&&(w.action!=="start"||typeof w.input!=="object"||w.input===null||!("script"in w.input)||typeof _!=="number"||!Number.isSafeInteger(_)||_<1||_>Qi))throw new r("invalid_payload","Only a script start may wait for its job, within its bound.");let S=(B)=>{let G=bt(e);return _r(G,jr(JSON.stringify({...B,type:"job",version:2,generation:G.generation,id:An()})),f)},x=await S(w);if(_===void 0)return x;let W=Date.now()+_,R=x;while(R.ok&&["starting","running"].includes(R.job.state)&&R.job.output.length<ra&&na(R.job)<ta&&!f.aborted&&Date.now()<W){if(await new Promise((B)=>setTimeout(B,Math.min(ea,W-Date.now()))),f.aborted)break;try{let B=await S({jobId:w.jobId,action:"inspect",input:{after:0}});if(!B.ok)break;R=B}catch{break}}return R}function bt(e){if(e.expiresAtMs<=Date.now())throw new r("hands_jobs_unavailable","Hands authority expired.");let l=e.readIdentity?e.readIdentity():e;if(!l||!H(l.generation)||!L(l.fenceId)||l.generation<e.generation||l.generation===e.generation&&l.fenceId!==e.fenceId)throw new r("hands_jobs_unavailable","The live Hands fencing identity could not be verified.");return e.generation=l.generation,e.fenceId=l.fenceId,{...e}}function _r(e,l,f){if(f.aborted)return Promise.reject(new r("cancelled","Job control was cancelled."));return new Promise((_,w)=>{let S=Wi(e.socketPath),x="",W=!1,R,B=(U,D)=>{if(W)return;if(W=!0,clearTimeout(R),f.removeEventListener("abort",G),S.destroy(),U)w(U);else _(D)},G=()=>B(new r("cancelled","Job control waiter cancelled; inspect before retrying mutations."));f.addEventListener("abort",G,{once:!0}),S.setEncoding("utf8"),R=setTimeout(()=>B(new r("hands_job_result_unknown","Job control timed out; inspect before retrying mutations.")),Math.min(1e4,Math.max(1,e.expiresAtMs-Date.now()))),S.on("error",()=>B(new r("hands_job_result_unknown","Hands job control connection failed."))),S.once("connect",()=>S.write(JSON.stringify({version:1,scopeId:e.scopeId,fenceId:e.fenceId,executorLaunchId:e.executorLaunchId,request:l})+`
|
|
3
3
|
`)),S.on("data",(U)=>{if(x+=U,Buffer.byteLength(x)>Ge)B(new r("hands_job_result_unknown","Hands job result exceeded its bound."))}),S.once("end",()=>{if(Date.now()>=e.expiresAtMs){B(new r("hands_job_result_unknown","Hands authority expired before the result was acknowledged."));return}try{let U=Hr(x.trim());if(U.id!==l.id||U.generation!==e.generation||U.ok&&U.job.jobId!==l.jobId)throw Error("identity");B(void 0,U)}catch{B(new r("hands_job_result_unknown","Hands job response identity or shape was invalid."))}}),S.once("close",()=>{if(!W)B(new r("hands_job_result_unknown","Hands job control closed before an acknowledged result."))})})}function Zo(e){let l=qr(e.root),f=e.authority,_=Date.parse(e.leaseUntil),w=()=>{if(e.signal.throwIfAborted(),!Number.isFinite(_)||_<=Date.now())throw Error("local_device_gh_lease_expired")};if(w(),f.readOnly&&f.generation===null)return{root:l,readOnly:!0,signal:e.signal,deadlineMs:_,assertCurrent:w};let S=$r(l,e.runId),x=hr.get(S),W=x?.binding;if(!W?.environment||!W.workspace||W.localGithubConfinement!==!0)throw Error("local_device_gh_confinement_unavailable");let R=W.environment.current(),B=()=>{w();let U=W.environment.current(),D=bt(W);if(hr.get(S)!==x||U.github_auth!=="local_gh"||U.run_id!==W.runId||f.runId!==e.runId||U.device_id!==f.deviceId||U.root_id!==f.rootId||String(U.binding.root_grant_revision)!==f.rootRevision||U.binding.target_generation!==f.generation||U.binding.target_fence_id!==f.fenceId||D.generation!==f.generation||D.fenceId!==f.fenceId||U.snapshot_id!==R.snapshot_id||U.revision!==R.revision)throw Error("local_device_gh_authority_changed")};B();let G=ie(l,W.workspace);return{root:G.boundary,signal:e.signal,deadlineMs:_,privateDirectory:zi(W.environment.path),repoPath:G.path,readOnly:f.readOnly,forbiddenSecretValues:Object.values(R.variables),secretNames:(U)=>Object.entries(R.variables).filter(([,D])=>D.trim()===U.trim()).map(([D])=>`variable ${D}`),assertCurrent:B}}async function so(e,l){let f=Pe.parse(e.request),_=oe.parse(e.authority);if(_.contributorRefresh&&f.kind==="read"&&_.readOnly)return l(Zo(e));let w=Boolean(_.contributorRefresh);if(w&&(_.merge||f.kind!=="pr_mutation"||f.mutation.action!=="edit"||typeof f.mutation.body!=="string"||f.mutation.title!==void 0||f.mutation.base!==void 0||_.readOnly||_.runId!==e.runId||_.repoFullName!==f.repoFullName))throw Error("local_device_gh_contributor_refresh_authority_invalid");if(f.kind!=="pr_merge"&&!w){if(_.merge)throw Error("local_device_gh_merge_authority_invalid");return l(Zo(e))}if(!w&&(!_.merge||_.readOnly||_.runId!==e.runId||_.repoFullName!==f.repoFullName||_.merge.source==="agent"&&(_.generation===null||_.fenceId===null)))throw Error("local_device_gh_merge_authority_invalid");let S=qr(e.root),x=Ht(S),W=Date.parse(e.leaseUntil);if(!Number.isFinite(W)||W<=Date.now())throw Error("local_device_gh_lease_expired");let R=qr(ns());if(R===S||R.startsWith(S+In))throw Error("local_device_gh_private_scope_unavailable");let B=rs(ot(R,"reason-gh-merge-"));try{gt(B);let G=()=>{if(e.signal.throwIfAborted(),Date.now()>=W)throw Error("local_device_gh_lease_expired");let U=Ht(e.root);if(U.isSymbolicLink()||U.dev!==x.dev||U.ino!==x.ino||qr(e.root)!==S)throw Error("local_device_gh_authority_changed");gt(B)};return G(),await l({root:S,readOnly:!1,privateDirectory:B,forbiddenSecretValues:[],signal:e.signal,deadlineMs:W,assertCurrent:G})}finally{Pn(B,{recursive:!0,force:!0})}}var ds=43200000;function wt(e){return Number.isSafeInteger(e)&&Math.abs(e)<=8640000000000000?e:null}function as(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function cs(e,l){return Object.keys(e).length===l.length&&l.every((f)=>Object.hasOwn(e,f))}function ao(e){if(!as(e)||!cs(e,["version","outcome","clock_source","validation_now_ms","expiry_ms","remaining_ms","maximum_lifetime_ms","cli_artifact"])||e.version!==1||e.maximum_lifetime_ms!==43200000||typeof e.outcome!=="string"||!["accepted","parse","noncanonical","expired","over_cap"].includes(e.outcome)||typeof e.clock_source!=="string"||!["date_now","injected"].includes(e.clock_source))return null;for(let _ of["validation_now_ms","expiry_ms"]){let w=e[_];if(w!==null&&(typeof w!=="number"||wt(w)===null))return null}if(e.remaining_ms!==null&&(typeof e.remaining_ms!=="number"||!Number.isSafeInteger(e.remaining_ms)))return null;let l=typeof e.expiry_ms==="number"&&typeof e.validation_now_ms==="number"?e.expiry_ms-e.validation_now_ms:null;if(e.remaining_ms!==(l!==null&&Number.isSafeInteger(l)?l:null))return null;if(e.outcome==="parse"&&e.expiry_ms!==null)return null;if(e.outcome!=="parse"&&e.expiry_ms===null)return null;if(e.outcome==="expired"&&!(typeof l==="number"&&l<=0))return null;if(e.outcome==="over_cap"&&!(typeof l==="number"&&l>43200000))return null;if(e.outcome==="accepted"&&!(typeof l==="number"&&l>0&&l<=43200000))return null;let f=e.cli_artifact;if(!as(f)||!cs(f,["kind","status","sha256","observed_at_ms"])||f.observed_at_ms!==null&&(typeof f.observed_at_ms!=="number"||wt(f.observed_at_ms)===null))return null;if(f.kind==="entrypoint_file"){if(f.status!=="observed"||typeof f.sha256!=="string"||!/^[a-f0-9]{64}$/.test(f.sha256)||f.observed_at_ms===null)return null}else if(f.kind!=="unavailable"||f.sha256!==null||typeof f.status!=="string"||!["unsupported_entrypoint","read_failed","file_changed","size_limit","time_limit"].includes(f.status))return null;return e}var Tn=c({kind:s(["workspace_source","mcp_control"]),target_revision:o().int().nonnegative(),root_grant_revision:o().int().positive()}),ls=new RegExp(lt.tokenPattern),oa=c({token_url:At().max(2048),request_token:t().min(1).max(8192).regex(ls),aws_credentials_url:At().max(2048).nullable()});function us(e,l){let f=(_,w)=>{try{let S=new URL(_);return S.origin===new URL(l).origin&&S.pathname===w&&!S.username&&!S.password&&!S.search&&!S.hash}catch{return!1}};if(!ls.test(e.request_token)||!f(e.token_url,lt.tokenPath)||e.aws_credentials_url!==null&&!f(e.aws_credentials_url,lt.awsPath))return null;return{REASON_OIDC_TOKEN_URL:e.token_url,REASON_OIDC_REQUEST_TOKEN:e.request_token,...e.aws_credentials_url!==null?{AWS_CONTAINER_CREDENTIALS_FULL_URI:e.aws_credentials_url,AWS_CONTAINER_AUTHORIZATION_TOKEN:e.request_token}:{}}}function fs(e){return new TextEncoder().encode(e).byteLength}function sa(e){return fs(JSON.stringify(e)+`
|
|
4
4
|
`)}var yr=c({version:i(1),snapshot_id:k(),revision:o().int().positive(),run_id:t().min(1).max(160),device_id:k(),root_id:k(),binding:Tn.extend({target_generation:o().int().positive(),target_fence_id:k()}),expires_at:y.datetime({offset:!0}),variables:ee(t().max(128).regex(Lt),t().refine((e)=>!e.includes("\x00")&&fs(e)<=V.valueBytes)).refine((e)=>Object.keys(e).length<=V.variables),github_auth:i("local_gh").optional(),git:c({base_url:At().max(2048),token:t().min(1).max(4096).regex(/^[A-Za-z0-9._~-]+$/),expires_at:y.datetime({offset:!0})}).nullable(),cloud_access:oa.optional()}).refine((e)=>e.github_auth!=="local_gh"||e.git===null,"conflicting git authority").refine((e)=>sa(e)<=V.snapshotBytes,"snapshot too large");import{spawn as ia}from"child_process";import{basename as aa,isAbsolute as Au}from"path";var ca=0,ps=120000,_s=15000,da=65536;function Dn(e=process.execPath,l=process.argv[1]){let f=aa(e),_=(f.startsWith("bun")||f.startsWith("node"))&&typeof l==="string"&&l.length>0;return{command:e,prefix:_?[l]:[]}}function co(e={}){let{command:l,prefix:f}=Dn(e.executablePath,e.sourceEntrypoint),_=e.spawnProcess??ia,w=e.now??Date.now,S=null,x=0,W=!1,R=(G)=>{try{G.kill("SIGKILL")}catch{}},B=()=>{if(W)return;if(S&&w()-x<ps-_s)return;if(S){let U=S;S=null,R(U)}let G;try{G=_(l,[...f,"__device","__hands-worker","--handoff-fd",String(ca)],{cwd:"/",env:{PATH:process.env.PATH??"/usr/local/bin:/usr/bin:/bin"},shell:!1,stdio:["pipe","ignore","pipe"]})}catch{return}S=G,x=w(),G.on("error",()=>{if(S===G)S=null}),G.once("exit",(U,D)=>{if(S!==G)return;S=null,e.log?.("hands.worker_prespawn_exited",{exit_code:U,exit_signal:D})}),e.log?.("hands.worker_prespawned",{pid:G.pid??null})};return{arm:B,take(G){let U=S;if(!U||W)return null;let D=G.args.at(-1),re=G.options.env,J=G.options.cwd,z=[...f,"__device","__hands-worker","--config"];if(G.command!==l||G.args.length!==z.length+1||z.some((Re,Fe)=>G.args[Fe]!==Re)||typeof D!=="string"||!re||typeof J!=="string"||G.options.shell||JSON.stringify(G.options.stdio)!==JSON.stringify(["ignore","ignore","pipe"]))return null;S=null;let fe=U.stdin,ke={configPath:D,cwd:J,env:Object.fromEntries(Object.entries(re).filter((Re)=>typeof Re[1]==="string"))},be=JSON.stringify(ke);if(U.exitCode!==null||U.signalCode!==null||!fe||fe.destroyed||w()-x>=ps-_s||Buffer.byteLength(be,"utf8")>da)return R(U),null;return fe.on("error",()=>{return}),fe.end(be),U.once("exit",()=>{B()}),e.log?.("hands.worker_prespawn_taken",{pid:U.pid??null}),U},adopt(G){G.once("exit",()=>{B()})},close(){if(W=!0,S)R(S);S=null}}}import{accessSync as ma,constants as ha,statSync as ga}from"fs";import{homedir as ba,tmpdir as wa,userInfo as ya}from"os";import{delimiter as va,win32 as ka}from"path";var la=new Set(["ALL_PROXY","BUN_BE_BUN","BUN_OPTIONS","CURL_CA_BUNDLE","GIT_SSL_CAINFO","GRPC_DEFAULT_SSL_ROOTS_FILE_PATH","HTTPS_PROXY","HTTP_PROXY","NO_PROXY","NODE_EXTRA_CA_CERTS","NODE_OPTIONS","NODE_TLS_REJECT_UNAUTHORIZED","REQUESTS_CA_BUNDLE","SSLKEYLOGFILE","SSL_CERT_DIR","SSL_CERT_FILE","all_proxy","http_proxy","https_proxy","no_proxy"]);var ua=["BUN_CONFIG_","BUN_INSPECT","DYLD_","NODE_DEBUG"],fa=new Set(["BUN_INSTALL"]);var pa=/^--(?:max-old-space-size|max-semi-space-size|stack-size)=\d{1,9}$/;function _a(e){return(e??"").split(/\s+/).filter(Boolean).every((l)=>pa.test(l.replaceAll("_","-")))}function ms(e){return Object.keys(e).filter((l)=>la.has(l)&&!(l==="NODE_OPTIONS"&&_a(e[l]))||ua.some((f)=>l.startsWith(f))||l.startsWith("BUN_")&&!fa.has(l)).sort()}var Sa=new Set(["HOME","PATH","PWD","OLDPWD","SHLVL","_","TMPDIR","TMP","TEMP","SHELL","BASH_ENV","ENV","ZDOTDIR","PROMPT_COMMAND","IFS","CDPATH","GLOBIGNORE","SHELLOPTS","BASHOPTS","NODE_PATH"]),Ea=/^(?:ARA_|REASON_|PI_|GIT_|GH_|GITHUB_|LD_|DYLD_|BUN_|BASH_FUNC_|SSH_)/,Ra=/TOKEN|SECRET|PASSW|PASSPHRASE|CREDENTIAL|API_?KEY|ACCESS_?KEY|PRIVATE_?KEY|AUTH/i,Oa=/^[A-Za-z_][A-Za-z0-9_]*$/;function wr(e=process.env){let l=(w)=>{if(!(process.platform==="win32"?ka.isAbsolute(w):w.startsWith("/"))||/[\0\r\n]/.test(w)||w.length>32768)throw Error("invalid_host_execution_environment");return w};if(e.PATH!==void 0&&(/[\0\r\n]/.test(e.PATH)||e.PATH.length>32768))throw Error("invalid_host_execution_environment");let f=new Set(ms(e)),_=Object.fromEntries(Object.entries(e).filter((w)=>{let[S,x]=w;return typeof x==="string"&&x.length<=32768&&!x.includes("\x00")&&S.length<=128&&Oa.test(S)&&!f.has(S)&&!Sa.has(S)&&!Ea.test(S)&&!Ra.test(S)}).sort(([w],[S])=>w.localeCompare(S)).slice(0,512));return{home:l(e.HOME||(process.platform==="win32"?e.USERPROFILE:void 0)||ba()),path:((w)=>process.platform==="win32"?kn(w):w)(Ar(e.PATH??"").join(va)||Cr),temporaryDirectory:l(e.TMPDIR||e.TMP||e.TEMP||wa()),variables:_}}function br(e=process.env,l=()=>ya().shell){if(process.platform==="win32")return se();let f=(w)=>{if(!w||!/^\/[A-Za-z0-9._/-]*\/(?:bash|zsh)$/.test(w))return!1;try{return ma(w,ha.X_OK),ga(w).isFile()}catch{return!1}};if(f(e.SHELL))return e.SHELL;let _;try{_=l()}catch{_=void 0}return f(_)?_:"/bin/zsh"}import{readdir as xa}from"fs/promises";var Pa=15000;function wn(e){let l=e instanceof Error&&"code"in e?e.code:null;return l==="EPERM"||l==="EACCES"}function bn(e){return new r("folder_access_denied",`macOS blocked Reason from opening ${e}. Allow Reason in System Settings \u203A Privacy & Security \u203A Files and Folders `+"(or Full Disk Access), then restart the Reason app or worker on this Mac and try again: until it restarts it keeps the earlier refusal.")}async function hs(e,{timeoutMs:l=Pa,open:f=(_)=>xa(_)}={}){let _,w=new Promise((S)=>{_=setTimeout(()=>S("pending"),l)});try{if(await Promise.race([f(e).then(()=>"open"),w])==="pending")throw new r("folder_access_pending",`macOS is asking whether Reason may open ${e}. Answer the prompt on this Mac, then try again.`)}catch(S){if(wn(S))throw bn(e);if(S instanceof r)throw S}finally{clearTimeout(_)}}import{chmodSync as ic,closeSync as ac,constants as Kn,fstatSync as cc,lstatSync as Ns,openSync as dc,readSync as lc,realpathSync as Gn,unlinkSync as uc}from"fs";import{lookup as fc}from"dns/promises";import{createRequire as pc}from"module";import{request as _c}from"http";import{request as mc}from"https";import it from"net";import{platform as Ws}from"os";import{basename as hc,extname as gc,isAbsolute as Ls,relative as Jn,resolve as kt,sep as Vn}from"path";var gs=String.raw`
|
|
5
5
|
async (roots) => {
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Ye,ft}from"./vm-hands-entry-lite-2v4zh9ze.js";import{Qe}from"./vm-hands-entry-lite-
|
|
2
|
+
import{Ye,ft}from"./vm-hands-entry-lite-2v4zh9ze.js";import{Qe}from"./vm-hands-entry-lite-c4zazjyw.js";import{$o,le,Kr,gt,Mo}from"./vm-hands-entry-lite-2tbf0swk.js";import{E}from"./vm-hands-entry-lite-46pwqvpf.js";import{a,nr}from"./vm-hands-entry-lite-8dfw96ym.js";import{spawnSync as H}from"child_process";import{dirname as w}from"path";import{spawn as A}from"child_process";import{accessSync as _,constants as v}from"fs";import{basename as C,join as O}from"path";var l=null;function S(e){if(l===e)l=null;if(e.exitCode===null&&e.signalCode===null)e.kill("SIGTERM")}var qr=(e,t)=>{if(l)S(l);let s=O(e,$o);try{_(s,v.X_OK)}catch{return()=>{}}let n;try{n=A(s,["--app",e,"--name",C(e,".app"),"--permission",t==="screen"?"screen_recording":"accessibility"],{detached:!0,stdio:"ignore"})}catch{return()=>{}}return n.on("error",()=>{if(l===n)l=null}),n.once("exit",()=>{if(l===n)l=null}),n.unref(),l=n,()=>S(n)};import{chmodSync as ne,existsSync as se,mkdirSync as re,readFileSync as D,realpathSync as ie,renameSync as oe,statSync as j,writeFileSync as ae}from"fs";import{dirname as de,isAbsolute as G,join as N,resolve as T,sep as b}from"path";function F(e=a()){return N(nr(e),"reason","protected-path-grants.json")}var f=null;function L(e){let t=JSON.parse(e);if(!Array.isArray(t?.grants))return[];return t.grants.flatMap((s)=>{let n=s;return n&&typeof n.path==="string"&&G(n.path)&&(n.kind==="file"||n.kind==="folder")&&typeof n.grantedAt==="number"?[{path:n.path,kind:n.kind,grantedAt:n.grantedAt}]:[]})}function y(e=F()){try{let{mtimeMs:t}=j(e);if(f&&f.file===e&&f.mtimeMs===t)return f.grants;let s=L(D(e,"utf8"));return f={file:e,mtimeMs:t,grants:s},s}catch{return[]}}function W(e,t){return e.kind==="file"?t===e.path:t===e.path||t.startsWith(`${e.path}${b}`)}function U(e,t){let s=T(e);return y(t).some((n)=>W(n,s))}function So(e,t){return E(e)&&!U(e,t)}function Eo(e,t,s){let n=t?"file-read* file-write*":"file-read*";return y(s).filter((r)=>r.path===e||r.path.startsWith(`${e}${b}`)).map((r)=>`(allow ${n} (${r.kind==="file"?"literal":"subpath"} ${JSON.stringify(r.path)}))`)}var P="x-apple.systempreferences:com.apple.preference.security",J="curl -fsSL https://reasonmachines.com/install.sh | bash",q=180000,B=2000;var k={screen:{label:"Screen & System Audio Recording",purpose:"desktop video, computer-use screenshots",level:"required",pane:`${P}?Privacy_ScreenCapture`},accessibility:{label:"Accessibility",purpose:"computer-use clicks and typing, desktop input",level:"required",pane:`${P}?Privacy_Accessibility`},disk:{label:"Full Disk Access",purpose:"Sessions in Desktop, Documents, Downloads, iCloud Drive and Mail",level:"recommended",pane:`${P}?Privacy_AllFiles`}};function R(e){return e.executable}function K(e,t){if(e==="computer_use_identity_missing")return`Reason's background identity is not installed (${e}); reinstall Reason: ${J}`;if(e==="computer_use_identity_outdated")return`Reason's background identity is outdated (${Kr(t)??"unknown"}; this CLI is ${Qe}) (${e}); \`reason update\` installs this release's`;return`Reason's background identity cannot run computer use for this CLI (${e}); run the installed \`reason\``}function us(e=a()){let t=gt(e);if(t.length>0)return{state:"ready",path:w(w(w(t[0]))),prefix:t};let s=Mo(t,e)??"computer_use_identity_unavailable";return{state:s,path:le(e),detail:K(s,e)}}function V(){return{identity:()=>us(),grants:(e)=>Ye(e),request:(e,t)=>ft(e,t),worker:async()=>(await import("./status-zqw8s5y5.js")).connectionMacState(),open:(e)=>{H("/usr/bin/open",e,{stdio:"ignore",timeout:1e4})},tile:qr,restartConnection:async()=>(await import("./connect-cli-33btt5ny.js")).restartConnection(),sleep:(e)=>new Promise((t)=>setTimeout(t,e)),now:()=>Date.now()}}function M(e,t,s){if(e.state!=="ready"||!t)return"unknown";return t[s]?"granted":"missing"}async function ds(e){let t=e.identity(),s=t.state==="ready"?await e.grants(t.prefix):null,n=await e.worker(),r=n?R(n):null,i=!r||n?.full_disk_access==="unknown"?"unknown":n?.full_disk_access==="granted"?"granted":"missing",c=(u,d,o)=>{let{label:p,purpose:h,level:m}=k[u];return{id:u,label:p,purpose:h,level:m,state:d,holder:o}};return{identity:{state:t.state,path:t.path,detail:t.state==="ready"?null:t.detail},worker_detail:r?null:"Full Disk Access is read from this computer's running worker; `reason connect` starts it.",permissions:[c("screen",M(t,s,"screen"),t.path),c("accessibility",M(t,s,"accessibility"),t.path),c("disk",i,r)]}}function Ks(e){let t=e.identity.state==="ready"?null:e.identity.state,s=e.permissions.filter((i)=>i.state==="granted").length,n=[...t?[t]:[],...e.permissions.filter((i)=>i.state!=="granted"&&!(t&&i.id!=="disk")).map((i)=>`${i.label} ${i.state}`)],r=!t&&e.permissions.some((i)=>i.state==="missing");return`Permissions: ${s} of ${e.permissions.length}${n.length>0?` (${n.join(", ")})`:""}`+(r?" \u2014 reason permissions allow":n.length>0?" \u2014 reason permissions":"")}async function x(e,t){let s=t.now()+q;for(;;){if(await e())return!0;if(t.now()>=s)return!1;await t.sleep(B)}}async function Js(e,t){let s=t.host??V(),{io:n}=t,r=await ds(s),i=r.permissions.filter((o)=>e.includes(o.id)&&o.state!=="granted");if(i.length===0)return n.stdout.write(`Reason permissions: ${e.map((o)=>k[o].label).join(", ")} already allowed.
|
|
3
3
|
`),0;let c=!1,u=!1,d=s.identity();for(let o of i){let{label:p,pane:h}=k[o.id];if(o.id!=="disk"){if(d.state!=="ready"){if(!c)n.stderr.write(`Reason permissions: ${d.detail}
|
|
4
4
|
`);c=!0;continue}let g=o.id;await s.request(d.prefix,g),s.open([h]);let I=s.tile(d.path,g);if(n.stdout.write(`Allow Reason in System Settings > Privacy & Security > ${p}.
|
|
5
5
|
`),!t.wait)continue;if(n.stdout.write(`Waiting for it (Ctrl-C to stop)\u2026
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{ot,D}from"./vm-hands-entry-lite-
|
|
2
|
+
import{ot,D}from"./vm-hands-entry-lite-t46k8t4n.js";import{R}from"./vm-hands-entry-lite-a3p6xz53.js";import{_,rr}from"./vm-hands-entry-lite-4anjdcth.js";import{be}from"./vm-hands-entry-lite-yretc2th.js";function zi(e,i){let t=R(e,"REASON_API_URL")?.trim();if(!t)return rr(i);let n=new URL(t);if(n.protocol!=="https:"&&!(n.protocol==="http:"&&["127.0.0.1","localhost","::1"].includes(n.hostname)))throw Error("REASON_API_URL must use HTTPS (HTTP is allowed only for loopback development).");return n.origin}function es(e){return R(e,"REASON_API_URL")?.trim()?zi(e,"production"):void 0}function ts(e){return R(e,"REASON_API_KEY")?.trim()||void 0}async function As(e,i){let t=e.env??process.env,n=ts(t);if(!n)return(e.getCredentials??ot)({apiOrigin:es(t),signal:i});let a=zi(t,e.channel??_({env:t})),o=await(e.fetchImpl??fetch)(a+"/v3/self",{redirect:"error",headers:{authorization:"Bearer "+n,accept:"application/json"},signal:i}),p=await o.json().catch(()=>({})),r=be(p)?p:{};if(!o.ok){let s=typeof r.detail==="string"?r.detail:typeof r.message==="string"?r.message:"API key authentication failed ("+o.status+")";throw new D(o.status,typeof r.error==="string"?r.error:"api_key_auth_failed",s)}if(typeof r.org_id!=="string"||!r.org_id)throw Error("The API key in the environment did not resolve to a Workspace.");let l=Array.isArray(r.scopes)?r.scopes.filter((s)=>typeof s==="string"):[];return{credentialKind:"api_key",apiOrigin:a,accessToken:n,orgId:r.org_id,clientId:"api-key",refreshToken:"",expiresAt:"",scopes:l}}export{zi,es,ts,As};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{_,Ho,ke}from"./vm-hands-entry-lite-4anjdcth.js";import{l,Ut,We,Dr,zt,Nr,dt}from"./vm-hands-entry-lite-dgfx0rbn.js";import{bt,ar}from"./vm-hands-entry-lite-07apxfh8.js";import{fn}from"./vm-hands-entry-lite-
|
|
2
|
+
import{_,Ho,ke}from"./vm-hands-entry-lite-4anjdcth.js";import{l,Ut,We,Dr,zt,Nr,dt}from"./vm-hands-entry-lite-dgfx0rbn.js";import{bt,ar}from"./vm-hands-entry-lite-07apxfh8.js";import{fn}from"./vm-hands-entry-lite-pb02nft0.js";import{F,m,te,He}from"./vm-hands-entry-lite-99wrj4vv.js";import{U}from"./vm-hands-entry-lite-mh46pt40.js";import{Bo}from"./vm-hands-entry-lite-2tbf0swk.js";import{xe,Ze,Xn,Vr}from"./vm-hands-entry-lite-mj7yar3a.js";import{f,v,h}from"./vm-hands-entry-lite-h1qjggz0.js";import{a}from"./vm-hands-entry-lite-8dfw96ym.js";import{Xo,an,y,t,k,At,o,d,Ie,u,n,c,g,_s,s,i,cn}from"./vm-hands-entry-lite-wzv13c8k.js";import{closeSync as qh,existsSync as zh,mkdirSync as Kh,openSync as Vh,readdirSync as Jh,realpathSync as pe,rmSync as Gh}from"fs";import{dirname as Xh,join as J,resolve as Zh}from"path";import{createHash as It}from"crypto";import{platform as Ot}from"os";import{join as Dt}from"path";var Mt=g("store",[c({version:i(1),store:i("keychain")}),c({version:i(1),store:i("file"),api_key:t().min(1).max(4096)})]),Ne=(e)=>Dt(e,"api-key.json");function $e(e){let r=It("sha256").update(`reason-connect-api-key
|
|
3
3
|
${e}`).digest("hex");return new We(Ut(),Ot(),r)}function we(e,r=$e(e)){if(!f(Ne(e)))return null;let p=Mt.parse(JSON.parse(h(Ne(e))));if(p.store==="file")return p.api_key;try{let b=r.loadBinding();return b?new TextDecoder().decode(b):null}catch(b){if(!(b instanceof l))throw b;throw Error("worker_api_key_unreadable")}}import{readdirSync as Zt,renameSync as Go,rmSync as Yo}from"fs";import{join as ee}from"path";import{createHash as Wt}from"crypto";import{platform as Nt}from"os";import{join as W}from"path";function w(e){return{state:W(m(e),"device.json"),control:W(m(e),"control.json"),lock:W(m(e),"lifecycle.lock"),socket:W(m(e),"control.sock"),daemon:W(m(e),"daemon.json"),releaseCheck:W(m(e),"release-check.json"),updateDeferral:W(m(e),"update-deferral.json"),firstHeartbeat:W(m(e),"first-heartbeat.json")}}var uo=n({version:i(1),device_id:t().min(1).max(160),offer:Ie().optional(),enrollment_ms:o().int().nonnegative().max(ar).optional()});function z(e,r=!1){v(m(e),r);let p=["local-device.key","local-device.binding","device.json"].filter((b)=>{let R=W(m(e),b);if(!f(R))return!1;return h(R),!0});return e.lifetime==="persistent"&&p.join()==="device.json"?Ht(e):new Dr(m(e))}function Ht(e){return new We(Ut(),Nt(),$t(e))}function $t(e){let r=jt(e);return Wt("sha256").update(`reason-worker
|
|
4
4
|
${r?.directory??m(e)}`).digest("hex")}var Bt="keychain-scope.json";var Ft=c({version:i(1),directory:t().min(1),devicePublicKey:t().min(1)});function jt(e){let r=W(m(e),Bt);if(!f(r))return null;let p=Ft.safeParse(JSON.parse(h(r))),b=w(e).state;if(!p.success||!f(b))return null;return JSON.parse(h(b))?.devicePublicKey===p.data.devicePublicKey?p.data:null}function B(e){if(!f(m(e)))return null;let r=Nr(w(e).state,{proofStore:z(e),repair:!1}),p=r!==null&&Ho(e.apiOrigin,r.apiOrigin),b=p?[te(e),te({...e,apiOrigin:r.apiOrigin})]:[te(e)];if(r&&(!b.includes(r.worker?.configDigest??"")||r.worker.lifetime!==e.lifetime||r.apiOrigin!==e.apiOrigin&&!p||r.roots.length>32||r.roots[0]?.path!==e.workspaceRoot||r.handsSlots!==e.slots))throw Error("worker_config_binding_mismatch");return r}var qt=c({version:i(1),drained:d(),revoked:d()});function N(e){let r=w(e).control;return f(r)?qt.parse(JSON.parse(h(r))):{version:1,drained:!1,revoked:!1}}var Vt=c({read:d(),write:d(),execute:d(),discover_environment:d(),expose_mcp:i(!1)}),Jt=c({version:i(1),organization_id:t().min(1).max(160),enrollment_ticket:t().min(1).max(4096),code_verifier:t().regex(/^[A-Za-z0-9._~-]{43,128}$/),root_fingerprint_key:t().regex(/^[a-f0-9]{64}$/),root:c({path_fingerprint:t().regex(/^[a-f0-9]{64}$/),permissions:Vt,execution_mode:s(["confined","host"]).default("confined")}),folders:u(c({path_fingerprint:t().regex(/^[a-f0-9]{64}$/)})).min(1).max(31).optional()}),Ro=n({device_id:t().min(1).max(160),organization_id:t().min(1).max(160),auth_scheme:i("p256"),protocol_version:i(2),roots:u(n({id:t().min(1),label:t(),path_fingerprint:t()})).min(1).max(32),headless:n({lifecycle:s(["persistent","ephemeral"]),expires_at:y.datetime({offset:!0})}),first_heartbeat:Ie().optional()});var qo=c({version:i(1),install_id:k(),fingerprint_key:t().regex(/^[a-f0-9]{64}$/)}),zo=n({enrollment_ticket:t().min(1).max(4096),expires_at:y.datetime({offset:!0}),device_kind:i("headless"),lifecycle:s(["persistent","ephemeral"]),device_expires_at:y.datetime({offset:!0})});var Ko=n({credentialKind:s(["oauth","api_key"]).optional(),apiOrigin:At(),clientId:t(),accessToken:t().min(1).max(32768),refreshToken:t().max(32768),expiresAt:y.datetime({offset:!0}),scopes:u(t().max(128)).max(128),orgId:t().min(1).max(160)});var qe=8;var Qt=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,_e=(e)=>ee(m(e),"workspaces"),er="account.json",tr=(e)=>f(ee(e,er));function Se(e){let r;try{r=Zt(_e(e))}catch{return[]}return r.filter((p)=>Qt.test(p)).sort().map((p)=>{let b=ee(_e(e),p),R=ee(b,"worker.json"),S=null;try{let P=F.safeParse(JSON.parse(h(R)));if(P.success&&P.data.stateDirectory===b)S=P.data}catch{}return{organizationId:p,directory:b,configPath:R,config:S,account:tr(b)}})}var rr=(e)=>ee(_e(e),"listed.json");function nr(e){try{let r=JSON.parse(h(rr(e))),p=r.names&&typeof r.names==="object"&&!Array.isArray(r.names)?Object.fromEntries(Object.entries(r.names).filter((R)=>typeof R[1]==="string")):{},b=r.refused&&typeof r.refused==="object"?r.refused:null;return{listed:r.listed===!0,reason:r.reason==="sign_in"?"sign_in":null,blocked:Array.isArray(r.blocked)?r.blocked.filter((R)=>typeof R==="string"):[],names:p,...b&&typeof b.device==="string"&&typeof b.roots==="string"&&typeof b.at==="number"&&Number.isFinite(b.at)&&typeof b.count==="number"&&Number.isInteger(b.count)&&b.count>=1?{refused:{device:b.device,roots:b.roots,at:b.at,count:b.count}}:{}}}catch{return null}}function ze(e,r){let p=Se(e),b=p.filter((C)=>C.account),R=p.filter((C)=>!C.account),S=nr(e),P=S&&!S.listed?S.reason:null,E=P||R.length===0&&S&&!S.listed?[]:R;if(b.length===0&&E.length===0&&(P||S&&!S.listed))return{workspaces:null,off:P};return{off:P,workspaces:[...b,...E].map(({organizationId:C,config:D,account:I})=>{let A=!1,M=null,T=!1,he=null;try{A=D?N(D).revoked:!1,M=D&&!A?B(D):null;let Le=D?dt(w(D).daemon):null;T=r&&!!M&&Le?.state==="connected",he=T?zt(Le,M):null}catch{}return{...he?{permission_recovery:he}:{},organization_id:C,device_id:M?.deviceId??null,name:S?.names?.[C]??null,root:M?.roots[0]?{id:M.roots[0].id,permissions:M.roots[0].permissions}:null,state:A?"removed":T?"connected":"not_running",blocked:!I&&!A&&!T&&(S?.blocked.includes(C)??!1),...I?{account:!0}:{}}})}}import{readFileSync as ir}from"fs";function pr(e){try{let r=JSON.parse(ir(`${e}.keep-awake.json`,"utf8"));return r!==null&&typeof r==="object"&&"version"in r&&r.version===1&&"enabled"in r&&r.enabled===!0?"battery_and_ac":void 0}catch(r){return r.code==="ENOENT"?"battery_and_ac":void 0}}import{chmodSync as qi,lstatSync as Xe,mkdtempSync as zi,realpathSync as sr,rmdirSync as Ki,rmSync as Vi,unlinkSync as Ji}from"fs";import{createConnection as cr,createServer as Yi}from"net";import{basename as Je,dirname as Ge,join as ne}from"path";var lr=s(["status","drain","resume","stop","reload_roots"]),dr=c({version:i(1),instanceId:t(),deviceId:t(),phase:s(["starting","running","reconnecting","stopping"]),drained:d(),activeClaims:o().int().nonnegative(),activeSessions:o().int().nonnegative().optional(),executionEligible:d(),supportedOperations:u(s(bt)).max(bt.length).optional(),capabilityReadiness:_s(s(bt),d()).optional(),lastHeartbeat:t().nullable(),expiresAt:t()}),ra=c({nonce:t(),action:lr}),ur=n({nonce:k()}),fr=c({version:i(1),nonce:k(),socketPath:t().max(100)});function mr(e){return ne(w(e).lock,"control.json")}function Qe(e){return v(w(e).lock),ur.parse(JSON.parse(h(ne(w(e).lock,"owner.json"))))}function Ye(e){if(!f(e))return!1;let r=Xe(e);if(!r.isSocket()||r.uid!==process.getuid?.()||(r.mode&63)!==0)throw Error("worker_control_socket_not_private");return!0}function et(e,r){let p=mr(e);if(!f(p)){let S=w(e).socket;if(!f(S)||!Xe(S).isSocket())return null;return Ye(S)?S:null}let b=fr.parse(JSON.parse(h(p)));if(b.nonce!==r)throw Error("worker_instance_changed");if(process.platform==="win32"){if(!hr.test(b.socketPath))throw Error("worker_control_endpoint_invalid");return b.socketPath}let R=Ge(b.socketPath);if(Ge(R)!==sr("/tmp")||!/^(?:reason|ara)-worker-[A-Za-z0-9]{6}$/.test(Je(R))||Je(b.socketPath)!=="control.sock"||Buffer.byteLength(b.socketPath)>100)throw Error("worker_control_endpoint_invalid");if(!f(R))return null;return v(R),Ye(b.socketPath)?b.socketPath:null}var hr=/^\\\\\.\\pipe\\reason-worker-[0-9a-f-]{36}$/;function gr(e,r){try{let p=JSON.parse(h(ne(w(e).lock,"owner.json"))),b=p&&typeof p==="object"?p[r]:void 0;return typeof b==="string"?b:null}catch{return null}}function tt(e){return gr(e,"runtime_version")}function rt(e,r){if(r)return r.message==="worker_control_timeout"?"socket_timeout":"bad_reply";try{if(!f(ne(w(e).lock,"owner.json")))return"no_lock";return et(e,Qe(e).nonce)?"socket_refused":"no_socket"}catch{return"bad_reply"}}var na=c({instance:t().nullable(),since:o().int().nonnegative()});async function G(e,r){let p=w(e);if(!f(ne(p.lock,"owner.json")))return null;let b=Qe(e),R=et(e,b.nonce);if(!R)return null;return new Promise((S,P)=>{let E=cr(R),C="",D=!1,I=(A,M)=>{if(D)return;if(D=!0,E.destroy(),M)P(M);else S(A)};E.setTimeout(2000,()=>E.destroy(Error("worker_control_timeout"))),E.on("connect",()=>E.write(JSON.stringify({nonce:b.nonce,action:r})+`
|
|
5
5
|
`)),E.on("data",(A)=>{if(C+=A.toString(),Buffer.byteLength(C)>16384)E.destroy(Error("worker_control_oversize"))}),E.on("error",(A)=>{if("code"in A&&["ECONNREFUSED","ENOENT"].includes(String(A.code)))I(null);else I(null,A.message==="worker_control_timeout"?A:Error("worker_control_unavailable"))}),E.on("end",()=>{try{let A=dr.parse(JSON.parse(C));if(A.instanceId!==b.nonce)throw Error("worker_instance_changed");I(A)}catch{I(null,Error("worker_control_invalid_response"))}}),E.once("close",()=>I(null,Error("worker_control_unavailable")))})}import{realpathSync as br}from"fs";import{constants as Re}from"fs";import{open as wr}from"fs/promises";var da={platform:process.platform,home:a,async openFile(e){let r=await wr(e,Re.O_RDONLY|Re.O_NOFOLLOW|Re.O_NONBLOCK);return{isFile:async()=>(await r.stat()).isFile(),close:()=>r.close()}}};var za=Bo(br(process.execPath));var hs=Buffer.from([0,255,3,4]);import{execFile as on}from"child_process";import{promisify as sn}from"util";var Pr=/#w=(\d{1,5})&h=(\d{1,5})$/;function at(e){return typeof e==="number"&&Number.isInteger(e)&&e>0&&e<=32768?e:void 0}function st(e){let r=Pr.exec(e);if(!r)return;let p=at(Number(r[1])),b=at(Number(r[2]));return p&&b?{width:p,height:b}:void 0}var ct="[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}",Cr=new RegExp(`^/media/pr-screenshots/(${ct})/(${ct})/([a-z0-9][a-z0-9._-]*)\\.(png|jpe?g|gif|webp|webm|mp4)$`,"i");var Ar=new Set(["png","jpg","jpeg","gif","webp"]),xr=new Set(["webm","mp4"]);function Ir(e){if(!e)return null;try{return new URL(e).origin}catch{return null}}function Or(e){let r=st(e);return Boolean(r&&e===`#w=${r.width}&h=${r.height}`)}function lt(e,r){let p;try{p=new URL(e)}catch{return null}let b=Ir(r),R=p.hostname==="ara.so"||p.hostname.endsWith(".ara.so")||p.hostname==="reasonmachines.ai"||p.hostname.endsWith(".reasonmachines.ai")||p.hostname==="reasonmachines.com"||p.hostname.endsWith(".reasonmachines.com");if(p.protocol!=="https:"||!R&&p.origin!==b||p.username||p.password||p.port||p.search||p.hash&&!Or(p.hash))return null;let S=Cr.exec(p.pathname);if(!S)return null;let P=S[1]?.toLowerCase(),E=S[2]?.toLowerCase(),C=S[3]?.toLowerCase(),D=S[4]?.toLowerCase();if(!P||!E||!C||!D)return null;let I=Ar.has(D)?"image":xr.has(D)?"video":null;if(!I)return null;let A=/^(before|after)[\s:_-]+/.exec(C),M=p.pathname.replace(/^\/media\//,"");return{url:p.toString(),storagePath:M,runId:P,artifactId:E,fileName:`${C}.${D}`,kind:I,phase:A?.[1]==="before"||A?.[1]==="after"?A[1]:null}}var Mr=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,ut=(e)=>Boolean(e&&typeof e==="object"&&!Array.isArray(e)),K=()=>{throw Error("cloud_browser_media_request_invalid")};function Pe(e){if(!ut(e)||Object.keys(e).some((S)=>!["runId","configuredMediaOrigin","media"].includes(S))||typeof e.runId!=="string"||!Mr.test(e.runId)||typeof e.configuredMediaOrigin!=="string"||e.configuredMediaOrigin.length>2048||!Array.isArray(e.media)||e.media.length<1||e.media.length>8)return K();let r;try{r=new URL(e.configuredMediaOrigin)}catch{return K()}if(r.protocol!=="https:"||r.username||r.password||r.port||!He(r.origin,{mode:"public_web"}).allowed)return K();let p=e.runId.toLowerCase(),b=new Set,R=e.media.map((S)=>{if(!ut(S)||Object.keys(S).some((E)=>!["url","sourceUrl","kind"].includes(E))||typeof S.url!=="string"||S.url.length>2048||typeof S.sourceUrl!=="string"||S.sourceUrl.length>8192||!["image","video"].includes(String(S.kind)))return K();let P=lt(S.url,r.origin);if(!P||new URL(P.url).origin!==r.origin||P.runId!==p||P.kind!==S.kind||P.url!==S.url||b.has(S.url))return K();if(b.add(S.url),S.sourceUrl!==S.url){let E;try{E=new URL(S.sourceUrl)}catch{return K()}let C=/^\/(?:[a-f0-9]{40}|[a-f0-9]{64})\/([a-f0-9]+)$/.exec(E.pathname)?.[1];if(S.kind!=="image"||E.origin!=="https://camo.githubusercontent.com"||E.username||E.password||E.search||E.hash||!C||C.length%2!==0||Buffer.from(C,"hex").toString("utf8")!==S.url)return K()}return{url:S.url,sourceUrl:S.sourceUrl,kind:S.kind}});return{runId:e.runId,configuredMediaOrigin:r.origin,media:R}}var x=t().uuid(),X=t().regex(/^[a-f0-9]{64}$/),V=y.datetime({precision:3}),Ce=t().regex(/^[a-zA-Z0-9_-]{1,160}$/),pt=t().max(2048).regex(/^https:\/\/github\.com\/[A-Za-z0-9_-]+\/[A-Za-z0-9_.-]+\/pull\/[1-9][0-9]*$/).refine((e)=>![".",".."].includes(e.split("/")[4])),H=n({kind:i("primary_mac"),version:i(1),organizationId:Ce,userId:Ce,sessionId:Ce,runId:x,deviceId:x,rootId:x,rootRevision:t().min(1).max(64),binding:s(["workspace_source","mcp_control"]),targetRevision:o().int().nonnegative(),generation:x,profile:t().regex(/^(Default|Profile [0-9]+)$/),extensionInstanceId:t().min(1).max(1024)}).strict().refine((e)=>e.binding!=="workspace_source"||e.targetRevision===0),Tr=cn().transform((e,r)=>{try{return fn(e)}catch{return r.addIssue({code:"custom",message:"proof_visual_contract_invalid"}),Xo}}),ue=n({version:i(1),owner:H,contextId:x,preparedAt:V,expiresAt:V,prUrl:pt,headSha:t().regex(/^[a-f0-9]{40}$/),skillDigest:X,evidenceKind:s(["image","video"]),visualPlan:Tr.optional(),uploadOrigin:t().url().refine((e)=>{let r=new URL(e);return r.protocol==="https:"&&r.origin===e&&!r.username&&!r.password}).optional()}).strict().refine((e)=>Date.parse(e.expiresAt)>Date.parse(e.preparedAt)&&Date.parse(e.expiresAt)-Date.parse(e.preparedAt)<=300000),Lr=n({version:i(1),producer:i("primary_mac"),context:ue,captureId:x,operationId:x,attemptId:x,tabId:o().int().positive(),startedAt:V,finishedAt:V,sha256:X,media:g("contentType",[n({contentType:i("image/png"),sizeBytes:o().int().min(24).max(8388608),width:o().int().min(1).max(4096),height:o().int().min(1).max(4096)}).strict(),n({contentType:i("video/webm"),sizeBytes:o().int().min(128).max(10485760),durationSeconds:o().min(0.05).max(15),frameCount:o().int().min(1).max(450),receivedFrameCount:o().int().min(1).max(2000)}).strict()])}).strict().superRefine((e,r)=>{let p=Date.parse(e.startedAt),b=Date.parse(e.finishedAt);if(p<Date.parse(e.context.preparedAt)||b<p||b>Date.parse(e.context.expiresAt)||b-p>30000||e.media.contentType==="video/webm"&&(e.media.receivedFrameCount<e.media.frameCount||Math.abs((b-p)/1000-e.media.durationSeconds)>0.1))r.addIssue({code:"custom",message:"mac_pr_proof_capture_chronology_invalid"})}),yc=g("action",[n({action:i("screenshot"),context_id:x,tab_id:o().int().positive()}).strict(),n({action:i("start_video"),context_id:x,tab_id:o().int().positive(),seconds:o().int().min(1).max(15)}).strict(),n({action:i("stop_video"),recording_operation_id:x}).strict()]),fe=n({login:t().regex(/^[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,37}[a-zA-Z0-9])?$/),id:t().regex(/^[1-9][0-9]{0,19}$/).nullable()}).strict(),ce=t().regex(/^[1-9][0-9]{0,19}$/),le=n({version:i(1),owner:H,expectedActorId:ce.nullable(),repositoryId:ce,repositoryFullName:t().max(200).regex(/^[A-Za-z0-9_-]+\/[A-Za-z0-9_.-]+$/).refine((e)=>![".",".."].includes(e.split("/")[1]))}).strict(),Wr=["browser_unavailable","github_page_unavailable","identity_check_failed","operation_incomplete","attachment_unavailable"],Hr=g("status",[le.extend({status:i("ready"),observedActor:fe,checkedAt:V}),le.extend({status:i("not_ready"),reason:s(["authentication_required","identity_mismatch","authority_lost","unavailable"]),cause:s(Wr).optional()})]).refine((e)=>e.status!=="ready"||e.expectedActorId===null||e.observedActor.id===e.expectedActorId),Y=n({version:i(1),owner:H,expectedActorId:ce.nullable(),authenticatedActor:fe,attemptId:x,captureId:x,prUrl:pt,repositoryId:ce,headSha:t().regex(/^[a-f0-9]{40}$/),sha256:X,sizeBytes:o().int().min(128).max(10485760),contentType:i("video/webm")}).strict(),ht=t().regex(/^https:\/\/github\.com\/user-attachments\/assets\/[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/),$r=g("status",[Y.extend({status:i("not_attempted"),reason:s(["authentication_required","attachment_unavailable","identity_mismatch","capture_invalid","authority_lost"])}),Y.extend({status:i("uncertain"),reason:i("upload_outcome_unknown")}),Y.extend({status:i("uploaded"),observedActor:fe,nativeUrl:ht,uploadedAt:V})]).refine((e)=>(e.expectedActorId===null||e.authenticatedActor.id===e.expectedActorId)&&(e.status!=="uploaded"||e.observedActor.id===e.authenticatedActor.id&&e.observedActor.login===e.authenticatedActor.login)),de=Y.extend({nativeUrl:ht,observedActor:fe,bodySha256:X}),Br=g("status",[de.extend({status:i("incomplete"),reason:s(["authentication_required","identity_mismatch","playback_unverified","authority_lost"])}),de.extend({status:i("verified"),sourceSha256:X,width:o().int().min(1).max(4096),height:o().int().min(1).max(4096),durationSeconds:o().positive().max(30),advancedSeconds:o().min(0.05).max(10),advancedFrames:o().int().positive(),playbackRestored:i(!0),verifiedAt:V})]).refine((e)=>(e.expectedActorId===null||e.authenticatedActor.id===e.expectedActorId)&&e.observedActor.id===e.authenticatedActor.id&&e.observedActor.login===e.authenticatedActor.login&&(e.status!=="verified"||e.sourceSha256===e.sha256)),Ur=cn().transform((e,r)=>{try{let p=Pe(e);if(p.media.some((b)=>b.kind!=="image"))throw Error();return p}catch{return r.addIssue({code:"custom",message:"proof_media_request_invalid"}),Xo}}),Fr=g("action",[n({action:i("auth_check"),input:le}).strict(),n({action:i("prepare"),context:ue}).strict(),n({action:i("capture_png"),owner:H,contextId:x,tabId:o().int().positive()}).strict(),n({action:i("start_video"),owner:H,contextId:x,tabId:o().int().positive(),seconds:o().int().min(1).max(15)}).strict(),n({action:i("inspect_capture"),owner:H,captureId:x}).strict(),n({action:i("publish_video"),input:Y}).strict(),n({action:i("verify_png_media"),owner:H,media:Ur}).strict().refine((e)=>e.media.runId===e.owner.runId),n({action:i("verify_saved_media"),input:de}).strict(),n({action:i("publish_png"),owner:H,attemptId:x,captureId:x,sha256:X,sizeBytes:o().int().min(24).max(8388608),storagePath:t().max(512),uploadUrl:t().url().max(8192)}).strict()]);var jr=n({requestId:x,command:Fr}).strict();var qr={type:"object",required:["action"],properties:{action:{type:"string",enum:["screenshot","start_video","stop_video"]},context_id:{type:"string",format:"uuid"},tab_id:{type:"integer",minimum:1},seconds:{type:"integer",minimum:1,maximum:15},recording_operation_id:{type:"string",format:"uuid"}},additionalProperties:!1},ft={type:"string",format:"uuid",description:"capture_context_id from tools.pr.prepareProof."},mt={type:"integer",minimum:1,description:"An already-owned tab's id."},_c={...qr,oneOf:[{type:"object",required:["action","context_id","tab_id"],additionalProperties:!1,properties:{action:{type:"string",const:"screenshot"},context_id:ft,tab_id:mt}},{type:"object",required:["action","context_id","tab_id","seconds"],additionalProperties:!1,properties:{action:{type:"string",const:"start_video"},context_id:ft,tab_id:mt,seconds:{type:"integer",minimum:1,maximum:15}}},{type:"object",required:["action","recording_operation_id"],additionalProperties:!1,properties:{action:{type:"string",const:"stop_video"},recording_operation_id:{type:"string",format:"uuid",description:"The recording_operation_id start_video returned."}}}]};var Rc=n({operationId:t().uuid(),attemptId:t().uuid(),contextId:t().uuid(),tabId:o().int().positive()}).strict();var zr=String.raw`async (media) => {
|