@awebai/oats 0.68.1 → 0.69.2
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 +180 -36
- package/docs/capabilities.md +73 -10
- package/docs/capability-manifest.schema.json +1 -1
- package/docs/configuration.md +68 -2
- package/docs/design/2026-09-23-workspace-module-contracts.md +6 -4
- package/docs/design/2026-10-22-module-upgrade.md +1 -1
- package/docs/desktop-cli-api.md +600 -25
- package/docs/desktop-instance-start.md +59 -3
- package/docs/desktop.md +175 -10
- package/docs/execution-targets.md +536 -62
- package/docs/harness-trust.md +3 -1
- package/docs/implementation.md +33 -15
- package/docs/integrations.md +2 -2
- package/docs/knowledge.md +25 -16
- package/docs/oats-local.schema.json +2 -2
- package/docs/official-catalog.md +6 -5
- package/docs/packages.md +14 -14
- package/docs/release-notes/v0.69.0.md +658 -0
- package/docs/release-notes/v0.69.1.md +25 -0
- package/docs/release-notes/v0.69.2.md +259 -0
- package/docs/servers.md +51 -7
- package/docs/soul.schema.json +1 -0
- package/docs/souls-and-instances.md +46 -9
- package/docs/tui.md +177 -21
- package/docs/upgrading.md +16 -7
- package/docs/workspaces.md +2 -2
- package/injects/instance-boundary.md +19 -33
- package/injects/work-attached.md +8 -13
- package/injects/work-checkout.md +16 -30
- package/injects/work-directory.md +9 -15
- package/injects/work-workspace.md +8 -19
- package/injects/work-worktree.md +18 -33
- package/lib/capability-contract.mjs +2 -2
- package/lib/core.mjs +496 -127
- package/lib/file-pieces.mjs +49 -0
- package/lib/instance-background.mjs +54 -0
- package/lib/instance-events.mjs +25 -4
- package/lib/instance-inspect.mjs +3 -0
- package/lib/instance-lifecycle.mjs +35 -0
- package/lib/instance-resolution.mjs +3 -2
- package/lib/instance-same-work.mjs +67 -0
- package/lib/instance-upgrade.mjs +18 -0
- 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/materialize.mjs +23 -2
- package/lib/resolve.mjs +32 -5
- package/lib/schedule.mjs +3 -3
- package/lib/servers.mjs +136 -27
- package/lib/session-end.mjs +82 -0
- package/lib/session-input.mjs +43 -9
- package/lib/session-resume-contract.mjs +33 -0
- package/lib/session-resume.mjs +337 -0
- package/lib/session-seen.mjs +163 -0
- package/lib/session-viewer.mjs +147 -44
- package/lib/soul-composition.mjs +15 -11
- package/lib/start-env.mjs +110 -0
- package/lib/tmux-server-scope.mjs +139 -14
- package/lib/workspace.mjs +41 -6
- package/package-catalog.json +11 -5
- package/package.json +1 -1
- package/packages/client/cli-adapter.mjs +39 -8
- package/packages/client/cli-locator.mjs +3 -2
- package/packages/client/deployment-data.mjs +16 -0
- package/packages/client/deployment-panel.mjs +7 -0
- package/packages/client/file-output-exec.mjs +98 -0
- package/packages/client/instance-tree.mjs +64 -14
- package/packages/client/launch-prompt-outcome.mjs +25 -13
- package/packages/client/own-codes.mjs +2 -0
- package/packages/client/panel-views.mjs +11 -3
- package/packages/client/remote-roster.mjs +5 -1
- package/packages/client/roster-sections.mjs +50 -6
- package/packages/client/same-work.mjs +49 -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/soul-rows.mjs +2 -0
- package/packages/client/spawn-apply-contract.mjs +2 -1
- package/packages/client/spawn-decision.mjs +4 -1
- package/packages/client/spawn-preview-contract.mjs +12 -1
- package/packages/client/spawn-preview.mjs +2 -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 +2 -2
- package/packages/tui/lib/client.mjs +7 -3
- package/packages/tui/lib/main.mjs +49 -14
- package/packages/tui/lib/model.mjs +146 -55
- package/packages/tui/lib/store.mjs +84 -27
- package/packages/tui/lib/term/text.mjs +12 -9
- package/packages/tui/lib/views/frame.mjs +74 -7
- package/packages/tui/lib/views/help.mjs +10 -3
- package/packages/tui/lib/views/instances.mjs +41 -3
- package/skills/oats-getting-started/SKILL.md +117 -4
|
@@ -1,11 +1,17 @@
|
|
|
1
|
-
/**
|
|
2
|
-
*
|
|
3
|
-
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
1
|
+
/** Where the OATS tmux server and the agents' harnesses run on a systemd host (awebai/oats#915).
|
|
2
|
+
* systemd-oomd ends a whole cgroup under memory pressure, and a unit's stop ends its cgroup: a
|
|
3
|
+
* server started inside a unit of the user manager (the schedule tick's oneshot, a Desktop run as a
|
|
4
|
+
* user service, a client launched from a desktop session in its `app-*.scope`) would share that
|
|
5
|
+
* unit's fate. On Linux, on the unified cgroup hierarchy, from inside a service, or a scope of the
|
|
6
|
+
* user manager, the server's start runs under `systemd-run --user --scope`: the server is then a
|
|
7
|
+
* sibling of that unit, not part of it. Each agent's harness, wherever the server runs, is launched
|
|
8
|
+
* in a scope of its own too (agentScope), so that such a kill ends one agent and never the server
|
|
9
|
+
* or the others. Everything else starts as before. */
|
|
10
|
+
import { execFileSync } from "node:child_process";
|
|
7
11
|
import { createHash, randomBytes } from "node:crypto";
|
|
8
|
-
import { readFileSync } from "node:fs";
|
|
12
|
+
import { readFileSync, statSync } from "node:fs";
|
|
13
|
+
import { canonicalHomePath } from "./real-path.mjs";
|
|
14
|
+
import { systemTool } from "./system-tools.mjs";
|
|
9
15
|
|
|
10
16
|
const HIERARCHY = "the cgroup hierarchy is not the unified one, so there is no unified cgroup path to judge";
|
|
11
17
|
/** The last component of an absolute cgroup path, when it names a systemd service. */
|
|
@@ -14,15 +20,27 @@ function serviceOf(path) {
|
|
|
14
20
|
const last = path.split("/").pop();
|
|
15
21
|
return last.endsWith(".service") ? last : null;
|
|
16
22
|
}
|
|
23
|
+
/** The user manager's own unit, as a cgroup path component. */
|
|
24
|
+
const USER_MANAGER = /^user@\d+\.service$/;
|
|
25
|
+
/** The unit a unified cgroup path's last component names, when a server started there is to leave
|
|
26
|
+
* it: a service, system or user (as #915 began), or a scope under the user manager (a desktop
|
|
27
|
+
* application's or a terminal's `app-*.scope`, an agent's `oats-agent-*.scope`, the manager's own
|
|
28
|
+
* `init.scope`). A login session's `session-N.scope` sits beside the user manager, not in it: not one. */
|
|
29
|
+
function unitOf(path) {
|
|
30
|
+
const service = serviceOf(path);
|
|
31
|
+
if (service || typeof path !== "string" || !path.startsWith("/")) return service;
|
|
32
|
+
const parts = path.split("/"), last = parts.pop();
|
|
33
|
+
return last.endsWith(".scope") && parts.some((part) => USER_MANAGER.test(part)) ? last : null;
|
|
34
|
+
}
|
|
17
35
|
|
|
18
|
-
/** → { wrap: true, unit } (inside `unit`, start the server in its own scope), { wrap: false },
|
|
19
|
-
* { wrap: false, warn: { unit, reason } } (inside a service, known only from INVOCATION_ID, on a
|
|
36
|
+
/** → { wrap: true, unit } (inside `unit`, start the server in its own scope: unitOf), { wrap: false },
|
|
37
|
+
* or { wrap: false, warn: { unit, reason } } (inside a service, known only from INVOCATION_ID, on a
|
|
20
38
|
* hierarchy this cannot judge). `cgroup` is the text of /proc/self/cgroup, null when unreadable. */
|
|
21
39
|
export function serverScopePlan({ platform, cgroup, invocationId }) {
|
|
22
40
|
if (platform !== "linux" || typeof cgroup !== "string") return { wrap: false };
|
|
23
41
|
const lines = cgroup.split("\n").filter(Boolean);
|
|
24
42
|
if (lines.length === 1 && lines[0].startsWith("0::") && lines[0].slice(3).startsWith("/")) {
|
|
25
|
-
const unit =
|
|
43
|
+
const unit = unitOf(lines[0].slice(3));
|
|
26
44
|
return unit ? { wrap: true, unit } : { wrap: false };
|
|
27
45
|
}
|
|
28
46
|
if (!invocationId) return { wrap: false };
|
|
@@ -31,9 +49,12 @@ export function serverScopePlan({ platform, cgroup, invocationId }) {
|
|
|
31
49
|
return { wrap: false, warn: { unit: named || "a systemd service", reason: HIERARCHY } };
|
|
32
50
|
}
|
|
33
51
|
|
|
34
|
-
/** Where the creator runs → { platform, cgroup, invocationId }: `io`'s when it says, else
|
|
35
|
-
* OATS_TEST_CGROUP (the text of a /proc/self/cgroup, judged as Linux), else this
|
|
36
|
-
* cgroup when it cannot be read, or off Linux).
|
|
52
|
+
/** Where the creator runs → { platform, cgroup, invocationId, systemdBooted }: `io`'s when it says, else
|
|
53
|
+
* for a test only OATS_TEST_CGROUP (the text of a /proc/self/cgroup, judged as Linux), else this
|
|
54
|
+
* process's own (null cgroup when it cannot be read, or off Linux). `systemdBooted` is sd_booted's
|
|
55
|
+
* answer (/run/systemd/system is a directory); for a test, io.systemdBooted or OATS_TEST_SYSTEMD_BOOTED
|
|
56
|
+
* ("1" or "0"), and a test's placement (io.cgroup, OATS_TEST_CGROUP) is a systemd host's unless one of
|
|
57
|
+
* those says otherwise. */
|
|
37
58
|
export function creatorPlacement(io) {
|
|
38
59
|
const seam = process.env.OATS_TEST_CGROUP;
|
|
39
60
|
const platform = io?.platform ?? (seam !== undefined ? "linux" : process.platform);
|
|
@@ -44,7 +65,16 @@ export function creatorPlacement(io) {
|
|
|
44
65
|
else cgroup = null;
|
|
45
66
|
}
|
|
46
67
|
const invocationId = io && "invocationId" in io ? io.invocationId : process.env.INVOCATION_ID;
|
|
47
|
-
|
|
68
|
+
const booted = process.env.OATS_TEST_SYSTEMD_BOOTED;
|
|
69
|
+
const systemdBooted = typeof io?.systemdBooted === "boolean" ? io.systemdBooted
|
|
70
|
+
: booted !== undefined ? booted === "1"
|
|
71
|
+
: seam !== undefined || io?.cgroup !== undefined ? true // a test's placement: a systemd host's
|
|
72
|
+
: platform === "linux" && sdBooted();
|
|
73
|
+
return { platform, cgroup, invocationId, systemdBooted };
|
|
74
|
+
}
|
|
75
|
+
/** sd_booted(3): whether this host was booted with systemd as its init. */
|
|
76
|
+
function sdBooted() {
|
|
77
|
+
try { return statSync("/run/systemd/system").isDirectory(); } catch { return false; }
|
|
48
78
|
}
|
|
49
79
|
|
|
50
80
|
/** The scope's name, one per start that starts the server: a prefix per server address (the socket
|
|
@@ -60,3 +90,98 @@ export function serverScopeUnit({ socket, env }) {
|
|
|
60
90
|
export function serverScopeWarning({ unit, reason }) {
|
|
61
91
|
return `the OATS tmux server was started inside ${unit}: it ends when that unit stops; start the OATS tmux server from your own shell, or enable the user systemd bus (${reason})`;
|
|
62
92
|
}
|
|
93
|
+
|
|
94
|
+
// ---- the agent's scope ------------------------------------------------------------------------------
|
|
95
|
+
|
|
96
|
+
/** Whether a creator judged at `placement` (creatorPlacement) launches agents' harnesses in scopes of
|
|
97
|
+
* their own: Linux booted with systemd, on the unified hierarchy, whatever unit the creator is in or
|
|
98
|
+
* not in (the harness is the server's child, wherever the server is). A host without systemd (a
|
|
99
|
+
* container's own init, another init system) has no user manager and no systemd-oomd: nothing to
|
|
100
|
+
* keep an agent out of, so nothing is wrapped and nothing said, as off Linux. */
|
|
101
|
+
export function agentScopeHost({ platform, cgroup, systemdBooted }) {
|
|
102
|
+
if (platform !== "linux" || !systemdBooted || typeof cgroup !== "string") return false;
|
|
103
|
+
const lines = cgroup.split("\n").filter(Boolean);
|
|
104
|
+
return lines.length === 1 && lines[0].startsWith("0::/");
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** An agent's scope name, one per launch: a prefix per home (the first 12 hex of the sha256 of its
|
|
108
|
+
* canonical path) and a random part. A scope ends with its last process, so a later launch of the
|
|
109
|
+
* same home never reuses its name (as serverScopeUnit). */
|
|
110
|
+
export function agentScopeUnit({ home }) {
|
|
111
|
+
return `oats-agent-${createHash("sha256").update(canonicalHomePath(home)).digest("hex").slice(0, 12)}-${randomBytes(4).toString("hex")}`;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** The names `systemd-run --user` finds the user manager by: the session bus, else the runtime
|
|
115
|
+
* directory's bus and the manager's private socket. The probe runs with the pane's values of these
|
|
116
|
+
* and no others. */
|
|
117
|
+
export const SCOPE_ENV_NAMES = Object.freeze(["XDG_RUNTIME_DIR", "DBUS_SESSION_BUS_ADDRESS"]);
|
|
118
|
+
const PROBE_TIMEOUT_MS = 5000;
|
|
119
|
+
const PROBE_ARGS = Object.freeze(["--user", "--scope", "--collect", "--quiet", "--"]);
|
|
120
|
+
/** The real probe: a scope around the system's `true`, run with `env` → { ok: true } | { reason }. */
|
|
121
|
+
function runScopeProbe({ systemdRun, trueFile, env }) {
|
|
122
|
+
try {
|
|
123
|
+
execFileSync(systemdRun, [...PROBE_ARGS, trueFile], { env, timeout: PROBE_TIMEOUT_MS, stdio: ["ignore", "ignore", "pipe"], encoding: "utf8" });
|
|
124
|
+
return { ok: true };
|
|
125
|
+
} catch (e) {
|
|
126
|
+
if (e?.code === "ETIMEDOUT" || (e?.signal && e?.status == null)) return { reason: `it did not answer within ${PROBE_TIMEOUT_MS / 1000} s` };
|
|
127
|
+
return { reason: String(e?.stderr ?? "").trim().split("\n")[0] || (Number.isInteger(e?.status) ? `exit ${e.status}` : String(e?.message || "failed")) };
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
/** The probes' answers, per probe (the real one, or a test's io.scopeProbe), per systemd-run and the
|
|
131
|
+
* pane's SCOPE_ENV_NAMES: one probe per kernel process for each, so a sweep of many starts probes once. */
|
|
132
|
+
const probed = new WeakMap();
|
|
133
|
+
function probeOnce(probe, { systemdRun, trueFile, env }) {
|
|
134
|
+
let answers = probed.get(probe);
|
|
135
|
+
if (!answers) probed.set(probe, answers = new Map());
|
|
136
|
+
const key = JSON.stringify([systemdRun, ...SCOPE_ENV_NAMES.map((name) => env[name] ?? null)]);
|
|
137
|
+
if (!answers.has(key)) answers.set(key, probe({ systemdRun, trueFile, env: { ...env } }));
|
|
138
|
+
return answers.get(key);
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* Whether this launch's harness runs in a scope of its own → { wrapper: { systemdRun, env } } (the
|
|
143
|
+
* system's systemd-run and env, absolute: agentScopeArgv), { warning } (a systemd host where it runs in
|
|
144
|
+
* the server's cgroup, and why), or {} (a host where nothing changes: off Linux, not booted with
|
|
145
|
+
* systemd, a cgroup hierarchy other than the unified one; nothing said). `paneEnv()` gives the pane's SCOPE_ENV_NAMES as { env } (a name it does not set
|
|
146
|
+
* is not in `env`) or { reason } (they cannot be read); it is called only on a host that wraps.
|
|
147
|
+
* The probe is the guard: the launch is wrapped only once `systemd-run --user --scope` has started a
|
|
148
|
+
* scope with the pane's own environment. `io` is a test's: its placement (creatorPlacement, with
|
|
149
|
+
* io.systemdBooted), its
|
|
150
|
+
* system directories (io.systemToolDirs) and its probe (io.scopeProbe, given what the real probe is
|
|
151
|
+
* given). An `io` without a scopeProbe judges no scope at all: its tmux is a test's, and the host's
|
|
152
|
+
* user manager is never reached unless a test opts in.
|
|
153
|
+
*/
|
|
154
|
+
export function agentScope({ io, paneEnv }) {
|
|
155
|
+
if (!agentScopeHost(creatorPlacement(io))) return {};
|
|
156
|
+
const probe = io ? io.scopeProbe : runScopeProbe;
|
|
157
|
+
if (!probe) return {};
|
|
158
|
+
const unscoped = (reason) => ({ warning: agentScopeWarning(reason) });
|
|
159
|
+
const where = io?.systemToolDirs ? { dirs: io.systemToolDirs } : {};
|
|
160
|
+
const systemdRun = systemTool("systemd-run", where), clean = systemTool("env", where), trueFile = systemTool("true", where);
|
|
161
|
+
const missing = systemdRun.reason ?? clean.reason ?? trueFile.reason;
|
|
162
|
+
if (missing) return unscoped(missing);
|
|
163
|
+
const pane = paneEnv();
|
|
164
|
+
if (pane.reason) return unscoped(pane.reason);
|
|
165
|
+
const answer = probeOnce(probe, { systemdRun: systemdRun.file, trueFile: trueFile.file, env: pane.env });
|
|
166
|
+
if (!answer?.ok) return unscoped(`\`systemd-run --user --scope\` could not start a scope in the pane's environment: ${answer?.reason || "the probe failed"}`);
|
|
167
|
+
return { wrapper: { systemdRun: systemdRun.file, env: clean.file } };
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** The words before the harness's own `/bin/sh -c` that run it in a scope named `unit` (agentScopeUnit):
|
|
171
|
+
* systemd-run execs the system's env, which execs what follows with INVOCATION_ID removed (the
|
|
172
|
+
* scope's own, which systemd-run exports to what it runs, as for the server). The process keeps its
|
|
173
|
+
* pid through each exec, so the harness stays the pane's direct child and its exit status is the
|
|
174
|
+
* pane shell's to read. */
|
|
175
|
+
export function agentScopeArgv({ systemdRun, env }, unit) {
|
|
176
|
+
return [systemdRun, "--user", "--scope", "--collect", "--quiet", "--unit", unit, "--", env, "-u", "INVOCATION_ID"];
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/** The answer's warning when the harness runs in the server's cgroup. */
|
|
180
|
+
const AGENT_SCOPE_PREFIX = "the agent's harness runs in the OATS tmux server's cgroup, not a scope of its own: ";
|
|
181
|
+
export function agentScopeWarning(reason) {
|
|
182
|
+
return `${AGENT_SCOPE_PREFIX}${reason}`;
|
|
183
|
+
}
|
|
184
|
+
/** Whether a warning is agentScopeWarning's: said of the host, not of the one launch that met it. */
|
|
185
|
+
export function isAgentScopeWarning(text) {
|
|
186
|
+
return typeof text === "string" && text.startsWith(AGENT_SCOPE_PREFIX);
|
|
187
|
+
}
|
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 });
|
|
@@ -930,10 +964,10 @@ export function standaloneRepo(ref, commit, discovery, { remote: injected } = {}
|
|
|
930
964
|
// even when the workspace (and its defaults) cannot be read. ANY mention of
|
|
931
965
|
// oats.core in the soul — `{ from: package }`, `{ from: here }`, `{ from: <repo> }`
|
|
932
966
|
// or `off` — suppresses the kernel default: the soul's own choice is then judged
|
|
933
|
-
// by the loop below exactly like every other capability (S4).
|
|
967
|
+
// by the loop below exactly like every other capability (S4). The default is added
|
|
968
|
+
// after the soul's own entries, so its instructions follow theirs, as any default's do.
|
|
934
969
|
const kept = {};
|
|
935
970
|
const declaredCaps = soul.definition.capabilities || {};
|
|
936
|
-
if (!Object.hasOwn(declaredCaps, STANDALONE_DEFAULT_CAPABILITY)) kept[STANDALONE_DEFAULT_CAPABILITY] = { from: "package" };
|
|
937
971
|
for (const [name, choice] of Object.entries(declaredCaps)) {
|
|
938
972
|
const from = isObject(choice) ? choice.from : null;
|
|
939
973
|
if (choice === "off") continue;
|
|
@@ -949,6 +983,7 @@ export function standaloneRepo(ref, commit, discovery, { remote: injected } = {}
|
|
|
949
983
|
problems.push({ code: "E_NOT_A_MEMBER", repoKey: key, path: `${soul.path}/soul.yaml#/capabilities/${pointerKey(name)}`, message: `${show(name)} comes from ${show(from)}, which cannot be confirmed as a member without the workspace` });
|
|
950
984
|
}
|
|
951
985
|
}
|
|
986
|
+
if (!Object.hasOwn(declaredCaps, STANDALONE_DEFAULT_CAPABILITY)) kept[STANDALONE_DEFAULT_CAPABILITY] = { from: "package" };
|
|
952
987
|
return { ...soul, capabilities: kept };
|
|
953
988
|
});
|
|
954
989
|
return {
|
package/package-catalog.json
CHANGED
|
@@ -3,12 +3,12 @@
|
|
|
3
3
|
"packages": {
|
|
4
4
|
"oats.okf": {
|
|
5
5
|
"url": "https://github.com/awebai/oats-okf.git",
|
|
6
|
-
"ref": "v5.
|
|
6
|
+
"ref": "v5.5.0",
|
|
7
7
|
"path": "oats-package"
|
|
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.16.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.2",
|
|
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",
|
|
@@ -124,6 +124,11 @@ export function spawnArgv(agent, workspaceDir, taskFile, opts = {}) {
|
|
|
124
124
|
if (typeof opts.yolo !== "boolean") throw Object.assign(new Error("yolo must be a boolean"), { code: "E_BAD_ARGS" });
|
|
125
125
|
argv.push(opts.yolo ? "--yolo" : "--no-yolo");
|
|
126
126
|
}
|
|
127
|
+
// Run in background (feature instance-background, #1579): the instance's own flag, as the soul's default or not.
|
|
128
|
+
if (opts.background !== undefined) {
|
|
129
|
+
if (typeof opts.background !== "boolean") throw Object.assign(new Error("background must be a boolean"), { code: "E_BAD_ARGS" });
|
|
130
|
+
argv.push(opts.background ? "--background" : "--no-background");
|
|
131
|
+
}
|
|
127
132
|
if (opts.suggestName) argv.push("--suggest-name");
|
|
128
133
|
argv.push("--json");
|
|
129
134
|
return argv;
|
|
@@ -332,6 +337,15 @@ export function cliServerRemove(bin, id, io = {}) {
|
|
|
332
337
|
if (typeof id !== "string" || !MACHINE_ID.test(id)) return Promise.resolve(badMachineArgs());
|
|
333
338
|
return runJson(bin, ["server", "remove", id, "--json"], { cwd: io.cwd || process.cwd(), exec: io.exec, timeout: io.timeout });
|
|
334
339
|
}
|
|
340
|
+
/** `oats session inspect --home <home> --json` on this computer (#1569): the kernel's observation of an
|
|
341
|
+
* instance's terminal, whose `paneId` is the agent's pane by the kernel's own rule, in a window of one pane
|
|
342
|
+
* or several. A clean exit is required for success (`strictExit`). */
|
|
343
|
+
export function cliSessionInspect(bin, { home } = {}, io = {}) {
|
|
344
|
+
if (typeof bin !== "string" || !isAbsolute(bin) || typeof home !== "string" || !isAbsolute(home) || home.includes("\0")) {
|
|
345
|
+
return Promise.resolve({ schemaVersion: 1, ok: false, error: { code: "E_BAD_ARGS", message: "Invalid inspect home" } });
|
|
346
|
+
}
|
|
347
|
+
return runJson(bin, ["session", "inspect", "--home", home, "--json"], { cwd: io.cwd || process.cwd(), exec: io.exec, timeout: io.timeout || 15_000, strictExit: true });
|
|
348
|
+
}
|
|
335
349
|
/** `oats server forget <server> --instance <instance> --json` (#1131): drop this computer's saved route to a
|
|
336
350
|
* remote instance its host no longer lists. Both values are one roster row's identity, each one argv entry,
|
|
337
351
|
* never option-shaped. A clean exit is required for success (`strictExit`): an answer the CLI did not finish
|
|
@@ -639,22 +653,39 @@ export function operationArgs(args) {
|
|
|
639
653
|
if (entries.length > 8 || entries.some(([k, v]) => !/^[a-z][a-z0-9-]{0,63}$/.test(k) || typeof v !== 'string' || !v || v.length > 1024 || /[\x00-\x1f\x7f]/.test(v))) return null;
|
|
640
654
|
return entries.flatMap(([k, v]) => ['--arg', `${k}=${v}`]);
|
|
641
655
|
}
|
|
642
|
-
/**
|
|
643
|
-
* (
|
|
644
|
-
*
|
|
645
|
-
*
|
|
646
|
-
*
|
|
647
|
-
|
|
656
|
+
/** A verb that writes one field of an instance's own record: `oats instance <verb> <instance> <values…> --home <home>
|
|
657
|
+
* (--dir <context> | --server <server>) --json`, addressed as `oats instance stop` is (lifecycle-cli.mjs: a routed
|
|
658
|
+
* command never carries --dir). Shared by `instance color` and `instance background` (server/instance-record.mjs);
|
|
659
|
+
* each checks its own value first. Anything out of shape is refused here and nothing runs. A read's deadline:
|
|
660
|
+
* 30 s, 45 s routed. The envelope comes back as the kernel printed it; the caller decodes it. */
|
|
661
|
+
function runInstanceRecord(bin, { instance, home, context, server }, verb, values, io) {
|
|
648
662
|
const fail = code => ({ schemaVersion: 1, ok: false, error: { code } });
|
|
649
663
|
if (typeof bin !== "string" || !isAbsolute(bin) || typeof instance !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(instance)
|
|
650
|
-
|| typeof home !== "string" || !isAbsolute(home) || home.includes("\0")
|
|
664
|
+
|| typeof home !== "string" || !isAbsolute(home) || home.includes("\0")
|
|
651
665
|
|| (server !== undefined ? !/^[a-z0-9][a-z0-9-]{0,63}$/.test(server ?? "") : typeof context !== "string" || !isAbsolute(context))) return fail("E_BAD_ARGS");
|
|
652
|
-
const argv = ["instance",
|
|
666
|
+
const argv = ["instance", verb, instance, ...values, "--home", home,
|
|
653
667
|
...(server !== undefined ? ["--server", server] : ["--dir", context]), "--json"];
|
|
654
668
|
const limit = server !== undefined ? 45_000 : 30_000;
|
|
655
669
|
return runJson(bin, argv, { cwd: server !== undefined ? io.cwd : context, exec: io.exec, strictExit: true,
|
|
656
670
|
timeout: Number.isFinite(io.timeout) && io.timeout > 0 ? Math.min(io.timeout, limit) : limit });
|
|
657
671
|
}
|
|
672
|
+
const instanceRecordRefused = () => ({ schemaVersion: 1, ok: false, error: { code: "E_BAD_ARGS" } });
|
|
673
|
+
/** An instance's colour (feature instance-color, awebai/oats#1421 §2): `oats instance color <instance>
|
|
674
|
+
* (<color> | --clear) …` (runInstanceRecord). `color` is a palette name (soul-colors.mjs SOUL_COLORS) or null to
|
|
675
|
+
* clear; anything else is refused here and nothing runs. */
|
|
676
|
+
export async function cliInstanceColor(bin, args, io = {}) {
|
|
677
|
+
const { color } = args;
|
|
678
|
+
if (!(color === null || SOUL_COLORS.includes(color))) return instanceRecordRefused();
|
|
679
|
+
return runInstanceRecord(bin, args, "color", color === null ? ["--clear"] : [color], io);
|
|
680
|
+
}
|
|
681
|
+
/** Whether an instance runs in the background (feature instance-background, awebai/oats#1579): `oats instance
|
|
682
|
+
* background <instance> (on | off) …` (runInstanceRecord). `background` is a boolean; anything else is refused
|
|
683
|
+
* here and nothing runs. Over `--server`, a host without the feature refuses it (E_REMOTE_INCOMPATIBLE). */
|
|
684
|
+
export async function cliInstanceBackground(bin, args, io = {}) {
|
|
685
|
+
const { background } = args;
|
|
686
|
+
if (typeof background !== "boolean") return instanceRecordRefused();
|
|
687
|
+
return runInstanceRecord(bin, args, "background", [background ? "on" : "off"], io);
|
|
688
|
+
}
|
|
658
689
|
|
|
659
690
|
/** `maxAge` (feature observe-max-age) is inspect's alone; `features` is the probe's list and
|
|
660
691
|
* gates the flags (also `instructions`, `skills` and `composedSkills`), so an undeclared kernel gets the flagless argv even when a value is given. */
|
|
@@ -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; };
|
|
@@ -219,9 +223,18 @@ export function deploymentStatusData(document, deployment) {
|
|
|
219
223
|
// instanceColor, the one rule of which colour a row shows). Validated, never check()ed: anything
|
|
220
224
|
// else is dropped and the row reads as one with no colour.
|
|
221
225
|
if (own(instance, 'color') && instanceColor(instance) !== null) row.color = instanceColor(instance);
|
|
226
|
+
// Feature instance-background (#1579): the row is placed in the Background section. Exactly true only; any
|
|
227
|
+
// other value is dropped, never checked: the row stays in the main tree.
|
|
228
|
+
if (own(instance, 'background') && instance.background === true) row.background = true;
|
|
222
229
|
// #802 (feature worktree-event): a spawn running its worktree hooks, verifiably alive. Boolean true only;
|
|
223
230
|
// any other value is dropped, never checked: the row stays an ordinary one.
|
|
224
231
|
if (own(instance, 'spawnInProgress') && instance.spawnInProgress === true) row.spawnInProgress = true;
|
|
232
|
+
// Session resume: how the instance's last session ended, one of SESSION_ENDS exactly. Any other value is
|
|
233
|
+
// dropped, never checked: the row reads as one that did not say.
|
|
234
|
+
if (own(instance, 'sessionEnd') && SESSION_END_VALUES.includes(instance.sessionEnd)) row.sessionEnd = instance.sessionEnd;
|
|
235
|
+
// #1577 (feature instance-same-work): the child does its parent's work, so its parent line is drawn
|
|
236
|
+
// (same-work.mjs). Boolean true only; any other value is dropped, never checked: the row reads unflagged.
|
|
237
|
+
if (own(instance, 'sameWork') && instance.sameWork === true) row.sameWork = true;
|
|
225
238
|
if (own(instance, 'modules')) row.modules = modules(instance.modules);
|
|
226
239
|
if (own(instance, 'soul')) row.soul = soulSource(instance.soul);
|
|
227
240
|
if (own(instance, 'workspace')) row.workspace = recordedWorkspace(instance.workspace);
|
|
@@ -365,6 +378,9 @@ export function soulsData(document) {
|
|
|
365
378
|
out.key = out.kind === 'package' ? out.qualifiedName : out.name;
|
|
366
379
|
if (own(row, 'key')) check(soulKey(row.key) && row.key === out.key);
|
|
367
380
|
flags(row, ['private', 'spawnable'], out);
|
|
381
|
+
// Feature instance-background (#1579): the soul declares `background: true`, the default of the spawn dialog's
|
|
382
|
+
// Run in background switch. Exactly true only; any other value is dropped, never checked (as an instance row's).
|
|
383
|
+
if (own(row, 'background') && row.background === true) out.background = true;
|
|
368
384
|
// desktop-facts: whether a spawn here would refuse, and the file. The row's flat harness/model/harnessFrom
|
|
369
385
|
// are not kept: with launch-preference (0.30) the soul and this machine choose them, and the row's `launch`
|
|
370
386
|
// (below) carries the kernel's report of that choice; before 0.30 they were always the kernel's default.
|
|
@@ -108,12 +108,19 @@ 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 } : {}),
|
|
114
|
+
// #1577: the kernel's same-work flag (deployment-data.mjs keeps it as true only); same-work.mjs reads it.
|
|
115
|
+
...(i.sameWork === true ? { sameWork: true } : {}),
|
|
111
116
|
...(i.captured ? { captured: true } : {}),
|
|
112
117
|
// Needs input (PR K): the validated claim (or null, unknown) as status reported it; absent stays absent.
|
|
113
118
|
// The client's liveness is merged before projection, so running/runtimeState beside it are the probe's.
|
|
114
119
|
...(i.waitingOnYou !== undefined ? { waitingOnYou: i.waitingOnYou } : {}),
|
|
115
120
|
// Feature instance-color: the row's colour as instanceColor reads it, present only when it is one.
|
|
116
121
|
...(instanceColor(i) !== null ? { color: instanceColor(i) } : {}),
|
|
122
|
+
// Feature instance-background (#1579): exactly true, else absent (instance-tree.mjs backgroundPlacement).
|
|
123
|
+
...(i.background === true ? { background: true } : {}),
|
|
117
124
|
team: i.team || null,
|
|
118
125
|
};
|
|
119
126
|
}
|
|
@@ -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
|
+
}
|