humanish 0.140.0 → 0.142.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (155) hide show
  1. package/ARCHITECTURE.md +1 -0
  2. package/CHANGELOG.md +23 -0
  3. package/README.md +2 -0
  4. package/dist/actors/codex/restricted-participant.js +1 -1
  5. package/dist/actors/computer-use/external-handoff.d.ts +22 -0
  6. package/dist/actors/computer-use/external-handoff.js +83 -0
  7. package/dist/actors/computer-use/loop/observation.d.ts +7 -0
  8. package/dist/actors/computer-use/loop/observation.js +17 -1
  9. package/dist/actors/computer-use/loop/types.d.ts +6 -0
  10. package/dist/analysis/admission.d.ts +8 -0
  11. package/dist/analysis/admission.js +15 -4
  12. package/dist/analysis/analysis-limits.d.ts +6 -0
  13. package/dist/analysis/analysis-limits.js +6 -0
  14. package/dist/analysis/analysis-lock.d.ts +8 -0
  15. package/dist/analysis/analysis-lock.js +129 -0
  16. package/dist/analysis/automatic-completion.js +7 -0
  17. package/dist/analysis/automatic-config.d.ts +5 -2
  18. package/dist/analysis/automatic-config.js +23 -8
  19. package/dist/analysis/automatic.js +13 -7
  20. package/dist/analysis/execute.d.ts +17 -6
  21. package/dist/analysis/execute.js +37 -19
  22. package/dist/analysis/gemini-wire.d.ts +8 -0
  23. package/dist/analysis/gemini-wire.js +165 -0
  24. package/dist/analysis/image-tokens.d.ts +4 -2
  25. package/dist/analysis/image-tokens.js +24 -3
  26. package/dist/analysis/job.d.ts +2 -0
  27. package/dist/analysis/job.js +7 -2
  28. package/dist/analysis/openai-wire.d.ts +5 -0
  29. package/dist/analysis/openai-wire.js +101 -0
  30. package/dist/analysis/provider.d.ts +15 -7
  31. package/dist/analysis/provider.js +21 -101
  32. package/dist/analysis/recording-ended.d.ts +16 -0
  33. package/dist/analysis/recording-ended.js +29 -0
  34. package/dist/analysis/responses.d.ts +3 -0
  35. package/dist/analysis/responses.js +19 -0
  36. package/dist/analysis/service.d.ts +1 -3
  37. package/dist/analysis/service.js +34 -53
  38. package/dist/analysis/source.d.ts +1 -1
  39. package/dist/analysis/types.d.ts +8 -2
  40. package/dist/analysis/validation.d.ts +1 -0
  41. package/dist/analysis/validation.js +13 -12
  42. package/dist/browser-control/protocol.d.ts +8 -0
  43. package/dist/browser-control/protocol.js +21 -0
  44. package/dist/cli/commands/analysis-signals.d.ts +10 -4
  45. package/dist/cli/commands/analysis-signals.js +28 -6
  46. package/dist/cli/commands/analyze.js +9 -7
  47. package/dist/cli/commands/observe.js +26 -1
  48. package/dist/cli/commands/run-command.d.ts +1 -1
  49. package/dist/cli/commands/run-command.js +12 -0
  50. package/dist/cli/commands/runs.js +8 -2
  51. package/dist/cli/commands/study-remote.d.ts +13 -0
  52. package/dist/cli/commands/study-remote.js +125 -0
  53. package/dist/cli/commands/study-route-computer-use.js +28 -4
  54. package/dist/cli/commands/study-route-scripted.js +3 -2
  55. package/dist/cli/commands/study-route-shared-world.js +3 -2
  56. package/dist/cli/commands/study-route-terminal.js +3 -2
  57. package/dist/cli/commands/study-run.js +34 -0
  58. package/dist/cli/commands/watch.js +5 -0
  59. package/dist/cli/doctor.js +7 -2
  60. package/dist/cli/findings.d.ts +30 -0
  61. package/dist/cli/findings.js +114 -15
  62. package/dist/cli/io.d.ts +8 -0
  63. package/dist/cli/io.js +3 -1
  64. package/dist/evidence/browser-hygiene.d.ts +12 -1
  65. package/dist/evidence/browser-hygiene.js +45 -2
  66. package/dist/feedback/export-bundle.js +1 -1
  67. package/dist/guest/external-links.d.ts +14 -0
  68. package/dist/guest/external-links.js +48 -0
  69. package/dist/guest/runtime-desktop.js +5 -2
  70. package/dist/keys/key-resolution.d.ts +10 -0
  71. package/dist/keys/key-resolution.js +33 -5
  72. package/dist/observer/data.d.ts +4 -0
  73. package/dist/observer/listen.d.ts +7 -2
  74. package/dist/observer/listen.js +10 -4
  75. package/dist/observer/render.d.ts +2 -0
  76. package/dist/observer/render.js +1 -1
  77. package/dist/observer/run-routes.js +12 -3
  78. package/dist/observer-app.html +2 -2
  79. package/dist/remote/launch.d.ts +53 -0
  80. package/dist/remote/launch.js +320 -0
  81. package/dist/remote/observer-proxy.d.ts +11 -0
  82. package/dist/remote/observer-proxy.js +66 -0
  83. package/dist/remote/plan.d.ts +35 -0
  84. package/dist/remote/plan.js +114 -0
  85. package/dist/remote/reattach.d.ts +17 -0
  86. package/dist/remote/reattach.js +81 -0
  87. package/dist/remote/runner.d.ts +68 -0
  88. package/dist/remote/runner.js +216 -0
  89. package/dist/routes/computer-use/e2b-desktop/desktop.js +27 -17
  90. package/dist/routes/computer-use/e2b-desktop/start.js +1 -1
  91. package/dist/routes/computer-use/e2b-desktop/teardown.js +1 -1
  92. package/dist/routes/computer-use/in-process-desktop.js +2 -2
  93. package/dist/routes/computer-use/live-phase.js +1 -1
  94. package/dist/routes/computer-use/setup.js +2 -2
  95. package/dist/routes/computer-use/types.d.ts +2 -0
  96. package/dist/routes/scripted/types.d.ts +2 -0
  97. package/dist/routes/shared-world/route.js +1 -1
  98. package/dist/routes/shared-world/types.d.ts +2 -0
  99. package/dist/routes/terminal/types.d.ts +2 -0
  100. package/dist/run/costs.d.ts +2 -1
  101. package/dist/run/display.d.ts +6 -1
  102. package/dist/run/display.js +11 -0
  103. package/dist/run/host-suspension.js +4 -1
  104. package/dist/run/preflight-receipts.d.ts +3 -12
  105. package/dist/run/preflight-receipts.js +7 -67
  106. package/dist/run/pricing.d.ts +13 -1
  107. package/dist/run/pricing.js +50 -4
  108. package/dist/run/process-owner.d.ts +28 -0
  109. package/dist/run/process-owner.js +83 -0
  110. package/dist/run/projection.js +1 -1
  111. package/dist/run/reclaim.d.ts +6 -0
  112. package/dist/run/reclaim.js +32 -2
  113. package/dist/run/results.d.ts +1 -1
  114. package/dist/run/route-shell.js +1 -1
  115. package/dist/run/run-cost.d.ts +2 -1
  116. package/dist/run/run-cost.js +6 -1
  117. package/dist/run/run-index.d.ts +3 -1
  118. package/dist/run/run-index.js +23 -11
  119. package/dist/run/run.d.ts +29 -5
  120. package/dist/run/run.js +43 -17
  121. package/dist/run/sandbox-creates.d.ts +10 -3
  122. package/dist/run/sandbox-creates.js +48 -6
  123. package/dist/run/status.d.ts +57 -2
  124. package/dist/run/status.js +87 -1
  125. package/dist/run/stored-runs.d.ts +3 -0
  126. package/dist/run/stored-runs.js +9 -4
  127. package/dist/run-study.d.ts +5 -0
  128. package/dist/study/doctor.js +14 -1
  129. package/dist/study/requirements.d.ts +1 -1
  130. package/dist/study/requirements.js +8 -6
  131. package/dist/study/route-inputs.js +4 -0
  132. package/dist/study/run-study-events.d.ts +8 -2
  133. package/dist/study/run-study-events.js +9 -2
  134. package/dist/substrates/e2b/base-module.d.ts +3 -0
  135. package/dist/substrates/e2b/base-module.js +40 -0
  136. package/dist/substrates/e2b/desktop-browser.d.ts +1 -1
  137. package/dist/substrates/e2b/desktop-browser.js +27 -7
  138. package/dist/substrates/e2b/desktop-executor.d.ts +7 -0
  139. package/dist/substrates/e2b/desktop-executor.js +3 -0
  140. package/dist/substrates/e2b/desktop-handoff.d.ts +22 -0
  141. package/dist/substrates/e2b/desktop-handoff.js +86 -0
  142. package/dist/substrates/e2b/sdk.d.ts +24 -0
  143. package/dist/substrates/e2b/sdk.js +5 -1
  144. package/dist/substrates/e2b/shell-only.d.ts +5 -0
  145. package/dist/substrates/e2b/shell-only.js +27 -0
  146. package/dist/substrates/local/runtime-release.js +8 -8
  147. package/dist/substrates/modal/sandbox.js +27 -28
  148. package/dist/substrates/modal/sdk.d.ts +7 -0
  149. package/dist/tui-app.js +115 -115
  150. package/docs/architecture/observer.md +7 -3
  151. package/docs/contracts/schemas.md +24 -3
  152. package/docs/contracts/study-analysis.md +52 -4
  153. package/docs/product/automatic-analysis.md +55 -9
  154. package/package.json +2 -2
  155. package/skills/humanish/SKILL.md +118 -5
