@awebai/oats 0.52.0 → 0.53.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -1
- package/bin/oats.mjs +304 -92
- package/docs/capabilities.md +66 -4
- package/docs/configuration.md +66 -3
- package/docs/desktop-cli-api.md +673 -58
- package/docs/desktop-instance-start.md +25 -12
- package/docs/execution-targets.md +1 -0
- package/docs/implementation.md +175 -11
- package/docs/integrations.md +6 -3
- package/docs/knowledge.md +2 -2
- package/docs/macos-test-runs.md +246 -0
- package/docs/official-catalog.md +5 -5
- package/docs/packages.md +14 -14
- package/docs/release-lane.md +210 -6
- package/docs/release-notes/v0.53.0.md +1274 -0
- package/docs/schedules.md +7 -1
- package/docs/souls-and-instances.md +237 -15
- package/docs/tui.md +453 -21
- package/docs/upgrading.md +298 -0
- package/docs/workspaces.md +3 -3
- package/lib/automations.mjs +22 -22
- package/lib/claim.mjs +93 -4
- package/lib/config-data.mjs +4 -1
- package/lib/core.mjs +569 -121
- package/lib/instance-events.mjs +19 -1
- package/lib/instance-git.mjs +39 -3
- package/lib/instance-inspect.mjs +5 -6
- package/lib/instance-lifecycle.mjs +145 -18
- package/lib/instance-resolution.mjs +59 -6
- package/lib/launch-preference.mjs +226 -15
- package/lib/local-edit.mjs +118 -0
- package/lib/packages.mjs +13 -4
- package/lib/pi-bridge.mjs +308 -0
- package/lib/refused-text.mjs +11 -0
- package/lib/remote.mjs +190 -25
- package/lib/resolve.mjs +2 -1
- package/lib/retained-after-retire.mjs +2 -2
- package/lib/retire-output.mjs +12 -1
- package/lib/schedule-host.mjs +6 -35
- package/lib/shell-word.mjs +13 -0
- package/lib/soul-launch-verbs.mjs +153 -0
- package/lib/stable-node.mjs +62 -0
- package/lib/teams-verbs.mjs +18 -46
- package/lib/workspace.mjs +49 -19
- package/package-catalog.json +4 -4
- package/package.json +2 -1
- package/packages/client/attach-exit.mjs +25 -0
- package/packages/client/cli-adapter.mjs +16 -3
- package/packages/client/cli-locator.mjs +2 -2
- package/packages/client/deployment-contract.mjs +4 -0
- package/packages/client/deployment-facts.mjs +71 -10
- package/packages/client/deployment-panel.mjs +49 -11
- package/packages/client/deployment-read-cli.mjs +7 -3
- package/packages/client/display-text.mjs +8 -2
- package/packages/client/instance-acts.mjs +46 -10
- package/packages/client/instance-events-contract.mjs +4 -2
- package/packages/client/instance-presentation.mjs +66 -2
- package/packages/client/instance-tree.mjs +23 -14
- package/packages/client/kernel-lines.mjs +31 -0
- package/packages/client/kernel-made.mjs +23 -0
- package/packages/client/launch-prompt-outcome.mjs +51 -16
- package/packages/client/lifecycle-contract.mjs +45 -4
- package/packages/client/liveness.mjs +14 -1
- package/packages/client/own-codes.mjs +31 -0
- package/packages/client/panel-views.mjs +18 -11
- package/packages/client/readiness-contract.mjs +3 -1
- package/packages/client/remote-address.mjs +34 -9
- package/packages/client/remote-identity-memory.mjs +94 -0
- package/packages/client/remote-roster.mjs +92 -6
- package/packages/client/session-attach.mjs +175 -0
- package/packages/client/spawn-apply-contract.mjs +16 -4
- package/packages/client/spawn-messages.mjs +26 -3
- package/packages/client/spawn-preview-cli.mjs +8 -2
- package/packages/client/spawn-preview-contract.mjs +5 -1
- package/packages/client/terminal-exec.mjs +21 -0
- package/packages/client/workspace-choices.mjs +95 -0
- package/packages/client/workspace-views.mjs +39 -3
- package/packages/record/README.md +21 -0
- package/packages/record/bin/setup.mjs +108 -15
- package/packages/tui/README.md +30 -12
- package/packages/tui/lib/actions.mjs +16 -1
- package/packages/tui/lib/client.mjs +32 -1
- package/packages/tui/lib/config.mjs +151 -0
- package/packages/tui/lib/main.mjs +117 -46
- package/packages/tui/lib/model.mjs +392 -0
- package/packages/tui/lib/read.mjs +473 -0
- package/packages/tui/lib/store.mjs +364 -0
- package/packages/tui/lib/term/keys.mjs +44 -0
- package/packages/tui/lib/term/screen.mjs +16 -4
- package/packages/tui/lib/term/text.mjs +60 -0
- package/packages/tui/lib/term/tty.mjs +13 -3
- package/packages/tui/lib/views/detail.mjs +46 -0
- package/packages/tui/lib/views/frame.mjs +230 -36
- package/packages/tui/lib/views/help.mjs +125 -13
- package/packages/tui/lib/views/instances.mjs +137 -0
- package/packages/tui/lib/views/scroll.mjs +19 -0
- package/packages/tui/lib/views/switcher.mjs +97 -0
- package/skills/oats-getting-started/SKILL.md +2 -2
|
@@ -0,0 +1,473 @@
|
|
|
1
|
+
// The effects of the TUI: finding the deployment, the kernel's record, one exec for every kernel
|
|
2
|
+
// call, the observer of every served deployment, the roster of other machines, the refresh loop,
|
|
3
|
+
// the liveness collector, and the two looks at the file system the switcher needs.
|
|
4
|
+
// This version of the TUI ONLY READS: nothing here changes a deployment, and nothing writes a file.
|
|
5
|
+
// No function of this module decodes a kernel answer. Each one passes values between the shared
|
|
6
|
+
// functions (client.mjs), which decide what a roster, a row and a failed read are, once, for both
|
|
7
|
+
// clients: the TUI never writes "stopped" for a row and never builds the collector's input by hand.
|
|
8
|
+
import { execFile as nodeExecFile, spawn as nodeSpawn } from "node:child_process";
|
|
9
|
+
import { lstatSync, opendirSync, realpathSync, statSync } from "node:fs";
|
|
10
|
+
import { basename, dirname, join } from "node:path";
|
|
11
|
+
import { fileURLToPath } from "node:url";
|
|
12
|
+
import { COLLECTOR, INSTANCE_VARIABLES, MAX_DEPLOYMENT_OBSERVATIONS, acceptProbe, cliDeploymentRead, cliReadsRemotes, cliRecord, cliRemoteRoster, createDeploymentObserver, createRefreshLoop, deploymentsInside, failedEntry, livenessAnswers, livenessInput, mapBounded, observeIdentities, observedEntry, panelInstances, parseProbeStdout, remoteRosterState, rosterRows, validateWorkspace } from "./client.mjs";
|
|
13
|
+
|
|
14
|
+
/** The kernel this TUI shipped with: the absolute path of the install's own bin/oats.mjs, found by
|
|
15
|
+
* URL from this file. Every kernel call is `node <this path> …`, so the TUI depends on no shebang,
|
|
16
|
+
* no execute bit and no `PATH`, and never talks to another install's kernel. */
|
|
17
|
+
export const KERNEL_BIN = fileURLToPath(new URL("../../../bin/oats.mjs", import.meta.url));
|
|
18
|
+
|
|
19
|
+
/** How long the probe waits for `version --json`. */
|
|
20
|
+
const PROBE_TIMEOUT_MS = 10_000;
|
|
21
|
+
const PROBE_MAX_BUFFER = 1024 * 1024;
|
|
22
|
+
/** The collector's limits: the Desktop's own for the same program. */
|
|
23
|
+
const COLLECTOR_TIMEOUT_MS = 30_000;
|
|
24
|
+
const COLLECTOR_MAX_BUFFER = 16 * 1024 * 1024;
|
|
25
|
+
/** The oldest remote observation the kernel may reuse for a cycle nobody asked for, in seconds. A
|
|
26
|
+
* cycle somebody asked for (the refresh key, the return from a suspend) is live: 0. */
|
|
27
|
+
const BACKGROUND_MAX_AGE = 60;
|
|
28
|
+
|
|
29
|
+
/** Delete each name of INSTANCE_VARIABLES from `env` itself: the process environment, in place.
|
|
30
|
+
* A TUI started in an agent's pane inherits that instance's variables, and a kernel command that
|
|
31
|
+
* runs with them answers for the instance instead of the directory it was asked about. The shared
|
|
32
|
+
* withoutInstanceVariables returns a copy and is not enough: every child of the TUI, the collector
|
|
33
|
+
* included, inherits the process environment. Nothing else is touched; `env` is returned. */
|
|
34
|
+
export function leaveInstance(env) {
|
|
35
|
+
for (const name of INSTANCE_VARIABLES) delete env[name];
|
|
36
|
+
return env;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** A step that must not stop the ones after it: a child, a stream or a directory that is already gone. */
|
|
40
|
+
const quietly = (act) => { try { return act(); } catch { return undefined; } };
|
|
41
|
+
|
|
42
|
+
/** The filesystem the three functions below read when they are given none. findDeployment: one
|
|
43
|
+
* realpath and one stat of the start, then one lstat per directory. A symbolic link named
|
|
44
|
+
* oats-local.yaml is not a deployment's file (lstat does not follow it).
|
|
45
|
+
* `list(dir, limit)` is the look inside a folder the shared deploymentsInside asks for:
|
|
46
|
+
* -> { entries: [{ name, isDirectory }], limited }. It reads at most `limit` entries, and one more
|
|
47
|
+
* only to say whether the folder holds more (`limited`), so a folder of any size costs a bounded
|
|
48
|
+
* read. `isDirectory` is the entry's own type: a link to a directory is not a directory, and
|
|
49
|
+
* nothing is followed. It throws for a folder that cannot be opened; the shared function answers
|
|
50
|
+
* that as a folder that holds nothing. */
|
|
51
|
+
const DEPLOYMENT_IO = Object.freeze({
|
|
52
|
+
realpath: (path) => realpathSync(path),
|
|
53
|
+
isDirectory: (path) => statSync(path).isDirectory(),
|
|
54
|
+
isDeployment: (dir) => lstatSync(join(dir, "oats-local.yaml")).isFile(),
|
|
55
|
+
list: (dir, limit) => {
|
|
56
|
+
const handle = opendirSync(dir), entries = [];
|
|
57
|
+
try {
|
|
58
|
+
for (let entry; entries.length < limit && (entry = handle.readSync());) entries.push({ name: entry.name, isDirectory: entry.isDirectory() });
|
|
59
|
+
return { entries, limited: entries.length >= limit && handle.readSync() !== null };
|
|
60
|
+
} finally { quietly(() => handle.closeSync()); }
|
|
61
|
+
},
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
/** The deployment `start` is in: (start directory, io?) -> { ok: true, deployment } | { ok: false, dir }.
|
|
65
|
+
* `start` is made canonical (io.realpath), so a path given through a symbolic link names the
|
|
66
|
+
* directory it leads to. From there it walks up, the root included, asking the shared
|
|
67
|
+
* validateWorkspace at each directory; the first that answers is the deployment (its `.path`), so
|
|
68
|
+
* the nearest one wins. Nothing but existence is read from any directory: the content is the
|
|
69
|
+
* kernel's to read. A start that cannot be resolved, or that is not a directory, answers
|
|
70
|
+
* { ok: false, dir: start } without walking: the TUI does not guess a parent for a path that was
|
|
71
|
+
* mistyped. Outside every deployment `dir` is the canonical start. Never throws. */
|
|
72
|
+
export function findDeployment(start, io = {}) {
|
|
73
|
+
const { realpath, isDirectory, isDeployment } = { ...DEPLOYMENT_IO, ...io };
|
|
74
|
+
let dir;
|
|
75
|
+
try { dir = realpath(start); if (typeof dir !== "string" || isDirectory(dir) !== true) return { ok: false, dir: start }; } catch { return { ok: false, dir: start }; }
|
|
76
|
+
for (let at = dir; ; at = dirname(at)) {
|
|
77
|
+
const found = validateWorkspace(at, { isDeployment });
|
|
78
|
+
if (found) return { ok: true, deployment: found.path };
|
|
79
|
+
if (dirname(at) === at) return { ok: false, dir };
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** The deployments the switcher offers unasked: those directly inside `<home>/Agents` that this run
|
|
84
|
+
* does not serve. (home, served, io?) -> { offered: [{ path, name }], limited }.
|
|
85
|
+
* Which folders are deployments, their order and the limit of the look are the shared
|
|
86
|
+
* deploymentsInside's; this adds only what a run knows. Each path is made canonical (io.realpath)
|
|
87
|
+
* BEFORE it is compared with `served`, whose ids are canonical: a `~/Agents` reached through a
|
|
88
|
+
* link would otherwise offer a deployment the run already shows. One that cannot be resolved (it
|
|
89
|
+
* went away since the look) is left out, and so is a second folder that leads to the same place.
|
|
90
|
+
* `name` is the folder's name as it was listed, `path` the canonical one to admit. `limited` says
|
|
91
|
+
* the folder holds more entries than were read. Nothing is read from any deployment: an offered
|
|
92
|
+
* one is read when it is picked. Never throws: a missing or unreadable `~/Agents` offers nothing. */
|
|
93
|
+
export function offeredDeployments(home, served, io = {}) {
|
|
94
|
+
try {
|
|
95
|
+
const { realpath, isDeployment, list } = { ...DEPLOYMENT_IO, ...io };
|
|
96
|
+
const inside = deploymentsInside(join(home, "Agents"), { list, isDeployment });
|
|
97
|
+
const taken = new Set(served), offered = [];
|
|
98
|
+
for (const listed of inside.paths) {
|
|
99
|
+
const path = quietly(() => realpath(listed));
|
|
100
|
+
if (typeof path !== "string" || taken.has(path)) continue;
|
|
101
|
+
taken.add(path);
|
|
102
|
+
offered.push({ path, name: basename(listed) });
|
|
103
|
+
}
|
|
104
|
+
return { offered, limited: inside.limited };
|
|
105
|
+
} catch { return { offered: [], limited: false }; }
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** Whether `path` is a deployment NOW: (path, io?) -> { ok: true, deployment } | { ok: false }.
|
|
109
|
+
* Asked when an offered deployment is picked: the offer is as old as the last look, and the
|
|
110
|
+
* folder may have stopped being a deployment since. The path is made canonical (io.realpath) and
|
|
111
|
+
* the shared validateWorkspace is asked about that directory itself. Unlike findDeployment it
|
|
112
|
+
* walks nowhere: a folder that is no longer a deployment must not open the one above it in its
|
|
113
|
+
* place. `deployment` is the canonical path, the id a served deployment has. Never throws. */
|
|
114
|
+
export function admitDeployment(path, io = {}) {
|
|
115
|
+
try {
|
|
116
|
+
const { realpath, isDeployment } = { ...DEPLOYMENT_IO, ...io };
|
|
117
|
+
const found = validateWorkspace(realpath(path), { isDeployment });
|
|
118
|
+
return found ? { ok: true, deployment: found.path } : { ok: false };
|
|
119
|
+
} catch { return { ok: false }; }
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** Run the kernel once with `version --json` and make its record:
|
|
123
|
+
* -> Promise<{ ok: true, cli } | { ok: false, reason }>, never rejected.
|
|
124
|
+
* The answer is read with the shared parseProbeStdout and judged by the shared acceptProbe; an
|
|
125
|
+
* accepted one becomes `cliRecord(payload, { bin, source: "tui" })`, the record every shared gate
|
|
126
|
+
* reads. `reason` is acceptProbe's own when it refused, and one of the TUI's four when there was
|
|
127
|
+
* no answer to judge. A nonzero exit or a timeout is a refusal even when stdout looks valid: a
|
|
128
|
+
* kernel that prints a record and then fails is not one to read with. The exec error's message,
|
|
129
|
+
* stderr and argv never reach `reason`; acceptProbe's reason quotes the payload's own fields, so
|
|
130
|
+
* the caller shows it as it shows any kernel text.
|
|
131
|
+
* NOT detached, unlike every later child: it runs before the terminal is taken, and a Ctrl+C then
|
|
132
|
+
* must end it with the TUI. `timeoutMs` is for tests. */
|
|
133
|
+
export function probeKernel({ bin = KERNEL_BIN, env = process.env, execFile = nodeExecFile, timeoutMs = PROBE_TIMEOUT_MS } = {}) {
|
|
134
|
+
return new Promise((done) => {
|
|
135
|
+
const refuse = (reason) => done({ ok: false, reason });
|
|
136
|
+
try {
|
|
137
|
+
execFile(process.execPath, [bin, "version", "--json"], { timeout: timeoutMs, shell: false, encoding: "utf8", maxBuffer: PROBE_MAX_BUFFER, env }, (error, stdout) => {
|
|
138
|
+
if (error) return refuse(typeof error.syscall === "string" && error.syscall.startsWith("spawn") ? "it did not start" : error.killed === true ? `it did not answer within ${timeoutMs / 1000} seconds` : "it failed");
|
|
139
|
+
const payload = parseProbeStdout(stdout);
|
|
140
|
+
if (!payload) return refuse("it answered something that is not a version record");
|
|
141
|
+
const verdict = acceptProbe(payload);
|
|
142
|
+
return verdict.ok ? done({ ok: true, cli: cliRecord(payload, { bin, source: "tui" }) }) : refuse(verdict.reason);
|
|
143
|
+
});
|
|
144
|
+
} catch { refuse("it did not start"); }
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** A child that did not end well, as execFile reports one: the facts on an Error, and no text of the child's. */
|
|
149
|
+
const failure = (facts) => Object.assign(new Error("the child did not end with an answer"), facts);
|
|
150
|
+
/** A child the reader ended itself: its time limit, or the reader giving it up. As execFile's timeout. */
|
|
151
|
+
const ended = () => failure({ code: null, signal: "SIGTERM", killed: true });
|
|
152
|
+
/** What was thrown, as the message the shared rule takes for a read that threw. */
|
|
153
|
+
const said = (error) => String(error?.message ?? error);
|
|
154
|
+
|
|
155
|
+
/** The reader of a run: its cycles over every served deployment, the roster of other machines,
|
|
156
|
+
* their children, and the way out.
|
|
157
|
+
* -> { start(), request({ live }), touch(), voidInFlight(), stop(), children() }
|
|
158
|
+
*
|
|
159
|
+
* `cli` is probeKernel's record (`cli.bin` the absolute path of bin/oats.mjs). The reader keeps no
|
|
160
|
+
* answer of its own: what a run holds is the caller's store, asked for when it is needed.
|
|
161
|
+
* getServed() the ids of the deployments this run serves, in order (canonical paths). Read
|
|
162
|
+
* once, at the start of each cycle: a deployment that joins while a cycle runs is
|
|
163
|
+
* read by the next one, and one that is not in the list is never read.
|
|
164
|
+
* getEntry(id) the entry the store holds for that deployment now.
|
|
165
|
+
* onEntry({ id, entry, number }) each deployment's entry of a cycle. The reader decides
|
|
166
|
+
* nothing about a failed read (the shared failedEntry does). `number` is the
|
|
167
|
+
* cycle's: it grows by one per cycle and is never reused, and every deployment of
|
|
168
|
+
* one cycle answers under the same one, so a store can refuse an answer that
|
|
169
|
+
* arrives out of order; a cycle that emits nothing leaves a gap.
|
|
170
|
+
* getRoster() { remote: { remoteGroups, rosterAnswered, rosterFailure }, memory, notes }: what
|
|
171
|
+
* the store holds of the other machines now, and its two Maps of identities.
|
|
172
|
+
* onRoster(event) { collecting: true } when a roster read starts, and
|
|
173
|
+
* { roster: { remote, memory, notes, at } } for each outcome taken (see `takeRoster`).
|
|
174
|
+
* `clock()` answers the time of a cycle as an ISO string, once per cycle. `now()` answers
|
|
175
|
+
* milliseconds and is read only for the roster's 15 seconds.
|
|
176
|
+
*
|
|
177
|
+
* ONE EXEC FOR EVERY KERNEL CALL. The shared reader and observer run unchanged: they are handed an
|
|
178
|
+
* `exec` with execFile's signature that runs `node <bin> <argv…>` and remembers the child.
|
|
179
|
+
*
|
|
180
|
+
* EVERY CHILD RUNS IN A SESSION OF ITS OWN (`detached: true`, and nothing else added). The
|
|
181
|
+
* terminal guard's suspend sends SIGTSTP to the whole foreground process group, so a child left in
|
|
182
|
+
* the TUI's group would be stopped with it, and a stopped read holds its timeout and its
|
|
183
|
+
* kernel-side work until `fg`. In its own session a read goes on while the TUI is stopped. A
|
|
184
|
+
* terminal's SIGHUP therefore no longer reaches it by itself: it is ended by the TUI on the way out.
|
|
185
|
+
* This is why the exec stands on `spawn` and not on node's execFile: execFile hands spawn a fixed
|
|
186
|
+
* list of options, `detached` is not one of them, and a child it starts stays in the TUI's group
|
|
187
|
+
* whatever it is asked. `run` below is the part of execFile's contract the shared readers use.
|
|
188
|
+
*
|
|
189
|
+
* ENDING A CHILD holds because this version only reads. A KERNEL CALL THAT CHANGES SOMETHING MUST
|
|
190
|
+
* NEVER BE KILLED BY THE TUI: a killed stop or start leaves a marker that refuses every later one.
|
|
191
|
+
* So every child is remembered with its kind, only kind "read" is ever signalled, and a later
|
|
192
|
+
* version's writing calls get a kind of their own.
|
|
193
|
+
*
|
|
194
|
+
* `timers` are the loop's, the idle timer's and the children's time limits (for tests). */
|
|
195
|
+
export function createReader({ cli, getServed, getEntry, getRoster, onEntry, onRoster, env = process.env, clock = () => new Date().toISOString(), now = Date.now, spawn = nodeSpawn, timers = { setTimeout, clearTimeout }, collector = COLLECTOR, idleMs = 600_000, focusedMs = 5000, blurredMs = 30_000, rosterMs = 15_000 }) {
|
|
196
|
+
/** child -> { kind, exited, giveUp }: every child that has not ended and was not ended. */
|
|
197
|
+
const remembered = new Map();
|
|
198
|
+
let started = false, stopped = false, idleTimer = null;
|
|
199
|
+
/** `counter` numbers the cycles. `epoch` moves when the cycles in flight are made void; `flight`
|
|
200
|
+
* is the epoch the cycle now running began in (the loop runs one at a time). `served` is what
|
|
201
|
+
* getServed() answered at the start of that cycle. */
|
|
202
|
+
let counter = 0, epoch = 0, flight = 0, served = [];
|
|
203
|
+
/** The roster of other machines. `rosterFlight` is the read in flight (a token of its own, so an
|
|
204
|
+
* answer knows whether it is still awaited), or null. `rosterEnded` is now() when the last read
|
|
205
|
+
* that was not given up ended, or null while none has. `gatedSaid`: a kernel that reads no
|
|
206
|
+
* other machine was answered for, which happens once in a run. */
|
|
207
|
+
let rosterFlight = null, rosterEnded = null, gatedSaid = false;
|
|
208
|
+
|
|
209
|
+
/** execFile for a child in a session of its own: start `node <args…>` detached, remember it, and
|
|
210
|
+
* call back once with `(error, stdout, stderr)` as execFile does. `error` is null after exit 0
|
|
211
|
+
* with no signal; else it carries `code` (the exit status, or the spawn error's code), `signal`
|
|
212
|
+
* and `killed`: `killed: true` when the time limit ended it, and
|
|
213
|
+
* `code: "ERR_CHILD_PROCESS_STDIO_MAXBUFFER"` when it printed more than `maxBuffer` bytes. The
|
|
214
|
+
* other options go to spawn as they are, with `detached: true` added. Returns the child.
|
|
215
|
+
* The child is forgotten when it ends: `close`, `error` for one that did not start, or the
|
|
216
|
+
* moment the reader ends it. */
|
|
217
|
+
function run(kind, args, { timeout = 0, maxBuffer = Infinity, encoding = "utf8", ...rest }, callback) {
|
|
218
|
+
const child = spawn(process.execPath, args, { ...rest, detached: true });
|
|
219
|
+
const printed = { stdout: "", stderr: "" }, record = { kind, exited: false, giveUp };
|
|
220
|
+
let over = false, severed = false, verdict = null, timer = null;
|
|
221
|
+
function finish(error) {
|
|
222
|
+
if (over) return;
|
|
223
|
+
over = true;
|
|
224
|
+
if (timer !== null) { timers.clearTimeout(timer); timer = null; }
|
|
225
|
+
remembered.delete(child);
|
|
226
|
+
callback(error, printed.stdout, printed.stderr);
|
|
227
|
+
}
|
|
228
|
+
/** End the child, once, and never wait for it. A child leads a process group of its own, so
|
|
229
|
+
* SIGTERM goes to the GROUP: what the kernel started dies with it. Only a child of kind "read"
|
|
230
|
+
* not yet seen to exit is signalled: after `exit` its pid is free to name another process, and
|
|
231
|
+
* so is its group's. Then, whatever its kind or state, its pipes are destroyed and it is
|
|
232
|
+
* unref'd and forgotten: a child that ignores the signal, or a grandchild that holds its pipe,
|
|
233
|
+
* keeps neither a cycle nor the process leaving. */
|
|
234
|
+
function sever() {
|
|
235
|
+
if (severed) return;
|
|
236
|
+
severed = true;
|
|
237
|
+
if (record.kind === "read" && !record.exited) {
|
|
238
|
+
const group = Number.isInteger(child.pid) && child.pid > 1 && quietly(() => process.kill(-child.pid, "SIGTERM")) === true;
|
|
239
|
+
if (!group) quietly(() => child.kill("SIGTERM"));
|
|
240
|
+
}
|
|
241
|
+
for (const stream of [child.stdout, child.stderr, child.stdin]) quietly(() => stream?.destroy());
|
|
242
|
+
quietly(() => child.unref());
|
|
243
|
+
remembered.delete(child);
|
|
244
|
+
}
|
|
245
|
+
/** The reader's own decision (stop(), voidInFlight()): end the child and answer for it now. */
|
|
246
|
+
function giveUp(error) {
|
|
247
|
+
if (over) return;
|
|
248
|
+
sever();
|
|
249
|
+
finish(error);
|
|
250
|
+
}
|
|
251
|
+
/** The child's own limit, in time or in size: end it now, and answer for it one turn of the
|
|
252
|
+
* event loop LATER. A process that was stopped past the limit runs its overdue timers before
|
|
253
|
+
* it hears the signal that it continues: answered at once, such a read would become an entry
|
|
254
|
+
* before voidInFlight() could be called for it. (node's execFile leaves the same room: it
|
|
255
|
+
* answers at `close`.) */
|
|
256
|
+
function expire(error) {
|
|
257
|
+
if (over || severed) return;
|
|
258
|
+
verdict = error;
|
|
259
|
+
sever();
|
|
260
|
+
setImmediate(() => finish(error));
|
|
261
|
+
}
|
|
262
|
+
for (const name of ["stdout", "stderr"]) {
|
|
263
|
+
const stream = child[name];
|
|
264
|
+
if (!stream) continue;
|
|
265
|
+
let bytes = 0;
|
|
266
|
+
stream.setEncoding(encoding);
|
|
267
|
+
stream.on("error", () => {});
|
|
268
|
+
stream.on("data", (chunk) => {
|
|
269
|
+
bytes += Buffer.byteLength(chunk, encoding);
|
|
270
|
+
if (bytes > maxBuffer) expire(failure({ code: "ERR_CHILD_PROCESS_STDIO_MAXBUFFER" }));
|
|
271
|
+
else printed[name] += chunk;
|
|
272
|
+
});
|
|
273
|
+
}
|
|
274
|
+
child.once("exit", () => { record.exited = true; });
|
|
275
|
+
child.once("close", (code, signal) => finish(verdict ?? (code === 0 && signal === null ? null : failure({ code, signal, killed: false }))));
|
|
276
|
+
child.on("error", (error) => { if (!child.pid) finish(error); });
|
|
277
|
+
if (timeout > 0) {
|
|
278
|
+
timer = timers.setTimeout(() => { timer = null; expire(ended()); }, timeout);
|
|
279
|
+
timer?.unref?.();
|
|
280
|
+
}
|
|
281
|
+
remembered.set(child, record);
|
|
282
|
+
return child;
|
|
283
|
+
}
|
|
284
|
+
function endReads() {
|
|
285
|
+
for (const record of [...remembered.values()]) if (record.kind === "read") record.giveUp(ended());
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/** The exec handed to the shared readers: execFile's signature, for `node <bin> <argv…>` (see
|
|
289
|
+
* `run`). It throws where nothing may be started (after stop(), or for a cycle made void before
|
|
290
|
+
* its reads began); the shared reader answers that as a failed read, which such a cycle never
|
|
291
|
+
* emits. Where the options carry no environment the reader's own is put there: the shared
|
|
292
|
+
* roster read names none, and a child must see what leaveInstance left, whoever started it. */
|
|
293
|
+
function exec(bin, argv, options, callback) {
|
|
294
|
+
if (stopped || flight !== epoch) throw new Error("this read was given up before it started");
|
|
295
|
+
return run("read", [bin, ...argv], options.env === undefined ? { ...options, env } : options, callback);
|
|
296
|
+
}
|
|
297
|
+
/** The shared observer, with the shared reader over this exec and no reader of the TUI's own: a
|
|
298
|
+
* failed read has the same reasons here as in the Desktop. It admits a deployment of the cycle
|
|
299
|
+
* now running and no other. */
|
|
300
|
+
const observer = createDeploymentObserver({
|
|
301
|
+
getContext: (id) => (served.includes(id) ? { deployment: id, cli, revision: 0 } : null),
|
|
302
|
+
read: (kernel, options) => cliDeploymentRead(kernel, options, { exec, env }),
|
|
303
|
+
});
|
|
304
|
+
|
|
305
|
+
/** Run the collector with `input` on stdin: what it printed, or null when it exited nonzero, was
|
|
306
|
+
* ended by a signal, timed out, overflowed or did not start. Never rejected. A collector that
|
|
307
|
+
* dies before it read answers the write with EPIPE on stdin: heard, so it is not an uncaught
|
|
308
|
+
* exception. */
|
|
309
|
+
function collect(input) {
|
|
310
|
+
return new Promise((done) => {
|
|
311
|
+
try {
|
|
312
|
+
const child = run("read", [collector], { env, shell: false, timeout: COLLECTOR_TIMEOUT_MS, maxBuffer: COLLECTOR_MAX_BUFFER, encoding: "utf8" },
|
|
313
|
+
(error, stdout) => done(error || typeof stdout !== "string" ? null : stdout));
|
|
314
|
+
child.stdin?.on("error", () => {});
|
|
315
|
+
child.stdin?.end(input);
|
|
316
|
+
} catch { done(null); }
|
|
317
|
+
});
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
/** One outcome of the roster read into what the caller holds: the shared rule, called once per
|
|
321
|
+
* outcome, with the Desktop's two `catch`es (remote-roster.mjs says why a caller has them).
|
|
322
|
+
* `outcome` is { gated: true }, { envelope } for what the read resolved to, or { thrown } for a
|
|
323
|
+
* read that was rejected; `at` is the time of the cycle that began the read.
|
|
324
|
+
* What an answer makes of the groups held is remoteRosterState's; the groups it reports go to
|
|
325
|
+
* the memory of identities (observeIdentities), which is what keeps a machine in its workspace
|
|
326
|
+
* while it does not answer. If that step throws, the state just made is taken again as a read
|
|
327
|
+
* that threw, so its groups are marked not reached instead of shown as read. `changed` is not
|
|
328
|
+
* used: this client keeps the memory for the run and writes none of it. */
|
|
329
|
+
function takeRoster(outcome, at) {
|
|
330
|
+
const held = getRoster();
|
|
331
|
+
let state = remoteRosterState(held.remote, outcome, at), identities = { memory: held.memory, notes: held.notes };
|
|
332
|
+
if (state.reported !== null) {
|
|
333
|
+
try { identities = observeIdentities(identities, state.reported, at); } catch (error) { state = remoteRosterState(state, { thrown: said(error) }, at); }
|
|
334
|
+
}
|
|
335
|
+
onRoster({ roster: { remote: { remoteGroups: state.remoteGroups, rosterAnswered: state.rosterAnswered, rosterFailure: state.rosterFailure }, memory: identities.memory, notes: identities.notes, at } });
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
/** Begin the roster read when this cycle is to begin one. NOT AWAITED BY THE CYCLE: a machine
|
|
339
|
+
* that answers slowly (the read may take a minute) never holds this machine's rows.
|
|
340
|
+
* A kernel that reads no other machine (the shared cliReadsRemotes) is never asked: the gated
|
|
341
|
+
* outcome is taken once, so the store holds what the shared rule makes of it.
|
|
342
|
+
* ONE READ AT A TIME: while one is in flight nothing starts, not for a live request either.
|
|
343
|
+
* The local rows of that request are read; the roster's answer is the one already on its way.
|
|
344
|
+
* NEVER SOONER THAN `rosterMs` AFTER THE END OF THE LAST ONE, unless somebody asked (`live`:
|
|
345
|
+
* the refresh key, the return from a suspend, a pick in the switcher). From the END, not the
|
|
346
|
+
* start: a read that took 20 s would otherwise be followed at once by the next, and a slow
|
|
347
|
+
* machine would be asked without a pause. The loop's own slowing after ten minutes without a
|
|
348
|
+
* key makes it 30 s.
|
|
349
|
+
* The read is the shared cliRemoteRoster over this exec: a child of kind "read" in a session of
|
|
350
|
+
* its own, ended on every way out like any other, with the shared time limit and no working
|
|
351
|
+
* directory of the TUI's choosing (registrations are the user's, not a deployment's). --max-age
|
|
352
|
+
* is not a flag of this read. */
|
|
353
|
+
function readRoster(live, at) {
|
|
354
|
+
if (!cliReadsRemotes(cli)) {
|
|
355
|
+
if (!gatedSaid) { gatedSaid = true; takeRoster({ gated: true }, at); }
|
|
356
|
+
return;
|
|
357
|
+
}
|
|
358
|
+
if (rosterFlight !== null) return;
|
|
359
|
+
if (!live && rosterEnded !== null && now() - rosterEnded < rosterMs) return;
|
|
360
|
+
onRoster({ collecting: true });
|
|
361
|
+
const mine = rosterFlight = {};
|
|
362
|
+
let read;
|
|
363
|
+
// The shared read looks up the working directory before it promises anything: where that
|
|
364
|
+
// directory was removed under the TUI it throws, and that is a read that failed like another.
|
|
365
|
+
try { read = cliRemoteRoster(cli.bin, { exec }); } catch (error) { read = Promise.reject(error); }
|
|
366
|
+
read.then((envelope) => ({ envelope }), (error) => ({ thrown: said(error) })).then((outcome) => {
|
|
367
|
+
// Given up (voidInFlight(), stop()): whatever it answered is no evidence, and is dropped.
|
|
368
|
+
if (rosterFlight !== mine) return;
|
|
369
|
+
rosterFlight = null;
|
|
370
|
+
rosterEnded = now();
|
|
371
|
+
takeRoster(outcome, at);
|
|
372
|
+
}).catch(() => {}); // what the caller's onRoster throws must not be a rejection nobody hears, which ends the process with the terminal taken; the loop does the same for a cycle
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
/** One deployment of a cycle: its two kernel reads, then the collector over its rows. It emits
|
|
376
|
+
* exactly once, unless the reader was stopped or the cycle made void meanwhile: then it emits
|
|
377
|
+
* nothing and starts nothing more. */
|
|
378
|
+
async function readDeployment(id, { live, at, number, over }) {
|
|
379
|
+
const answer = await observer.observe(id, { maxAge: live ? 0 : BACKGROUND_MAX_AGE });
|
|
380
|
+
if (over()) return;
|
|
381
|
+
if (!answer.ok) return void onEntry({ id, entry: failedEntry(getEntry(id), answer.reason, at), number });
|
|
382
|
+
const rows = rosterRows(answer.roster, cli);
|
|
383
|
+
// No rows, no collector: livenessAnswers([], null) is [].
|
|
384
|
+
const printed = rows.length ? await collect(JSON.stringify(livenessInput(rows))) : null;
|
|
385
|
+
if (over()) return;
|
|
386
|
+
const instances = panelInstances(rows, livenessAnswers(rows, printed));
|
|
387
|
+
onEntry({ id, entry: observedEntry({ roster: answer.roster, workspaceStatus: answer.workspaceStatus, observedAt: answer.observedAt }, instances, at), number });
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
/** One cycle: the roster read is begun if it is due, then every served deployment is read, at
|
|
391
|
+
* most MAX_DEPLOYMENT_OBSERVATIONS at a time (the shared observer admits no more: a third
|
|
392
|
+
* started beside two would be refused as busy and never read). The cycle is over when its
|
|
393
|
+
* deployments are; with none served it reads nothing local. */
|
|
394
|
+
async function cycle({ live }) {
|
|
395
|
+
if (stopped) return;
|
|
396
|
+
flight = epoch;
|
|
397
|
+
const mine = epoch, number = ++counter, at = clock();
|
|
398
|
+
const over = () => stopped || mine !== epoch;
|
|
399
|
+
readRoster(live, at);
|
|
400
|
+
served = [...getServed()];
|
|
401
|
+
await mapBounded(served, MAX_DEPLOYMENT_OBSERVATIONS, (id) => readDeployment(id, { live, at, number, over }));
|
|
402
|
+
}
|
|
403
|
+
const loop = createRefreshLoop({ run: cycle, focusedMs, blurredMs, timers });
|
|
404
|
+
|
|
405
|
+
function clearIdle() { if (idleTimer !== null) { timers.clearTimeout(idleTimer); idleTimer = null; } }
|
|
406
|
+
/** One timer: after `idleMs` with no key the loop reads as often as a window nobody looks at. */
|
|
407
|
+
function armIdle() {
|
|
408
|
+
clearIdle();
|
|
409
|
+
idleTimer = timers.setTimeout(() => { idleTimer = null; loop.setFocused(false); }, idleMs);
|
|
410
|
+
idleTimer?.unref?.(); // it never keeps the process alive
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
return {
|
|
414
|
+
/** Read now, then on the loop's cadence. Once: a second call, or one after stop(), does nothing.
|
|
415
|
+
* Answers the first cycle's promise. */
|
|
416
|
+
start() {
|
|
417
|
+
if (started || stopped) return Promise.resolve();
|
|
418
|
+
started = true;
|
|
419
|
+
armIdle();
|
|
420
|
+
return loop.start();
|
|
421
|
+
},
|
|
422
|
+
/** The loop's request: read now, or right after the cycle in flight, and resolve when that
|
|
423
|
+
* cycle is over. `{ live: true }` (the refresh key, the return from a suspend, a pick in the
|
|
424
|
+
* switcher) asks the kernel for nothing reused, and begins a roster read unless one is in
|
|
425
|
+
* flight. After stop() it starts nothing. */
|
|
426
|
+
request({ live = false } = {}) { return loop.request({ live }); },
|
|
427
|
+
/** Somebody is there: called on every key. The loop reads at the focused cadence again (at once
|
|
428
|
+
* when it was idle), and the idle timer starts over. Nothing before start() or after stop(). */
|
|
429
|
+
touch() {
|
|
430
|
+
if (!started || stopped) return;
|
|
431
|
+
loop.setFocused(true);
|
|
432
|
+
armIdle();
|
|
433
|
+
},
|
|
434
|
+
/** A CYCLE IN FLIGHT WHEN THE TUI STOPS EMITS NO ENTRY, WHATEVER IT ANSWERS. Called when the TUI
|
|
435
|
+
* is about to be stopped (Ctrl+Z, before the signal) and again on a return it did not ask for
|
|
436
|
+
* (stopped from outside, seen at SIGCONT).
|
|
437
|
+
* Why: the child runs on in its own session, but its stdout is a pipe to the stopped TUI. An
|
|
438
|
+
* answer larger than the pipe blocks it, and at the return an overdue time limit fires before
|
|
439
|
+
* the pipe is read, so the read can come back as a timeout or a cut answer even from a child
|
|
440
|
+
* that exited 0. Such a cycle is no evidence about the deployment, and "unavailable" after
|
|
441
|
+
* every long suspend would be a false report.
|
|
442
|
+
* So every cycle now in flight is void: it does not call onEntry, starts no collector and no
|
|
443
|
+
* read it had not started, and its failure becomes no entry; its number is never emitted. The
|
|
444
|
+
* children remembered are ended as stop() ends them. The reader stays usable: the loop goes
|
|
445
|
+
* on, and the next cycle (the caller requests a live one on the return) emits with the next
|
|
446
|
+
* number. A cycle requested but not begun is not in flight: it runs after the return.
|
|
447
|
+
* THE SAME HOLDS FOR A ROSTER READ IN FLIGHT, which is not part of a cycle and may outlive
|
|
448
|
+
* the one that began it: its child is ended, whatever it answers is dropped (no onRoster; the
|
|
449
|
+
* caller tells its store that nothing is being collected), and it is no longer in flight, so
|
|
450
|
+
* the live request of the return begins a new one at once. It does not count as a read that
|
|
451
|
+
* ended: it gave no answer to wait 15 s after.
|
|
452
|
+
* Synchronous and idempotent; safe before start() and after stop(). */
|
|
453
|
+
voidInFlight() {
|
|
454
|
+
epoch++;
|
|
455
|
+
rosterFlight = null;
|
|
456
|
+
endReads();
|
|
457
|
+
},
|
|
458
|
+
/** Leave: synchronous and idempotent, safe before start(). The loop and the idle timer are
|
|
459
|
+
* stopped, the observer disposed and every reading child ended (see `sever`), the roster's
|
|
460
|
+
* included. A cycle in flight ends without emitting and without starting anything, and so
|
|
461
|
+
* does a roster read; the follow-up the shared loop still runs after a stop does nothing. */
|
|
462
|
+
stop() {
|
|
463
|
+
stopped = true;
|
|
464
|
+
rosterFlight = null;
|
|
465
|
+
loop.stop();
|
|
466
|
+
observer.dispose();
|
|
467
|
+
clearIdle();
|
|
468
|
+
endReads();
|
|
469
|
+
},
|
|
470
|
+
/** The pids of the children remembered now (for tests). */
|
|
471
|
+
children() { return [...remembered.keys()].map((child) => child.pid).filter((pid) => Number.isInteger(pid)); },
|
|
472
|
+
};
|
|
473
|
+
}
|