@awebai/oats 0.68.0 → 0.69.1
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/oats.mjs +102 -22
- package/docs/capabilities.md +49 -5
- package/docs/configuration.md +68 -2
- package/docs/desktop-cli-api.md +355 -12
- package/docs/desktop-instance-start.md +88 -3
- package/docs/desktop.md +147 -13
- package/docs/execution-targets.md +514 -62
- package/docs/harness-trust.md +3 -1
- package/docs/implementation.md +28 -11
- package/docs/integrations.md +1 -1
- package/docs/oats-local.schema.json +2 -2
- package/docs/official-catalog.md +4 -3
- package/docs/packages.md +7 -7
- package/docs/release-notes/v0.68.1.md +102 -0
- package/docs/release-notes/v0.69.0.md +658 -0
- package/docs/release-notes/v0.69.1.md +25 -0
- package/docs/servers.md +44 -5
- package/docs/souls-and-instances.md +11 -7
- package/docs/tui.md +114 -31
- package/docs/upgrading.md +14 -5
- package/docs/workspaces.md +1 -1
- package/lib/core.mjs +345 -89
- package/lib/file-pieces.mjs +49 -0
- package/lib/instance-events.mjs +25 -4
- package/lib/launch-prompt-fixtures/README.md +62 -0
- package/lib/launch-prompt-fixtures/resume-confirmation.json +32 -0
- package/lib/launch-prompt-fixtures.mjs +49 -0
- package/lib/launch-prompt-resume.mjs +55 -0
- package/lib/login-environment.mjs +27 -9
- package/lib/schedule.mjs +3 -3
- package/lib/servers.mjs +117 -23
- package/lib/session-end.mjs +82 -0
- package/lib/session-input.mjs +43 -9
- package/lib/session-resume-contract.mjs +32 -0
- package/lib/session-resume.mjs +310 -0
- package/lib/session-seen.mjs +163 -0
- package/lib/session-viewer.mjs +147 -44
- package/lib/soul-composition.mjs +2 -1
- package/lib/start-env.mjs +110 -0
- package/lib/tmux-server-scope.mjs +139 -14
- package/lib/workspace.mjs +38 -4
- package/package-catalog.json +10 -4
- package/package.json +1 -1
- package/packages/client/cli-adapter.mjs +9 -0
- package/packages/client/cli-locator.mjs +3 -2
- package/packages/client/deployment-data.mjs +7 -0
- package/packages/client/deployment-panel.mjs +3 -0
- package/packages/client/file-output-exec.mjs +98 -0
- package/packages/client/instance-display-name.mjs +18 -0
- package/packages/client/launch-prompt-outcome.mjs +25 -13
- package/packages/client/own-codes.mjs +2 -0
- package/packages/client/session-attach.mjs +35 -5
- package/packages/client/session-resume-cli.mjs +64 -0
- package/packages/client/session-resume-trigger.mjs +167 -0
- package/packages/client/session-resume.mjs +332 -0
- package/packages/client/tmux-status.mjs +30 -7
- package/packages/client/waiting-on-you.mjs +11 -4
- package/packages/client/workspace-step.mjs +17 -5
- package/packages/record/lib/last-conversation.mjs +123 -0
- package/packages/record/lib/session-roots.mjs +10 -1
- package/packages/tui/README.md +1 -1
- package/packages/tui/lib/client.mjs +2 -1
- package/packages/tui/lib/main.mjs +5 -3
- package/packages/tui/lib/model.mjs +57 -15
- package/packages/tui/lib/store.mjs +8 -7
- package/packages/tui/lib/term/text.mjs +12 -9
- package/packages/tui/lib/views/capabilities.mjs +6 -6
- package/packages/tui/lib/views/frame.mjs +72 -7
- package/packages/tui/lib/views/help.mjs +9 -4
- package/packages/tui/lib/views/instances.mjs +46 -29
- package/packages/tui/lib/views/souls.mjs +9 -8
- package/skills/oats-getting-started/SKILL.md +117 -4
package/lib/workspace.mjs
CHANGED
|
@@ -358,14 +358,31 @@ function fromProblems(remote, capabilities, path, problems, { here }) {
|
|
|
358
358
|
export function validateLocal(value) {
|
|
359
359
|
const problems = withRemovedKeys(validateAgainst(schemaFor("local"), value), value, REMOVED_KEYS.local);
|
|
360
360
|
if (isObject(value) && isObject(value.settings)) for (const [cap, payload] of Object.entries(value.settings)) reservedKeyProblems(payload, `/settings/${pointerKey(cap)}`, problems);
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
361
|
+
if (isObject(value)) harnessConflictProblems(value["launch-configs"], problems);
|
|
362
|
+
return referenceProblems(problems, [["/workspace", value?.workspace], ["/standalone", value?.standalone]]);
|
|
363
|
+
}
|
|
364
|
+
/** runtime → harness (0.27.0, lead call 6): `runtime`, the pre-0.27 name, is still read; both,
|
|
365
|
+
* disagreeing, are refused. `configs` is a `launch-configs:` block. */
|
|
366
|
+
function harnessConflictProblems(configs, problems) {
|
|
367
|
+
if (!isObject(configs)) return;
|
|
368
|
+
for (const [name, entry] of Object.entries(configs)) {
|
|
364
369
|
if (isObject(entry) && Object.hasOwn(entry, "runtime") && Object.hasOwn(entry, "harness") && entry.runtime !== entry.harness) {
|
|
365
370
|
problems.push({ path: `/launch-configs/${pointerKey(name)}/runtime`, reason: "harness-conflict", message: `harness ${show(entry.harness)} and runtime ${show(entry.runtime)} disagree: \`runtime\` is the pre-0.27 name of \`harness\` — keep one` });
|
|
366
371
|
}
|
|
367
372
|
}
|
|
368
|
-
|
|
373
|
+
}
|
|
374
|
+
/** Schema + domain problems for the machine's launch configurations file (awebai/oats#1506): a map whose
|
|
375
|
+
* one key is `launch-configs:`, validated by oats-local.yaml's schema of that key and the same
|
|
376
|
+
* runtime/harness check. Any other top-level key is a problem, as is a missing `launch-configs:`. */
|
|
377
|
+
export function validateMachineLaunchConfigs(value) {
|
|
378
|
+
if (!isObject(value)) return [{ path: "", message: `expected a map whose one key is launch-configs, got ${value === null || value === undefined ? "an empty document" : typeof value}` }];
|
|
379
|
+
const problems = Object.keys(value).filter((key) => key !== "launch-configs")
|
|
380
|
+
.map((key) => ({ path: `/${pointerKey(key)}`, message: `${show(key)} is not read here: this file holds launch-configs only` }));
|
|
381
|
+
if (!Object.hasOwn(value, "launch-configs")) return [...problems, { path: "", message: "launch-configs is missing: it is this file's one key" }];
|
|
382
|
+
const local = schemaFor("local");
|
|
383
|
+
problems.push(...validateAgainst(local.properties["launch-configs"], value["launch-configs"], { root: local, path: "/launch-configs" }));
|
|
384
|
+
harnessConflictProblems(value["launch-configs"], problems);
|
|
385
|
+
return problems;
|
|
369
386
|
}
|
|
370
387
|
|
|
371
388
|
/* ───────────────────────────── file decoding ──────────────────────────── */
|
|
@@ -375,6 +392,7 @@ const FILE_KINDS = {
|
|
|
375
392
|
membership: { file: "oats-membership.yaml", validate: validateMembership },
|
|
376
393
|
soul: { file: "soul.yaml", validate: validateSoul },
|
|
377
394
|
local: { file: "oats-local.yaml", validate: validateLocal },
|
|
395
|
+
machine: { file: "launch-configs.yaml", validate: validateMachineLaunchConfigs },
|
|
378
396
|
};
|
|
379
397
|
|
|
380
398
|
/** Decode YAML/JSON bytes into plain data; syntax errors become one problem at "". */
|
|
@@ -446,6 +464,22 @@ export function loadLocal(dir) {
|
|
|
446
464
|
throw fail("E_LOCAL_MISSING", `no oats-local.yaml found walking up from ${resolve(dir)}${legacy.length ? ` (${legacy[0]} is a 0.25 deployment's configuration, which 0.26.0 no longer reads: retire its instances with 0.25, then \`oats onboard\` it)` : ""}`, { dir: resolve(dir), searched: visited, ...(legacy.length ? { legacy } : {}) });
|
|
447
465
|
}
|
|
448
466
|
|
|
467
|
+
/** The machine's launch configurations file at `file` (awebai/oats#1506) → `{ path, configs }`, `configs`
|
|
468
|
+
* its `launch-configs:` block as written, or null when there is no file. A file that is there but cannot
|
|
469
|
+
* be read, decoded or validated is E_LAUNCH_CONFIG_INVALID naming it: it is never skipped. */
|
|
470
|
+
export function loadMachineLaunchConfigs(file) {
|
|
471
|
+
let bytes;
|
|
472
|
+
try { bytes = readFileSync(file); }
|
|
473
|
+
catch (e) {
|
|
474
|
+
if (e?.code === "ENOENT") { recordLocalInput(file, null); return null; }
|
|
475
|
+
throw fail("E_LAUNCH_CONFIG_INVALID", `the machine's launch configurations ${file} cannot be read (${e?.code || "unreadable"})`, { file });
|
|
476
|
+
}
|
|
477
|
+
recordLocalInput(file, bytes);
|
|
478
|
+
const read = readDeclaration("machine", bytes, { kind: "machine", path: file });
|
|
479
|
+
if (read.problems) throw fail("E_LAUNCH_CONFIG_INVALID", `the machine's launch configurations ${file} are invalid: ${read.problems.map((p) => `${p.path || "/"}: ${p.message}`).join("; ")}`, { file, problems: read.problems });
|
|
480
|
+
return { path: file, configs: read.value["launch-configs"] };
|
|
481
|
+
}
|
|
482
|
+
|
|
449
483
|
/** Observe the workspace host: → { key, url, commit, workspace, observedAt }. */
|
|
450
484
|
export async function observeWorkspace(ref, { at, remote: injected, remoteOptions } = {}) {
|
|
451
485
|
const remote = remoteOf({ remote: injected, remoteOptions });
|
package/package-catalog.json
CHANGED
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
},
|
|
9
9
|
"oats.aweb": {
|
|
10
10
|
"url": "https://github.com/awebai/oats-aweb.git",
|
|
11
|
-
"ref": "v1.
|
|
11
|
+
"ref": "v1.32.0",
|
|
12
12
|
"path": "oats-package"
|
|
13
13
|
},
|
|
14
14
|
"oats.jira": {
|
|
@@ -28,7 +28,7 @@
|
|
|
28
28
|
},
|
|
29
29
|
"oats.engineering": {
|
|
30
30
|
"url": "https://github.com/awebai/oats-engineering.git",
|
|
31
|
-
"ref": "v1.
|
|
31
|
+
"ref": "v1.15.0",
|
|
32
32
|
"path": "oats-package"
|
|
33
33
|
},
|
|
34
34
|
"oats.cloning": {
|
|
@@ -41,9 +41,14 @@
|
|
|
41
41
|
"ref": "v1.0.0",
|
|
42
42
|
"path": "oats-package"
|
|
43
43
|
},
|
|
44
|
+
"oats.machine": {
|
|
45
|
+
"url": "https://github.com/awebai/oats-machine.git",
|
|
46
|
+
"ref": "v0.1.1",
|
|
47
|
+
"path": "oats-package"
|
|
48
|
+
},
|
|
44
49
|
"oats.framework": {
|
|
45
50
|
"url": "https://github.com/awebai/oats.git",
|
|
46
|
-
"ref": "oats-framework/v1.
|
|
51
|
+
"ref": "oats-framework/v1.15.1",
|
|
47
52
|
"path": "oats-package"
|
|
48
53
|
}
|
|
49
54
|
},
|
|
@@ -79,6 +84,7 @@
|
|
|
79
84
|
"oats.code-review": "oats.engineering",
|
|
80
85
|
"oats.maintainer": "oats.engineering",
|
|
81
86
|
"oats.folio": "oats.apps",
|
|
82
|
-
"oats.library": "oats.apps"
|
|
87
|
+
"oats.library": "oats.apps",
|
|
88
|
+
"oats.machine-care": "oats.machine"
|
|
83
89
|
}
|
|
84
90
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@awebai/oats",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.69.1",
|
|
4
4
|
"description": "OATS (Open Agent Team Specification) — durable souls, disposable instances, targetable capability packages, and the runtime-neutral oats CLI/kernel.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"agents",
|
|
@@ -332,6 +332,15 @@ export function cliServerRemove(bin, id, io = {}) {
|
|
|
332
332
|
if (typeof id !== "string" || !MACHINE_ID.test(id)) return Promise.resolve(badMachineArgs());
|
|
333
333
|
return runJson(bin, ["server", "remove", id, "--json"], { cwd: io.cwd || process.cwd(), exec: io.exec, timeout: io.timeout });
|
|
334
334
|
}
|
|
335
|
+
/** `oats session inspect --home <home> --json` on this computer (#1569): the kernel's observation of an
|
|
336
|
+
* instance's terminal, whose `paneId` is the agent's pane by the kernel's own rule, in a window of one pane
|
|
337
|
+
* or several. A clean exit is required for success (`strictExit`). */
|
|
338
|
+
export function cliSessionInspect(bin, { home } = {}, io = {}) {
|
|
339
|
+
if (typeof bin !== "string" || !isAbsolute(bin) || typeof home !== "string" || !isAbsolute(home) || home.includes("\0")) {
|
|
340
|
+
return Promise.resolve({ schemaVersion: 1, ok: false, error: { code: "E_BAD_ARGS", message: "Invalid inspect home" } });
|
|
341
|
+
}
|
|
342
|
+
return runJson(bin, ["session", "inspect", "--home", home, "--json"], { cwd: io.cwd || process.cwd(), exec: io.exec, timeout: io.timeout || 15_000, strictExit: true });
|
|
343
|
+
}
|
|
335
344
|
/** `oats server forget <server> --instance <instance> --json` (#1131): drop this computer's saved route to a
|
|
336
345
|
* remote instance its host no longer lists. Both values are one roster row's identity, each one argv entry,
|
|
337
346
|
* never option-shaped. A clean exit is required for success (`strictExit`): an answer the CLI did not finish
|
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
// Every candidate is canonicalized to an absolute executable and accepted
|
|
14
14
|
// ONLY if executable and `<bin> version --json` returns the v1 probe:
|
|
15
15
|
// {"schemaVersion":1,"name":"@awebai/oats","version":"0.24.x","desktopApi":1}
|
|
16
|
-
// Desktop accepts desktopApi === 1 and semver >=0.26.0 <0.
|
|
16
|
+
// Desktop accepts desktopApi === 1 and semver >=0.26.0 <0.70.0 (the band is
|
|
17
17
|
// spelled ONCE, in ACCEPT_RANGE below — this line only paraphrases it).
|
|
18
18
|
// API version — not source adjacency — is authoritative.
|
|
19
19
|
//
|
|
@@ -52,7 +52,7 @@ export const DESKTOP_API = 1;
|
|
|
52
52
|
// carry a `description` for every kind and `<kind> update <id> --description`
|
|
53
53
|
// sets one (feature `automation-descriptions`, which gates the Desktop's
|
|
54
54
|
// summary writes). The Desktop v1 surface is otherwise unchanged.
|
|
55
|
-
export const ACCEPT_RANGE = { min: [0, 26, 0], maxExclusive: [0,
|
|
55
|
+
export const ACCEPT_RANGE = { min: [0, 26, 0], maxExclusive: [0, 70, 0] };
|
|
56
56
|
/** The band as humans read it — derived, never hand-spelled, so the probe
|
|
57
57
|
* rejection reason, the backend's /api status and the degradation card can
|
|
58
58
|
* never disagree with the numbers actually enforced above. */
|
|
@@ -199,6 +199,7 @@ export function cliRecord(payload, { bin, source }) {
|
|
|
199
199
|
...(payload.automationsApi === 1 ? { automationsApi: 1 } : {}),
|
|
200
200
|
...(payload.capabilityShowApi === 1 ? { capabilityShowApi: 1 } : {}),
|
|
201
201
|
...(Array.isArray(payload.features) ? { features: payload.features } : {}),
|
|
202
|
+
...(typeof payload.sessionViewer?.prefixScroll === "boolean" ? { sessionViewer: { prefixScroll: payload.sessionViewer.prefixScroll } } : {}),
|
|
202
203
|
...(Array.isArray(payload.remote) ? { remote: payload.remote } : {}) };
|
|
203
204
|
}
|
|
204
205
|
|
|
@@ -13,6 +13,10 @@ import { instanceColor } from './instance-presentation.mjs';
|
|
|
13
13
|
const text = value => typeof value === 'string' && value.length <= 8192 && !value.includes('\0');
|
|
14
14
|
const absolute = value => text(value) && isAbsolute(value) && resolve(value) === value;
|
|
15
15
|
const own = (value, key) => Object.hasOwn(value, key);
|
|
16
|
+
/** How an instance's last session ended (`oats status --json` `sessionEnd`), by name: the only values a row keeps.
|
|
17
|
+
* The one list; clients read a row's `sessionEnd` against it (session-resume-trigger.mjs lostLocalHomes). */
|
|
18
|
+
export const SESSION_ENDS = Object.freeze({ lost: 'lost', stopped: 'stopped', exited: 'exited' });
|
|
19
|
+
const SESSION_END_VALUES = Object.values(SESSION_ENDS);
|
|
16
20
|
const bad = (code = 'E_CLI_PROTOCOL') => { throw Object.assign(new Error(code), { code }); };
|
|
17
21
|
const check = (condition, code) => { if (!condition) bad(code); };
|
|
18
22
|
const array = (value, limit = 2000) => { check(Array.isArray(value) && value.length <= limit); return value; };
|
|
@@ -222,6 +226,9 @@ export function deploymentStatusData(document, deployment) {
|
|
|
222
226
|
// #802 (feature worktree-event): a spawn running its worktree hooks, verifiably alive. Boolean true only;
|
|
223
227
|
// any other value is dropped, never checked: the row stays an ordinary one.
|
|
224
228
|
if (own(instance, 'spawnInProgress') && instance.spawnInProgress === true) row.spawnInProgress = true;
|
|
229
|
+
// Session resume: how the instance's last session ended, one of SESSION_ENDS exactly. Any other value is
|
|
230
|
+
// dropped, never checked: the row reads as one that did not say.
|
|
231
|
+
if (own(instance, 'sessionEnd') && SESSION_END_VALUES.includes(instance.sessionEnd)) row.sessionEnd = instance.sessionEnd;
|
|
225
232
|
if (own(instance, 'modules')) row.modules = modules(instance.modules);
|
|
226
233
|
if (own(instance, 'soul')) row.soul = soulSource(instance.soul);
|
|
227
234
|
if (own(instance, 'workspace')) row.workspace = recordedWorkspace(instance.workspace);
|
|
@@ -108,6 +108,9 @@ export function panelInstance(i) {
|
|
|
108
108
|
...(i.rollbackIncomplete ? { rollbackIncomplete: true } : {}),
|
|
109
109
|
// #802: a spawn setting up its worktree (deployment-data.mjs keeps it as true only).
|
|
110
110
|
...(i.spawnInProgress === true ? { spawnInProgress: true } : {}),
|
|
111
|
+
// Session resume: how the last session ended, as deployment-data.mjs validated it (SESSION_ENDS); absent stays
|
|
112
|
+
// absent. The resume trigger reads it (session-resume-trigger.mjs lostLocalHomes).
|
|
113
|
+
...(i.sessionEnd !== undefined ? { sessionEnd: i.sessionEnd } : {}),
|
|
111
114
|
...(i.captured ? { captured: true } : {}),
|
|
112
115
|
// Needs input (PR K): the validated claim (or null, unknown) as status reported it; absent stays absent.
|
|
113
116
|
// The client's liveness is merged before projection, so running/runtimeState beside it are the probe's.
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
/** The exec of a kernel change that must outlive the client: `execFile`'s signature and return (the child), with
|
|
2
|
+
* the child's output in files, never in pipes. A client that quits, crashes or is signalled while a pipe's reader
|
|
3
|
+
* is its own leaves the child writing into a pipe nobody reads: the write meets EPIPE (or SIGPIPE) and the change
|
|
4
|
+
* dies half done. So the child writes to files of its own, which nothing the client does can close.
|
|
5
|
+
*
|
|
6
|
+
* execFileToFiles(bin, argv, { cwd, env, encoding, maxBuffer }, callback) -> ChildProcess
|
|
7
|
+
*
|
|
8
|
+
* - The child starts in a session of its own (`detached`; `execFile` drops that option, so this stands on
|
|
9
|
+
* `spawn`), stdin `ignore`: a signal to the client's process group (Ctrl-C, a hang-up) never reaches it.
|
|
10
|
+
* - Before the spawn: a private dir (`mkdtemp` under the OS temp dir, mode 0700) and two files in it (`wx`,
|
|
11
|
+
* 0600), each with a write fd and a read fd. The write fds are the child's stdout and stderr. Right after the
|
|
12
|
+
* spawn the client's write fds are closed, both files unlinked and the dir removed: the child writes to its
|
|
13
|
+
* open inodes, the client reads back from its own fds, nothing is left on disk even after a client crash, and
|
|
14
|
+
* no path is reused. Any failure before the spawn returns closes and removes what was made, then throws.
|
|
15
|
+
* - On the child's `close`, each read fd is read from position 0, bounded by `maxBuffer` (default 1 MiB, as
|
|
16
|
+
* execFile): more is a RangeError with code ERR_CHILD_PROCESS_STDIO_MAXBUFFER, over any exit status, with what
|
|
17
|
+
* fits passed on. The fds are closed, then the callback is called once, as execFile calls it: `(null, stdout,
|
|
18
|
+
* stderr)` after exit 0 with no signal; otherwise an Error with `code` (the exit status), `signal` and
|
|
19
|
+
* `killed: false`, and no text of the child's output in its message (it names the command, as execFile's). Text is `encoding` (default utf8); `'buffer'` or null gives Buffers. A spawn that
|
|
20
|
+
* fails (no pid) calls back with its error and empty output.
|
|
21
|
+
* - IT NEVER SIGNALS THE CHILD: no kill timer, and a nonzero `timeout` throws a TypeError (no caller of this exec
|
|
22
|
+
* gives one; a caller ends its own wait, never the child). `shell` and `killSignal` are not read.
|
|
23
|
+
* The TUI's `changeExec` (packages/tui/lib/read.mjs) keeps the same promise with its own lifecycle bookkeeping
|
|
24
|
+
* (its run's directory, its let-go on the way out). */
|
|
25
|
+
import { spawn } from 'node:child_process';
|
|
26
|
+
import { chmodSync, closeSync, fstatSync, mkdtempSync, openSync, readSync, rmdirSync, unlinkSync } from 'node:fs';
|
|
27
|
+
import { tmpdir } from 'node:os';
|
|
28
|
+
import { join } from 'node:path';
|
|
29
|
+
|
|
30
|
+
/** The name every private dir of this exec starts with, under the OS temp dir. */
|
|
31
|
+
export const FILE_OUTPUT_PREFIX = 'oats-output-';
|
|
32
|
+
const STREAMS = ['stdout', 'stderr'];
|
|
33
|
+
const quietly = (fn) => { try { return fn(); } catch { return undefined; } };
|
|
34
|
+
|
|
35
|
+
/** At most `max` + 1 bytes of `fd` from position 0: `{ data, over }`. */
|
|
36
|
+
function readBack(fd, max) {
|
|
37
|
+
const size = fstatSync(fd).size, room = Number.isFinite(max) ? Math.min(size, max + 1) : size;
|
|
38
|
+
const buffer = Buffer.alloc(room);
|
|
39
|
+
let got = 0;
|
|
40
|
+
while (got < room) { const n = readSync(fd, buffer, got, room - got, got); if (n === 0) break; got += n; }
|
|
41
|
+
const over = got > max;
|
|
42
|
+
return { data: buffer.subarray(0, over ? max : got), over };
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export function execFileToFiles(bin, argv, options = {}, callback = () => {}) {
|
|
46
|
+
const { cwd, env, encoding = 'utf8', timeout, maxBuffer = 1024 * 1024 } = options ?? {};
|
|
47
|
+
if (timeout !== undefined && timeout !== null && timeout !== 0) throw new TypeError('execFileToFiles never signals its child: a timeout is refused');
|
|
48
|
+
if (typeof maxBuffer !== 'number' || !(maxBuffer >= 0)) throw new TypeError('maxBuffer must be a number of bytes, 0 or more');
|
|
49
|
+
if (typeof callback !== 'function') throw new TypeError('callback must be a function');
|
|
50
|
+
const text = (data) => (encoding && encoding !== 'buffer' ? data.toString(encoding) : data);
|
|
51
|
+
|
|
52
|
+
const write = {}, read = {}, paths = {};
|
|
53
|
+
let dir = null;
|
|
54
|
+
const removeFiles = () => {
|
|
55
|
+
for (const name of STREAMS) if (paths[name] !== undefined) quietly(() => unlinkSync(paths[name]));
|
|
56
|
+
if (dir !== null) quietly(() => rmdirSync(dir));
|
|
57
|
+
};
|
|
58
|
+
const closeAll = (fds) => { for (const name of STREAMS) if (fds[name] !== undefined) quietly(() => closeSync(fds[name])); };
|
|
59
|
+
let child;
|
|
60
|
+
try {
|
|
61
|
+
dir = mkdtempSync(join(tmpdir(), FILE_OUTPUT_PREFIX));
|
|
62
|
+
chmodSync(dir, 0o700);
|
|
63
|
+
for (const name of STREAMS) {
|
|
64
|
+
const path = join(dir, name);
|
|
65
|
+
write[name] = openSync(path, 'wx', 0o600);
|
|
66
|
+
paths[name] = path;
|
|
67
|
+
read[name] = openSync(path, 'r');
|
|
68
|
+
}
|
|
69
|
+
child = spawn(bin, argv, { cwd, env, detached: true, stdio: ['ignore', write.stdout, write.stderr], shell: false, windowsHide: true });
|
|
70
|
+
} catch (error) {
|
|
71
|
+
closeAll(write); closeAll(read); removeFiles();
|
|
72
|
+
throw error;
|
|
73
|
+
}
|
|
74
|
+
// The child holds its own copies now: the client's write fds, the names and the dir go at once.
|
|
75
|
+
closeAll(write); removeFiles();
|
|
76
|
+
|
|
77
|
+
let over = false;
|
|
78
|
+
function finish(error, readOutput) {
|
|
79
|
+
if (over) return;
|
|
80
|
+
over = true;
|
|
81
|
+
const output = {};
|
|
82
|
+
let verdict = error;
|
|
83
|
+
for (const name of STREAMS) {
|
|
84
|
+
const taken = readOutput ? quietly(() => readBack(read[name], maxBuffer)) : undefined;
|
|
85
|
+
output[name] = text(taken?.data ?? Buffer.alloc(0));
|
|
86
|
+
if (taken?.over && verdict?.code !== 'ERR_CHILD_PROCESS_STDIO_MAXBUFFER') verdict = Object.assign(new RangeError(`${name} maxBuffer length exceeded`), { code: 'ERR_CHILD_PROCESS_STDIO_MAXBUFFER' });
|
|
87
|
+
}
|
|
88
|
+
closeAll(read);
|
|
89
|
+
callback(verdict, output.stdout, output.stderr);
|
|
90
|
+
}
|
|
91
|
+
child.once('close', (code, signal) => {
|
|
92
|
+
const clean = code === 0 && signal === null;
|
|
93
|
+
finish(clean ? null : Object.assign(new Error(`Command failed: ${[bin, ...argv].join(' ')}`), { code, signal, killed: false, cmd: [bin, ...argv].join(' ') }), true);
|
|
94
|
+
});
|
|
95
|
+
// A spawn that failed has no pid; an error of a started child (none is expected: nothing signals it) waits for its close.
|
|
96
|
+
child.on('error', (error) => { if (!Number.isInteger(child.pid)) finish(error, false); });
|
|
97
|
+
return child;
|
|
98
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/** An instance name as words, for display only: the label of an instance row in the Desktop's and the TUI's sidebar
|
|
2
|
+
* (the product owner, 0.68.1: "like normal words with a space between them, with the first word with initial capital
|
|
3
|
+
* letter"). Every `-` is a space, a run of them one space, the ends trimmed, and only the first character upper-cased;
|
|
4
|
+
* every other character stays as it was.
|
|
5
|
+
* `oats-expert-maintainer-lanes` → "Oats expert maintainer lanes", `tui-leader-hint-developer-2` →
|
|
6
|
+
* "Tui leader hint developer 2", `x` → "X", `already Words` → "Already Words".
|
|
7
|
+
* The real name stays wherever it identifies the instance (a title, the hover card, a copy, a search, the accessible
|
|
8
|
+
* name, a tab, the CLI): this is the visible label alone. DOM-free and import-free, with no module state. */
|
|
9
|
+
|
|
10
|
+
/** `name` as words; '' for a non-string or a name with nothing but `-` and spaces. */
|
|
11
|
+
export function instanceDisplayName(name) {
|
|
12
|
+
if (typeof name !== 'string') return '';
|
|
13
|
+
const words = name.replace(/-+/g, ' ').trim();
|
|
14
|
+
if (!words) return '';
|
|
15
|
+
// The first character by code point, so a name that starts outside the BMP is not split.
|
|
16
|
+
const first = String.fromCodePoint(words.codePointAt(0));
|
|
17
|
+
return first.toUpperCase() + words.slice(first.length);
|
|
18
|
+
}
|
|
@@ -154,21 +154,38 @@ export const FLAG_IGNORED_BYTES = FLAG_IGNORED_UNITS * 6 + 256;
|
|
|
154
154
|
* The fact is `{reason, warnings, omitted}`. `reason` is the one value the notice has a clause for, else
|
|
155
155
|
* null. `warnings` is the answer's warnings in the order given, each as one display line: the withheld
|
|
156
156
|
* marker for one the filter withholds, and no line for an entry with nothing to show. None is picked,
|
|
157
|
-
* matched or dropped by its words: no client looks for the kernel's sentence among them.
|
|
158
|
-
*
|
|
159
|
-
* line that does not fit and every line after it are left out, and no line is cut inside; the first line
|
|
160
|
-
* always fits (a display line is at most MAX_DISPLAY_LINE units). `omitted` counts the lines left out, 0
|
|
161
|
-
* when none. An entry with nothing to show was never a line and is not counted. */
|
|
157
|
+
* matched or dropped by its words: no client looks for the kernel's sentence among them. The cut is
|
|
158
|
+
* boundedWarnings's. */
|
|
162
159
|
export function launchFlagIgnored(answer) {
|
|
163
160
|
if (!record(answer) || !record(answer.launchPrompts) || answer.launchPrompts.status !== 'flag-ignored') return null;
|
|
164
|
-
|
|
161
|
+
return { reason: answer.launchPrompts.reason === 'channels-unavailable' ? 'channels-unavailable' : null, ...boundedWarnings(answer.warnings) };
|
|
162
|
+
}
|
|
163
|
+
/** An answer's raw `warnings` as `{warnings, omitted}`: one display line per entry, in order, the withheld
|
|
164
|
+
* marker for one the filter withholds and no line for an entry with nothing to show (not an array: no
|
|
165
|
+
* lines). Lines are kept in order while both bounds hold: FLAG_IGNORED_WARNINGS lines, FLAG_IGNORED_UNITS
|
|
166
|
+
* units in total. The first line that does not fit and every line after it are left out, and no line is cut
|
|
167
|
+
* inside; the first line always fits (a display line is at most MAX_DISPLAY_LINE units). `omitted` counts
|
|
168
|
+
* the lines left out, 0 when none; an entry with nothing to show was never a line and is not counted. By
|
|
169
|
+
* position only, never by words. Shared by launchFlagIgnored and the session-resume reader. */
|
|
170
|
+
export function boundedWarnings(raw) {
|
|
171
|
+
const lines = Array.isArray(raw) ? raw.map(w => displayLine(w)).filter(line => line !== null) : [];
|
|
165
172
|
const warnings = [];
|
|
166
173
|
let units = 0;
|
|
167
174
|
for (const line of lines) {
|
|
168
175
|
if (warnings.length === FLAG_IGNORED_WARNINGS || units + line.length > FLAG_IGNORED_UNITS) break;
|
|
169
176
|
warnings.push(line); units += line.length;
|
|
170
177
|
}
|
|
171
|
-
return {
|
|
178
|
+
return { warnings, omitted: lines.length - warnings.length };
|
|
179
|
+
}
|
|
180
|
+
/** Whether `{warnings, omitted}` could be boundedWarnings's answer as it crossed a boundary: display lines
|
|
181
|
+
* within both bounds, `omitted` a non-negative safe integer, above 0 only where a cut can have happened
|
|
182
|
+
* (beside a full list, or beside lines that leave no room for another of MAX_DISPLAY_LINE units). */
|
|
183
|
+
export function boundedWarningsValid(warnings, omitted) {
|
|
184
|
+
if (!Array.isArray(warnings) || warnings.length > FLAG_IGNORED_WARNINGS || !warnings.every(cleanLine)
|
|
185
|
+
|| !Number.isSafeInteger(omitted) || omitted < 0) return false;
|
|
186
|
+
const units = warnings.reduce((sum, line) => sum + line.length, 0);
|
|
187
|
+
return units <= FLAG_IGNORED_UNITS
|
|
188
|
+
&& !(omitted > 0 && warnings.length < FLAG_IGNORED_WARNINGS && units <= FLAG_IGNORED_UNITS - MAX_DISPLAY_LINE);
|
|
172
189
|
}
|
|
173
190
|
/** The fact above as it crossed a boundary: the same fact, or undefined. Exactly the three keys; `reason`
|
|
174
191
|
* the one known value or null; `warnings` display lines within both bounds; `omitted` a non-negative safe
|
|
@@ -177,12 +194,7 @@ export function launchFlagIgnored(answer) {
|
|
|
177
194
|
* one fact and never what carried it. Idempotent: the reader's own answer decodes to itself. */
|
|
178
195
|
export function flagIgnoredFact(v) {
|
|
179
196
|
if (!record(v) || Object.keys(v).length !== 3 || !['reason', 'warnings', 'omitted'].every(k => Object.hasOwn(v, k))
|
|
180
|
-
|| v.reason !== null && v.reason !== 'channels-unavailable'
|
|
181
|
-
|| !Array.isArray(v.warnings) || v.warnings.length > FLAG_IGNORED_WARNINGS || !v.warnings.every(cleanLine)
|
|
182
|
-
|| !Number.isSafeInteger(v.omitted) || v.omitted < 0) return undefined;
|
|
183
|
-
const units = v.warnings.reduce((sum, line) => sum + line.length, 0);
|
|
184
|
-
if (units > FLAG_IGNORED_UNITS
|
|
185
|
-
|| v.omitted > 0 && v.warnings.length < FLAG_IGNORED_WARNINGS && units <= FLAG_IGNORED_UNITS - MAX_DISPLAY_LINE) return undefined;
|
|
197
|
+
|| v.reason !== null && v.reason !== 'channels-unavailable' || !boundedWarningsValid(v.warnings, v.omitted)) return undefined;
|
|
186
198
|
return { reason: v.reason, warnings: [...v.warnings], omitted: v.omitted };
|
|
187
199
|
}
|
|
188
200
|
/** The notice for the fact, `{headline, detail?}`, or null when `fact` is not one. `instance` is the name
|
|
@@ -16,6 +16,8 @@ export const CLIENT_OWN_CODES = Object.freeze([
|
|
|
16
16
|
'E_REMOTE_ROSTER', 'E_WORKSPACE_FEATURE', 'E_WORKSPACE_UNKNOWN',
|
|
17
17
|
// This computer's deployments list (#1390): a CLI without it.
|
|
18
18
|
'E_DEPLOYMENTS_FEATURE',
|
|
19
|
+
// The machine's session resume sweep (#1559): a CLI without it.
|
|
20
|
+
'E_RESUME_FEATURE',
|
|
19
21
|
// A spawn: its preview, its apply and the wake saved with it; a suggest read a newer one ended (E_SUPERSEDED, #1421 §3).
|
|
20
22
|
'E_APPLY_UNAVAILABLE', 'E_BACKEND_UNAVAILABLE', 'E_BUSY', 'E_FORBIDDEN_FRAME', 'E_INPUT_PREPARATION', 'E_INSTANCE_GONE',
|
|
21
23
|
'E_INTENT_EXPIRED', 'E_OUTCOME_UNKNOWN', 'E_PREFLIGHT_INCOMPLETE', 'E_PREVIEW_UNAVAILABLE', 'E_SUPERSEDED', 'E_TARGET_CHANGED',
|
|
@@ -28,6 +28,12 @@ import { HERDR_REMOVED, terminalFailure, terminalMessage } from './terminal-cont
|
|
|
28
28
|
|
|
29
29
|
/** The kernel feature of `session attach --detach-key` (docs/desktop-cli-api.md). */
|
|
30
30
|
export const DETACH_KEY_FEATURE = "session-attach-detach-key";
|
|
31
|
+
/** The kernel feature of `session attach --no-status-line` (lib/session-viewer.mjs, the same
|
|
32
|
+
* name): the viewer without its status line, for a client that shows the scroll keys itself. */
|
|
33
|
+
export const NO_STATUS_LINE_FEATURE = "session-attach-no-status-line";
|
|
34
|
+
/** The kernel feature of `sessionViewer.prefixScroll` (lib/session-viewer.mjs, the same name): a
|
|
35
|
+
* kernel that lists it has the viewer's own Shift+PageUp, and says whether its viewer takes C-b [. */
|
|
36
|
+
export const PREFIX_SCROLL_FEATURE = "session-attach-prefix-scroll";
|
|
31
37
|
/** The kernel feature under which a roster group's `probe.features` is the host's own list
|
|
32
38
|
* (docs/desktop-cli-api.md, `probe.features`). Without it that key says nothing. */
|
|
33
39
|
const PROBE_FEATURES_FEATURE = "server-probe-features";
|
|
@@ -51,6 +57,26 @@ export function hostDetachKeySupported(cli, group) {
|
|
|
51
57
|
&& probe?.ok === true && Array.isArray(probe.features) && probe.features.includes(DETACH_KEY_FEATURE);
|
|
52
58
|
}
|
|
53
59
|
|
|
60
|
+
/** The viewer's scroll keys a client may name for a tab, `{ shift, prefix }`, from what the tab's
|
|
61
|
+
* host's kernel says (docs/desktop-cli-api.md, `session-attach-prefix-scroll`): a kernel that lists
|
|
62
|
+
* the feature has Shift+PageUp, and C-b [ too where its `sessionViewer.prefixScroll` is true. A
|
|
63
|
+
* kernel without the feature, or one not known, has neither: an older viewer may pass Shift+PageUp
|
|
64
|
+
* to the agent. */
|
|
65
|
+
function scrollKeysOf(facts) {
|
|
66
|
+
const listed = Array.isArray(facts?.features) && facts.features.includes(PREFIX_SCROLL_FEATURE);
|
|
67
|
+
return { shift: listed, prefix: listed && facts.sessionViewer?.prefixScroll === true };
|
|
68
|
+
}
|
|
69
|
+
/** A tab of this machine: this machine's accepted probe (`cli`, lib/cli-locator.mjs cliRecord). */
|
|
70
|
+
export function localScrollKeys(cli) {
|
|
71
|
+
return scrollKeysOf(cli?.ok === true ? cli : null);
|
|
72
|
+
}
|
|
73
|
+
/** A tab of another machine: the group's last roster read, when this machine's CLI relays what each
|
|
74
|
+
* host lists about itself and that read succeeded; otherwise unknown, so neither key. */
|
|
75
|
+
export function hostScrollKeys(cli, group) {
|
|
76
|
+
const probe = group?.probe;
|
|
77
|
+
return scrollKeysOf(lists(cli, PROBE_FEATURES_FEATURE) && probe?.ok === true ? probe : null);
|
|
78
|
+
}
|
|
79
|
+
|
|
54
80
|
const coded = (code, message) => Object.assign(new Error(message), { code });
|
|
55
81
|
const herdrRemoved = message => coded('E_HERDR_REMOVED', message);
|
|
56
82
|
const unreachable = () => coded('E_TERM_REMOTE_UNREACHABLE', 'the remote server could not be reached');
|
|
@@ -111,13 +137,16 @@ export function remoteTargetKey(remote) {
|
|
|
111
137
|
* target { home } on this machine; { serverId, instance, home } on another (what
|
|
112
138
|
* `remoteTargetKey` admits, and it refuses as it always did)
|
|
113
139
|
* detachKey undefined for none; else a non-empty string, appended as `--detach-key <key>`
|
|
140
|
+
* statusLine false for a viewer without its status line, the scroll keys (`--no-status-line`),
|
|
141
|
+
* asked only of a CLI that advertises NO_STATUS_LINE_FEATURE: one without it
|
|
142
|
+
* shows the line whatever it is asked, so it is asked nothing
|
|
114
143
|
*
|
|
115
144
|
* The client holds no copy of the kernel's key grammar: a key the kernel does not accept is the
|
|
116
145
|
* kernel's refusal. A key for a CLI that does not take one throws `unsupported-detach-key`: a
|
|
117
146
|
* kernel without the feature ignores the flag and opens a viewer with no exit, so the flag is
|
|
118
147
|
* never tried (docs/desktop-cli-api.md). Its message is for a developer; a client decides what it
|
|
119
148
|
* offers with `detachKeySupported`. */
|
|
120
|
-
export function sessionAttachArgv(cli, target, { detachKey } = {}) {
|
|
149
|
+
export function sessionAttachArgv(cli, target, { detachKey, statusLine = true } = {}) {
|
|
121
150
|
let address;
|
|
122
151
|
if (target?.serverId !== undefined) {
|
|
123
152
|
remoteTargetKey(target);
|
|
@@ -126,10 +155,11 @@ export function sessionAttachArgv(cli, target, { detachKey } = {}) {
|
|
|
126
155
|
if (typeof target?.home !== "string" || !target.home.startsWith("/") || target.home.includes("\0")) throw new Error("invalid session home");
|
|
127
156
|
address = ["--home", target.home];
|
|
128
157
|
}
|
|
129
|
-
|
|
158
|
+
const quiet = statusLine === false && Array.isArray(cli?.features) && cli.features.includes(NO_STATUS_LINE_FEATURE) ? ["--no-status-line"] : [];
|
|
159
|
+
if (detachKey === undefined) return ["session", "attach", ...address, ...quiet];
|
|
130
160
|
if (typeof detachKey !== "string" || !detachKey) throw new TypeError("a detach key is a non-empty string");
|
|
131
161
|
if (!detachKeySupported(cli)) throw Object.assign(new Error(`installed oats ${cli?.version || "unknown"} does not support session attach --detach-key; update the CLI`), { code: "unsupported-detach-key" });
|
|
132
|
-
return ["session", "attach", ...address, "--detach-key", detachKey];
|
|
162
|
+
return ["session", "attach", ...address, "--detach-key", detachKey, ...quiet];
|
|
133
163
|
}
|
|
134
164
|
/** The preflight of an attach on another machine, and the viewer to start after it: { binary, args }.
|
|
135
165
|
*
|
|
@@ -139,14 +169,14 @@ export function sessionAttachArgv(cli, target, { detachKey } = {}) {
|
|
|
139
169
|
* detachKey as `sessionAttachArgv` takes it. The viewer's arguments are built before the
|
|
140
170
|
* inspect runs, so a key that cannot be used starts no process; the inspect never
|
|
141
171
|
* carries the key. */
|
|
142
|
-
export async function prepareRemoteTerm(cli, remote, { exec, run = (binary, args, options) => runTerminalCommand(binary, args, options, exec), signal, current = () => true, detachKey } = {}) {
|
|
172
|
+
export async function prepareRemoteTerm(cli, remote, { exec, run = (binary, args, options) => runTerminalCommand(binary, args, options, exec), signal, current = () => true, detachKey, statusLine } = {}) {
|
|
143
173
|
const check = () => { if (signal?.aborted || !current()) throw Object.assign(new Error('Terminal context changed'), { code: 'E_TERM_CONTEXT_CHANGED' }); };
|
|
144
174
|
check();
|
|
145
175
|
requireRemoteSupport(cli, "session");
|
|
146
176
|
const bin = cli.bin;
|
|
147
177
|
remoteTargetKey(remote);
|
|
148
178
|
const address = ["--server", remote.serverId, "--home", remote.home];
|
|
149
|
-
const args = sessionAttachArgv(cli, remote, { detachKey });
|
|
179
|
+
const args = sessionAttachArgv(cli, remote, { detachKey, statusLine });
|
|
150
180
|
check(); // actual execution owner, not only IPC admission
|
|
151
181
|
let stdout;
|
|
152
182
|
try {
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
/** The kernel's machine sweep, `oats session resume --json`, run by a client at its launch: it resumes every
|
|
2
|
+
* lost session on every local deployment. The answer is read by session-resume.mjs; this home runs it and
|
|
3
|
+
* passes on only the kernel's JSON: its envelope, a refusal's code and message, or a code of its own.
|
|
4
|
+
* argv ['session', 'resume', '--json']: no `--deployment` and no `--plan` from a client.
|
|
5
|
+
* cwd '/': the kernel resolves no deployment from the client's working directory.
|
|
6
|
+
* env the client's, cleaned (cli-environment.mjs) and without the instance variables (kernel-environment.mjs):
|
|
7
|
+
* a client started inside an instance must not scope the sweep to it. OATS_HOME_DIR passes through.
|
|
8
|
+
* It needs a compatible CLI (`cli.ok`, an absolute `cli.bin`) and the probe's `session-resume` feature: without
|
|
9
|
+
* either it runs nothing, and nothing falls back. There is no client-side deadline: the sweep starts sessions,
|
|
10
|
+
* and a client waits as long as it runs; when the client is gone first, the answer is just not shown. */
|
|
11
|
+
import { cliEnvironment } from './cli-environment.mjs';
|
|
12
|
+
import { withoutInstanceVariables } from './kernel-environment.mjs';
|
|
13
|
+
import { parseEnvelope } from './cli-adapter.mjs';
|
|
14
|
+
import { kernelMade } from './kernel-made.mjs';
|
|
15
|
+
import { execFileToFiles } from './file-output-exec.mjs';
|
|
16
|
+
|
|
17
|
+
export const SESSION_RESUME_FEATURE = 'session-resume';
|
|
18
|
+
/** A row per instance of every local deployment, with the start answer's warnings: far below this. */
|
|
19
|
+
export const SESSION_RESUME_MAX_BUFFER = 4 * 1024 * 1024;
|
|
20
|
+
const ARGV = Object.freeze(['session', 'resume', '--json']);
|
|
21
|
+
const CODE = /^E_[A-Z0-9_]{1,64}$/;
|
|
22
|
+
|
|
23
|
+
const compatible = (cli) => cli?.ok === true && typeof cli.bin === 'string' && cli.bin.startsWith('/');
|
|
24
|
+
/** Whether a probe (`oats version --json`, accepted, with an absolute bin) declares the sweep. */
|
|
25
|
+
export const resumeSupported = (cli) => compatible(cli) && Array.isArray(cli.features) && cli.features.includes(SESSION_RESUME_FEATURE);
|
|
26
|
+
|
|
27
|
+
/** A failure this home writes itself: a code and nothing else (no message, no stderr, no thrown text). */
|
|
28
|
+
const failure = (code) => ({ schemaVersion: 1, ok: false, error: { code } });
|
|
29
|
+
/** The kernel's refusal, passed on as its code and, when a string, its message (kernel prose, marked the kernel's). */
|
|
30
|
+
function refusal(error) {
|
|
31
|
+
if (typeof error?.code !== 'string' || !CODE.test(error.code)) return failure('E_CLI_PROTOCOL');
|
|
32
|
+
return { schemaVersion: 1, ok: false, error: kernelMade({ code: error.code, ...(typeof error.message === 'string' ? { message: error.message } : {}) }) };
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Run the sweep once. `cli` is the client's accepted probe (`{ ok, bin, features }`).
|
|
37
|
+
* `io.exec` is the caller's exec, with execFile's signature; it defaults to execFileToFiles. A caller's exec MUST
|
|
38
|
+
* start the child detached (a session of its own), give it files and never pipes for its output, and never
|
|
39
|
+
* signal it: the sweep outlives the client that started it (the TUI passes its `changeExec`). No `timeout` is
|
|
40
|
+
* given. `io.env` replaces process.env as the environment cleaned.
|
|
41
|
+
* Never rejects. Resolves the parsed `{ schemaVersion: 1, ok: true, result }` (exit 0 only); the kernel's refusal
|
|
42
|
+
* `{ schemaVersion: 1, ok: false, error: { code, message } }` whatever the exit (E_RESUME_BUSY exits 1); or
|
|
43
|
+
* `{ schemaVersion: 1, ok: false, error: { code } }`: E_CLI_UNAVAILABLE, E_RESUME_FEATURE (nothing ran),
|
|
44
|
+
* E_CLI_OUTPUT_LIMIT (over SESSION_RESUME_MAX_BUFFER), E_CLI_PROTOCOL (no envelope, or a refusal without a valid
|
|
45
|
+
* code), E_CLI_FAILED (a nonzero exit with no refusal, or an exec that threw).
|
|
46
|
+
*/
|
|
47
|
+
export function runResumeSweep(cli, io = {}) {
|
|
48
|
+
if (!compatible(cli)) return Promise.resolve(failure('E_CLI_UNAVAILABLE'));
|
|
49
|
+
if (!resumeSupported(cli)) return Promise.resolve(failure('E_RESUME_FEATURE'));
|
|
50
|
+
const env = withoutInstanceVariables(cliEnvironment(io.env ?? process.env));
|
|
51
|
+
return new Promise((done) => {
|
|
52
|
+
const fail = (code) => done(failure(code));
|
|
53
|
+
try {
|
|
54
|
+
(io.exec ?? execFileToFiles)(cli.bin, [...ARGV], { cwd: '/', env, shell: false, encoding: 'utf8', maxBuffer: SESSION_RESUME_MAX_BUFFER }, (error, stdout) => {
|
|
55
|
+
if (error?.code === 'ERR_CHILD_PROCESS_STDIO_MAXBUFFER') return fail('E_CLI_OUTPUT_LIMIT');
|
|
56
|
+
const envelope = parseEnvelope(stdout);
|
|
57
|
+
if (!envelope) return fail(error ? 'E_CLI_FAILED' : 'E_CLI_PROTOCOL');
|
|
58
|
+
if (envelope.ok === false) return done(refusal(envelope.error));
|
|
59
|
+
if (error) return fail('E_CLI_FAILED'); // success is exit 0 only
|
|
60
|
+
done(envelope);
|
|
61
|
+
});
|
|
62
|
+
} catch { fail('E_CLI_FAILED'); }
|
|
63
|
+
});
|
|
64
|
+
}
|