@@ -0,0 +1,81 @@
1
+ // Coming back to a remote run whose launcher let it go (a closed terminal): find its runner from
2
+ // the run directory here, serve its live Observer again and follow it to the end, as the launcher
3
+ // would have.
4
+ import { readContainedRegularFile } from "../run/contained-output.js";
5
+ import { bindExistingRunArtifactPaths } from "../run/paths.js";
6
+ import { isSandboxProviderId, parseSandboxReceipts, SANDBOX_RECEIPTS_ARTIFACT, } from "../run/sandbox-receipts.js";
7
+ import { loadE2BBaseModule } from "../substrates/e2b/base-module.js";
8
+ import { e2bConnection } from "../substrates/e2b/connection.js";
9
+ import { isSandboxNotFoundError } from "../substrates/e2b/sdk.js";
10
+ import { loadModalShellModule } from "../substrates/modal/sandbox.js";
11
+ import { followRemoteRun, watchSignals } from "./launch.js";
12
+ import { serveObserverProxy } from "./observer-proxy.js";
13
+ import { RUNNER_OBSERVER_PORT, runnerOf } from "./runner.js";
14
+ /**
15
+ * The remote run `runId` names, when its directory here has a remote.json and no run.json yet;
16
+ * undefined for any other run, which the Observer serves from its files as before.
17
+ */
18
+ export async function remoteRunHere(cwd, runId) {
19
+ let paths;
20
+ try {
21
+ paths = await bindExistingRunArtifactPaths(cwd, runId);
22
+ }
23
+ catch {
24
+ return undefined;
25
+ }
26
+ if ((await readText(paths, "run.json")) !== undefined)
27
+ return undefined;
28
+ const record = await readText(paths, "remote.json");
29
+ if (record === undefined)
30
+ return undefined;
31
+ const provider = JSON.parse(record).provider;
32
+ if (typeof provider !== "string" || !isSandboxProviderId(provider))
33
+ return undefined;
34
+ const journal = (await readText(paths, SANDBOX_RECEIPTS_ARTIFACT)) ?? "";
35
+ // Until the run is copied back, this directory's journal holds one receipt: the runner's, the
36
+ // only sandbox this machine creates for a remote run.
37
+ const [runner, ...others] = parseSandboxReceipts(journal);
38
+ if (runner === undefined || others.length > 0)
39
+ return undefined;
40
+ return { paths, runId, provider, runnerId: runner.sandboxId };
41
+ }
42
+ async function readText(root, file) {
43
+ const read = await readContainedRegularFile(root, file, 16 * 1024 * 1024);
44
+ return read.status === "read" ? Buffer.from(read.bytes).toString("utf8") : undefined;
45
+ }
46
+ /** Reconnect to `run`'s runner, serve its Observer on 127.0.0.1:`port` and follow it to the end. */
47
+ export async function reattachRemoteRun(context, run, port) {
48
+ const module = run.provider === "modal" ? await loadModalShellModule(context.env) : await loadE2BBaseModule();
49
+ let sandbox;
50
+ try {
51
+ // A Modal module takes its connection from context.env and ignores this one.
52
+ sandbox = await module.Sandbox.connect(run.runnerId, e2bConnection(context.env));
53
+ }
54
+ catch (error) {
55
+ if (!isSandboxNotFoundError(error))
56
+ throw error;
57
+ return {
58
+ runId: run.runId,
59
+ exitCode: 2,
60
+ error: `its runner sandbox is gone, so the run was not copied back. Stop anything it left with humanish reclaim --run ${run.runId}`,
61
+ };
62
+ }
63
+ const runner = runnerOf(sandbox);
64
+ const signals = watchSignals();
65
+ const proxy = await serveObserverProxy(await runner.sandbox.portAccess(RUNNER_OBSERVER_PORT), port);
66
+ try {
67
+ context.say(`Reconnected to run ${run.runId} on its runner.`);
68
+ return await followRemoteRun({
69
+ launch: context,
70
+ runner,
71
+ paths: run.paths,
72
+ runId: run.runId,
73
+ signals,
74
+ proxyUrl: proxy.url,
75
+ });
76
+ }
77
+ finally {
78
+ signals.dispose();
79
+ await proxy.close();
80
+ }
81
+ }
@@ -0,0 +1,68 @@
1
+ import type { E2BDesktopSandbox } from "../substrates/e2b/sdk.js";
2
+ import { type Shell } from "../substrates/shell.js";
3
+ /** The port the runner's Observer listens on. */
4
+ export declare const RUNNER_OBSERVER_PORT = 7000;
5
+ /** A runner sandbox and the shell into it. */
6
+ export interface Runner {
7
+ readonly sandbox: E2BDesktopSandbox;
8
+ readonly shell: Shell;
9
+ }
10
+ export declare function runnerOf(sandbox: E2BDesktopSandbox): Runner;
11
+ /**
12
+ * Install Node and the humanish package `tarball` (this machine's own humanish, packed), with the
13
+ * provider SDKs its participants need at `peers` (name@version). Returns the installed version.
14
+ */
15
+ export declare function installHumanish(runner: Runner, tarball: Uint8Array, peers: readonly string[]): Promise<string>;
16
+ /**
17
+ * Upload each project-relative file in `files`, and every file under each directory in
18
+ * `directories` that exists here, to the same place in the runner's project.
19
+ */
20
+ export declare function uploadProject(runner: Runner, cwd: string, files: readonly string[], directories: readonly string[]): Promise<number>;
21
+ /** What the runner's run is started with. */
22
+ export interface RemoteRunStart {
23
+ /** The study file, relative to the project. */
24
+ study: string;
25
+ runId: string;
26
+ ownerKey: string;
27
+ /** Only these names reach the run, each with its value from this machine. */
28
+ env: Readonly<Record<string, string>>;
29
+ }
30
+ /**
31
+ * Start the study's run in the runner as `humanish watch --serve`, so the run process itself serves
32
+ * the Observer with its live desktop streams, and writes its result to a file the launcher reads.
33
+ */
34
+ export declare function startRemoteRun(runner: Runner, start: RemoteRunStart): Promise<void>;
35
+ /** How the runner's run is going, read from its own files. */
36
+ export interface RemoteRunState {
37
+ /** status.json's `state`, once the run has written one. */
38
+ state?: string;
39
+ /** The result the run wrote when it ended, with the exit code the command would return. */
40
+ result?: {
41
+ exitCode: number;
42
+ result: unknown;
43
+ };
44
+ /** Whether the run's process is still alive in the runner. */
45
+ alive: boolean;
46
+ /** The last lines the run wrote to stderr. */
47
+ errTail: string;
48
+ }
49
+ export declare function readRemoteRun(runner: Runner, runId: string): Promise<RemoteRunState>;
50
+ /** One file of the runner's run directory: its path in the directory and its sha256. */
51
+ export interface RemoteFile {
52
+ path: string;
53
+ sha256: string;
54
+ }
55
+ /**
56
+ * The regular files of the runner's run directory and their digests. Refuses a directory that holds
57
+ * a link, which a run never writes.
58
+ */
59
+ export declare function listRemoteRun(runner: Runner, runId: string): Promise<RemoteFile[]>;
60
+ /** sha256sum lines, `<hex> ./<path>`, as RemoteFiles with paths relative to the directory. */
61
+ export declare function parseDigests(output: string): RemoteFile[];
62
+ /** The bytes of one file of the runner's run directory, checked against its listed digest. */
63
+ export declare function readRemoteFile(runner: Runner, runId: string, file: RemoteFile): Promise<Uint8Array>;
64
+ /**
65
+ * Ask the runner's run to stop as a signal would, so it reclaims its participants and ends. The
66
+ * `[h]` keeps the pattern from matching the shell that runs it.
67
+ */
68
+ export declare function stopRemoteRun(runner: Runner): Promise<void>;
@@ -0,0 +1,216 @@
1
+ // What the launcher does inside a runner sandbox, over the sandbox port's commands and files: install
2
+ // Node and this humanish, upload the study's files, start its run, read how it is going, and copy
3
+ // the finished run back.
4
+ import { createHash } from "node:crypto";
5
+ import { lstat, readFile, readdir, realpath } from "node:fs/promises";
6
+ import path from "node:path";
7
+ import { e2bShell } from "../substrates/e2b/shell.js";
8
+ import { shellQuote } from "../substrates/shell.js";
9
+ import { tailOf } from "../substrates/shell.js";
10
+ /** The project directory in the runner, under the sandbox user's home on both providers. */
11
+ const RUNNER_PROJECT = "project";
12
+ /** Where the runner keeps the launcher's own files: the result file and the run's output. */
13
+ const RUNNER_STATE = ".humanish-remote";
14
+ /** The port the runner's Observer listens on. */
15
+ export const RUNNER_OBSERVER_PORT = 7000;
16
+ /**
17
+ * The Node release the runner runs humanish on, with the sha256 nodejs.org publishes for each
18
+ * build (SHASUMS256.txt). The runner checks the download against it before extracting.
19
+ */
20
+ const NODE = {
21
+ version: "22.23.4",
22
+ sha256: {
23
+ x64: "b8492284c76a54baf58d61668dd0e41ee0fc98adabf9503d30f05d08f55b4406",
24
+ arm64: "f7a1e486dbc8b286847815b477d4fb5e9fb963ed4489c3e1588853d685f589f9",
25
+ },
26
+ };
27
+ export function runnerOf(sandbox) {
28
+ return { sandbox, shell: e2bShell(sandbox) };
29
+ }
30
+ /** A command failed in the runner; the message carries its exit code and output tail. */
31
+ class RunnerCommandError extends Error {
32
+ constructor(step, result) {
33
+ super(`${step} failed in the runner sandbox (exit ${result.exitCode}): ${tailOf(result.stderr || result.stdout)}`);
34
+ this.name = "RunnerCommandError";
35
+ }
36
+ }
37
+ async function runOrFail(runner, step, command, timeoutMs) {
38
+ const result = await runner.shell.run(command, { timeoutMs });
39
+ if (result.exitCode !== 0)
40
+ throw new RunnerCommandError(step, result);
41
+ return result;
42
+ }
43
+ /**
44
+ * Install Node and the humanish package `tarball` (this machine's own humanish, packed), with the
45
+ * provider SDKs its participants need at `peers` (name@version). Returns the installed version.
46
+ */
47
+ export async function installHumanish(runner, tarball, peers) {
48
+ await runner.shell.writeFile(`${RUNNER_STATE}/humanish.tgz`, toArrayBuffer(tarball));
49
+ const { version, sha256 } = NODE;
50
+ const script = [
51
+ "set -eu",
52
+ `cd "$HOME/${RUNNER_STATE}"`,
53
+ 'case "$(uname -m)" in x86_64) arch=x64;; aarch64|arm64) arch=arm64;; *) echo "unsupported CPU $(uname -m)" >&2; exit 1;; esac',
54
+ `if [ "$arch" = x64 ]; then sum=${sha256.x64}; else sum=${sha256.arm64}; fi`,
55
+ `curl -fsSL -o node.tgz "https://nodejs.org/dist/v${version}/node-v${version}-linux-$arch.tar.gz"`,
56
+ 'echo "$sum node.tgz" | sha256sum -c - >/dev/null',
57
+ "mkdir -p node && tar -xzf node.tgz --strip-components=1 -C node && rm node.tgz",
58
+ `export PATH="$HOME/${RUNNER_STATE}/node/bin:$PATH" npm_config_prefix="$HOME/${RUNNER_STATE}/node"`,
59
+ `npm install -g --no-fund --no-audit --loglevel=error ./humanish.tgz ${peers.map(shellQuote).join(" ")}`,
60
+ "humanish --version",
61
+ ].join("\n");
62
+ const result = await runOrFail(runner, "Installing humanish", `bash -c ${shellQuote(script)}`, 600_000);
63
+ return result.stdout.trim().split("\n").at(-1) ?? "";
64
+ }
65
+ /**
66
+ * Upload each project-relative file in `files`, and every file under each directory in
67
+ * `directories` that exists here, to the same place in the runner's project.
68
+ */
69
+ export async function uploadProject(runner, cwd, files, directories) {
70
+ const all = new Set(files);
71
+ for (const directory of directories)
72
+ for (const file of await filesUnder(cwd, directory))
73
+ all.add(file);
74
+ const root = await realpath(cwd);
75
+ for (const file of all) {
76
+ // A link could hand the runner a file from anywhere on this machine, such as a key file, so
77
+ // only a regular file whose real path is where the study names it is uploaded.
78
+ const real = await realpath(path.join(cwd, file)).catch(() => undefined);
79
+ if (real !== path.join(root, file) || !(await lstat(real)).isFile())
80
+ throw new Error(`${file} is a link or not a regular file, so it is not uploaded to the runner.`);
81
+ const bytes = await readFile(real);
82
+ await runner.shell.writeFile(`${RUNNER_PROJECT}/${file}`, toArrayBuffer(bytes));
83
+ }
84
+ return all.size;
85
+ }
86
+ async function filesUnder(cwd, directory) {
87
+ let entries;
88
+ try {
89
+ entries = await readdir(path.join(cwd, directory), { recursive: true, withFileTypes: true });
90
+ }
91
+ catch {
92
+ return [];
93
+ }
94
+ return entries
95
+ .filter((entry) => entry.isFile())
96
+ .map((entry) => path.relative(cwd, path.join(entry.parentPath, entry.name)).split(path.sep).join("/"));
97
+ }
98
+ /**
99
+ * Start the study's run in the runner as `humanish watch --serve`, so the run process itself serves
100
+ * the Observer with its live desktop streams, and writes its result to a file the launcher reads.
101
+ */
102
+ export async function startRemoteRun(runner, start) {
103
+ const args = [
104
+ "humanish",
105
+ "watch",
106
+ start.study,
107
+ "--serve",
108
+ "--no-open",
109
+ "--port",
110
+ String(RUNNER_OBSERVER_PORT),
111
+ "--all-interfaces",
112
+ "--result-file",
113
+ `$HOME/${RUNNER_STATE}/result.json`,
114
+ "--run-id",
115
+ start.runId,
116
+ "--owner-key",
117
+ start.ownerKey,
118
+ ];
119
+ const line = [
120
+ `cd "$HOME/${RUNNER_PROJECT}"`,
121
+ `export PATH="$HOME/${RUNNER_STATE}/node/bin:$PATH"`,
122
+ `exec ${args.map((arg) => (arg.startsWith("$HOME") ? `"${arg}"` : shellQuote(arg))).join(" ")} > "$HOME/${RUNNER_STATE}/watch.out" 2> "$HOME/${RUNNER_STATE}/watch.err"`,
123
+ ].join("; ");
124
+ const env = { ...start.env, DO_NOT_TRACK: "1", HUMANISH_TELEMETRY_DISABLED: "1" };
125
+ const result = await runner.shell.start(`bash -c ${shellQuote(line)}`, {
126
+ env,
127
+ timeoutMs: 60_000,
128
+ });
129
+ if (result.exitCode !== 0)
130
+ throw new RunnerCommandError("Starting the run", result);
131
+ }
132
+ export async function readRemoteRun(runner, runId) {
133
+ const read = async (file) => {
134
+ const result = await runner.shell.run(`cat -- ${shellQuote(file)} 2>/dev/null`, {
135
+ timeoutMs: 30_000,
136
+ });
137
+ return result.exitCode === 0 ? result.stdout : undefined;
138
+ };
139
+ const status = parseJson(await read(`${RUNNER_PROJECT}/.humanish/runs/${runId}/status.json`));
140
+ const result = parseJson(await read(`${RUNNER_STATE}/result.json`));
141
+ const err = await runner.shell.run(`tail -c 2000 ${RUNNER_STATE}/watch.err 2>/dev/null`, {
142
+ timeoutMs: 30_000,
143
+ });
144
+ const alive = await runner.shell.run("pgrep -f '[h]umanish watch' >/dev/null", {
145
+ timeoutMs: 30_000,
146
+ });
147
+ return {
148
+ ...(typeof status?.state === "string" ? { state: status.state } : {}),
149
+ ...(typeof result?.exitCode === "number"
150
+ ? { result: { exitCode: result.exitCode, result: result.result } }
151
+ : {}),
152
+ alive: alive.exitCode === 0,
153
+ errTail: tailOf(err.stdout),
154
+ };
155
+ }
156
+ function parseJson(text) {
157
+ if (text === undefined)
158
+ return undefined;
159
+ try {
160
+ const value = JSON.parse(text);
161
+ return value !== null && typeof value === "object"
162
+ ? value
163
+ : undefined;
164
+ }
165
+ catch {
166
+ return undefined;
167
+ }
168
+ }
169
+ /**
170
+ * The regular files of the runner's run directory and their digests. Refuses a directory that holds
171
+ * a link, which a run never writes.
172
+ */
173
+ export async function listRemoteRun(runner, runId) {
174
+ const dir = `${RUNNER_PROJECT}/.humanish/runs/${runId}`;
175
+ const links = await runOrFail(runner, "Listing the run", `cd ${shellQuote(dir)} && find . ! -type f ! -type d -print -quit`, 60_000);
176
+ if (links.stdout.trim() !== "")
177
+ throw new Error(`The runner's run directory holds something other than files and folders (${tailOf(links.stdout)}), so it is not copied.`);
178
+ const listed = await runOrFail(runner, "Listing the run", `cd ${shellQuote(dir)} && find . -type f -print0 | xargs -0 -r sha256sum`, 300_000);
179
+ return parseDigests(listed.stdout);
180
+ }
181
+ /** sha256sum lines, `<hex> ./<path>`, as RemoteFiles with paths relative to the directory. */
182
+ export function parseDigests(output) {
183
+ const files = [];
184
+ for (const line of output.split("\n")) {
185
+ const match = /^([0-9a-f]{64}) [ *]\.\/(.+)$/.exec(line);
186
+ if (match === null)
187
+ continue;
188
+ files.push({ sha256: match[1], path: match[2] });
189
+ }
190
+ return files;
191
+ }
192
+ /** The bytes of one file of the runner's run directory, checked against its listed digest. */
193
+ export async function readRemoteFile(runner, runId, file) {
194
+ const read = runner.sandbox.files.read;
195
+ if (read === undefined)
196
+ throw new Error("This sandbox cannot read files back.");
197
+ const stream = await read.call(runner.sandbox.files, `${RUNNER_PROJECT}/.humanish/runs/${runId}/${file.path}`, { format: "stream", requestTimeoutMs: 300_000 });
198
+ const parts = [];
199
+ for await (const chunk of stream)
200
+ parts.push(chunk);
201
+ const bytes = Buffer.concat(parts);
202
+ const digest = createHash("sha256").update(bytes).digest("hex");
203
+ if (digest !== file.sha256)
204
+ throw new Error(`${file.path} changed or arrived damaged while it was copied from the runner.`);
205
+ return bytes;
206
+ }
207
+ /**
208
+ * Ask the runner's run to stop as a signal would, so it reclaims its participants and ends. The
209
+ * `[h]` keeps the pattern from matching the shell that runs it.
210
+ */
211
+ export async function stopRemoteRun(runner) {
212
+ await runner.shell.run("pkill -TERM -f '[h]umanish watch' || true", { timeoutMs: 30_000 });
213
+ }
214
+ function toArrayBuffer(bytes) {
215
+ return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
216
+ }
@@ -1,4 +1,6 @@
1
+ import { externalHandoffReader } from "../../../substrates/e2b/desktop-handoff.js";
1
2
  import { createE2BDesktopExecutor } from "../../../substrates/e2b/desktop-executor.js";
