@reason-machines/cli-linux-x64 0.2.549 → 0.2.551
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 +2 -2
- package/bin/runtime/srt/sandbox-runtime.mjs +40 -40
- package/bin/vm-hands/{api-credentials-kfqpzeyv.js → api-credentials-y0xh9jwb.js} +1 -1
- package/bin/vm-hands/{api-ysyr7xfb.js → api-m9gg0565.js} +1 -1
- package/bin/vm-hands/{connect-cli-kfbh66m0.js → connect-cli-3tyxbhs6.js} +1 -1
- package/bin/vm-hands/{local-automation-qb8khqm3.js → local-automation-ar507dxs.js} +1 -1
- package/bin/vm-hands/{local-capabilities-4xhwe7eh.js → local-capabilities-z5hvc77q.js} +1 -1
- package/bin/vm-hands/{local-display-session-zq777cgj.js → local-display-session-hw6qn83k.js} +1 -1
- package/bin/vm-hands/local-display-video-brg49bds.js +2 -0
- package/bin/vm-hands/{local-managed-process-hzh5kc4y.js → local-managed-process-mhtteam2.js} +1 -1
- package/bin/vm-hands/{managed-runtime-77n2qbvx.js → managed-runtime-sy6mh3w4.js} +1 -1
- package/bin/vm-hands/{permissions-cvzpdxrc.js → permissions-rxyjkh7m.js} +1 -1
- package/bin/vm-hands/{serve-service-s4r7emgx.js → serve-service-hmph0j95.js} +1 -1
- package/bin/vm-hands/{status-3m7v4bvn.js → status-w6dkn7t3.js} +1 -1
- package/bin/vm-hands/version-3g8vw5s4.js +2 -0
- package/bin/vm-hands/{vm-hands-entry-lite-jt07chxx.js → vm-hands-entry-lite-4aygecag.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-rjkaddpm.js → vm-hands-entry-lite-68cffvy8.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-w8vm0a63.js → vm-hands-entry-lite-6fvbzxry.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-d3t04dnm.js → vm-hands-entry-lite-7xj5rhjt.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-0t9tpg8v.js → vm-hands-entry-lite-95zqwfjf.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-rrh60fpm.js → vm-hands-entry-lite-b0qd73a5.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-dk8yvj81.js → vm-hands-entry-lite-b1m8a3fg.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-jxa0db0z.js → vm-hands-entry-lite-b5tf61cd.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-sv97sdhk.js → vm-hands-entry-lite-jgy1s741.js} +102 -6
- package/bin/vm-hands/{vm-hands-entry-lite-p2xjj79t.js → vm-hands-entry-lite-s4txp2pr.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-r5ws10mn.js → vm-hands-entry-lite-s74mc4mm.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-07hnpt33.js → vm-hands-entry-lite-sztw8k3v.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-rtn4bbwb.js → vm-hands-entry-lite-t7kgebwg.js} +1 -1
- package/bin/vm-hands/vm-hands-entry-lite-v99zhd40.js +2 -0
- package/bin/vm-hands/{vm-hands-entry-lite-6vddgzvm.js → vm-hands-entry-lite-w6dfxhwa.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-bej2f4sz.js → vm-hands-entry-lite-ykfm3bm1.js} +1 -1
- package/bin/vm-hands/vm-hands-entry-lite.js +1 -1
- package/bin/vm-hands/{vm-hands-executor-kf75wag6.js → vm-hands-executor-q0kjbq4a.js} +1 -1
- package/bin/vm-hands/{vm-hands-op-runner-xk5wnqtp.js → vm-hands-op-runner-1m7vyj1q.js} +1 -1
- package/bin/vm-hands/{vm-hands-runtime-7hq5npb1.js → vm-hands-runtime-knf7c36f.js} +3 -3
- package/package.json +1 -1
- package/bin/vm-hands/local-display-video-jssh2mwa.js +0 -2
- package/bin/vm-hands/version-z5er8jsj.js +0 -2
- package/bin/vm-hands/vm-hands-entry-lite-qj0znc2b.js +0 -2
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{We,go,j,Ve,Ht,Tr,x}from"./vm-hands-entry-lite-
|
|
2
|
+
import{We,go,j,Ve,Ht,Tr,x}from"./vm-hands-entry-lite-b0qd73a5.js";import{K}from"./vm-hands-entry-lite-xrqztkhv.js";import{pt}from"./vm-hands-entry-lite-k9vk84wa.js";import{gt}from"./vm-hands-entry-lite-95zqwfjf.js";import{Ir}from"./vm-hands-entry-lite-4aygecag.js";import{Pt,Hi}from"./vm-hands-entry-lite-xe0benev.js";import{G,qe}from"./vm-hands-entry-lite-68cffvy8.js";import{xe,Jn}from"./vm-hands-entry-lite-ykfm3bm1.js";import{St}from"./vm-hands-entry-lite-07apxfh8.js";import{a}from"./vm-hands-entry-lite-8dfw96ym.js";import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{C}from"./vm-hands-entry-lite-b6gsggvp.js";import{spawn as v,spawnSync as st}from"child_process";import{createHash as it,randomUUID as ge}from"crypto";import{closeSync as at,copyFileSync as ae,existsSync as D,fstatSync as ct,mkdirSync as ce,openSync as lt,readdirSync as L,readFileSync as X,readlinkSync as ut,renameSync as he,rmSync as dt,statSync as mt,writeFileSync as ft}from"fs";import{connect as ht}from"net";import{tmpdir as U,userInfo as _e}from"os";import{basename as le,delimiter as _t,dirname as B,join as f}from"path";var z=`import { spawn, execFileSync } from "node:child_process";
|
|
3
3
|
import { createHash, randomUUID } from "node:crypto";
|
|
4
4
|
import { readFileSync, readlinkSync, lstatSync, realpathSync, statSync, mkdtempSync, mkdirSync, chmodSync, writeFileSync, readdirSync, rmSync, openSync, readSync, closeSync, renameSync } from "node:fs";
|
|
5
5
|
import { tmpdir } from "node:os";
|
|
@@ -222,10 +222,12 @@ export function macComputerActionObservation(result, before) {
|
|
|
222
222
|
}
|
|
223
223
|
export function actionTool(action, app, target, elements = []) {
|
|
224
224
|
if (!record(action)) fail("cloud_computer_action_invalid");
|
|
225
|
-
const keys={click_pixel:["kind","x","y"],click_element:["kind","element_index","role"],type_text:["kind","text"],key_press:["kind","key"],drag:["kind","from_x","from_y","to_x","to_y","duration_ms","steps"]}[action.kind];
|
|
225
|
+
const keys={click_pixel:["kind","x","y"],click_element:["kind","element_index","role"],type_text:["kind","text"],key_press:["kind","key"],drag:["kind","from_x","from_y","to_x","to_y","duration_ms","steps"],press_and_hold:["kind","x","y","hold_ms"]}[action.kind];
|
|
226
226
|
if (!keys || Object.keys(action).some(key=>!keys.includes(key))) fail("cloud_computer_action_invalid");
|
|
227
227
|
const point = (x,y) => { if (!Number.isSafeInteger(x)||!Number.isSafeInteger(y)||x<0||y<0||x>=target.width||y>=target.height) fail("cloud_computer_action_out_of_bounds"); };
|
|
228
228
|
if (action.kind === "click_pixel") { point(action.x,action.y); return ["click",{app,x:action.x,y:action.y,click_count:1,mouse_button:"left"}]; }
|
|
229
|
+
// Runs as Linux X input (linuxHumanInput), never an OCU tool.
|
|
230
|
+
if (action.kind === "press_and_hold") { point(action.x,action.y); if(!Number.isSafeInteger(action.hold_ms)||action.hold_ms<500||action.hold_ms>15000)fail("cloud_computer_action_invalid"); return ["press_and_hold",{app,x:action.x,y:action.y,hold_ms:action.hold_ms}]; }
|
|
229
231
|
if (action.kind === "click_element") {
|
|
230
232
|
if (!Number.isSafeInteger(action.element_index) || action.element_index < 0 || action.element_index > 9999
|
|
231
233
|
|| typeof action.role !== "string" || action.role.length > 128) fail("cloud_computer_action_invalid");
|
|
@@ -390,6 +392,95 @@ export function windowsInput(target, action, execute = execFileSync) {
|
|
|
390
392
|
}
|
|
391
393
|
return { content: [{ type: "text", text: "Input sent." }] };
|
|
392
394
|
}
|
|
395
|
+
// Human-like pointer input on Linux (X11, xdotool). Slider CAPTCHAs, press-and-hold
|
|
396
|
+
// checks and Turnstile score the pointer's motion: a straight 12-point line in 240 ms
|
|
397
|
+
// or a click with no hold reads as a bot. A drag follows a minimum-jerk path with a
|
|
398
|
+
// small wobble, a slight overshoot on long drags and uneven timing; a hold keeps the
|
|
399
|
+
// button down with 1-pixel micro-moves. One xdotool command line holds the button
|
|
400
|
+
// for the whole motion. Points are snapshot pixels, mapped onto the window.
|
|
401
|
+
export const minimumJerk = t => t * t * t * (10 - 15 * t + 6 * t * t);
|
|
402
|
+
export function humanDragPath(drag, rng = Math.random) {
|
|
403
|
+
const { from_x, from_y, to_x, to_y, duration_ms, steps } = drag ?? {};
|
|
404
|
+
if (![from_x, from_y, to_x, to_y].every(value => Number.isSafeInteger(value) && value >= 0)) fail("cloud_computer_action_invalid");
|
|
405
|
+
if (!Number.isSafeInteger(duration_ms) || duration_ms < 100 || duration_ms > 10000 || !Number.isSafeInteger(steps) || steps < 1 || steps > 240) fail("cloud_computer_action_invalid");
|
|
406
|
+
const dx = to_x - from_x, dy = to_y - from_y, distance = Math.hypot(dx, dy);
|
|
407
|
+
const nx = distance ? -dy / distance : 0, ny = distance ? dx / distance : 0;
|
|
408
|
+
const wobble = Math.min(2.5, distance / 60) * (rng() < 0.5 ? -1 : 1), phase = rng() * Math.PI;
|
|
409
|
+
// A long drag overshoots the target a little and comes back, as a hand does.
|
|
410
|
+
const overshoot = distance >= 80 && steps >= 8 ? 2 + rng() * 4 : 0;
|
|
411
|
+
const correction = overshoot ? Math.max(2, Math.round(steps * 0.15)) : 0, main = steps - correction;
|
|
412
|
+
const points = [];
|
|
413
|
+
for (let step = 1; step <= main; step++) {
|
|
414
|
+
const t = step / main, reach = minimumJerk(t) * (distance + overshoot) / (distance || 1), side = wobble * Math.sin(Math.PI * t + phase) * (1 - t);
|
|
415
|
+
points.push({ x: from_x + dx * reach + nx * side, y: from_y + dy * reach + ny * side });
|
|
416
|
+
}
|
|
417
|
+
for (let step = 1; step <= correction; step++) {
|
|
418
|
+
const past = (distance + overshoot * (1 - minimumJerk(step / correction))) / (distance || 1);
|
|
419
|
+
points.push({ x: from_x + dx * past, y: from_y + dy * past });
|
|
420
|
+
}
|
|
421
|
+
const base = duration_ms / steps;
|
|
422
|
+
const path = points.map(point => ({ x: Math.round(point.x), y: Math.round(point.y), delay_ms: Math.max(4, Math.round(base * (0.75 + rng() * 0.5))) }));
|
|
423
|
+
Object.assign(path[path.length - 1], { x: to_x, y: to_y });
|
|
424
|
+
return path;
|
|
425
|
+
}
|
|
426
|
+
export function pressAndHoldPlan(hold, rng = Math.random) {
|
|
427
|
+
const { x, y, hold_ms } = hold ?? {};
|
|
428
|
+
if (!Number.isSafeInteger(x) || !Number.isSafeInteger(y) || x < 0 || y < 0 || !Number.isSafeInteger(hold_ms) || hold_ms < 500 || hold_ms > 15000) fail("cloud_computer_action_invalid");
|
|
429
|
+
const moves = [];
|
|
430
|
+
let elapsed = 0;
|
|
431
|
+
for (let wait = 400 + Math.round(rng() * 500); elapsed + wait < hold_ms; wait = 400 + Math.round(rng() * 500)) {
|
|
432
|
+
elapsed += wait;
|
|
433
|
+
moves.push({ x: x + Math.round(rng() * 2 - 1), y: y + Math.round(rng() * 2 - 1), delay_ms: wait });
|
|
434
|
+
}
|
|
435
|
+
return { x, y, moves, release_after_ms: hold_ms - elapsed };
|
|
436
|
+
}
|
|
437
|
+
const xdotoolSeconds = ms => (Math.max(0, ms) / 1000).toFixed(3);
|
|
438
|
+
/** xdotool argv for an action; \`screen(point)\` maps snapshot pixels to [screenX, screenY]. */
|
|
439
|
+
export function xdotoolHumanArgs(action, screen, rng = Math.random) {
|
|
440
|
+
if (action.kind === "press_and_hold") {
|
|
441
|
+
const plan = pressAndHoldPlan(action, rng);
|
|
442
|
+
const args = ["mousemove", ...screen(plan), "sleep", "0.080", "mousedown", "1"];
|
|
443
|
+
for (const move of plan.moves) args.push("sleep", xdotoolSeconds(move.delay_ms), "mousemove", ...screen(move));
|
|
444
|
+
return [...args, "sleep", xdotoolSeconds(plan.release_after_ms), "mouseup", "1"];
|
|
445
|
+
}
|
|
446
|
+
const args = ["mousemove", ...screen({ x: action.from_x, y: action.from_y }), "sleep", xdotoolSeconds(40 + rng() * 60),
|
|
447
|
+
"mousedown", "1", "sleep", xdotoolSeconds(60 + rng() * 80)];
|
|
448
|
+
for (const point of humanDragPath(action, rng)) args.push("mousemove", ...screen(point), "sleep", xdotoolSeconds(point.delay_ms));
|
|
449
|
+
return [...args, "sleep", xdotoolSeconds(50 + rng() * 70), "mouseup", "1"];
|
|
450
|
+
}
|
|
451
|
+
/** The target's on-screen window: the visible one of its process titled as observed, else its largest. */
|
|
452
|
+
export function linuxTargetWindow(target, execute = execFileSync) {
|
|
453
|
+
const env = { ...process.env, DISPLAY: process.env.DISPLAY || ":99" };
|
|
454
|
+
const run = args => execute("xdotool", args, { encoding: "utf8", env, timeout: 5000, stdio: ["ignore", "pipe", "ignore"] }).trim();
|
|
455
|
+
let ids;
|
|
456
|
+
try { ids = run(["search", "--onlyvisible", "--pid", String(target.pid)]).split(/\\s+/).filter(id => /^\\d+$/.test(id)); } catch { fail("cloud_computer_window_unavailable"); }
|
|
457
|
+
const windows = ids.flatMap(id => {
|
|
458
|
+
try {
|
|
459
|
+
const shell = Object.fromEntries(run(["getwindowgeometry", "--shell", id]).split("\\n").map(line => line.split("=")));
|
|
460
|
+
const geometry = { id, x: Number(shell.X), y: Number(shell.Y), width: Number(shell.WIDTH), height: Number(shell.HEIGHT) };
|
|
461
|
+
if (![geometry.x, geometry.y, geometry.width, geometry.height].every(Number.isFinite) || geometry.width < 2 || geometry.height < 2) return [];
|
|
462
|
+
let name = ""; try { name = run(["getwindowname", id]); } catch {}
|
|
463
|
+
return [{ ...geometry, name }];
|
|
464
|
+
} catch { return []; }
|
|
465
|
+
});
|
|
466
|
+
const window = windows.find(item => item.name === target.title) ?? windows.sort((a, b) => b.width * b.height - a.width * a.height)[0];
|
|
467
|
+
if (!window) fail("cloud_computer_window_unavailable");
|
|
468
|
+
return window;
|
|
469
|
+
}
|
|
470
|
+
export function linuxHumanInput(target, action, execute = execFileSync, rng = Math.random) {
|
|
471
|
+
const window = linuxTargetWindow(target, execute);
|
|
472
|
+
const screen = point => [String(window.x + Math.floor(Math.min(Math.max(point.x, 0), target.width - 1) * window.width / target.width)),
|
|
473
|
+
String(window.y + Math.floor(Math.min(Math.max(point.y, 0), target.height - 1) * window.height / target.height))];
|
|
474
|
+
try {
|
|
475
|
+
execute("xdotool", xdotoolHumanArgs(action, screen, rng), { env: { ...process.env, DISPLAY: process.env.DISPLAY || ":99" },
|
|
476
|
+
stdio: "ignore", timeout: 30000 + (action.hold_ms ?? action.duration_ms ?? 0) });
|
|
477
|
+
} catch {
|
|
478
|
+
// A stopped command may leave the button down: release it.
|
|
479
|
+
try { execute("xdotool", ["mouseup", "1"], { env: { ...process.env, DISPLAY: process.env.DISPLAY || ":99" }, stdio: "ignore", timeout: 5000 }); } catch {}
|
|
480
|
+
fail("cloud_computer_input_failed");
|
|
481
|
+
}
|
|
482
|
+
return { content: [{ type: "text", text: "Input sent." }] };
|
|
483
|
+
}
|
|
393
484
|
const explicitTabTools = new Set(["navigate", "wait_load", "page_info", "cdp", "move_mouse", "wait_file_chooser"]);
|
|
394
485
|
export function validateBrowserTab(request) {
|
|
395
486
|
if (explicitTabTools.has(request.tool) && (!record(request.arguments) || !Number.isSafeInteger(request.arguments.tab_id) || request.arguments.tab_id <= 0)) fail("cloud_automation_browser_tab_id_required");
|
|
@@ -809,7 +900,12 @@ export async function runCloudAutomation(request) {
|
|
|
809
900
|
if (request.action?.kind === "click_element") assertAccessibilityTreeMatches(request.expected, target);
|
|
810
901
|
assertSafeComputerTarget(target,request.action);
|
|
811
902
|
const [tool,args]=actionTool(request.action,request.app,target,accessibility.elements);
|
|
812
|
-
|
|
903
|
+
// Human-like pointer input (Experiments: captcha_handling): a press-and-hold, and drags with
|
|
904
|
+
// eased, uneven motion, sent as X input on Linux; OCU's own drag is a 240 ms straight line.
|
|
905
|
+
const human = request.humanInput === true && (request.action.kind === "press_and_hold" || request.action.kind === "drag");
|
|
906
|
+
if (request.action.kind === "press_and_hold" && (!human || process.platform !== "linux")) fail("cloud_computer_action_unsupported");
|
|
907
|
+
const result=human && process.platform === "linux" ? linuxHumanInput(target,request.action)
|
|
908
|
+
: process.platform === "win32" && WINDOWS_INPUT_ACTIONS.has(request.action.kind) ? windowsInput(target,request.action) : await call(tool,args);
|
|
813
909
|
return process.platform === "darwin"
|
|
814
910
|
? {ok:true,...macComputerActionObservation(result,target)}
|
|
815
911
|
: {ok:true,target,result};
|
|
@@ -854,7 +950,7 @@ if(process.env.REASON_CLOUD_GATEWAY_EXEC === "1") {
|
|
|
854
950
|
process.stdout.write(JSON.stringify(cloudAutomationFailure(error))+"\\n");process.exitCode=1;
|
|
855
951
|
}
|
|
856
952
|
}
|
|
857
|
-
`;import{spawn as
|
|
858
|
-
`).at(-1)?.slice(-300)??"";if(!
|
|
859
|
-
`);if(O)return u(O);u(new r("desktop_delegate_failed",`Reason's desktop operation failed (${J}${Y?`: ${Y}`:""}).`))})),t.aborted)S();c.stdin.end(JSON.stringify(o))})}async function Q(e,o,t,n={}){let s=await Bt(e,{op:"automation",call:o},t,n);if(!Number.isSafeInteger(s.code)||typeof s.stdout!=="string"||typeof s.stderr!=="string")throw new r("desktop_delegate_failed","Reason's desktop reply is malformed.");return{code:s.code,stdout:Buffer.from(s.stdout,"base64"),stderr:s.stderr}}import{execFile as He,spawn as je}from"child_process";import{closeSync as Xe,mkdirSync as Ke,openSync as Je}from"fs";import{dirname as E,join as Ye}from"path";import{promisify as ze}from"util";var Ze=ze(He),ee="x-apple.systempreferences:com.apple.preference.security",Qe={accessibility:`${ee}?Privacy_Accessibility`,screen:`${ee}?Privacy_ScreenCapture`},et=64,A=new Map;function T(e,o){let t=A.get(e);if(t?.has(o))return!1;if(!t){if(A.size>=et)A.delete(A.keys().next().value);t=new Set,A.set(e,t)}return t.add(o),!0}function tt(){let e=a(),o=Jn(xe(e),process.env),t=Ye(e,".local","share","reason","desktop-install.log");Ke(E(t),{recursive:!0,mode:448});let n=Je(t,"a",384);try{let s=je(o,["desktop","install"],{detached:!0,stdio:["ignore",n,n],env:{...process.env,REASON_DESKTOP_BACKGROUND:"1"}});s.on("error",()=>{return}),s.unref()}finally{Xe(n)}}var N={open:async(e,o)=>{await Ze("/usr/bin/open",e,{signal:o,timeout:1e4,maxBuffer:8192})},request:(e,o)=>pt(e,o),tile:Ir,installDesktop:tt},te=!1;async function oe(e,o,t){try{await o.open(["-a","Google Chrome",e],t)}catch{t.throwIfAborted(),await o.open([e],t)}}async function ne(e,o,t,n){if(await t.open([Qe[o]],n).catch(()=>{}),e[0]&&!n.aborted)t.tile(E(E(E(e[0]))),o)}async function ot(e,o,t,n,s){for(let i of t){if(!T(e,`grant:${i}`))continue;s.throwIfAborted(),await n.request(o,i).catch(()=>null),await ne(o,i,n,s)}}var rt={name:"open_tab",description:"Open a web page in the user's own Chrome on this Mac. Reason cannot read, screenshot or click in that tab, and no tab_id is returned: browser control needs Reason's Chrome extension. An actual browser call opens its setup page.",inputSchema:{type:"object",properties:{url:{type:"string",description:"An http or https URL."}},required:["url"],additionalProperties:!1}};function re(e){return{code:0,stderr:"",stdout:Buffer.from(JSON.stringify({ok:!0,...e}))}}function nt(e){if(typeof e!=="string")return null;try{let o=new URL(e);return o.protocol==="https:"||o.protocol==="http:"?o.href:null}catch{return null}}async function se(e,o=N){let{call:t,runId:n,signal:s}=e;if(t.kind==="browser"){if(t.operation==="discover")return re({result:{tools:[rt]}});if(t.operation!=="call")throw new r("automation_browser_setup_required","Browser control is not set up on this Mac yet. Request a browser operation or connect Chrome from Reason to set it up.")}if(e.desktopMissing&&!te){te=!0;try{o.installDesktop()}catch{}}if(t.kind==="computer"){if(e.identity.length>0&&T(n,"grant:probe")){let c=await o.request(e.identity).catch(()=>null),d=c?[...c.accessibility?[]:["accessibility"],...c.screen?[]:["screen"]]:[];for(let m of d)T(n,`grant:${m}`);for(let m of d)await ne(e.identity,m,o,s)}throw new r("automation_computer_setup_required","Computer use is not set up on this Mac yet; Reason asked macOS for any missing permission.")}if(T(n,"page:chrome-extension"))await oe(go,o,s).catch(()=>{});let i=t.arguments,u=t.operation==="call"&&t.tool==="open_tab"&&i&&typeof i==="object"&&!Array.isArray(i)?nt(i.url):null;if(!u)throw new r("automation_browser_setup_required","Browser control is not set up on this Mac yet; Reason opened its Chrome Web Store page. open_tab still opens pages.");return await oe(u,o,s),re({result:{content:[{type:"text",text:JSON.stringify({opened:u,browser:"the user's Chrome",controllable:!1,note:"Opened for the user to see. Reason cannot read or act in this tab until Reason's Chrome extension is added (its Chrome Web Store page is open)."})}]}})}async function ie(e,o=N){if(e.call.kind!=="computer"||e.call.operation!=="permission_status"||e.output.code!==0||e.identity.length===0)return e.output;let t;try{t=JSON.parse(e.output.stdout.toString("utf8"))}catch{return e.output}if(!t||typeof t!=="object"||Array.isArray(t))return e.output;let n=t.permissions;if(!n||typeof n!=="object")return e.output;let s=n,i=[...s.accessibility==="missing"?["accessibility"]:[],...s.screenRecording==="missing"?["screen"]:[]];if(i.length===0)return e.output;return await ot(e.runId,e.identity,i,o,e.signal),{...e.output,stdout:Buffer.from(JSON.stringify({...t,requested:i}))}}var H=172032,_t=18874368,yt=8192,bt=65536,xt=55000,kt=60000,Rt=4,It=40000,vt=/^[0-9a-f-]{36}$/,ue=z,Ot=ge();function P(e){return Boolean(e)&&typeof e==="object"&&!Array.isArray(e)}function D(){throw new r("invalid_automation_request","Reason automation request is malformed.")}function _e(e){let o=Object.keys(e).sort().join(",");if(o==="call"||o==="browser,call"){let t=e.call,n=o==="browser,call";if(!P(t)||t.version!==1||t.kind!=="computer"&&t.kind!=="browser"||n&&(e.browser!==St||t.kind!=="browser")||JSON.stringify(t).length>bt)D();return{call:t,userChrome:n}}if(o==="offset,output_id"){if(typeof e.output_id!=="string"||!vt.test(e.output_id)||!Number.isSafeInteger(e.offset)||e.offset<0)D();return{output_id:e.output_id,offset:e.offset}}return D()}function Pn(e=process.platform,o=x){if(e==="darwin")return!0;return(e==="linux"||e==="win32")&&o()?.features.computer===!0}var At="__computer-use";function Us(e=x){return e()?.userChrome??{code:"user_chrome_browser_use_missing"}}function ye(e,o,t,n){return new Promise((s)=>{let i=R(e,o,{env:t,stdio:"ignore",windowsHide:!0}),u=setTimeout(()=>{i.kill("SIGKILL"),s(-1)},n);i.once("error",()=>{clearTimeout(u),s(-1)}),i.once("exit",(c)=>{clearTimeout(u),s(c??-1)})})}function Et(e,o,t,n){return new Promise((s)=>{let i=R(e,o,{env:t,stdio:["ignore","pipe","ignore"],windowsHide:!0}),u="";i.stdout.setEncoding("utf8").on("data",(d)=>{u+=d});let c=setTimeout(()=>{i.kill("SIGKILL"),s(null)},n);i.once("error",()=>{clearTimeout(c),s(null)}),i.once("close",(d)=>{clearTimeout(c),s(d===0?u:null)})})}function Ct(e){return v(e)?f(L(),"open-browser-use"):"/tmp/open-browser-use"}function v(e){return e.platform==="win32-x64"||e.platform==="win32-arm64"}var Tt=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,Nt=33554432;function Dt(e,o){let t;try{t=e===null?null:JSON.parse(e)}catch{return null}let n=P(t)&&P(t.result)?t.result.metadata:null;if(!P(n)||n.extensionId!==o)return null;return typeof n.extensionInstanceId==="string"&&Tt.test(n.extensionInstanceId)?n.extensionInstanceId:null}async function be(e,o,t){let n=t.storages.map((c)=>{try{return U(c).filter((d)=>d.endsWith(".log")||d.endsWith(".ldb")).map((d)=>f(c,d))}catch{return[]}}),s;try{s=n.some((c)=>c.length>0)?U(t.socketDir).filter((c)=>c.endsWith(".sock")):[]}catch{return[]}let i=[];for(let c of s){let d=f(t.socketDir,c),m=Dt(await Et(e,["info","--socket",d,"--timeout","2s"],o,5000),t.extensionId);if(m)i.push({instance:m,socket:d})}let u=[];for(let[c,d]of(i.length>0?n:[]).entries())for(let m of d)try{if(mt(m).size>Nt)continue;let l=X(m),p=i.find((g)=>l.includes(g.instance));if(p){u.push({storage:t.storages[c],...p});break}}catch{}return u}async function Mt(e,o,t){return(await be(e,o,t))[0]?.instance??null}function Se(e,o,t){return Mt(e.nativeHost,o,{socketDir:Ct(e),extensionId:j,storages:[f(t,"browser-profile","Default","Local Extension Settings",j)]})}var de=/^(Default|Profile ([0-9]+))$/;async function Ut(e,o,t=a(),n=Ht){let s=f(t,"Library","Application Support","Google","Chrome"),i=[];try{i=U(s)}catch(l){if(l.code==="EPERM")throw new r("browser_use_chrome_access_denied","macOS blocked Reason from reading Chrome's profiles. Allow Full Disk Access for Reason on this Mac and try again.")}let u=(l)=>Number(de.exec(l)?.[2]??-1),c=i.filter((l)=>de.test(l)&&M(f(s,l,"Extensions",We))).sort((l,p)=>u(l)-u(p)),d=(l)=>f(s,l,"Local Extension Settings",We);return(await be(e,o,{socketDir:n,extensionId:We,storages:c.map(d)})).map(({storage:l,instance:p,socket:g})=>({profile:c.find((w)=>d(w)===l),instance:p,socket:g}))}async function Lt(e,o,t=a(),n=Ht){let s=(await Ut(e,o,t,n))[0]?.instance;if(!s)throw new r("automation_user_chrome_not_connected","No Chrome profile on this Mac is connected to Reason. Open Chrome with the Reason extension, then try again.");return s}function pe(e){return new Promise((o)=>{let t=ht({path:e}),n=(s)=>{t.destroy(),o(s)};t.setTimeout(1000,()=>n(!1)),t.once("error",()=>n(!1)),t.once("connect",()=>n(!0))})}async function ke(e,o){let t=Date.now()+o;while(Date.now()<t){if(await e())return!0;await new Promise((n)=>setTimeout(n,200))}return!1}var q=new Map;function F(e,o){let t=q.get(e);if(!t)t=o().finally(()=>q.delete(e)),q.set(e,t);return t}async function $t(e,o){if(await pe(e))return;if(dt(e,{force:!0}),await ye("dbus-daemon",["--session",`--address=unix:path=${e}`,"--fork"],o,1e4)!==0||!await ke(()=>pe(e),5000))throw new r("automation_unavailable","Reason could not start the desktop session bus.")}async function me(e,o,t){let n=e.platform==="darwin-arm64"||v(e)?async()=>await Se(e,o,t)!==null:async()=>await ye(e.nativeHost,["info"],o,5000)===0;if(await n())return;let s=["--profile-directory=Default",`--load-extension=${e.extensionDir}`,"--no-first-run","--no-default-browser-check","--window-size=1280,800","about:blank"],i,u=null,c=0;if(e.platform==="darwin-arm64"){let l=f(t,"browser-profile");G(l);let p=f(l,"NativeMessagingHosts");ce(p,{recursive:!0,mode:448});let g=Tr(e.platform).nativeHostManifests[0];ae(g,f(p,le(g)));let w=e.browser.slice(0,e.browser.indexOf(".app/")+4),h=s.filter((I)=>I!=="about:blank").concat("--no-startup-window","--use-mock-keychain");i=R("/usr/bin/open",["-g","-n","-a",w,"--args",`--user-data-dir=${l}`,...h],{env:o,stdio:"ignore"})}else if(v(e)){let l=f(t,"browser-profile");G(l),st(C("icacls"),[B(e.browser),"/grant","*S-1-15-2-1:(OI)(CI)(RX)","*S-1-15-2-2:(OI)(CI)(RX)"],{stdio:"ignore",windowsHide:!0,timeout:60000});let p=s.filter((g)=>g!=="about:blank").concat("--no-startup-window","--keep-alive-for-test");i=R(e.browser,[`--user-data-dir=${l}`,...p],{detached:!0,stdio:"ignore",env:o})}else{let l=f(o.HOME,".config","google-chrome"),p=f(l,"NativeMessagingHosts");ce(p,{recursive:!0,mode:448});let g=Tr(e.platform).nativeHostManifests[0];ae(g,f(p,le(g)));let w=process.geteuid?.()===0?["--no-sandbox"]:[];u=f(t,"browser.log");let h=lt(u,"a",384);c=ct(h).size,i=R(e.browser,[`--user-data-dir=${l}`,...s,...w,"--force-renderer-accessibility"],{detached:!0,stdio:["ignore",h,h],env:{...o,ACCESSIBILITY_ENABLED:"1"}}),at(h)}let d=!1;i.once("error",()=>{d=!0}),i.once("exit",(l)=>{d||=l!==0}),i.unref();let m=!1;if(await ke(async()=>d||(m=await n()),It),!m){if(u&&X(u).subarray(c).toString("utf8").includes("No usable sandbox"))throw new r("automation_browser_sandbox_unavailable","Chromium found no usable sandbox on this machine. Run the worker as a non-root user with unprivileged user namespaces enabled, or in a container with seccomp unconfined.");throw new r("automation_browser_unavailable","Reason could not connect the desktop browser.")}}async function zs(e){await ve(e,!0)}function qs(e){return Re(e,Ie(e))}function Re(e,o){return e.platform==="darwin-arm64"||v(e)?f(o,"browser-profile"):f(o,"home",".config","google-chrome")}function Ie(e){let o=f(e.root,"automation");if(!M(o)||!Wt(e.automation))return e.automation;if(!qt(Re(e,o)))try{he(o,e.automation)}catch{}return M(o)?o:e.automation}function Wt(e){try{return U(e).length===0}catch(o){return o.code==="ENOENT"}}function qt(e){let o;try{o=ut(f(e,"SingletonLock"))}catch{return!1}let t=Number(o.slice(o.lastIndexOf("-")+1));if(!Number.isSafeInteger(t)||t<=0)return!0;try{return process.kill(t,0),!0}catch(n){return n.code==="EPERM"}}async function ve(e,o){Pt({root:e.root,automation:e.automation,extensionDir:e.extensionDir});let t=Ie(e);G(t);let n=we().username,s={USER:n,LOGNAME:n,REASON_AUTOMATION_OCU:e.ocu,REASON_AUTOMATION_OBU:e.nativeHost};if(e.platform==="darwin-arm64"||v(e)){let l=v(e)?{...s,...Ft(),HOME:a()}:{...s,HOME:a(),PATH:`${B(e.node)}:/usr/bin:/bin:/usr/sbin:/sbin`,REASON_AUTOMATION_OCU:process.execPath,REASON_AUTOMATION_OCU_SUBCOMMAND:At};if(!o)return l;await F("browser",()=>me(e,l,t));let p=await Se(e,l,t);if(!p)throw new r("automation_browser_unavailable","Reason could not connect the desktop browser.");return{...l,REASON_AUTOMATION_OBU_INSTANCE:p,REASON_AUTOMATION_BACKGROUND_TABS:"1"}}let i=await qe(),u=f(t,"home"),c=f(t,"runtime");G(u),G(c);let d=f(t,"bus"),m={...s,HOME:u,PATH:`${B(e.node)}:/usr/bin:/bin`,DISPLAY:i.display,XAUTHORITY:i.xauthority,XDG_RUNTIME_DIR:c,DBUS_SESSION_BUS_ADDRESS:`unix:path=${d}`,...i.sound?{PULSE_SERVER:Ve(i.sound)}:{}};if(await F("bus",()=>$t(d,m)),o)await F("browser",()=>me(e,m,t));return m}function Ft(){let e=process.env.SystemRoot??"C:\\Windows",o=Object.fromEntries(["SystemDrive","USERPROFILE","LOCALAPPDATA","APPDATA","ProgramData","ProgramFiles","PATHEXT","ComSpec","USERNAME","USERDOMAIN","COMPUTERNAME","NUMBER_OF_PROCESSORS","PROCESSOR_ARCHITECTURE","PSModuleAnalysisCachePath"].flatMap((n)=>process.env[n]?[[n,process.env[n]]]:[])),t=f(e,"System32");return{...o,SystemRoot:e,windir:e,TEMP:L(),TMP:L(),PATH:[t,f(t,"WindowsPowerShell","v1.0"),e].join(wt)}}async function Gt(e,o,t){let n=we().username,s={USER:n,LOGNAME:n,HOME:a(),PATH:`${B(e.node)}:/usr/bin:/bin:/usr/sbin:/sbin`,REASON_AUTOMATION_OBU:o,REASON_AUTOMATION_BACKGROUND_TABS:"1"},i=await Lt(o,s);return t.throwIfAborted(),{...s,REASON_AUTOMATION_OBU_INSTANCE:i}}function jt(e){if(process.platform!=="win32")return["--input-type=module","--eval",e];let o=f(L(),`reason-automation-${it("sha256").update(e).digest("hex").slice(0,16)}.mjs`);if(!M(o)||X(o,"utf8")!==e){let t=`${o}.${process.pid}.tmp`;ft(t,e,{mode:384}),he(t,o)}return[o]}function Oe(e,o,t,n){if(typeof ue!=="string")return Promise.reject(new r("automation_unavailable","This Reason build has no automation runtime."));let s=ue;return new Promise((i,u)=>{let c=R(e,jt(s),{env:{...o,REASON_CLOUD_GATEWAY_EXEC:"1",REASON_AUTOMATION_INLINE_RESULT:"1"},stdio:["pipe","pipe","pipe"],detached:process.platform!=="win32",windowsHide:!0}),d=[],m=0,l="",p=null,g=!1,w=(_)=>{if(p??=_,process.platform==="win32"&&c.pid){R(f(process.env.SystemRoot??"C:\\Windows","System32","taskkill.exe"),["/pid",String(c.pid),"/t","/f"],{stdio:"ignore",windowsHide:!0}).once("error",()=>c.kill("SIGKILL"));return}try{process.kill(-c.pid,"SIGKILL")}catch{c.kill("SIGKILL")}},h=(_)=>{if(g)return;g=!0,clearTimeout(I),n.removeEventListener("abort",S),_()},I=setTimeout(()=>w(new r("automation_timed_out","Reason automation did not finish in time.")),xt),S=()=>w(new r("cancelled","Reason cancelled the automation call."));if(n.addEventListener("abort",S,{once:!0}),c.stdout.on("data",(_)=>{if(m+=_.byteLength,m>_t)w(new r("automation_output_too_large","Reason automation output is too large."));else d.push(_)}),c.stderr.setEncoding("utf8").on("data",(_)=>{l=(l+_).slice(-yt)}),c.stdin.on("error",()=>{}),c.once("error",()=>h(()=>u(p??new r("automation_unavailable","Reason could not start the automation runtime.")))),c.once("close",(_)=>h(()=>{if(p)u(p);else i({code:_??1,stdout:Buffer.concat(d),stderr:l})})),n.aborted)S();c.stdin.end(t)})}var k=new Map;function Xt(e,o,t){for(let[s,i]of k)if(i.expiresAt<=t)k.delete(s);while(k.size>=Rt)k.delete(k.keys().next().value);let n=ge();return k.set(n,{runId:e,bytes:o,expiresAt:t+kt}),n}async function Ae(e,o,t,n={}){let s=await(n.environment??ve)(e,o.kind==="browser");return t.throwIfAborted(),await(n.runtime??Oe)(e.node,s,JSON.stringify(o),t)}async function Ws(e,o){let t=_e({call:e});if(!("call"in t))D();let n=x();if(!n?.features.computer||t.call.kind==="browser"&&!n.features.browser)throw new r("automation_unavailable","Run `reason desktop install` on this machine to enable computer and browser use.");return await Ae(n,t.call,o)}function fe(e,o,t){let n=e.stdout.byteLength>H?Xt(o,e.stdout,t):void 0;return{code:e.code,stderr:e.stderr,instance_id:Ot,output_bytes:e.stdout.byteLength,chunk:e.stdout.subarray(0,H).toString("base64"),...n?{output_id:n}:{}}}async function Rn(e,o={}){let t=_e(e.payload),n=(o.now??Date.now)();if("output_id"in t){let h=k.get(t.output_id);if(!h||h.runId!==e.runId||h.expiresAt<=n||t.offset>h.bytes.byteLength)throw new r("automation_output_unavailable","Reason automation output expired.");return{chunk:h.bytes.subarray(t.offset,t.offset+H).toString("base64")}}let s=(o.components??x)(),i=(o.platform??process.platform)==="darwin",u=i?(o.macIdentity??gt)():[],c=o.macSetup??N,d=!s?.features.computer||t.call.kind==="browser"&&!t.userChrome&&!s.features.browser;if(i&&(d||u.length===0||t.call.kind==="browser"&&t.userChrome&&!e.userChrome))return fe(await se({runId:e.runId,call:t.call,identity:u,desktopMissing:d,signal:e.signal},c),e.runId,n);if(!s?.features.computer)throw new r("automation_unavailable","Run `reason desktop install` on this machine to enable computer and browser use.");let m=t.userChrome?e.userChrome:void 0;if(t.userChrome&&!m)throw new r("automation_user_chrome_unavailable","Your own Chrome is not enabled on this computer: run `reason desktop install` on this Mac (and `reason connect --user-chrome on` if you turned it off).");if(t.call.kind==="browser"&&!m&&!s.features.browser)throw new r("automation_browser_not_installed",!s.platform.startsWith("linux")?"Browser use is unavailable on this machine: re-run `reason desktop install`.":"Browser use is unavailable on this machine: install a non-snap Chromium at /usr/bin/chromium, then re-run `reason desktop install`.");e.signal.throwIfAborted();let l=t.call.kind==="browser"&&t.call.operation!=="record_start"&&t.call.operation!=="record_stop",p=await Hi(e.runId,e.signal,o.now,l?"call":"run"),g="account"in o?o.account??null:K(),w;try{if(m){let h=await(o.userChromeEnvironment??Gt)(s,m,e.signal);e.signal.throwIfAborted(),w=await(o.runtime??Oe)(s.node,h,JSON.stringify(t.call),e.signal)}else if(g)w=await(o.delegate??Q)(g,t.call,e.signal);else w=await Ae(s,t.call,e.signal,o)}finally{p()}if(i)w=await ie({runId:e.runId,call:t.call,identity:u,output:w,signal:e.signal},c);return fe(w,e.runId,n)}
|
|
953
|
+
`;import{spawn as Ce}from"child_process";import{lstatSync as V,readFileSync as Z,rmSync as Ne}from"fs";import{basename as Pe}from"path";var Me="__desktop-call",De="/usr/bin/setpriv",Le=27262976,Ue=8192,$e=2000;function q(e){return Boolean(e)&&typeof e==="object"&&!Array.isArray(e)}function Be(e){try{return JSON.parse(e)}catch{return null}}function Fe(){return[process.execPath,...Pe(process.execPath).startsWith("bun")&&process.argv[1]?[process.argv[1]]:[],Me]}function He(e){let o=(i)=>{try{return V(i).uid}catch{return null}},t=V("/tmp/.X11-unix",{throwIfNoEntry:!1});if(!t?.isDirectory()||t.uid!==0)return;let n=["/tmp/.X99-lock","/tmp/.X11-unix/X99"].filter((i)=>{let u=o(i);return u!==null&&u!==e.uid});if(!n.length)return;let s="";try{let i=Z("/tmp/.X99-lock","utf8").trim();if(/^\d+$/.test(i))s=Z(`/proc/${i}/comm`,"utf8").trim()}catch{}if(/^X/.test(s))return;for(let i of n)Ne(i,{force:!0})}function Bt(e,o,t,n={}){if(t.throwIfAborted(),(o.op==="display"||o.op==="automation")&&process.platform==="linux"&&process.getuid?.()===0)try{He(e)}catch{}let s=n.command??Fe();return new Promise((i,u)=>{let c=(n.spawnProcess??Ce)(De,[`--reuid=${e.uid}`,`--regid=${e.gid}`,"--clear-groups","--no-new-privs","--",...s],{cwd:e.home,detached:!0,stdio:["pipe","pipe","pipe"],env:{HOME:e.home,USER:e.username,LOGNAME:e.username,PATH:"/usr/local/bin:/usr/bin:/bin"}}),d=[],m=0,l="",p=null,g=!1,_,h=(y)=>{try{process.kill(-c.pid,y)}catch{c.kill(y)}},I=(y)=>{p??=y,h("SIGTERM"),_??=setTimeout(()=>h("SIGKILL"),$e)},S=()=>I(new r("cancelled","Reason cancelled the desktop operation."));t.addEventListener("abort",S,{once:!0});let w=(y)=>{if(g)return;g=!0,clearTimeout(_),t.removeEventListener("abort",S),y()};if(c.stdout.on("data",(y)=>{if(m+=y.byteLength,m>Le)I(new r("desktop_delegate_failed","Reason's desktop reply is too large."));else d.push(y)}),c.stderr.setEncoding("utf8").on("data",(y)=>{l=(l+y).slice(-Ue)}),c.stdin.on("error",()=>{}),c.once("error",()=>w(()=>u(p??new r("desktop_delegate_unavailable","Reason could not start its desktop as the desktop account.")))),c.once("close",(y,Ee)=>w(()=>{if(p)return u(p);let b=Be(Buffer.concat(d).toString("utf8"));if(q(b)&&b.ok===!0&&q(b.result))return i(b.result);let A=q(b)&&b.ok===!1&&typeof b.code==="string"&&typeof b.message==="string"?new r(b.code.slice(0,120),b.message.slice(0,2000)):null,J=`exited ${y??Ee}${A?"":" with no reply"}`,Y=l.trim().split(`
|
|
954
|
+
`).at(-1)?.slice(-300)??"";if(!A||A.code==="desktop_delegate_failed")process.stderr.write(`Reason worker: desktop call ${J}${l?`: ${l.trim().slice(-500)}`:""}
|
|
955
|
+
`);if(A)return u(A);u(new r("desktop_delegate_failed",`Reason's desktop operation failed (${J}${Y?`: ${Y}`:""}).`))})),t.aborted)S();c.stdin.end(JSON.stringify(o))})}async function Q(e,o,t,n={}){let s=await Bt(e,{op:"automation",call:o},t,n);if(!Number.isSafeInteger(s.code)||typeof s.stdout!=="string"||typeof s.stderr!=="string")throw new r("desktop_delegate_failed","Reason's desktop reply is malformed.");return{code:s.code,stdout:Buffer.from(s.stdout,"base64"),stderr:s.stderr}}import{execFile as Ge,spawn as je}from"child_process";import{closeSync as Xe,mkdirSync as Ke,openSync as Je}from"fs";import{dirname as E,join as Ye}from"path";import{promisify as ze}from"util";var Ze=ze(Ge),ee="x-apple.systempreferences:com.apple.preference.security",Qe={accessibility:`${ee}?Privacy_Accessibility`,screen:`${ee}?Privacy_ScreenCapture`},et=64,O=new Map;function T(e,o){let t=O.get(e);if(t?.has(o))return!1;if(!t){if(O.size>=et)O.delete(O.keys().next().value);t=new Set,O.set(e,t)}return t.add(o),!0}function tt(){let e=a(),o=Jn(xe(e),process.env),t=Ye(e,".local","share","reason","desktop-install.log");Ke(E(t),{recursive:!0,mode:448});let n=Je(t,"a",384);try{let s=je(o,["desktop","install"],{detached:!0,stdio:["ignore",n,n],env:{...process.env,REASON_DESKTOP_BACKGROUND:"1"}});s.on("error",()=>{return}),s.unref()}finally{Xe(n)}}var N={open:async(e,o)=>{await Ze("/usr/bin/open",e,{signal:o,timeout:1e4,maxBuffer:8192})},request:(e,o)=>pt(e,o),tile:Ir,installDesktop:tt},te=!1;async function oe(e,o,t){try{await o.open(["-a","Google Chrome",e],t)}catch{t.throwIfAborted(),await o.open([e],t)}}async function ne(e,o,t,n){if(await t.open([Qe[o]],n).catch(()=>{}),e[0]&&!n.aborted)t.tile(E(E(E(e[0]))),o)}async function ot(e,o,t,n,s){for(let i of t){if(!T(e,`grant:${i}`))continue;s.throwIfAborted(),await n.request(o,i).catch(()=>null),await ne(o,i,n,s)}}var rt={name:"open_tab",description:"Open a web page in the user's own Chrome on this Mac. Reason cannot read, screenshot or click in that tab, and no tab_id is returned: browser control needs Reason's Chrome extension. An actual browser call opens its setup page.",inputSchema:{type:"object",properties:{url:{type:"string",description:"An http or https URL."}},required:["url"],additionalProperties:!1}};function re(e){return{code:0,stderr:"",stdout:Buffer.from(JSON.stringify({ok:!0,...e}))}}function nt(e){if(typeof e!=="string")return null;try{let o=new URL(e);return o.protocol==="https:"||o.protocol==="http:"?o.href:null}catch{return null}}async function se(e,o=N){let{call:t,runId:n,signal:s}=e;if(t.kind==="browser"){if(t.operation==="discover")return re({result:{tools:[rt]}});if(t.operation!=="call")throw new r("automation_browser_setup_required","Browser control is not set up on this Mac yet. Request a browser operation or connect Chrome from Reason to set it up.")}if(e.desktopMissing&&!te){te=!0;try{o.installDesktop()}catch{}}if(t.kind==="computer"){if(e.identity.length>0&&T(n,"grant:probe")){let c=await o.request(e.identity).catch(()=>null),d=c?[...c.accessibility?[]:["accessibility"],...c.screen?[]:["screen"]]:[];for(let m of d)T(n,`grant:${m}`);for(let m of d)await ne(e.identity,m,o,s)}throw new r("automation_computer_setup_required","Computer use is not set up on this Mac yet; Reason asked macOS for any missing permission.")}if(T(n,"page:chrome-extension"))await oe(go,o,s).catch(()=>{});let i=t.arguments,u=t.operation==="call"&&t.tool==="open_tab"&&i&&typeof i==="object"&&!Array.isArray(i)?nt(i.url):null;if(!u)throw new r("automation_browser_setup_required","Browser control is not set up on this Mac yet; Reason opened its Chrome Web Store page. open_tab still opens pages.");return await oe(u,o,s),re({result:{content:[{type:"text",text:JSON.stringify({opened:u,browser:"the user's Chrome",controllable:!1,note:"Opened for the user to see. Reason cannot read or act in this tab until Reason's Chrome extension is added (its Chrome Web Store page is open)."})}]}})}async function ie(e,o=N){if(e.call.kind!=="computer"||e.call.operation!=="permission_status"||e.output.code!==0||e.identity.length===0)return e.output;let t;try{t=JSON.parse(e.output.stdout.toString("utf8"))}catch{return e.output}if(!t||typeof t!=="object"||Array.isArray(t))return e.output;let n=t.permissions;if(!n||typeof n!=="object")return e.output;let s=n,i=[...s.accessibility==="missing"?["accessibility"]:[],...s.screenRecording==="missing"?["screen"]:[]];if(i.length===0)return e.output;return await ot(e.runId,e.identity,i,o,e.signal),{...e.output,stdout:Buffer.from(JSON.stringify({...t,requested:i}))}}var H=172032,wt=18874368,yt=8192,bt=65536,xt=55000,kt=60000,vt=4,It=40000,Rt=/^[0-9a-f-]{36}$/,ue=z,At=ge();function P(e){return Boolean(e)&&typeof e==="object"&&!Array.isArray(e)}function M(){throw new r("invalid_automation_request","Reason automation request is malformed.")}function we(e){let o=Object.keys(e).sort().join(",");if(o==="call"||o==="browser,call"){let t=e.call,n=o==="browser,call";if(!P(t)||t.version!==1||t.kind!=="computer"&&t.kind!=="browser"||n&&(e.browser!==St||t.kind!=="browser")||JSON.stringify(t).length>bt)M();return{call:t,userChrome:n}}if(o==="offset,output_id"){if(typeof e.output_id!=="string"||!Rt.test(e.output_id)||!Number.isSafeInteger(e.offset)||e.offset<0)M();return{output_id:e.output_id,offset:e.offset}}return M()}function Pn(e=process.platform,o=x){if(e==="darwin")return!0;return(e==="linux"||e==="win32")&&o()?.features.computer===!0}var Ot="__computer-use";function Us(e=x){return e()?.userChrome??{code:"user_chrome_browser_use_missing"}}function ye(e,o,t,n){return new Promise((s)=>{let i=v(e,o,{env:t,stdio:"ignore",windowsHide:!0}),u=setTimeout(()=>{i.kill("SIGKILL"),s(-1)},n);i.once("error",()=>{clearTimeout(u),s(-1)}),i.once("exit",(c)=>{clearTimeout(u),s(c??-1)})})}function Et(e,o,t,n){return new Promise((s)=>{let i=v(e,o,{env:t,stdio:["ignore","pipe","ignore"],windowsHide:!0}),u="";i.stdout.setEncoding("utf8").on("data",(d)=>{u+=d});let c=setTimeout(()=>{i.kill("SIGKILL"),s(null)},n);i.once("error",()=>{clearTimeout(c),s(null)}),i.once("close",(d)=>{clearTimeout(c),s(d===0?u:null)})})}function Tt(e){return R(e)?f(U(),"open-browser-use"):"/tmp/open-browser-use"}function R(e){return e.platform==="win32-x64"||e.platform==="win32-arm64"}var Ct=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,Nt=33554432;function Mt(e,o){let t;try{t=e===null?null:JSON.parse(e)}catch{return null}let n=P(t)&&P(t.result)?t.result.metadata:null;if(!P(n)||n.extensionId!==o)return null;return typeof n.extensionInstanceId==="string"&&Ct.test(n.extensionInstanceId)?n.extensionInstanceId:null}async function be(e,o,t){let n=t.storages.map((c)=>{try{return L(c).filter((d)=>d.endsWith(".log")||d.endsWith(".ldb")).map((d)=>f(c,d))}catch{return[]}}),s;try{s=n.some((c)=>c.length>0)?L(t.socketDir).filter((c)=>c.endsWith(".sock")):[]}catch{return[]}let i=[];for(let c of s){let d=f(t.socketDir,c),m=Mt(await Et(e,["info","--socket",d,"--timeout","2s"],o,5000),t.extensionId);if(m)i.push({instance:m,socket:d})}let u=[];for(let[c,d]of(i.length>0?n:[]).entries())for(let m of d)try{if(mt(m).size>Nt)continue;let l=X(m),p=i.find((g)=>l.includes(g.instance));if(p){u.push({storage:t.storages[c],...p});break}}catch{}return u}async function Dt(e,o,t){return(await be(e,o,t))[0]?.instance??null}function Se(e,o,t){return Dt(e.nativeHost,o,{socketDir:Tt(e),extensionId:j,storages:[f(t,"browser-profile","Default","Local Extension Settings",j)]})}var de=/^(Default|Profile ([0-9]+))$/;async function Lt(e,o,t=a(),n=Ht){let s=f(t,"Library","Application Support","Google","Chrome"),i=[];try{i=L(s)}catch(l){if(l.code==="EPERM")throw new r("browser_use_chrome_access_denied","macOS blocked Reason from reading Chrome's profiles. Allow Full Disk Access for Reason on this Mac and try again.")}let u=(l)=>Number(de.exec(l)?.[2]??-1),c=i.filter((l)=>de.test(l)&&D(f(s,l,"Extensions",We))).sort((l,p)=>u(l)-u(p)),d=(l)=>f(s,l,"Local Extension Settings",We);return(await be(e,o,{socketDir:n,extensionId:We,storages:c.map(d)})).map(({storage:l,instance:p,socket:g})=>({profile:c.find((_)=>d(_)===l),instance:p,socket:g}))}async function Ut(e,o,t=a(),n=Ht){let s=(await Lt(e,o,t,n))[0]?.instance;if(!s)throw new r("automation_user_chrome_not_connected","No Chrome profile on this Mac is connected to Reason. Open Chrome with the Reason extension, then try again.");return s}function pe(e){return new Promise((o)=>{let t=ht({path:e}),n=(s)=>{t.destroy(),o(s)};t.setTimeout(1000,()=>n(!1)),t.once("error",()=>n(!1)),t.once("connect",()=>n(!0))})}async function ke(e,o){let t=Date.now()+o;while(Date.now()<t){if(await e())return!0;await new Promise((n)=>setTimeout(n,200))}return!1}var W=new Map;function F(e,o){let t=W.get(e);if(!t)t=o().finally(()=>W.delete(e)),W.set(e,t);return t}async function $t(e,o){if(await pe(e))return;if(dt(e,{force:!0}),await ye("dbus-daemon",["--session",`--address=unix:path=${e}`,"--fork"],o,1e4)!==0||!await ke(()=>pe(e),5000))throw new r("automation_unavailable","Reason could not start the desktop session bus.")}async function me(e,o,t){let n=e.platform==="darwin-arm64"||R(e)?async()=>await Se(e,o,t)!==null:async()=>await ye(e.nativeHost,["info"],o,5000)===0;if(await n())return;let s=["--profile-directory=Default",`--load-extension=${e.extensionDir}`,"--no-first-run","--no-default-browser-check","--window-size=1280,800","about:blank"],i,u=null,c=0;if(e.platform==="darwin-arm64"){let l=f(t,"browser-profile");G(l);let p=f(l,"NativeMessagingHosts");ce(p,{recursive:!0,mode:448});let g=Tr(e.platform).nativeHostManifests[0];ae(g,f(p,le(g)));let _=e.browser.slice(0,e.browser.indexOf(".app/")+4),h=s.filter((I)=>I!=="about:blank").concat("--no-startup-window","--use-mock-keychain");i=v("/usr/bin/open",["-g","-n","-a",_,"--args",`--user-data-dir=${l}`,...h],{env:o,stdio:"ignore"})}else if(R(e)){let l=f(t,"browser-profile");G(l),st(C("icacls"),[B(e.browser),"/grant","*S-1-15-2-1:(OI)(CI)(RX)","*S-1-15-2-2:(OI)(CI)(RX)"],{stdio:"ignore",windowsHide:!0,timeout:60000});let p=s.filter((g)=>g!=="about:blank").concat("--no-startup-window","--keep-alive-for-test");i=v(e.browser,[`--user-data-dir=${l}`,...p],{detached:!0,stdio:"ignore",env:o})}else{let l=f(o.HOME,".config","google-chrome"),p=f(l,"NativeMessagingHosts");ce(p,{recursive:!0,mode:448});let g=Tr(e.platform).nativeHostManifests[0];ae(g,f(p,le(g)));let _=process.geteuid?.()===0?["--no-sandbox"]:[];u=f(t,"browser.log");let h=lt(u,"a",384);c=ct(h).size,i=v(e.browser,[`--user-data-dir=${l}`,...s,..._,"--force-renderer-accessibility"],{detached:!0,stdio:["ignore",h,h],env:{...o,ACCESSIBILITY_ENABLED:"1"}}),at(h)}let d=!1;i.once("error",()=>{d=!0}),i.once("exit",(l)=>{d||=l!==0}),i.unref();let m=!1;if(await ke(async()=>d||(m=await n()),It),!m){if(u&&X(u).subarray(c).toString("utf8").includes("No usable sandbox"))throw new r("automation_browser_sandbox_unavailable","Chromium found no usable sandbox on this machine. Run the worker as a non-root user with unprivileged user namespaces enabled, or in a container with seccomp unconfined.");throw new r("automation_browser_unavailable","Reason could not connect the desktop browser.")}}async function zs(e){await Re(e,!0)}function qs(e){return ve(e,Ie(e))}function ve(e,o){return e.platform==="darwin-arm64"||R(e)?f(o,"browser-profile"):f(o,"home",".config","google-chrome")}function Ie(e){let o=f(e.root,"automation");if(!D(o)||!qt(e.automation))return e.automation;if(!Wt(ve(e,o)))try{he(o,e.automation)}catch{}return D(o)?o:e.automation}function qt(e){try{return L(e).length===0}catch(o){return o.code==="ENOENT"}}function Wt(e){let o;try{o=ut(f(e,"SingletonLock"))}catch{return!1}let t=Number(o.slice(o.lastIndexOf("-")+1));if(!Number.isSafeInteger(t)||t<=0)return!0;try{return process.kill(t,0),!0}catch(n){return n.code==="EPERM"}}async function Re(e,o){Pt({root:e.root,automation:e.automation,extensionDir:e.extensionDir});let t=Ie(e);G(t);let n=_e().username,s={USER:n,LOGNAME:n,REASON_AUTOMATION_OCU:e.ocu,REASON_AUTOMATION_OBU:e.nativeHost};if(e.platform==="darwin-arm64"||R(e)){let l=R(e)?{...s,...Ft(),HOME:a()}:{...s,HOME:a(),PATH:`${B(e.node)}:/usr/bin:/bin:/usr/sbin:/sbin`,REASON_AUTOMATION_OCU:process.execPath,REASON_AUTOMATION_OCU_SUBCOMMAND:Ot};if(!o)return l;await F("browser",()=>me(e,l,t));let p=await Se(e,l,t);if(!p)throw new r("automation_browser_unavailable","Reason could not connect the desktop browser.");return{...l,REASON_AUTOMATION_OBU_INSTANCE:p,REASON_AUTOMATION_BACKGROUND_TABS:"1"}}let i=await qe(),u=f(t,"home"),c=f(t,"runtime");G(u),G(c);let d=f(t,"bus"),m={...s,HOME:u,PATH:`${B(e.node)}:/usr/bin:/bin`,DISPLAY:i.display,XAUTHORITY:i.xauthority,XDG_RUNTIME_DIR:c,DBUS_SESSION_BUS_ADDRESS:`unix:path=${d}`,...i.sound?{PULSE_SERVER:Ve(i.sound)}:{}};if(await F("bus",()=>$t(d,m)),o)await F("browser",()=>me(e,m,t));return m}function Ft(){let e=process.env.SystemRoot??"C:\\Windows",o=Object.fromEntries(["SystemDrive","USERPROFILE","LOCALAPPDATA","APPDATA","ProgramData","ProgramFiles","PATHEXT","ComSpec","USERNAME","USERDOMAIN","COMPUTERNAME","NUMBER_OF_PROCESSORS","PROCESSOR_ARCHITECTURE","PSModuleAnalysisCachePath"].flatMap((n)=>process.env[n]?[[n,process.env[n]]]:[])),t=f(e,"System32");return{...o,SystemRoot:e,windir:e,TEMP:U(),TMP:U(),PATH:[t,f(t,"WindowsPowerShell","v1.0"),e].join(_t)}}async function Gt(e,o,t){let n=_e().username,s={USER:n,LOGNAME:n,HOME:a(),PATH:`${B(e.node)}:/usr/bin:/bin:/usr/sbin:/sbin`,REASON_AUTOMATION_OBU:o,REASON_AUTOMATION_BACKGROUND_TABS:"1"},i=await Ut(o,s);return t.throwIfAborted(),{...s,REASON_AUTOMATION_OBU_INSTANCE:i}}function jt(e){if(process.platform!=="win32")return["--input-type=module","--eval",e];let o=f(U(),`reason-automation-${it("sha256").update(e).digest("hex").slice(0,16)}.mjs`);if(!D(o)||X(o,"utf8")!==e){let t=`${o}.${process.pid}.tmp`;ft(t,e,{mode:384}),he(t,o)}return[o]}function Ae(e,o,t,n){if(typeof ue!=="string")return Promise.reject(new r("automation_unavailable","This Reason build has no automation runtime."));let s=ue;return new Promise((i,u)=>{let c=v(e,jt(s),{env:{...o,REASON_CLOUD_GATEWAY_EXEC:"1",REASON_AUTOMATION_INLINE_RESULT:"1"},stdio:["pipe","pipe","pipe"],detached:process.platform!=="win32",windowsHide:!0}),d=[],m=0,l="",p=null,g=!1,_=(w)=>{if(p??=w,process.platform==="win32"&&c.pid){v(f(process.env.SystemRoot??"C:\\Windows","System32","taskkill.exe"),["/pid",String(c.pid),"/t","/f"],{stdio:"ignore",windowsHide:!0}).once("error",()=>c.kill("SIGKILL"));return}try{process.kill(-c.pid,"SIGKILL")}catch{c.kill("SIGKILL")}},h=(w)=>{if(g)return;g=!0,clearTimeout(I),n.removeEventListener("abort",S),w()},I=setTimeout(()=>_(new r("automation_timed_out","Reason automation did not finish in time.")),xt),S=()=>_(new r("cancelled","Reason cancelled the automation call."));if(n.addEventListener("abort",S,{once:!0}),c.stdout.on("data",(w)=>{if(m+=w.byteLength,m>wt)_(new r("automation_output_too_large","Reason automation output is too large."));else d.push(w)}),c.stderr.setEncoding("utf8").on("data",(w)=>{l=(l+w).slice(-yt)}),c.stdin.on("error",()=>{}),c.once("error",()=>h(()=>u(p??new r("automation_unavailable","Reason could not start the automation runtime.")))),c.once("close",(w)=>h(()=>{if(p)u(p);else i({code:w??1,stdout:Buffer.concat(d),stderr:l})})),n.aborted)S();c.stdin.end(t)})}var k=new Map;function Xt(e,o,t){for(let[s,i]of k)if(i.expiresAt<=t)k.delete(s);while(k.size>=vt)k.delete(k.keys().next().value);let n=ge();return k.set(n,{runId:e,bytes:o,expiresAt:t+kt}),n}async function Oe(e,o,t,n={}){let s=await(n.environment??Re)(e,o.kind==="browser");return t.throwIfAborted(),await(n.runtime??Ae)(e.node,s,JSON.stringify(o),t)}async function Ws(e,o){let t=we({call:e});if(!("call"in t))M();let n=x();if(!n?.features.computer||t.call.kind==="browser"&&!n.features.browser)throw new r("automation_unavailable","Run `reason desktop install` on this machine to enable computer and browser use.");return await Oe(n,t.call,o)}function fe(e,o,t){let n=e.stdout.byteLength>H?Xt(o,e.stdout,t):void 0;return{code:e.code,stderr:e.stderr,instance_id:At,output_bytes:e.stdout.byteLength,chunk:e.stdout.subarray(0,H).toString("base64"),...n?{output_id:n}:{}}}async function Rn(e,o={}){let t=we(e.payload),n=(o.now??Date.now)();if("output_id"in t){let h=k.get(t.output_id);if(!h||h.runId!==e.runId||h.expiresAt<=n||t.offset>h.bytes.byteLength)throw new r("automation_output_unavailable","Reason automation output expired.");return{chunk:h.bytes.subarray(t.offset,t.offset+H).toString("base64")}}let s=(o.components??x)(),i=(o.platform??process.platform)==="darwin",u=i?(o.macIdentity??gt)():[],c=o.macSetup??N,d=!s?.features.computer||t.call.kind==="browser"&&!t.userChrome&&!s.features.browser;if(i&&(d||u.length===0||t.call.kind==="browser"&&t.userChrome&&!e.userChrome))return fe(await se({runId:e.runId,call:t.call,identity:u,desktopMissing:d,signal:e.signal},c),e.runId,n);if(!s?.features.computer)throw new r("automation_unavailable","Run `reason desktop install` on this machine to enable computer and browser use.");let m=t.userChrome?e.userChrome:void 0;if(t.userChrome&&!m)throw new r("automation_user_chrome_unavailable","Your own Chrome is not enabled on this computer: run `reason desktop install` on this Mac (and `reason connect --user-chrome on` if you turned it off).");if(t.call.kind==="browser"&&!m&&!s.features.browser)throw new r("automation_browser_not_installed",!s.platform.startsWith("linux")?"Browser use is unavailable on this machine: re-run `reason desktop install`.":"Browser use is unavailable on this machine: install a non-snap Chromium at /usr/bin/chromium, then re-run `reason desktop install`.");e.signal.throwIfAborted();let l=t.call.kind==="browser"&&t.call.operation!=="record_start"&&t.call.operation!=="record_stop",p=await Hi(e.runId,e.signal,o.now,l?"call":"run"),g="account"in o?o.account??null:K(),_;try{if(m){let h=await(o.userChromeEnvironment??Gt)(s,m,e.signal);e.signal.throwIfAborted(),_=await(o.runtime??Ae)(s.node,h,JSON.stringify(t.call),e.signal)}else if(g)_=await(o.delegate??Q)(g,t.call,e.signal);else _=await Oe(s,t.call,e.signal,o)}finally{p()}if(i)_=await ie({runId:e.runId,call:t.call,identity:u,output:_,signal:e.signal},c);return fe(_,e.runId,n)}
|
|
860
956
|
export{Bt,Pn,Us,zs,qs,Ws,Rn};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{nt,Et,cr,on,xt,kt,Di,sn,Oi,Ni,Li}from"./vm-hands-entry-lite-fxzadxz4.js";import{Pe,sr,ni,wt,Go,oe,Ko,Jo,tt,Re,nn,oi,vt,li,ui,di,pi,hi,fi,mi,gi,_i,yi,wi,bi,vi,pe,Z,Te,q,Si,Ei,xi,ki,Ci,Ai,Pi,Ri,St,Ti}from"./vm-hands-entry-lite-07apxfh8.js";import{ue,X,I,N}from"./vm-hands-entry-lite-48rphbjm.js";import{P,Yt}from"./vm-hands-entry-lite-sb7b4z8t.js";import{mr,eo,to,at,ro,no,io,oo,so,ao,yr,wr,br,wn,bn,vr,lo,vn,Sr,me,ge,Ot,Er,kr,Nt}from"./vm-hands-entry-lite-
|
|
2
|
+
import{nt,Et,cr,on,xt,kt,Di,sn,Oi,Ni,Li}from"./vm-hands-entry-lite-fxzadxz4.js";import{Pe,sr,ni,wt,Go,oe,Ko,Jo,tt,Re,nn,oi,vt,li,ui,di,pi,hi,fi,mi,gi,_i,yi,wi,bi,vi,pe,Z,Te,q,Si,Ei,xi,ki,Ci,Ai,Pi,Ri,St,Ti}from"./vm-hands-entry-lite-07apxfh8.js";import{ue,X,I,N}from"./vm-hands-entry-lite-48rphbjm.js";import{P,Yt}from"./vm-hands-entry-lite-sb7b4z8t.js";import{mr,eo,to,at,ro,no,io,oo,so,ao,yr,wr,br,wn,bn,vr,lo,vn,Sr,me,ge,Ot,Er,kr,Nt}from"./vm-hands-entry-lite-s74mc4mm.js";import{O,T,b}from"./vm-hands-entry-lite-kmtz5h74.js";import{Xi,Yi,_n,Zi,yn,Qi,st,fr}from"./vm-hands-entry-lite-b1m8a3fg.js";import{K}from"./vm-hands-entry-lite-xrqztkhv.js";import{Ue}from"./vm-hands-entry-lite-5tnma5qb.js";import{H}from"./vm-hands-entry-lite-w29d7ey0.js";import{hr,gn,Ji}from"./vm-hands-entry-lite-9azmqs47.js";import{vo,So,dt,Eo,xo,ko,Co,Ao,Po,Ro}from"./vm-hands-entry-lite-k9vk84wa.js";import{Dr,Vt,Or,Hn,Un}from"./vm-hands-entry-lite-645wzfhr.js";import{Ft,qe,jt}from"./vm-hands-entry-lite-68cffvy8.js";import{Nn,x,yo}from"./vm-hands-entry-lite-b0qd73a5.js";import{wo,bo}from"./vm-hands-entry-lite-4aygecag.js";import{Bt,Pn,Rn}from"./vm-hands-entry-lite-jgy1s741.js";import{ye,ho,fo}from"./vm-hands-entry-lite-2hfrcr50.js";import{be}from"./vm-hands-entry-lite-yretc2th.js";import{Mt}from"./vm-hands-entry-lite-yptpy066.js";import{ve,Ut,zt,qt,E}from"./vm-hands-entry-lite-72nj66ab.js";import{a,ie}from"./vm-hands-entry-lite-8dfw96ym.js";import{t,k,o,d,u,n,W,g,ee,s,i,Zo}from"./vm-hands-entry-lite-wzv13c8k.js";import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{fe,Ne,Le,$e,ln}from"./vm-hands-entry-lite-b6gsggvp.js";import{Me}from"./vm-hands-entry-lite-3gbf905c.js";import{request as Fl}from"http";import{request as Ul}from"https";import{lookup as Hl}from"dns/promises";import{isIP as jl}from"net";async function ql(e){let l=new URL(e.url);return await new Promise((c,p)=>{let m=(l.protocol==="https:"?Ul:Fl)(l,{method:"POST",headers:{...e.headers,"accept-encoding":"identity"},signal:e.signal,timeout:Di},(f)=>c({response:f,close:()=>{f.destroy(),m.destroy(),f.socket?.destroy()}}));m.once("error",p),m.once("timeout",()=>m.destroy(Object.assign(Error("custom_endpoint_timeout"),{code:"ETIMEDOUT"}))),m.end(e.body)})}var es=new Set(["ENOTFOUND","EAI_AGAIN","EAI_NONAME","EAI_NODATA","EAI_FAIL","DNSException"]),Wl=new Set(["ECONNREFUSED","ETIMEDOUT","ECONNRESET","EHOSTUNREACH","ENETUNREACH","EHOSTDOWN","ENETDOWN","EPIPE","ECONNABORTED","EADDRNOTAVAIL","ConnectionRefused","ConnectionClosed","ConnectionTimedOut","Timeout"]);function ts(e,l=0){if(!e||typeof e!=="object"||l>3)return null;let c=e.code;if(typeof c==="string"){if(es.has(c))return"custom_endpoint_host_not_found";if(Wl.has(c))return"custom_endpoint_connection_failed";if(/^(?:ERR_TLS_|ERR_SSL_|CERT_|UNABLE_TO_(?:GET|VERIFY|DECRYPT)|DEPTH_ZERO_SELF_SIGNED|SELF_SIGNED_CERT|HOSTNAME_MISMATCH|EPROTO$)/.test(c))return"custom_endpoint_tls_failed"}for(let p of[...e instanceof AggregateError?e.errors:[],e.cause]){let m=ts(p,l+1);if(m)return m}return null}async function Vl(e,l){let c=ts(e),p=new URL(l).hostname.replace(/^\[|\]$/g,"");if(c!==null&&c!=="custom_endpoint_connection_failed"||jl(p)!==0)return c;let m;return await Promise.race([Hl(p).then(()=>!0,(h)=>!es.has(String(h?.code))),new Promise((h)=>{m=setTimeout(()=>h(!0),5000)})]).finally(()=>clearTimeout(m))?c:"custom_endpoint_host_not_found"}function zl(e){for(let l=42;;l++){if(l===127)l=256;let c=String.fromCodePoint(l);if(!e.includes(c))return c}}function Gl(e,l){let c=Buffer.from(e),p=Buffer.from(l),m=new Uint32Array(c.length);for(let h=1,y=0;h<c.length;h++){while(y&&c[h]!==c[y])y=m[y-1];if(c[h]===c[y])y++;m[h]=y}let f=0;return(h,y=!1)=>{let S=Buffer.allocUnsafe(h.length*p.length+f),w=0;for(let _ of h){while(f&&c[f]!==_){let v=m[f-1];w+=c.copy(S,w,0,f-v),f=v}if(c[f]===_){if(f++,f===c.length)w+=p.copy(S,w),f=0}else S[w++]=_}if(y)w+=c.copy(S,w,0,f),f=0;return S.subarray(0,w)}}async function rs(e){e.signal.throwIfAborted();let l=Oi.safeParse(e.payload);if(!l.success)throw new r("custom_endpoint_invalid_request","Invalid local model request.");let c=l.data,p=Ni.parse(await e.credential(e.signal));if(!sn(c,{baseUrl:c.baseUrl,api:p.api,execution:"device"}))throw new r("custom_endpoint_invalid_request","The request does not match the configured API.");e.signal.throwIfAborted();let m,f,h=0,y=0,S=0,w=zl(p.apiKey),_=Gl(p.apiKey,w),v=async(C,A)=>{e.signal.throwIfAborted(),await new Promise((F,L)=>{let M=()=>{e.signal.removeEventListener("abort",M),L(e.signal.reason)};if(e.signal.addEventListener("abort",M,{once:!0}),e.signal.aborted){M();return}Promise.resolve().then(()=>(e.signal.throwIfAborted(),e.emit(C,A))).then(()=>{e.signal.removeEventListener("abort",M),F()},(B)=>{e.signal.removeEventListener("abort",M),L(B)})})},R=async(C)=>{if(h+=C.length,h>cr)throw new r("custom_endpoint_response_too_large","Local model response exceeds the transport limit.");for(let A=0;A<C.length;A+=Et){if(S>=on)throw new r("custom_endpoint_response_too_large","Local model response exceeds the chunk limit.");await v(`custom_endpoint.chunk.${S++}`,{eof:!1,data:C.subarray(A,A+Et).toString("base64")})}};try{let C=await ql({url:c.url,body:c.body,signal:e.signal,headers:{...c.headers,...p.api==="anthropic-messages"?{"x-api-key":p.apiKey}:{authorization:`Bearer ${p.apiKey}`}}});m=C.response,f=C.close;let A=m.statusCode??500;if(A>=300&&A<400)throw new r("custom_endpoint_redirect_refused","Local model redirects are not followed.");if(m.headers["content-encoding"]&&m.headers["content-encoding"]!=="identity")throw new r("custom_endpoint_encoding_unsupported","The local server must honor identity encoding.");let F={};for(let L of["content-type","retry-after","x-request-id","request-id"]){let M=m.headers[L];if(typeof M==="string")F[L]=M.replaceAll(p.apiKey,w).slice(0,4096)}await v("custom_endpoint.headers",{status:A,statusText:(m.statusMessage??"").replaceAll(p.apiKey,w).slice(0,256),headers:F});for await(let L of m){e.signal.throwIfAborted();let M=Buffer.isBuffer(L)?L:Buffer.from(L);if(y+=M.length,y>cr)throw new r("custom_endpoint_response_too_large","Local model response exceeds the transport limit.");await R(_(M))}return await R(_(Buffer.alloc(0),!0)),await v(`custom_endpoint.chunk.${S}`,{eof:!0}),{bytes:h,chunks:S}}catch(C){if(e.signal.throwIfAborted(),C instanceof r)throw C;throw new r((m?null:await Vl(C,c.url))??"custom_endpoint_request_failed","The local model server could not complete the request.")}finally{f?.()}}import{join as ls}from"path";function Yl(e,l){return e===ls(l,".ara","workspace")||e===ls(l,".reason","workspace")}function cs(e,l){let c=e.filter((p)=>Yl(p.path,l));return c.length===1?c[0].path:null}var Kl=/^[a-f0-9]{64}$/;var cn=32,Xl=/^\/[^\x00-\x1f\x7f\\]*$/;function Pr(e){if(typeof e!=="string"||e.length>4096||!Xl.test(e))return!1;if(e==="/")return!0;return e.split("/").slice(1).every((l)=>l!==""&&l!=="."&&l!=="..")}function Ir(e,l){let c=l==="win32"?/^([A-Za-z]):[\\/]*(.*)$/.exec(e):null;if(!c)return e;let p=c[2].split(/[\\/]+/).filter(Boolean).join("/");return`/${c[1].toUpperCase()}:${p?`/${p}`:""}`}function un(e){if(!e||typeof e!=="object"||Array.isArray(e))return;let l=e;if(!Pr(l.home)||!Array.isArray(l.roots)||l.roots.length>cn)return;let c=[];for(let p of l.roots){if(!p||typeof p!=="object"||Array.isArray(p))return;let{path_fingerprint:m,path:f}=p;if(typeof m!=="string"||!Kl.test(m)||!Pr(f))return;c.push({path_fingerprint:m,path:f})}return{home:l.home,roots:c}}function Jl(e){let l=/^Reason contributor (rc_[0-9a-f]{32})$/.exec(e.name)?.[1];return e.email.toLowerCase()==="343777287+reason-contributors@users.noreply.github.com"&&l?l:void 0}function Zl(e){return Jl(e)??e.email.toLowerCase()}function dn(e){let l=/^Co-authored-by:\s*([^<>\r\n]+) <([^<>\s]+)>$/i.exec(e.trim());return l?Zl({name:l[1],email:l[2]}):e.trim().toLowerCase()}var Kt=(e)=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/[a-z]/gi,(l)=>`[${l.toLowerCase()}${l.toUpperCase()}]`),Ql=[...ve.map((e)=>`/(${e.map(Kt).join("/")})(/|$)`),...Ut.map((e)=>`/(${e.map(Kt).join("/")})(/|$)`),...[...zt].map((e)=>`/(${Kt(e)})$`),`/${Kt(".env.")}[^/]*$`,...qt.map((e)=>`/[^/]*${Kt(e)}$`)],us=`function localGithubSandboxProfile(root, temporary) {
|
|
3
3
|
return ['(version 1)','(deny default)','(import "system.sb")','(allow process-exec process-fork)',
|
|
4
4
|
'(allow file-read* (subpath "/bin") (subpath "/sbin") (subpath "/usr/bin") (subpath "/usr/sbin") (subpath "/usr/libexec") (subpath "/usr/share") (subpath "/private/var/select") (literal "/private/var/db/xcode_select_link"))',
|
|
5
5
|
'(allow file-read-metadata (path-ancestors "/opt/homebrew/bin") (path-ancestors "/usr/local/bin") (path-ancestors "/Library/Developer/CommandLineTools"))',
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Jt,H}from"./vm-hands-entry-lite-w29d7ey0.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{Io,P,Je,Se,Xe,ne,Ye,Vn,Ee,Qt,ae,U,L,ce,zr,qr,Kn}from"./vm-hands-entry-lite-sb7b4z8t.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-kmtz5h74.js";import{Cr,Ar,xn,uo,Ue,kn}from"./vm-hands-entry-lite-5tnma5qb.js";import{K}from"./vm-hands-entry-lite-xrqztkhv.js";import{ji}from"./vm-hands-entry-lite-xe0benev.js";import{p,ze,$t,ut,po,_e,we}from"./vm-hands-entry-lite-2hfrcr50.js";import{v,h,mo}from"./vm-hands-entry-lite-hfx1q0b0.js";import{E}from"./vm-hands-entry-lite-72nj66ab.js";import{tr}from"./vm-hands-entry-lite-rtn4bbwb.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-b6gsggvp.js";var Ri=()=>{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),j=_[x]??x;return`Invalid input: expected ${S}, received ${j}`}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:Ri()}}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 Oi}from"crypto";import{isAbsolute as Bo,join as jo,relative as Mo,resolve as qt,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(Jt),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()}),xi=/^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(!xi.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(Fr(l,e))return!1;return!Fr(e,l)||E(jo(Wo,Mo(qt(e),qt(l))))}function Fr(e,l){let f=Mo(qt(e),qt(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 Oi("sha256").update(JSON.stringify(x)).digest("hex")}var Pi=4,Ii=[2375,2376,9222,9229];function mr(e){let l=new Set(Ii);for(let f of e){let _=new URL(f);l.add(Number(_.port||(["https:","wss:"].includes(_.protocol)?443:80)))}return l}function Gr(){throw new r("preview_unavailable","The live Hands preview binding is unavailable or stale.")}var Ai=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)Gr()}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 W=await j(R,B,G);if(W!=="moved")return W;let D=await j(R,B,G);return D==="moved"?null:D}async function j(R,B,G){try{w(e.authority.owner);let W=e.identity();if(!W||G.aborted||R.expiresAtMs<=Date.now()||R.expiresAtMs>e.expiresAtMs)return null;let D=B.opened,re=D!==void 0&&W.generation>D.generation,J=S(W);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())>Ai)return null}else if(!J||R.expiresAtMs>Date.parse(J.expires_at)||D&&(W.generation!==D.generation||W.fenceId!==D.fenceId))return null;let z=await e.inspect(R.jobId,G),fe=e.identity(),ve=fe&&S(fe);w(e.authority.owner);let be=J&&{generation:W.generation,fenceId:W.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!==W.generation||fe.fenceId!==W.fenceId||ve?.snapshot_id!==J?.snapshot_id||ve?.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!==W.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&&W.generation===R.generation&&W.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:W,deviceRelayUrl:D}=ut(R);if(G.aborted||W.expiresAtMs<=Date.now()||W.expiresAtMs>Date.now()+p.lifetimeMs||new URL(D).origin!==e.authority.relayOrigin)Gr();let re=_(W),J=f.get(re);if(J){if(!ze(J.binding,W)||J.relay!==D)Gr();if(await J.opened,!await $t(()=>J.port.check())||G.aborted||J.abort.signal.aborted)Gr();return{opened:!0,binding:W}}if(f.size>=Pi)Gr();let z=new AbortController,fe={},ve=we({binding:W,deniedPorts:e.authority.deniedPorts,readCurrentJob:()=>x(W,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:W,deviceRelayUrl:D,port:ve,signal:z.signal}),Fe={binding:W,relay:D,abort:z,port:ve,opened:Re};f.set(re,Fe);let qe=()=>{if(G.removeEventListener("abort",be),l.signal.removeEventListener("abort",be),f.get(re)===Fe)f.delete(re)};try{if((await Re).closed.then(qe),G.removeEventListener("abort",be),w(B),z.signal.aborted||!await $t(()=>ve.check()))Gr();return{opened:!0,binding:W}}catch{z.abort(),qe(),Gr()}},async close(R,B){w(B);let{binding:G}=po(R),W=f.get(_(G));if(!W||!ze(W.binding,G))Gr();return W.abort.abort(),await W.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*Ye;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)<=Ee))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 j=Date.parse(e.expires_at);if(!Number.isSafeInteger(j)||j<=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(j,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 j=setTimeout(x,Math.max(1,l.leaseExpiresAtMs-Date.now())),R=[],B=0,G=0,W=0,D=!1,re=!1,J=!1,z,fe,ve,be=(le)=>{ve=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 Ke=R.at(-1),Le=he&&Ke!==void 0&&"data"in Ke&&Ke.data.length+xe.length<=ne;if(xe.length>ne||B+xe.length>Vn){be("pty_input_backpressure");return}if(Le)Ke.data=Buffer.concat([Ke.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((ke)=>Number.isSafeInteger(ke)&&ke>=1&&ke<=Ee))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 Kn(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 qe(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>W+1)W=le.firstCursor-1;for(let he of le.pty.output){if(he.cursor<=W)continue;if(he.cursor!==W+1)ar("pty_output_gap");let xe=Buffer.from(he.dataBase64,"base64");if(_.bufferedAmount+xe.length>Ko)return!1;ye(xe),W=he.cursor}if(W!==le.nextCursor)ar("pty_output_gap");return!0}async function Ve(le,he){let xe;try{await Promise.race([e.emit(le,he),new Promise((Ke,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(Qt),he=f.request({jobId:l.jobId,action:"cancel",input:{}},le),xe,Ke=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,Ke]);if(le.aborted)ar("pty_cleanup_unconfirmed");return Fe(Le)}finally{le.removeEventListener("abort",xe)}}try{await new Promise((Le,Be)=>{let ke=setTimeout(()=>{x(),Be(new r("pty_relay_unavailable","Terminal pairing timed out."))},5000),Me=()=>{clearTimeout(ke),Be(new r("cancelled","Terminal pairing was cancelled."))};if(w.signal.addEventListener("abort",Me,{once:!0}),_.once("open",()=>{clearTimeout(ke),w.signal.removeEventListener("abort",Me),Le()}),w.signal.aborted)Me()}),f.assertCurrent(),D=!0,z=await qe({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 qe({jobId:l.jobId,action:"inspect",input:{after:W}})}if(z.state!=="running"||z.inputSequence!==0||z.leaseExpiresAtMs<=Date.now())ar("pty_not_ready");await Ve("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,Ke=!1;while(!w.signal.aborted){let Le=z.firstCursor>W+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 qe({jobId:l.jobId,action:"resize",input:{sequence:Rr,...or}}),z.inputSequence!==Rr)ar("job_input_sequence")}continue}let ke=ht(z)||Ke?void 0:R.shift();if(ke){B-=$o(ke);let Me=++G;try{z=await qe("data"in ke?{jobId:l.jobId,action:"input",input:{sequence:Me,dataBase64:ke.data.toString("base64")}}:{jobId:l.jobId,action:"resize",input:{sequence:Me,cols:ke.cols,rows:ke.rows}})}catch(rr){if(!(rr instanceof r)||rr.code!=="job_input_backpressure")throw rr;G-=1,R.unshift(ke),B+=$o(ke),Ke=!0;continue}if(z.inputSequence!==Me)ar("job_input_sequence")}else if(await new Promise((Me)=>{let rr=setTimeout(Me,Ke||!Be?10:50);if(S=()=>{clearTimeout(rr),Me()},w.signal.aborted||!Ke&&R.length)S()}),Ke=!1,S=()=>{},!w.signal.aborted&&Be)try{z=await qe({jobId:l.jobId,action:"inspect",input:{after:W}})}catch(Me){if(!J||!(Me instanceof r)||Me.code!=="cancelled")throw Me}}}catch(le){ve??=le}finally{if(re=!1,R.length=0,clearTimeout(j),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 Ve("pty.stopped",le)}catch(le){ve??=le}_.terminate()}if(ve)throw ve;if(e.signal.aborted)ar("cancelled");if(!z)ar("pty_cleanup_unconfirmed");return{receipt:Re(z)}}import{createHash as Ti,randomUUID as An}from"crypto";import{spawnSync as es}from"child_process";import{closeSync as Jo,constants as On,fstatSync as Di,fsyncSync as Ci,lstatSync as Ht,mkdirSync as Hi,mkdtempSync as rs,openSync as Xo,readFileSync as Ni,readdirSync as ts,realpathSync as Vr,rmSync as Pn,unlinkSync as Li}from"fs";import{createConnection as Bi}from"net";import{dirname as Wi,join as ot,sep as In}from"path";import{tmpdir as ns}from"os";var hr=new Map,Jr=new Map;function Ur(e,l){return Ti("sha256").update(JSON.stringify([e,l])).digest("hex")}function gt(e){try{Hi(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)||Vr(e)!==e)throw new r("hands_jobs_unavailable","Hands job state must be a private canonical directory.")}function zi(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 Ki(e){if(process.platform==="win32")return Ui();let l=e.map((f)=>{try{return Vr(f)}catch{return f}});for(let f of[()=>Ui(),()=>Vr("/dev/shm"),()=>Vr(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=Ur(e.root,e.runId),f=e.previousRuntimeDirectories?.find((x)=>zi(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(Ki(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 Gi=60000,Ji=5000;function Vi(e){if(process.platform==="win32")return qi(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 qi(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=Di(_);if(!w.isFile()||w.nlink!==1||!A(w)||w.size>4096)return null;let S=null;try{S=JSON.parse(Ni(_,"utf8"))}catch{}let x;if(S===null){if((l.now??Date.now)()-w.mtimeMs<Gi)return null;x={reason:"never_written",executorLaunchId:null}}else{let{version:B,scopeId:G,pid:W,createdAtMs:D,executorLaunchId:re}=S;if(B!==1||G!==e.scopeId||typeof re!=="string"||typeof W!=="number"||!Number.isSafeInteger(W)||W<1||W===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")}}))(W))x={reason:"owner_exited",executorLaunchId:re};else{let z=(l.startedAtMs??Vi)(W);if(z===null||z<=D+Ji)return null;x={reason:"pid_reused",executorLaunchId:re}}}let j=Ht(f);if(j.dev!==w.dev||j.ino!==w.ino)return null;Li(f);let R=Xo(e.journalDirectory,On.O_RDONLY);try{Ci(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=Ur(l.root,l.runId);if(hr.has(f)||l.operationId!==void 0&&Jr.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)Jr.set(l.operationId,_);return()=>{if(hr.get(_.key)===_)hr.delete(_.key);if(l.operationId!==void 0&&Jr.get(l.operationId)===_)Jr.delete(l.operationId);_.previews?.dispose();for(let w of _.terminals.values())w.abort()}}var Yi=5000,Xi=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)||!U(e.targetGeneration))l("Reason sent an invalid Hands rebind.");let f=Jr.get(e.operationId);if(!f||f.binding.root!==e.root)return l("No live Hands supervisor owns this operation.");for(let w=Date.now()+Yi;;){if(e.signal?.aborted)l("The Hands rebind was cancelled.");if(Jr.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,Xi))}if(Jr.get(e.operationId)!==f||hr.get(f.key)!==f)l("The Hands supervisor is no longer current.");let _=Ur(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?Jr.get(e.operationId):hr.get(Ur(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(Ur(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(Ur(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=Ur(e.root,e.runId),f=hr.get(l),_=f?.binding,w=_?.runId,S=_?.previewAuthority,x=_?.environment,j=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||!j||!R||!_.workspace)return B();let G=Object.freeze({..._.workspace}),W=bt(_),D=x.current(),re=()=>{if(hr.get(l)!==f||j.organization_id!==S.owner.organization_id||j.user_id!==S.owner.user_id||j.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!==W.generation||z.fenceId!==W.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!==W.generation||fe.binding.target_fence_id!==W.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!==W.generation||R.target_fence_id!==W.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,W.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:W.generation,fenceId:W.fenceId,executorLaunchId:W.executorLaunchId},request:(z,fe)=>_r(W,zr(JSON.stringify({...z,type:"job",version:2,generation:W.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(Ur(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 Zi=1e4,Qi=20,ea=Se/2,ra=Je/2,ta=(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||_>Zi))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,zr(JSON.stringify({...B,type:"job",version:2,generation:G.generation,id:An()})),f)},x=await S(w);if(_===void 0)return x;let j=Date.now()+_,R=x;while(R.ok&&["starting","running"].includes(R.job.state)&&R.job.output.length<ea&&ta(R.job)<ra&&!f.aborted&&Date.now()<j){if(await new Promise((B)=>setTimeout(B,Math.min(Qi,j-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||!U(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=Bi(e.socketPath),x="",j=!1,R,B=(W,D)=>{if(j)return;if(j=!0,clearTimeout(R),f.removeEventListener("abort",G),S.destroy(),W)w(W);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{Jt,H}from"./vm-hands-entry-lite-w29d7ey0.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{Io,P,Je,Se,Xe,ne,Ye,Vn,Ee,Qt,ae,U,L,ce,zr,qr,Kn}from"./vm-hands-entry-lite-sb7b4z8t.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-kmtz5h74.js";import{Cr,Ar,xn,uo,Ue,kn}from"./vm-hands-entry-lite-5tnma5qb.js";import{K}from"./vm-hands-entry-lite-xrqztkhv.js";import{ji}from"./vm-hands-entry-lite-xe0benev.js";import{p,ze,$t,ut,po,_e,we}from"./vm-hands-entry-lite-2hfrcr50.js";import{v,h,mo}from"./vm-hands-entry-lite-hfx1q0b0.js";import{E}from"./vm-hands-entry-lite-72nj66ab.js";import{tr}from"./vm-hands-entry-lite-t7kgebwg.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-b6gsggvp.js";var Ri=()=>{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),j=_[x]??x;return`Invalid input: expected ${S}, received ${j}`}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:Ri()}}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 Oi}from"crypto";import{isAbsolute as Bo,join as jo,relative as Mo,resolve as qt,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(Jt),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()}),xi=/^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(!xi.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(Fr(l,e))return!1;return!Fr(e,l)||E(jo(Wo,Mo(qt(e),qt(l))))}function Fr(e,l){let f=Mo(qt(e),qt(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 Oi("sha256").update(JSON.stringify(x)).digest("hex")}var Pi=4,Ii=[2375,2376,9222,9229];function mr(e){let l=new Set(Ii);for(let f of e){let _=new URL(f);l.add(Number(_.port||(["https:","wss:"].includes(_.protocol)?443:80)))}return l}function Gr(){throw new r("preview_unavailable","The live Hands preview binding is unavailable or stale.")}var Ai=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)Gr()}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 W=await j(R,B,G);if(W!=="moved")return W;let D=await j(R,B,G);return D==="moved"?null:D}async function j(R,B,G){try{w(e.authority.owner);let W=e.identity();if(!W||G.aborted||R.expiresAtMs<=Date.now()||R.expiresAtMs>e.expiresAtMs)return null;let D=B.opened,re=D!==void 0&&W.generation>D.generation,J=S(W);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())>Ai)return null}else if(!J||R.expiresAtMs>Date.parse(J.expires_at)||D&&(W.generation!==D.generation||W.fenceId!==D.fenceId))return null;let z=await e.inspect(R.jobId,G),fe=e.identity(),ve=fe&&S(fe);w(e.authority.owner);let be=J&&{generation:W.generation,fenceId:W.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!==W.generation||fe.fenceId!==W.fenceId||ve?.snapshot_id!==J?.snapshot_id||ve?.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!==W.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&&W.generation===R.generation&&W.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:W,deviceRelayUrl:D}=ut(R);if(G.aborted||W.expiresAtMs<=Date.now()||W.expiresAtMs>Date.now()+p.lifetimeMs||new URL(D).origin!==e.authority.relayOrigin)Gr();let re=_(W),J=f.get(re);if(J){if(!ze(J.binding,W)||J.relay!==D)Gr();if(await J.opened,!await $t(()=>J.port.check())||G.aborted||J.abort.signal.aborted)Gr();return{opened:!0,binding:W}}if(f.size>=Pi)Gr();let z=new AbortController,fe={},ve=we({binding:W,deniedPorts:e.authority.deniedPorts,readCurrentJob:()=>x(W,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:W,deviceRelayUrl:D,port:ve,signal:z.signal}),Fe={binding:W,relay:D,abort:z,port:ve,opened:Re};f.set(re,Fe);let qe=()=>{if(G.removeEventListener("abort",be),l.signal.removeEventListener("abort",be),f.get(re)===Fe)f.delete(re)};try{if((await Re).closed.then(qe),G.removeEventListener("abort",be),w(B),z.signal.aborted||!await $t(()=>ve.check()))Gr();return{opened:!0,binding:W}}catch{z.abort(),qe(),Gr()}},async close(R,B){w(B);let{binding:G}=po(R),W=f.get(_(G));if(!W||!ze(W.binding,G))Gr();return W.abort.abort(),await W.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*Ye;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)<=Ee))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 j=Date.parse(e.expires_at);if(!Number.isSafeInteger(j)||j<=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(j,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 j=setTimeout(x,Math.max(1,l.leaseExpiresAtMs-Date.now())),R=[],B=0,G=0,W=0,D=!1,re=!1,J=!1,z,fe,ve,be=(le)=>{ve=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 Ke=R.at(-1),Le=he&&Ke!==void 0&&"data"in Ke&&Ke.data.length+xe.length<=ne;if(xe.length>ne||B+xe.length>Vn){be("pty_input_backpressure");return}if(Le)Ke.data=Buffer.concat([Ke.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((ke)=>Number.isSafeInteger(ke)&&ke>=1&&ke<=Ee))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 Kn(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 qe(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>W+1)W=le.firstCursor-1;for(let he of le.pty.output){if(he.cursor<=W)continue;if(he.cursor!==W+1)ar("pty_output_gap");let xe=Buffer.from(he.dataBase64,"base64");if(_.bufferedAmount+xe.length>Ko)return!1;ye(xe),W=he.cursor}if(W!==le.nextCursor)ar("pty_output_gap");return!0}async function Ve(le,he){let xe;try{await Promise.race([e.emit(le,he),new Promise((Ke,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(Qt),he=f.request({jobId:l.jobId,action:"cancel",input:{}},le),xe,Ke=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,Ke]);if(le.aborted)ar("pty_cleanup_unconfirmed");return Fe(Le)}finally{le.removeEventListener("abort",xe)}}try{await new Promise((Le,Be)=>{let ke=setTimeout(()=>{x(),Be(new r("pty_relay_unavailable","Terminal pairing timed out."))},5000),Me=()=>{clearTimeout(ke),Be(new r("cancelled","Terminal pairing was cancelled."))};if(w.signal.addEventListener("abort",Me,{once:!0}),_.once("open",()=>{clearTimeout(ke),w.signal.removeEventListener("abort",Me),Le()}),w.signal.aborted)Me()}),f.assertCurrent(),D=!0,z=await qe({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 qe({jobId:l.jobId,action:"inspect",input:{after:W}})}if(z.state!=="running"||z.inputSequence!==0||z.leaseExpiresAtMs<=Date.now())ar("pty_not_ready");await Ve("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,Ke=!1;while(!w.signal.aborted){let Le=z.firstCursor>W+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 qe({jobId:l.jobId,action:"resize",input:{sequence:Rr,...or}}),z.inputSequence!==Rr)ar("job_input_sequence")}continue}let ke=ht(z)||Ke?void 0:R.shift();if(ke){B-=$o(ke);let Me=++G;try{z=await qe("data"in ke?{jobId:l.jobId,action:"input",input:{sequence:Me,dataBase64:ke.data.toString("base64")}}:{jobId:l.jobId,action:"resize",input:{sequence:Me,cols:ke.cols,rows:ke.rows}})}catch(rr){if(!(rr instanceof r)||rr.code!=="job_input_backpressure")throw rr;G-=1,R.unshift(ke),B+=$o(ke),Ke=!0;continue}if(z.inputSequence!==Me)ar("job_input_sequence")}else if(await new Promise((Me)=>{let rr=setTimeout(Me,Ke||!Be?10:50);if(S=()=>{clearTimeout(rr),Me()},w.signal.aborted||!Ke&&R.length)S()}),Ke=!1,S=()=>{},!w.signal.aborted&&Be)try{z=await qe({jobId:l.jobId,action:"inspect",input:{after:W}})}catch(Me){if(!J||!(Me instanceof r)||Me.code!=="cancelled")throw Me}}}catch(le){ve??=le}finally{if(re=!1,R.length=0,clearTimeout(j),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 Ve("pty.stopped",le)}catch(le){ve??=le}_.terminate()}if(ve)throw ve;if(e.signal.aborted)ar("cancelled");if(!z)ar("pty_cleanup_unconfirmed");return{receipt:Re(z)}}import{createHash as Ti,randomUUID as An}from"crypto";import{spawnSync as es}from"child_process";import{closeSync as Jo,constants as On,fstatSync as Di,fsyncSync as Ci,lstatSync as Ht,mkdirSync as Hi,mkdtempSync as rs,openSync as Xo,readFileSync as Ni,readdirSync as ts,realpathSync as Vr,rmSync as Pn,unlinkSync as Li}from"fs";import{createConnection as Bi}from"net";import{dirname as Wi,join as ot,sep as In}from"path";import{tmpdir as ns}from"os";var hr=new Map,Jr=new Map;function Ur(e,l){return Ti("sha256").update(JSON.stringify([e,l])).digest("hex")}function gt(e){try{Hi(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)||Vr(e)!==e)throw new r("hands_jobs_unavailable","Hands job state must be a private canonical directory.")}function zi(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 Ki(e){if(process.platform==="win32")return Ui();let l=e.map((f)=>{try{return Vr(f)}catch{return f}});for(let f of[()=>Ui(),()=>Vr("/dev/shm"),()=>Vr(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=Ur(e.root,e.runId),f=e.previousRuntimeDirectories?.find((x)=>zi(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(Ki(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 Gi=60000,Ji=5000;function Vi(e){if(process.platform==="win32")return qi(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 qi(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=Di(_);if(!w.isFile()||w.nlink!==1||!A(w)||w.size>4096)return null;let S=null;try{S=JSON.parse(Ni(_,"utf8"))}catch{}let x;if(S===null){if((l.now??Date.now)()-w.mtimeMs<Gi)return null;x={reason:"never_written",executorLaunchId:null}}else{let{version:B,scopeId:G,pid:W,createdAtMs:D,executorLaunchId:re}=S;if(B!==1||G!==e.scopeId||typeof re!=="string"||typeof W!=="number"||!Number.isSafeInteger(W)||W<1||W===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")}}))(W))x={reason:"owner_exited",executorLaunchId:re};else{let z=(l.startedAtMs??Vi)(W);if(z===null||z<=D+Ji)return null;x={reason:"pid_reused",executorLaunchId:re}}}let j=Ht(f);if(j.dev!==w.dev||j.ino!==w.ino)return null;Li(f);let R=Xo(e.journalDirectory,On.O_RDONLY);try{Ci(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=Ur(l.root,l.runId);if(hr.has(f)||l.operationId!==void 0&&Jr.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)Jr.set(l.operationId,_);return()=>{if(hr.get(_.key)===_)hr.delete(_.key);if(l.operationId!==void 0&&Jr.get(l.operationId)===_)Jr.delete(l.operationId);_.previews?.dispose();for(let w of _.terminals.values())w.abort()}}var Yi=5000,Xi=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)||!U(e.targetGeneration))l("Reason sent an invalid Hands rebind.");let f=Jr.get(e.operationId);if(!f||f.binding.root!==e.root)return l("No live Hands supervisor owns this operation.");for(let w=Date.now()+Yi;;){if(e.signal?.aborted)l("The Hands rebind was cancelled.");if(Jr.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,Xi))}if(Jr.get(e.operationId)!==f||hr.get(f.key)!==f)l("The Hands supervisor is no longer current.");let _=Ur(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?Jr.get(e.operationId):hr.get(Ur(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(Ur(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(Ur(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=Ur(e.root,e.runId),f=hr.get(l),_=f?.binding,w=_?.runId,S=_?.previewAuthority,x=_?.environment,j=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||!j||!R||!_.workspace)return B();let G=Object.freeze({..._.workspace}),W=bt(_),D=x.current(),re=()=>{if(hr.get(l)!==f||j.organization_id!==S.owner.organization_id||j.user_id!==S.owner.user_id||j.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!==W.generation||z.fenceId!==W.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!==W.generation||fe.binding.target_fence_id!==W.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!==W.generation||R.target_fence_id!==W.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,W.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:W.generation,fenceId:W.fenceId,executorLaunchId:W.executorLaunchId},request:(z,fe)=>_r(W,zr(JSON.stringify({...z,type:"job",version:2,generation:W.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(Ur(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 Zi=1e4,Qi=20,ea=Se/2,ra=Je/2,ta=(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||_>Zi))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,zr(JSON.stringify({...B,type:"job",version:2,generation:G.generation,id:An()})),f)},x=await S(w);if(_===void 0)return x;let j=Date.now()+_,R=x;while(R.ok&&["starting","running"].includes(R.job.state)&&R.job.output.length<ea&&ta(R.job)<ra&&!f.aborted&&Date.now()<j){if(await new Promise((B)=>setTimeout(B,Math.min(Qi,j-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||!U(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=Bi(e.socketPath),x="",j=!1,R,B=(W,D)=>{if(j)return;if(j=!0,clearTimeout(R),f.removeEventListener("abort",G),S.destroy(),W)w(W);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",(W)=>{if(x+=W,Buffer.byteLength(x)>Xe)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 W=qr(x.trim());if(W.id!==l.id||W.generation!==e.generation||W.ok&&W.job.jobId!==l.jobId)throw Error("identity");B(void 0,W)}catch{B(new r("hands_job_result_unknown","Hands job response identity or shape was invalid."))}}),S.once("close",()=>{if(!j)B(new r("hands_job_result_unknown","Hands job control closed before an acknowledged result."))})})}function Zo(e){let l=Vr(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=Ur(l,e.runId),x=hr.get(S),j=x?.binding;if(!j?.environment||!j.workspace||j.localGithubConfinement!==!0)throw Error("local_device_gh_confinement_unavailable");let R=j.environment.current(),B=()=>{w();let W=j.environment.current(),D=bt(j);if(hr.get(S)!==x||W.github_auth!=="local_gh"||W.run_id!==j.runId||f.runId!==e.runId||W.device_id!==f.deviceId||W.root_id!==f.rootId||String(W.binding.root_grant_revision)!==f.rootRevision||W.binding.target_generation!==f.generation||W.binding.target_fence_id!==f.fenceId||D.generation!==f.generation||D.fenceId!==f.fenceId||W.snapshot_id!==R.snapshot_id||W.revision!==R.revision)throw Error("local_device_gh_authority_changed")};B();let G=ie(l,j.workspace);return{root:G.boundary,signal:e.signal,deadlineMs:_,privateDirectory:Wi(j.environment.path),repoPath:G.path,readOnly:f.readOnly,forbiddenSecretValues:Object.values(R.variables),secretNames:(W)=>Object.entries(R.variables).filter(([,D])=>D.trim()===W.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=Vr(e.root),x=Ht(S),j=Date.parse(e.leaseUntil);if(!Number.isFinite(j)||j<=Date.now())throw Error("local_device_gh_lease_expired");let R=Vr(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()>=j)throw Error("local_device_gh_lease_expired");let W=Ht(e.root);if(W.isSymbolicLink()||W.dev!==x.dev||W.ino!==x.ino||Vr(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:j,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),na=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 oa(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:na.optional()}).refine((e)=>e.github_auth!=="local_gh"||e.git===null,"conflicting git authority").refine((e)=>oa(e)<=V.snapshotBytes,"snapshot too large");import{spawn as sa}from"child_process";import{basename as ia,isAbsolute as Iu}from"path";var aa=0,ps=120000,_s=15000,ca=65536;function Dn(e=process.execPath,l=process.argv[1]){let f=ia(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??sa,w=e.now??Date.now,S=null,x=0,j=!1,R=(G)=>{try{G.kill("SIGKILL")}catch{}},B=()=>{if(j)return;if(S&&w()-x<ps-_s)return;if(S){let W=S;S=null,R(W)}let G;try{G=_(l,[...f,"__device","__hands-worker","--handoff-fd",String(aa)],{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",(W,D)=>{if(S!==G)return;S=null,e.log?.("hands.worker_prespawn_exited",{exit_code:W,exit_signal:D})}),e.log?.("hands.worker_prespawned",{pid:G.pid??null})};return{arm:B,take(G){let W=S;if(!W||j)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=W.stdin,ve={configPath:D,cwd:J,env:Object.fromEntries(Object.entries(re).filter((Re)=>typeof Re[1]==="string"))},be=JSON.stringify(ve);if(W.exitCode!==null||W.signalCode!==null||!fe||fe.destroyed||w()-x>=ps-_s||Buffer.byteLength(be,"utf8")>ca)return R(W),null;return fe.on("error",()=>{return}),fe.end(be),W.once("exit",()=>{B()}),e.log?.("hands.worker_prespawn_taken",{pid:W.pid??null}),W},adopt(G){G.once("exit",()=>{B()})},close(){if(j=!0,S)R(S);S=null}}}import{accessSync as _a,constants as ma,statSync as ha}from"fs";import{homedir as ga,tmpdir as ba,userInfo as wa}from"os";import{delimiter as ya,win32 as va}from"path";var da=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 la=["BUN_CONFIG_","BUN_INSPECT","DYLD_","NODE_DEBUG"],ua=new Set(["BUN_INSTALL"]);var fa=/^--(?:max-old-space-size|max-semi-space-size|stack-size)=\d{1,9}$/;function pa(e){return(e??"").split(/\s+/).filter(Boolean).every((l)=>fa.test(l.replaceAll("_","-")))}function ms(e){return Object.keys(e).filter((l)=>da.has(l)&&!(l==="NODE_OPTIONS"&&pa(e[l]))||la.some((f)=>l.startsWith(f))||l.startsWith("BUN_")&&!ua.has(l)).sort()}var ka=new Set(["HOME","PATH","PWD","OLDPWD","SHLVL","_","TMPDIR","TMP","TEMP","SHELL","BASH_ENV","ENV","ZDOTDIR","PROMPT_COMMAND","IFS","CDPATH","GLOBIGNORE","SHELLOPTS","BASHOPTS","NODE_PATH"]),Sa=/^(?:ARA_|REASON_|PI_|GIT_|GH_|GITHUB_|LD_|DYLD_|BUN_|BASH_FUNC_|SSH_)/,Ea=/TOKEN|SECRET|PASSW|PASSPHRASE|CREDENTIAL|API_?KEY|ACCESS_?KEY|PRIVATE_?KEY|AUTH/i,Ra=/^[A-Za-z_][A-Za-z0-9_]*$/;function wr(e=process.env){let l=(w)=>{if(!(process.platform==="win32"?va.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&&Ra.test(S)&&!f.has(S)&&!ka.has(S)&&!Sa.test(S)&&!Ea.test(S)}).sort(([w],[S])=>w.localeCompare(S)).slice(0,512));return{home:l(e.HOME||(process.platform==="win32"?e.USERPROFILE:void 0)||ga()),path:((w)=>process.platform==="win32"?kn(w):w)(Ar(e.PATH??"").join(ya)||Cr),temporaryDirectory:l(e.TMPDIR||e.TMP||e.TEMP||ba()),variables:_}}function br(e=process.env,l=()=>wa().shell){if(process.platform==="win32")return se();let f=(w)=>{if(!w||!/^\/[A-Za-z0-9._/-]*\/(?:bash|zsh)$/.test(w))return!1;try{return _a(w,ma.X_OK),ha(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 Oa}from"fs/promises";var xa=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=xa,open:f=(_)=>Oa(_)}={}){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 sc,closeSync as ic,constants as zn,fstatSync as ac,lstatSync as Ns,openSync as cc,readSync as dc,realpathSync as $n,unlinkSync as lc}from"fs";import{lookup as uc}from"dns/promises";import{createRequire as fc}from"module";import{request as pc}from"http";import{request as _c}from"https";import it from"net";import{platform as Ws}from"os";import{basename as mc,extname as hc,isAbsolute as Ls,relative as Gn,resolve as kt,sep as Jn}from"path";var gs=String.raw`
|
|
5
5
|
async (roots) => {
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{_,Ho,ke}from"./vm-hands-entry-lite-4anjdcth.js";import{l,Gt,Ke,Lr,Kt,Mr,ht}from"./vm-hands-entry-lite-w29d7ey0.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,Gt,Ke,Lr,Kt,Mr,ht}from"./vm-hands-entry-lite-w29d7ey0.js";import{bt,ar}from"./vm-hands-entry-lite-07apxfh8.js";import{fn}from"./vm-hands-entry-lite-s4txp2pr.js";import{F,m,te,He}from"./vm-hands-entry-lite-s74mc4mm.js";import{j}from"./vm-hands-entry-lite-b0qd73a5.js";import{Bo}from"./vm-hands-entry-lite-95zqwfjf.js";import{xe,Ze,Xn,Vr}from"./vm-hands-entry-lite-ykfm3bm1.js";import{f,v,h}from"./vm-hands-entry-lite-hfx1q0b0.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 Uh,existsSync as Fh,mkdirSync as jh,openSync as qh,readdirSync as zh,realpathSync as pe,rmSync as Kh}from"fs";import{dirname as Jh,join as J,resolve as Gh}from"path";import{createHash as It}from"crypto";import{platform as Ot}from"os";import{join as Mt}from"path";var Tt=g("store",[c({version:i(1),store:i("keychain")}),c({version:i(1),store:i("file"),api_key:t().min(1).max(4096)})]),We=(e)=>Mt(e,"api-key.json");function Ne(e){let r=It("sha256").update(`reason-connect-api-key
|
|
3
3
|
${e}`).digest("hex");return new Ke(Gt(),Ot(),r)}function we(e,r=Ne(e)){if(!f(We(e)))return null;let p=Tt.parse(JSON.parse(h(We(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 Jo,rmSync as Go}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 lo=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 Lr(m(e))}function Ht(e){return new Ke(Gt(),Nt(),$t(e))}function $t(e){let r=Ft(e);return Wt("sha256").update(`reason-worker
|
|
4
4
|
${r?.directory??m(e)}`).digest("hex")}var Bt="keychain-scope.json";var Ut=c({version:i(1),directory:t().min(1),devicePublicKey:t().min(1)});function Ft(e){let r=W(m(e),Bt);if(!f(r))return null;let p=Ut.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=Mr(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 jt=c({version:i(1),drained:d(),revoked:d()});function N(e){let r=w(e).control;return f(r)?jt.parse(JSON.parse(h(r))):{version:1,drained:!1,revoked:!1}}var zt=c({read:d(),write:d(),execute:d(),discover_environment:d(),expose_mcp:i(!1)}),Vt=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:zt,execution_mode:s(["confined","host"]).default("confined")}),folders:u(c({path_fingerprint:t().regex(/^[a-f0-9]{64}$/)})).min(1).max(31).optional()}),So=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 jo=c({version:i(1),install_id:k(),fingerprint_key:t().regex(/^[a-f0-9]{64}$/)}),qo=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 zo=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 je=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 qe(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:M,account:I})=>{let A=!1,T=null,D=!1,he=null;try{A=M?N(M).revoked:!1,T=M&&!A?B(M):null;let Le=M?ht(w(M).daemon):null;D=r&&!!T&&Le?.state==="connected",he=D?Kt(Le,T):null}catch{}return{...he?{permission_recovery:he}:{},organization_id:C,device_id:T?.deviceId??null,name:S?.names?.[C]??null,root:T?.roots[0]?{id:T.roots[0].id,permissions:T.roots[0].permissions}:null,state:A?"removed":D?"connected":"not_running",blocked:!I&&!A&&!D&&(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 ji,lstatSync as Xe,mkdtempSync as qi,realpathSync as sr,rmdirSync as zi,rmSync as Ki,unlinkSync as Vi}from"fs";import{createConnection as cr,createServer as Gi}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()}),ta=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 ra=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="",M=!1,I=(A,T)=>{if(M)return;if(M=!0,E.destroy(),T)P(T);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 la={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 qa=Bo(br(process.execPath));var hs=Buffer.from([0,255,3,4]);import{execFile as nn}from"child_process";import{promisify as on}from"util";var Er=/#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=Er.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}",Pr=new RegExp(`^/media/pr-screenshots/(${ct})/(${ct})/([a-z0-9][a-z0-9._-]*)\\.(png|jpe?g|gif|webp|webm|mp4)$`,"i");var Cr=new Set(["png","jpg","jpeg","gif","webp"]),Ar=new Set(["webm","mp4"]);function xr(e){if(!e)return null;try{return new URL(e).origin}catch{return null}}function Ir(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=xr(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&&!Ir(p.hash))return null;let S=Pr.exec(p.pathname);if(!S)return null;let P=S[1]?.toLowerCase(),E=S[2]?.toLowerCase(),C=S[3]?.toLowerCase(),M=S[4]?.toLowerCase();if(!P||!E||!C||!M)return null;let I=Cr.has(M)?"image":Ar.has(M)?"video":null;if(!I)return null;let A=/^(before|after)[\s:_-]+/.exec(C),T=p.pathname.replace(/^\/media\//,"");return{url:p.toString(),storagePath:T,runId:P,artifactId:E,fileName:`${C}.${M}`,kind:I,phase:A?.[1]==="before"||A?.[1]==="after"?A[1]:null}}var Or=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,dt=(e)=>Boolean(e&&typeof e==="object"&&!Array.isArray(e)),K=()=>{throw Error("cloud_browser_media_request_invalid")};function Pe(e){if(!dt(e)||Object.keys(e).some((S)=>!["runId","configuredMediaOrigin","media"].includes(S))||typeof e.runId!=="string"||!Or.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(!dt(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}$/),mt=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:mt,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),Dr=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"],Nr=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:mt,repositoryId:ce,headSha:t().regex(/^[a-f0-9]{40}$/),sha256:X,sizeBytes:o().int().min(128).max(10485760),contentType:i("video/webm")}).strict(),pt=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}$/),Hr=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:pt,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:pt,observedActor:fe,bodySha256:X}),$r=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)),Br=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}}),Ur=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:Br}).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 Fr=n({requestId:x,command:Ur}).strict();var jr={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},ut={type:"string",format:"uuid",description:"capture_context_id from tools.pr.prepareProof."},ft={type:"integer",minimum:1,description:"An already-owned tab's id."},_c={...jr,oneOf:[{type:"object",required:["action","context_id","tab_id"],additionalProperties:!1,properties:{action:{type:"string",const:"screenshot"},context_id:ut,tab_id:ft}},{type:"object",required:["action","context_id","tab_id","seconds"],additionalProperties:!1,properties:{action:{type:"string",const:"start_video"},context_id:ut,tab_id:ft,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 qr=String.raw`async (media) => {
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
var tr={name:"github-native-engineer-device-worker-production",version:"0.2.
|
|
2
|
+
var tr={name:"github-native-engineer-device-worker-production",version:"0.2.551",private:!0,type:"module",engines:{node:">=22",bun:">=1.3.0"},workspaces:["../../packages/runtime-distribution"],dependencies:{"@agentclientprotocol/sdk":"1.9.0","@anthropic-ai/sandbox-runtime":"^0.0.80","@earendil-works/pi-tui":"1.0.0","@reason/runtime-distribution":"workspace:*",diff:"8.0.4","open-browser-use-sdk":"0.1.42","playwright-core":"1.60.0",toml:"5.0.1",zod:"^4.4.3"},overrides:{"@hono/node-server":"^1.19.15","@earendil-works/pi-agent-core":"1.0.0","@earendil-works/pi-ai":"1.0.0","@earendil-works/pi-coding-agent":"1.0.0","@earendil-works/chord":"1.0.0","@earendil-works/pi-codemode":"1.0.0","@earendil-works/pi-mcp":"1.0.0","@earendil-works/pi-telemetry":"1.0.0","@earendil-works/pi-tui":"1.0.0","brace-expansion":"2.1.7",axios:"^1.20.0","basic-ftp":"^6.2.1","@grpc/grpc-js":"^1.14.5",browserslist:"^4.28.8","engine.io":"^6.6.7","fast-uri":"^3.1.8",hono:"^4.13.7","ip-address":"^10.7.4",nanoid:"^3.3.18",dompurify:"^3.4.17",postcss:"^8.5.23",qs:"^6.16.0","shell-quote":"^1.11.0","socket.io-parser":"^4.2.7",tmp:"^0.2.7",toml:"^5.0.1",undici:"^8.10.2",ws:"^8.21.0","js-yaml":"^4.3.2","@modelcontextprotocol/sdk":"^1.31.0","proxy-addr":"^2.0.8","source-map-js":"^1.2.2"}};
|
|
3
3
|
export{tr};
|