3
+ import { e2bShell } from "../../../substrates/e2b/shell.js";
2
4
  import { participantInbox, planParticipantComms } from "./comms.js";
3
5
  import { participantBrowserStateObserver } from "./fidelity.js";
4
6
  import { networkHooks, planParticipantNetwork } from "./network.js";
@@ -37,7 +39,7 @@ export function createE2BParticipantDesktop(spec, deps, warnings) {
37
39
  let finalization;
38
40
  async function prepare() {
39
41
  if (preparationStarted || finalization)
40
- throw new Error("Participant desktop preparation can only start once, before finalization.");
42
+ throw new Error("Participant desktop preparation can only start once, before the desktop is released.");
41
43
  preparationStarted = true;
42
44
  const desktop = await acquireParticipantDesktop(ctx, state);
43
45
  // The device claim is verified in the sandbox, and fails closed.
@@ -52,7 +54,7 @@ export function createE2BParticipantDesktop(spec, deps, warnings) {
52
54
  async function openSession() {
53
55
  const { desktop, allocation } = state;
54
56
  if (!prepared || !desktop || !allocation || opened || finalization)
55
- throw new Error("The participant desktop must be prepared and may only be opened once, before finalization.");
57
+ throw new Error("The participant desktop must be prepared and may only be opened once, before the desktop is released.");
56
58
  opened = true;
57
59
  await startParticipantStream(ctx, state, desktop);
58
60
  const inbox = participantInbox({
@@ -64,21 +66,29 @@ export function createE2BParticipantDesktop(spec, deps, warnings) {
64
66
  });
65
67
  // Capture that started pairs each checkpoint with the time of the read before it.
66
68
  const network = networkHooks(state.network);
67
- const executor = createE2BDesktopExecutor(desktop, state.launchedBrowserFamily === "chromium"
68
- ? {
69
- observeBrowserState: participantBrowserStateObserver({
70
- desktop,
71
- spec,
72
- deps,
73
- targetUrl,
74
- launchIdentity: state.browserLaunchIdentity,
75
- targetId: state.browserTargetId,
76
- fidelity: state.fidelity,
77
- warnings,
78
- ...(network === undefined ? {} : { onClock: network.onClock }),
79
- }),
80
- }
81
- : {});
69
+ // A web target's browser launch installs the stand-ins that write handed-off links down
70
+ // (desktop-handoff.ts). Without them the log is absent and every read is empty.
71
+ const readExternalHandoffs = state.browserLaunched
72
+ ? externalHandoffReader(e2bShell(desktop), { requestTimeoutMs: deps.requestTimeoutMs })
73
+ : undefined;
74
+ const executor = createE2BDesktopExecutor(desktop, {
75
+ ...(readExternalHandoffs === undefined ? {} : { readExternalHandoffs }),
76
+ ...(state.launchedBrowserFamily === "chromium"
77
+ ? {
78
+ observeBrowserState: participantBrowserStateObserver({
79
+ desktop,
80
+ spec,
81
+ deps,
82
+ targetUrl,
83
+ launchIdentity: state.browserLaunchIdentity,
84
+ targetId: state.browserTargetId,
85
+ fidelity: state.fidelity,
86
+ warnings,
87
+ ...(network === undefined ? {} : { onClock: network.onClock }),
88
+ }),
89
+ }
90
+ : {}),
91
+ });
82
92
  return {
83
93
  executor: allocation.open(state.speech?.wrap(executor) ?? executor).executor,
84
94
  ...(inbox === undefined ? {} : { inbox }),
@@ -203,7 +203,7 @@ export async function startParticipantStream(ctx, state, desktop) {
203
203
  // A browser participant streams its browser window when one was found. A CLI participant has
204
204
  // no window id and streams the whole desktop: a person studying a terminal app opens other windows, and
205
205
  // a stream bound to the first one would quietly stop being evidence.
206
- await startDesktopStream(desktop, state.browserWindowId);
206
+ await startDesktopStream(desktop, state.browserWindowId, deps.requestTimeoutMs);
207
207
  const candidateStreamUrl = desktop.stream.getUrl({
208
208
  authKey: desktop.stream.getAuthKey(),
209
209
  autoConnect: true,
@@ -106,7 +106,7 @@ export async function finishE2BDesktop(ctx, state, failed) {
106
106
  await deps.receiving.finishParticipant(spec.planned.id);
107
107
  }
108
108
  catch {
109
- warnings.push("Real email finalization is incomplete. Inspect communication cleanup with humanish comms recover.");
109
+ warnings.push("Real email cleanup is incomplete. Inspect communication cleanup with humanish comms recover.");
110
110
  }
111
111
  }
112
112
  if (ctx.comms && state.commsCatch?.deployed.ready) {
@@ -12,12 +12,12 @@ export function createInProcessDesktop(deps) {
12
12
  return {
13
13
  async prepare() {
14
14
  if (preparationStarted || finalization)
15
- throw new Error("Participant desktop preparation can only start once, before finalization.");
15
+ throw new Error("Participant desktop preparation can only start once, before the desktop is released.");
16
16
  preparationStarted = true;
17
17
  },
18
18
  async openSession() {
19
19
  if (!preparationStarted || opened || finalization)
20
- throw new Error("The participant desktop must be prepared and may only be opened once, before finalization.");
20
+ throw new Error("The participant desktop must be prepared and may only be opened once, before the desktop is released.");
21
21
  opened = true;
22
22
  if (deps.inProcessExecutor === undefined)
23
23
  throw new Error("The in-process route needs RunStudyOptions.inProcess.");
@@ -110,7 +110,7 @@ export async function runStudyParticipants(setup, participants) {
110
110
  await receiving?.finish();
111
111
  }
112
112
  catch {
113
- receivingWarnings.push("Email finalization could not complete. Inspect humanish comms recover; provider cleanup remains unresolved.");
113
+ receivingWarnings.push("Email cleanup could not complete. Inspect humanish comms recover; provider cleanup remains unresolved.");
114
114
  }
115
115
  // Stop the flush timer on every exit, including a throw from the participants.
116
116
  await liveTrace.stop?.();
@@ -233,8 +233,8 @@ export async function startCuaRun(plan, input, admitted, scope) {
233
233
  const { cwd, descriptor, participantRuns, participantPlan, publicRepo } = admitted;
234
234
  const { appUrl } = admitted;
235
235
  // The run's status record exists from here on, so anything watching the runs directory can
236
- // tell which study this is and that it is alive. The fail-closed returns below leave it finished
237
- // with no outcome when the scope closes; a crash leaves it stale, which reads as interrupted.
236
+ // tell which study this is and that it is alive. The fail-closed returns below leave it
237
+ // interrupted with no outcome when the scope closes; a killed process leaves it stale.
238
238
  const started = await scope.startRun(plan, input, {
239
239
  cwd,
240
240
  prefix: "cua",
@@ -59,6 +59,8 @@ export interface ComputerUseRunInput {
59
59
  cwd: string;
60
60
  open?: boolean;
61
61
  runId?: string;
62
+ /** The run key its sandboxes carry; see InternalRunStudyOptions.ownerKey. */
63
+ ownerKey?: string;
62
64
  /** CLI `--count` override for the homogeneous fan-out participant count (ignored when a `participants`
63
65
  * list is declared; a roster's length is authoritative). */
64
66
  countOverride?: number;
@@ -15,6 +15,8 @@ export interface ScriptedRunInput {
15
15
  cwd: string;
16
16
  open?: boolean;
17
17
  runId?: string;
18
+ /** The run key its sandboxes carry; see InternalRunStudyOptions.ownerKey. */
19
+ ownerKey?: string;
18
20
  /** Keys and subject env for the run. Defaults to process.env. Values are scrubbed; names persist. */
19
21
  env?: Readonly<Record<string, string | undefined>>;
20
22
  /** Runs after a clone subject's sandbox exists and before provisioning. */
@@ -226,7 +226,7 @@ async function runPlane(ctx, live, results, plane) {
226
226
  await ctx.receiving?.finish();
227
227
  }
228
228
  catch {
229
- ctx.warnings.push("Email finalization could not complete. Inspect humanish comms recover; provider cleanup remains unresolved.");
229
+ ctx.warnings.push("Email cleanup could not complete. Inspect humanish comms recover; provider cleanup remains unresolved.");
230
230
  }
231
231
  // Stop the participants' flush timer on every exit, before the final write.
232
232
  await live.flush?.stop();
@@ -31,6 +31,8 @@ export interface SharedWorldRunInput {
31
31
  cwd: string;
32
32
  open?: boolean;
33
33
  runId?: string;
34
+ /** The run key its sandboxes carry; see InternalRunStudyOptions.ownerKey. */
35
+ ownerKey?: string;
34
36
  onObserverReady?: (observer: ObserverResult & {
35
37
  ok: true;
36
38
  }) => Promise<void> | void;
@@ -106,6 +106,8 @@ export interface TerminalRunInput {
106
106
  cwd: string;
107
107
  open?: boolean;
108
108
  runId?: string;
109
+ /** The run key its sandboxes carry; see InternalRunStudyOptions.ownerKey. */
110
+ ownerKey?: string;
109
111
  /**
110
112
  * The operator environment the route reads the runtime key from (and from which it asserts no
111
113
  * banned credential is requested). Defaults to process.env. The runtime key goes only
@@ -1,5 +1,6 @@
1
1
  import { type PreparedRunArtifactPaths } from "./paths.js";
2
2
  import type { RunIndexEntry } from "./run-index.js";
3
+ import type { AnalysisProviderName } from "../analysis/types.js";
3
4
  /** Additive accounting for retained attempts. Null means no estimate, never an invented zero. */
4
5
  export interface CostTotals {
5
6
  estimatedTotalUsd: number | null;
@@ -39,7 +40,7 @@ export interface AnalysisAccounting {
39
40
  /** The known estimates of the dispatched attempts; 0 when every attempt sent nothing. */
40
41
  estimatedUsd: number | null;
41
42
  /** Who billed the dispatched attempts. */
42
- providers: Array<"openai" | "codex">;
43
+ providers: AnalysisProviderName[];
43
44
  /** History that could not be read whole; ANALYSIS_HISTORY_NOT_RECORDED when there is none. */
44
45
  warnings: string[];
45
46
  }
@@ -1,6 +1,6 @@
1
1
  import type { RunOutcome } from "./bundle.js";
2
2
  import type { ExecutionFailure } from "./judge.js";
3
- import { type RunLiveness } from "./status.js";
3
+ import { type RunAnalysisPhase, type RunLiveness } from "./status.js";
4
4
  /** The states a run is shown in. */
5
5
  export type RunDisplayState = "running" | "interrupted" | "passed" | "failed" | "blocked" | "timed_out" | "no_verdict" | "dry_run" | "unknown";
6
6
  /** A run as a surface shows it. */
@@ -31,6 +31,11 @@ export interface RunDisplayFacts {
31
31
  * show as passed.
32
32
  */
33
33
  export declare function runDisplay(facts: RunDisplayFacts): RunDisplay;
34
+ /**
35
+ * What a surface shows after a run's display while its automatic analysis runs, or once that
36
+ * analysis's process stopped without an end: the run's own result stays its participants'.
37
+ */
38
+ export declare function analysisPhaseLabel(phase: RunAnalysisPhase | undefined): string | undefined;
34
39
  /** A state in words: "passed", "timed out", "no verdict". */
35
40
  export declare function runDisplayLabel(state: RunDisplayState): string;
36
41
  /** What bundleDisplayFacts reads from run.json; a listing reads it from an unchecked file. */
@@ -61,6 +61,17 @@ export function runDisplay(facts) {
61
61
  return shown(facts.mode === "dry-run" ? "dry_run" : "no_verdict");
62
62
  return shown("unknown");
63
63
  }
64
+ /**
65
+ * What a surface shows after a run's display while its automatic analysis runs, or once that
66
+ * analysis's process stopped without an end: the run's own result stays its participants'.
67
+ */
68
+ export function analysisPhaseLabel(phase) {
69
+ if (phase?.state === "running")
70
+ return "analyzing";
71
+ if (phase?.state === "stopped")
72
+ return "analysis stopped";
73
+ return undefined;
74
+ }
64
75
  /** A state in words: "passed", "timed out", "no verdict". */
65
76
  export function runDisplayLabel(state) {
66
77
  return LABELS[state];
@@ -19,7 +19,10 @@ export const systemHostClock = {
19
19
  };
20
20
  /**
21
21
  * A wall-clock gap between two heartbeats this long or longer is a suspension. A shorter one is
22
- * most likely a busy event loop.
22
+ * most likely a busy event loop. It is twice RUN_STATUS_STALE_MS (src/run/status.ts) on purpose:
23
+ * that threshold is a reader's guess, made without the writer, so it errs early; this one is the
24
+ * writer's own record, and a route blames participant failures on it, so it errs late. A pause of
25
+ * 15 to 30 s reads as stale while it lasts and leaves no suspension on record.
23
26
  */
24
27
  const HOST_SUSPENSION_MIN_MS = 30_000;
25
28
  /** Run `onTick` every `intervalMs` on `clock`, and record each gap of 30 s or more. */
@@ -1,16 +1,7 @@
1
+ import { type ProcessOwner } from "./process-owner.js";
1
2
  import { type PreparedSelectedOutputDirectory } from "./contained-output.js";
2
- /**
3
- * Who opened a journal. A pid means nothing outside its host and pid namespace (a probe in a
4
- * container writing to a bind-mounted checkout has a pid the host cannot see), so reclaim trusts
5
- * a dead pid only when both match its own.
6
- */
7
- interface PreflightOwner {
8
- hostname: string;
9
- /** `pid:[inode]` from /proc/self/ns/pid, where the platform has one. */
10
- pidNamespace?: string;
11
- pid: number;
12
- /** Start time in clock ticks since boot (/proc/<pid>/stat), which tells a reused pid apart. */
13
- startTicks?: string;
3
+ /** Who opened a journal (src/run/process-owner.ts), when, and for how long. */
4
+ interface PreflightOwner extends ProcessOwner {
14
5
  createdAt: string;
15
6
  /** The probe's server-side timeout. */
16
7
  leaseMs: number;