@awebai/oats 0.69.4 → 0.69.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/bin/oats.mjs +141 -364
  2. package/docs/configuration.md +12 -0
  3. package/docs/design/2026-09-26-okf-knowledge-operations.md +2 -0
  4. package/docs/design/2026-10-29-warm-reader.md +261 -0
  5. package/docs/design/README.md +4 -0
  6. package/docs/desktop-cli-api.md +258 -13
  7. package/docs/execution-targets.md +36 -5
  8. package/docs/implementation.md +34 -9
  9. package/docs/integrations.md +2 -2
  10. package/docs/knowledge.md +18 -8
  11. package/docs/named-test-runs.md +4 -0
  12. package/docs/official-catalog.md +5 -5
  13. package/docs/packages.md +14 -14
  14. package/docs/release-notes/v0.69.5.md +146 -0
  15. package/docs/release-notes/v0.69.6.md +165 -0
  16. package/docs/schedules.md +8 -1
  17. package/docs/tui.md +23 -5
  18. package/docs/upgrading.md +20 -5
  19. package/docs/workspaces.md +2 -2
  20. package/lib/agents-root.mjs +51 -0
  21. package/lib/argv.mjs +41 -0
  22. package/lib/automation-api.mjs +7 -0
  23. package/lib/automation-scope.mjs +37 -0
  24. package/lib/automations.mjs +63 -12
  25. package/lib/captured-context.mjs +12 -0
  26. package/lib/compile-cache.mjs +36 -0
  27. package/lib/core.mjs +39 -1348
  28. package/lib/deployment-path.mjs +127 -0
  29. package/lib/deployments.mjs +2 -2
  30. package/lib/drift.mjs +95 -0
  31. package/lib/hot-reads.mjs +137 -0
  32. package/lib/install-stamp.mjs +61 -0
  33. package/lib/instance-address.mjs +21 -0
  34. package/lib/instance-events.mjs +8 -6
  35. package/lib/instance-lifecycle.mjs +4 -16
  36. package/lib/instance-listing.mjs +738 -0
  37. package/lib/instance-resolution.mjs +5 -166
  38. package/lib/kernel-features.mjs +10 -0
  39. package/lib/local-edit.mjs +1 -1
  40. package/lib/local-inputs.mjs +3 -0
  41. package/lib/materialize.mjs +2 -87
  42. package/lib/member-clone.mjs +192 -0
  43. package/lib/package-catalog.mjs +93 -0
  44. package/lib/packages.mjs +4 -24
  45. package/lib/read-call.mjs +143 -0
  46. package/lib/reader.mjs +203 -0
  47. package/lib/remote.mjs +47 -6
  48. package/lib/reserved-launch-env.mjs +20 -0
  49. package/lib/resolved-deployment.mjs +13 -5
  50. package/lib/roster-read.mjs +199 -0
  51. package/lib/schedule.mjs +5 -29
  52. package/lib/semver.mjs +12 -0
  53. package/lib/servers.mjs +10 -12
  54. package/lib/session-end.mjs +3 -2
  55. package/lib/session-input.mjs +35 -11
  56. package/lib/session-inspect.mjs +219 -0
  57. package/lib/soul-listing.mjs +216 -0
  58. package/lib/status-words.mjs +30 -0
  59. package/lib/version.mjs +9 -0
  60. package/lib/workspace-read.mjs +160 -0
  61. package/lib/write-file-atomic.mjs +28 -0
  62. package/package-catalog.json +4 -4
  63. package/package.json +1 -1
  64. package/packages/client/cli-locator.mjs +1 -0
  65. package/packages/client/cli-probe-contract.mjs +4 -2
  66. package/packages/client/deployment-observer.mjs +8 -3
  67. package/packages/client/deployment-panel.mjs +17 -1
  68. package/packages/client/deployment-read-cli.mjs +48 -27
  69. package/packages/client/own-codes.mjs +3 -0
  70. package/packages/client/warm-reader.mjs +241 -0
  71. package/packages/tui/lib/client.mjs +2 -1
  72. package/packages/tui/lib/read.mjs +59 -11
  73. package/packages/tui/lib/store.mjs +7 -3
  74. package/skills/oats-getting-started/SKILL.md +3 -3
@@ -0,0 +1,28 @@
1
+ /** writeFileAtomic: a file written through a temporary sibling and renamed over it. A leaf
2
+ * (awebai/oats#1630): deployments.mjs writes this computer's list with it without loading packages.mjs
3
+ * and the remote reader, and packages.mjs re-exports it. Node built-ins only. */
4
+ import { mkdirSync, writeFileSync, rmSync, openSync, fchmodSync, closeSync, renameSync } from "node:fs";
5
+ import { dirname, join, basename } from "node:path";
6
+
7
+ /** Sibling temp + rename: replaces the directory entry itself, never writing
8
+ * THROUGH a pre-planted symlink at `file`. The new file's permission bits are the process's default
9
+ * (its umask) unless `mode` gives them: then they are exactly `mode`, and in force before a byte of
10
+ * `contents` is written, so a file kept private is never readable by others on the way. */
11
+ export function writeFileAtomic(file, contents, { mode } = {}) {
12
+ mkdirSync(dirname(file), { recursive: true });
13
+ const tmp = join(dirname(file), `.${basename(file)}.oats-tmp-${process.pid}`);
14
+ try {
15
+ if (mode === undefined) writeFileSync(tmp, contents);
16
+ else {
17
+ // A new file (one left by a killed process of this pid goes first; "wx" opens nothing that is
18
+ // there), created with no more than `mode` (the umask only takes bits away), then set to it exactly.
19
+ rmSync(tmp, { force: true });
20
+ const fd = openSync(tmp, "wx", mode);
21
+ try { fchmodSync(fd, mode); writeFileSync(fd, contents); } finally { closeSync(fd); }
22
+ }
23
+ renameSync(tmp, file);
24
+ } finally {
25
+ // A failed removal is not answered: when the write or the rename failed, that error is (#1076).
26
+ try { rmSync(tmp, { force: true }); } catch { /* the first error is the one answered */ }
27
+ }
28
+ }
@@ -3,12 +3,12 @@
3
3
  "packages": {
4
4
  "oats.okf": {
5
5
  "url": "https://github.com/awebai/oats-okf.git",
6
- "ref": "v5.5.0",
6
+ "ref": "v5.7.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.32.0",
11
+ "ref": "v1.32.1",
12
12
  "path": "oats-package"
13
13
  },
14
14
  "oats.jira": {
@@ -33,7 +33,7 @@
33
33
  },
34
34
  "oats.cloning": {
35
35
  "url": "https://github.com/awebai/oats-cloning.git",
36
- "ref": "v1.0.1",
36
+ "ref": "v1.1.0",
37
37
  "path": "oats-package"
38
38
  },
39
39
  "oats.apps": {
@@ -48,7 +48,7 @@
48
48
  },
49
49
  "oats.framework": {
50
50
  "url": "https://github.com/awebai/oats.git",
51
- "ref": "oats-framework/v1.16.2",
51
+ "ref": "oats-framework/v1.16.4",
52
52
  "path": "oats-package"
53
53
  }
54
54
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@awebai/oats",
3
- "version": "0.69.4",
3
+ "version": "0.69.6",
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",
@@ -198,6 +198,7 @@ export function cliRecord(payload, { bin, source }) {
198
198
  ...(payload.workspaceApi === 2 ? { workspaceApi: 2 } : {}),
199
199
  ...(payload.automationsApi === 1 ? { automationsApi: 1 } : {}),
200
200
  ...(payload.capabilityShowApi === 1 ? { capabilityShowApi: 1 } : {}),
201
+ ...(payload.readerApi === 1 ? { readerApi: 1 } : {}),
201
202
  ...(Array.isArray(payload.features) ? { features: payload.features } : {}),
202
203
  ...(typeof payload.sessionViewer?.prefixScroll === "boolean" ? { sessionViewer: { prefixScroll: payload.sessionViewer.prefixScroll } } : {}),
203
204
  ...(Array.isArray(payload.remote) ? { remote: payload.remote } : {}) };
@@ -13,8 +13,10 @@
13
13
  Pure data; no node: imports so the renderer can share it with the server. */
14
14
 
15
15
  /** Top-level fields that legitimately differ between two probes of the same
16
- * CLI and therefore never participate in the signature. */
17
- export const PROBE_DIAGNOSTIC_FIELDS = Object.freeze(['probedAt', 'tried', 'source']);
16
+ * CLI and therefore never participate in the signature. `reader` is the warm
17
+ * reader's live state in /api/cli (warm-reader.mjs `status`): a diagnostic, so
18
+ * its changes never read as a CLI change and no page holds reader state. */
19
+ export const PROBE_DIAGNOSTIC_FIELDS = Object.freeze(['probedAt', 'tried', 'source', 'reader']);
18
20
  const DIAGNOSTIC = new Set(PROBE_DIAGNOSTIC_FIELDS);
19
21
 
20
22
  /* Object keys are sorted at every depth so the serialization order a
@@ -1,9 +1,12 @@
1
1
  /** Native deployment observations with bounded admission and both-outcome
2
- * ownership. No cache, queued work, reader fallback or generation conversion. */
2
+ * ownership. No cache, queued work or generation conversion, and no reader of
3
+ * deployment files of its own to fall back on: every fact is the kernel's answer
4
+ * to a read (`read`, the CLI's or the warm reader's, warm-reader.mjs). */
3
5
  import { isAbsolute, resolve } from 'node:path';
4
6
  import { cliDeploymentRead } from './deployment-read-cli.mjs';
5
7
  import { deploymentStatusData, workspaceStatusData, observationData } from './deployment-data.mjs';
6
8
  import { deploymentReadGate, deploymentFailure, validMaxAge } from './deployment-contract.mjs';
9
+ import { probeSignature } from './cli-probe-contract.mjs';
7
10
  export const MAX_DEPLOYMENT_OBSERVATIONS = 2; // each owns at most two CLI reads
8
11
 
9
12
  /** Run `fn` over `items` with at most `limit` calls in flight, first come first served; results keep
@@ -36,8 +39,10 @@ export function createDeploymentObserver({ getContext, read = cliDeploymentRead
36
39
  if (!value || value.deployment !== id || !absolute(id) || !Number.isSafeInteger(value.revision) || value.revision < 0) return deploymentFailure('E_BAD_ARGS');
37
40
  const gate = deploymentReadGate(value.cli, 'status');
38
41
  if (gate) return gate;
39
- const cli = { ok: value.cli.ok, bin: value.cli.bin, version: value.cli.version,
40
- workspaceApi: value.cli.workspaceApi, features: [...value.cli.features] };
42
+ // The record the reads run under: a copy of every gate-relevant field of the probe, all but its
43
+ // diagnostics (cli-probe-contract.mjs `probeSignature`). Those move only with the revision, so the
44
+ // stamp is as it was; a read sees the whole identity of the probe, which the warm reader is bound to.
45
+ const cli = JSON.parse(probeSignature(value.cli));
41
46
  const stamp = JSON.stringify([id, value.revision, cli]);
42
47
  return { ok: true, deployment: id, cli, stamp };
43
48
  }
@@ -6,6 +6,8 @@
6
6
  * here reads a clock, a file or a process: a client runs the collector itself (liveness-main.mjs, as a
7
7
  * child, with its own environment and limits) and gives what it printed to `livenessAnswers`, and it
8
8
  * passes the time of its call as `at`, an ISO string. Each client keeps its own store of entries.
9
+ * The collector runs only for a kernel without feature status-liveness (`kernelLiveness`): with it, the
10
+ * kernel's rows are the liveness reading and a client projects them with no answers, `panelInstances(rows, [])`.
9
11
  *
10
12
  * Not for a page: this module imports `node:path`. What a page shows of a deployment that is not
11
13
  * observed is in deployment-facts.mjs (`deploymentUnavailableText`), and the Desktop's
@@ -33,6 +35,20 @@ export function rosterRows(roster, cli) {
33
35
  })));
34
36
  }
35
37
 
38
+ /** The kernel feature under which `oats status --json` rows carry the complete local liveness reading. */
39
+ export const STATUS_LIVENESS_FEATURE = "status-liveness";
40
+
41
+ /** Whether this CLI's status rows are the liveness reading (feature status-liveness): their `running`,
42
+ * `runtimeState`, `runtimeError` and `tmux` are the kernel's, under its pane rule, and a client runs no
43
+ * collector and probes no terminal. `cli` is the probe record the read was made with, never a later one.
44
+ * Gate on the feature, never the version. Without it the collector runs as before (`livenessInput`,
45
+ * `livenessAnswers`). With it, a row the kernel answered `running: null` stays unknown with the kernel's
46
+ * state and text (origin "kernel", `panelInstances`), and a home with no `tmux` record has none: nothing
47
+ * fills a default session or window, so no terminal opens for it. */
48
+ export function kernelLiveness(cli) {
49
+ return Array.isArray(cli?.features) && cli.features.includes(STATUS_LIVENESS_FEATURE);
50
+ }
51
+
36
52
  /** The liveness collector's input (liveness.mjs `observeLiveness`), one per row, in the rows' order.
37
53
  * `running` is the kernel's answer: the collector leaves a row it answered `null` as the kernel has it. */
38
54
  export function livenessInput(rows) {
@@ -127,7 +143,7 @@ export function panelInstance(i) {
127
143
 
128
144
  /** The panel's rows: each row merged with its liveness answer and projected, in the roster's order
129
145
  * (`byRuntimeState`: running, unknown, stopped; by name within each).
130
- * `answers` are `livenessAnswers`'.
146
+ * `answers` are `livenessAnswers`', or `[]` under status-liveness (`kernelLiveness`): each row then as the kernel gave it.
131
147
  *
132
148
  * The merged row's `runtimeErrorOrigin` is set here or removed, whatever the row carried: when the
133
149
  * answer holds the `runtimeError`, the answer's speaker; when the answer has none and the kernel's row
@@ -13,14 +13,10 @@ const absolute = path => typeof path === 'string' && !path.includes('\0') && isA
13
13
  * Those are distinct native command contracts, not interchangeable generations.
14
14
  * `io.exec` is a client's own `execFile` (the rule is at cli-adapter.mjs `runJson`); `io.env` its environment. */
15
15
  export function cliDeploymentRead(cli, options, io = {}) {
16
- const action = options?.action;
17
- const gate = deploymentReadGate(cli, action);
18
- if (gate) return Promise.resolve(gate);
19
- if (!absolute(cli.bin) || !deploymentRecord(options) || Object.keys(options).some(k => !['action', 'context', 'maxAge'].includes(k))
20
- || !absolute(options.context) || !validMaxAge(options.maxAge)) return Promise.resolve(deploymentFailure('E_BAD_ARGS'));
21
- const context = options.context, bin = cli.bin;
22
- // --max-age only when the probe declares observe-max-age; otherwise the argv is the flagless one.
23
- const argv = [...(action === 'status' ? ['status'] : ['workspace', 'status']), '--dir', context, ...maxAgeArgv(cli.features, options.maxAge), '--json'];
16
+ const refused = deploymentReadRefusal(cli, options);
17
+ if (refused) return Promise.resolve(refused);
18
+ const context = options.context, bin = cli.bin, action = options.action;
19
+ const argv = deploymentReadArgv(cli, options);
24
20
  const env = withoutInstanceVariables(io.env ?? process.env);
25
21
  return new Promise(done => {
26
22
  const fail = code => done(deploymentFailure(code));
@@ -32,26 +28,51 @@ export function cliDeploymentRead(cli, options, io = {}) {
32
28
  if (Buffer.byteLength(stdout, 'utf8') > DEPLOYMENT_READ_MAX_BUFFER) return fail('E_CLI_OUTPUT_LIMIT');
33
29
  let document;
34
30
  try { document = JSON.parse(stdout); } catch { return fail(error ? 'E_CLI_FAILED' : 'E_CLI_PROTOCOL'); }
35
- if (!deploymentRecord(document)) return fail('E_CLI_PROTOCOL');
36
- if (document.schemaVersion === 1 && document.ok === false) {
37
- const reason = document.error;
38
- if (!deploymentRecord(reason) || !deploymentErrorCode(reason.code)
39
- || typeof reason.message !== 'string' || reason.message.length > 8192) return fail('E_CLI_PROTOCOL');
40
- // Only the bounded kernel error envelope, never stderr, argv, stacks or an exec error's message;
41
- // of `details`, only an unreadable remote's bounded cause (Spec D). A refusal cannot become success.
42
- // `origin: 'kernel'`: this reason is the one the installed CLI printed in its envelope, so the
43
- // kernel answered, in its own words. The reader's own failures (`deploymentFailure`: the gate, a
44
- // timeout, the output limit, a protocol failure, a failed run) carry no origin, and unmarked
45
- // reads as not the kernel's: who shows a reason decides by where it came from, never by its shape.
46
- const cause = reason.code === 'E_REMOTE_UNREADABLE' ? remoteFailureCause(reason.details) : null;
47
- return done({ ok: false, reason: { code: reason.code, message: reason.message, origin: 'kernel', ...(cause ? { cause } : {}) } });
48
- }
49
- if (error) return fail('E_CLI_FAILED');
50
- if (action === 'status') {
51
- if (Object.hasOwn(document, 'schemaVersion') || !absolute(document.root) || !Array.isArray(document.agents)) return fail('E_CLI_PROTOCOL');
52
- } else if (document.schemaVersion !== 1 || document.ok !== true || document.result?.workspaceStatusApi !== 1) return fail('E_CLI_PROTOCOL');
53
- done({ ok: true, document });
31
+ done(deploymentReadAnswer(action, { failed: !!error, document }));
54
32
  });
55
33
  } catch { fail('E_CLI_FAILED'); }
56
34
  });
57
35
  }
36
+
37
+ /* The three pieces below are the read's own, shared by its two routes: the CLI run above and the warm
38
+ * reader (warm-reader.mjs), which answers the same argv with the same JSON. Neither route has a check of
39
+ * its own, so a reader answer is held to exactly what the same CLI run would be. Not on the stable surface. */
40
+
41
+ /** The refusal of a read before anything runs (the probe's gate, then the input), or null. */
42
+ export function deploymentReadRefusal(cli, options) {
43
+ const gate = deploymentReadGate(cli, options?.action);
44
+ if (gate) return gate;
45
+ if (!absolute(cli.bin) || !deploymentRecord(options) || Object.keys(options).some(k => !['action', 'context', 'maxAge'].includes(k))
46
+ || !absolute(options.context) || !validMaxAge(options.maxAge)) return deploymentFailure('E_BAD_ARGS');
47
+ return null;
48
+ }
49
+
50
+ /** The argv of an admitted read (deploymentReadRefusal answered null).
51
+ * --max-age only when the probe declares observe-max-age; otherwise the argv is the flagless one. */
52
+ export function deploymentReadArgv(cli, options) {
53
+ return [...(options.action === 'status' ? ['status'] : ['workspace', 'status']), '--dir', options.context, ...maxAgeArgv(cli.features, options.maxAge), '--json'];
54
+ }
55
+
56
+ /** What the kernel's answer to a read is for its client: `document`, the JSON value it printed, parsed
57
+ * once; `failed`, whether it exited nonzero. → { ok: true, document } | { ok: false, reason }. */
58
+ export function deploymentReadAnswer(action, { failed, document }) {
59
+ if (!deploymentRecord(document)) return deploymentFailure('E_CLI_PROTOCOL');
60
+ if (document.schemaVersion === 1 && document.ok === false) {
61
+ const reason = document.error;
62
+ if (!deploymentRecord(reason) || !deploymentErrorCode(reason.code)
63
+ || typeof reason.message !== 'string' || reason.message.length > 8192) return deploymentFailure('E_CLI_PROTOCOL');
64
+ // Only the bounded kernel error envelope, never stderr, argv, stacks or an exec error's message;
65
+ // of `details`, only an unreadable remote's bounded cause (Spec D). A refusal cannot become success.
66
+ // `origin: 'kernel'`: this reason is the one the installed CLI printed in its envelope, so the
67
+ // kernel answered, in its own words. The reader's own failures (`deploymentFailure`: the gate, a
68
+ // timeout, the output limit, a protocol failure, a failed run) carry no origin, and unmarked
69
+ // reads as not the kernel's: who shows a reason decides by where it came from, never by its shape.
70
+ const cause = reason.code === 'E_REMOTE_UNREADABLE' ? remoteFailureCause(reason.details) : null;
71
+ return { ok: false, reason: { code: reason.code, message: reason.message, origin: 'kernel', ...(cause ? { cause } : {}) } };
72
+ }
73
+ if (failed) return deploymentFailure('E_CLI_FAILED');
74
+ if (action === 'status') {
75
+ if (Object.hasOwn(document, 'schemaVersion') || !absolute(document.root) || !Array.isArray(document.agents)) return deploymentFailure('E_CLI_PROTOCOL');
76
+ } else if (document.schemaVersion !== 1 || document.ok !== true || document.result?.workspaceStatusApi !== 1) return deploymentFailure('E_CLI_PROTOCOL');
77
+ return { ok: true, document };
78
+ }
@@ -25,6 +25,9 @@ export const CLIENT_OWN_CODES = Object.freeze([
25
25
  // Stop, start, restart and remove, and the plan a person confirms (a spawn's plan too).
26
26
  'E_LIFECYCLE_UNAVAILABLE', 'E_OPTION_UNAVAILABLE', 'E_PLAN_CHANGED', 'E_PLAN_EXPIRED', 'E_PLAN_LIMIT', 'E_PLAN_REQUIRED',
27
27
  'E_HOME_UNVERIFIED', 'E_START_UNCONFIRMED',
28
+ // The warm reader's client (packages/client/warm-reader.mjs): why a reader stopped answering, or never started.
29
+ // E_READER_STALE and E_READER_DEFECT are the reader's own refusal codes, the kernel's, and not here.
30
+ 'E_READER_EXIT', 'E_READER_HELLO_TIMEOUT', 'E_READER_MISMATCH', 'E_READER_OUTPUT_LIMIT', 'E_READER_PATH', 'E_READER_TIMEOUT',
28
31
  // keys.json (packages/client/keys-file.mjs): a write that could not keep every key, so none is made.
29
32
  'E_KEYS_UNWRITABLE',
30
33
  // An instance's Activity.
@@ -0,0 +1,241 @@
1
+ /** The warm reader's client (#1630, option C): the background deployment reads answered by one long-lived
2
+ * `oats reader --stdio` child of the installed CLI, kept warm, instead of one CLI run per read.
3
+ *
4
+ * `createWarmReader({ spawn, onStale })` answers `read(cli, options, io)`, a reader with
5
+ * `cliDeploymentRead`'s signature and answers: an observer takes it as its `read`
6
+ * (deployment-observer.mjs), so coalescing, the admission bound and probe-generation revocation are the
7
+ * observer's, unchanged. Whenever the rules below do not let the reader answer, the read is
8
+ * `cliDeploymentRead(cli, options, io)` itself, today's CLI read, unchanged: the reader is an accelerator
9
+ * of identical answers, never a second path with a shape of its own. Its answer goes through the same
10
+ * validation as the CLI's stdout (deployment-read-cli.mjs `deploymentReadAnswer`), parsed once.
11
+ *
12
+ * The rules are the contract's (docs/desktop-cli-api.md, "The warm reader"; the client rules agreed on
13
+ * #1630):
14
+ * - Start: only when the probe lists feature `warm-reader` and `readerApi: 1`, from the same binary and
15
+ * environment as the CLI reads (`withoutInstanceVariables`), no shell, stdin and stdout piped, stderr
16
+ * ignored (never read, never forwarded). Reads before its hello go to the CLI: no read waits for it.
17
+ * Not when that environment's PATH has a relative or empty entry: the CLI runs in each read's
18
+ * deployment, so such an entry can pick its interpreter (`#!/usr/bin/env node`) there, and one reader
19
+ * started once cannot do the same for every deployment.
20
+ * - Trust: a hello within the CLI read's timeout, `readerApi === 1`, the probe's `version`, and the read
21
+ * in `reads`. A wrong hello ends it, and the CLI answers until the record changes. The reader is bound
22
+ * to the probe record it started for (`probeSignature`); a read under another record ends it.
23
+ * - Routing: only background reads (`--max-age` > 0) go to it; a live read (0) never queues behind it.
24
+ * - Refusals: E_READER_UNSUPPORTED, E_READER_BAD_REQUEST or any other code: that read goes to the CLI, the
25
+ * reader is kept. E_READER_STALE (the install changed; the reader exits): the read goes to the CLI,
26
+ * `onStale()` runs (the Desktop probes again), and no reader starts before it settles. Without
27
+ * `onStale` (a client that never probes again) the record stays on the CLI. Not a failure.
28
+ * - Failures: an exit without an answer, the hello's timeout, a request's timeout, E_READER_DEFECT, an
29
+ * answer line over its bound. The reads in flight go to the CLI; the next start waits 1 s, doubling, at
30
+ * most 5 min; after 5 in a row without an answer, the CLI until the record changes.
31
+ * - Timeout: a request's deadline is the CLI read's own, counted from when it becomes the oldest
32
+ * unanswered one (queue wait does not count).
33
+ * - End: `stop()` closes its stdin, which ends it. A client's death closes that stdin too: the reader's
34
+ * lifeline is its client's exclusive hold of the write end.
35
+ *
36
+ * `status()` is a diagnostic for the client's own logs and API ({ state, code }), never a fact a page
37
+ * shows: refusal and fallback are silent. `spawn` is `node:child_process` `spawn` or a stand-in with its
38
+ * signature; the module starts nothing itself, so a client keeps the custody of its children. */
39
+ import { isAbsolute, resolve } from 'node:path';
40
+ import { cliDeploymentRead, deploymentReadRefusal, deploymentReadArgv, deploymentReadAnswer, DEPLOYMENT_READ_TIMEOUT, DEPLOYMENT_READ_MAX_BUFFER } from './deployment-read-cli.mjs';
41
+ import { maxAgeArgv } from './deployment-contract.mjs';
42
+ import { probeSignature } from './cli-probe-contract.mjs';
43
+ import { withoutInstanceVariables } from './kernel-environment.mjs';
44
+
45
+ export const WARM_READER_FEATURE = 'warm-reader';
46
+ export const READER_API = 1;
47
+ /** The reads the reader may answer, by the observer's action name, as its hello names them. */
48
+ const READS = Object.freeze({ status: 'status', 'workspace-status': 'workspace status' });
49
+ /** An answer line holds the CLI read's output (its own bound) in an envelope: the id, the exit and at
50
+ * most 8 KiB of stderr text. Past this, the line is not parsed. */
51
+ const LINE_LIMIT = DEPLOYMENT_READ_MAX_BUFFER + 64 * 1024;
52
+ const FIRST_BACKOFF_MS = 1000, MAX_BACKOFF_MS = 5 * 60_000, GIVE_UP_AFTER = 5;
53
+ const record = value => value !== null && typeof value === 'object' && !Array.isArray(value);
54
+ const absolute = path => typeof path === 'string' && !path.includes('\0') && isAbsolute(path) && resolve(path) === path;
55
+ const wanted = id => (typeof id === 'string' && id.length <= 64) || Number.isSafeInteger(id);
56
+ const later = timer => { if (typeof timer?.unref === 'function') timer.unref(); return timer; };
57
+ /** No program PATH finds depends on the process's cwd: every entry is an absolute directory, or there is no
58
+ * PATH (the system's default search path). */
59
+ const cwdFreePath = path => path === undefined || (typeof path === 'string' && path.split(':').every(entry => isAbsolute(entry)));
60
+
61
+ /** The probe lists the reader at the API this client speaks. */
62
+ export const readerAdvertised = cli => cli?.ok === true && absolute(cli.bin) && cli.readerApi === READER_API
63
+ && Array.isArray(cli.features) && cli.features.includes(WARM_READER_FEATURE);
64
+
65
+ export function createWarmReader({ spawn, onStale = null } = {}) {
66
+ if (typeof spawn !== 'function') throw new TypeError('createWarmReader needs a spawn');
67
+ // The record the reader belongs to, with what this client has learnt of readers under it. A new record
68
+ // starts afresh: no failures, no give-up, no mismatch.
69
+ let binding = null;
70
+ let child = null; // the running reader, or null
71
+ let stopped = false, sequence = 0;
72
+
73
+ function bind(cli) {
74
+ const key = probeSignature(cli);
75
+ if (binding?.key === key) return;
76
+ if (child) end(child);
77
+ binding = { key, advertised: readerAdvertised(cli), pathRefused: false, failures: 0, nextStartAt: 0, givenUp: false, mismatch: false, stale: false, code: null };
78
+ }
79
+
80
+ function read(cli, options, io = {}) {
81
+ const fallback = () => cliDeploymentRead(cli, options, io);
82
+ if (stopped || !record(cli)) return fallback();
83
+ bind(cli);
84
+ if (!binding.advertised || deploymentReadRefusal(cli, options)) return fallback();
85
+ // Background only: a positive --max-age the argv carries (the probe declares observe-max-age).
86
+ if (!(options.maxAge > 0) || !maxAgeArgv(cli.features, options.maxAge).length) return fallback();
87
+ const env = withoutInstanceVariables(io.env ?? process.env);
88
+ binding.pathRefused = !cwdFreePath(env.PATH);
89
+ if (binding.pathRefused) { binding.code = 'E_READER_PATH'; return fallback(); }
90
+ if (!child) { start(cli, env); return fallback(); }
91
+ if (!child.trusted || !child.reads.has(READS[options.action])) return fallback();
92
+ return ask(child, options.action, deploymentReadArgv(cli, options), fallback);
93
+ }
94
+
95
+ function start(cli, env) {
96
+ const b = binding;
97
+ if (b.givenUp || b.mismatch || b.stale || Date.now() < b.nextStartAt) return;
98
+ const c = { binding: b, version: cli.version, proc: null, trusted: false, reads: new Set(), pending: new Map(),
99
+ chunks: [], bytes: 0, helloTimer: null, headId: undefined, headTimer: null, done: false };
100
+ try {
101
+ c.proc = spawn(cli.bin, ['reader', '--stdio'], { env, stdio: ['pipe', 'pipe', 'ignore'], shell: false });
102
+ } catch { b.code = 'E_READER_EXIT'; return countFailure(b); }
103
+ child = c;
104
+ c.proc.stdin?.on?.('error', () => { /* a dead reader: its close says so */ });
105
+ c.proc.stdout?.on?.('error', () => {});
106
+ c.proc.stdout?.on?.('data', chunk => take(c, chunk));
107
+ c.proc.on?.('error', () => fail(c, 'E_READER_EXIT'));
108
+ c.proc.on?.('close', () => fail(c, 'E_READER_EXIT'));
109
+ c.helloTimer = later(setTimeout(() => fail(c, 'E_READER_HELLO_TIMEOUT', true), DEPLOYMENT_READ_TIMEOUT));
110
+ }
111
+
112
+ /** One request: answered by the reader, or by the CLI when the reader refuses it, fails or ends. */
113
+ function ask(c, action, argv, fallback) {
114
+ const id = ++sequence;
115
+ return new Promise(resolve => {
116
+ c.pending.set(id, { action, resolve, fallback });
117
+ armHead(c);
118
+ try { c.proc.stdin.write(`${JSON.stringify({ id, argv })}\n`); } catch { fail(c, 'E_READER_EXIT'); }
119
+ });
120
+ }
121
+
122
+ /** The oldest unanswered request's deadline starts when it becomes the oldest. */
123
+ function armHead(c) {
124
+ const head = c.pending.keys().next().value;
125
+ if (head === c.headId) return;
126
+ clearTimeout(c.headTimer);
127
+ c.headId = head; c.headTimer = null;
128
+ if (head !== undefined) c.headTimer = later(setTimeout(() => fail(c, 'E_READER_TIMEOUT', true), DEPLOYMENT_READ_TIMEOUT));
129
+ }
130
+
131
+ function settle(c, id, answer) {
132
+ const entry = c.pending.get(id);
133
+ c.pending.delete(id);
134
+ armHead(c);
135
+ entry.resolve(answer === undefined ? entry.fallback() : answer);
136
+ }
137
+
138
+ /** Lines out of the reader's stdout, each bounded before it is parsed. */
139
+ function take(c, chunk) {
140
+ if (c.done) return;
141
+ const bytes = typeof chunk === 'string' ? Buffer.from(chunk, 'utf8') : chunk;
142
+ let from = 0;
143
+ while (!c.done) {
144
+ const newline = bytes.indexOf(10, from);
145
+ const piece = bytes.subarray(from, newline < 0 ? bytes.length : newline);
146
+ c.bytes += piece.length;
147
+ if (c.bytes > LINE_LIMIT) return fail(c, 'E_READER_OUTPUT_LIMIT', true);
148
+ if (piece.length) c.chunks.push(piece);
149
+ if (newline < 0) return;
150
+ const line = Buffer.concat(c.chunks).toString('utf8');
151
+ c.chunks = []; c.bytes = 0; from = newline + 1;
152
+ frame(c, line);
153
+ }
154
+ }
155
+
156
+ function frame(c, line) {
157
+ let value;
158
+ try { value = JSON.parse(line); } catch { return; } // no frame: ignored (a request it misses times out)
159
+ if (!record(value)) return;
160
+ if (!c.trusted) return Object.hasOwn(value, 'readerApi') ? hello(c, value) : undefined;
161
+ if (Object.hasOwn(value, 'refused')) return refusal(c, value);
162
+ if (!wanted(value.id) || !c.pending.has(value.id) || !Number.isSafeInteger(value.exit) || !Object.hasOwn(value, 'answer')) return;
163
+ c.binding.failures = 0; c.binding.nextStartAt = 0;
164
+ // `answer` is the JSON value the CLI prints, parsed once with the line; `stderr` is never read.
165
+ settle(c, value.id, deploymentReadAnswer(c.pending.get(value.id).action, { failed: value.exit !== 0, document: value.answer }));
166
+ }
167
+
168
+ function hello(c, value) {
169
+ clearTimeout(c.helloTimer);
170
+ const reads = Array.isArray(value.reads) && value.reads.every(r => typeof r === 'string') ? value.reads : null;
171
+ if (value.readerApi !== READER_API || value.version !== c.version || !reads || !Object.values(READS).some(r => reads.includes(r))) {
172
+ // Not the reader this probe vouches for: no retries under this record.
173
+ c.binding.mismatch = true; c.binding.code = 'E_READER_MISMATCH';
174
+ return end(c);
175
+ }
176
+ c.trusted = true; c.reads = new Set(reads);
177
+ }
178
+
179
+ function refusal(c, value) {
180
+ const code = record(value.refused) && typeof value.refused.code === 'string' ? value.refused.code.slice(0, 64) : null;
181
+ if (code === 'E_READER_STALE') return stale(c);
182
+ if (code === 'E_READER_DEFECT') return fail(c, 'E_READER_DEFECT');
183
+ if (code) c.binding.code = code;
184
+ if (wanted(value.id) && c.pending.has(value.id)) settle(c, value.id); // that read to the CLI; the reader is kept
185
+ }
186
+
187
+ function stale(c) {
188
+ if (c.done) return;
189
+ const b = c.binding;
190
+ b.stale = true; b.code = 'E_READER_STALE';
191
+ end(c);
192
+ if (typeof onStale !== 'function') return; // the record stays on the CLI
193
+ Promise.resolve().then(onStale).catch(() => {}).finally(() => { b.stale = false; });
194
+ }
195
+
196
+ function countFailure(b) {
197
+ b.failures++;
198
+ b.nextStartAt = Date.now() + Math.min(FIRST_BACKOFF_MS * 2 ** (b.failures - 1), MAX_BACKOFF_MS);
199
+ if (b.failures >= GIVE_UP_AFTER) b.givenUp = true;
200
+ }
201
+
202
+ /** A failure of this reader (once): counted against its record, then it ends. `signal`: it stopped
203
+ * answering, so it may not be reading its stdin either. */
204
+ function fail(c, code, signal = false) {
205
+ if (c.done) return;
206
+ c.binding.code = code;
207
+ countFailure(c.binding);
208
+ end(c, signal);
209
+ }
210
+
211
+ /** End a reader: close its stdin (and signal it when it stopped answering), and hand every read in
212
+ * flight to the CLI. */
213
+ function end(c, signal = false) {
214
+ if (c.done) return;
215
+ c.done = true;
216
+ clearTimeout(c.helloTimer); clearTimeout(c.headTimer);
217
+ if (child === c) child = null;
218
+ try { c.proc.stdin?.end?.(); } catch { /* already closed */ }
219
+ if (signal) try { c.proc.kill?.('SIGTERM'); } catch { /* already gone */ }
220
+ const pending = [...c.pending.values()];
221
+ c.pending.clear();
222
+ for (const entry of pending) entry.resolve(entry.fallback());
223
+ }
224
+
225
+ function status() {
226
+ if (stopped) return { state: 'stopped', code: binding?.code ?? null };
227
+ if (!binding || !binding.advertised) return { state: 'off', code: null };
228
+ if (binding.pathRefused && !child) return { state: 'off', code: binding.code };
229
+ const state = binding.givenUp ? 'given-up' : binding.mismatch ? 'mismatch' : binding.stale ? 'stale'
230
+ : child ? (child.trusted ? 'ready' : 'starting') : binding.failures ? 'backoff' : 'idle';
231
+ return { state, code: binding.code };
232
+ }
233
+
234
+ /** The client quits: the reader ends (its stdin closes), and every later read is the CLI's. */
235
+ function stop() {
236
+ stopped = true;
237
+ if (child) end(child);
238
+ }
239
+
240
+ return { read, status, stop };
241
+ }
@@ -13,8 +13,9 @@ export { cliDeploymentList } from "../../client/deployment-list-cli.mjs";
13
13
  export { deploymentsListSupported } from "../../client/deployment-list.mjs";
14
14
  export { cliRemoteRoster } from "../../client/cli-adapter.mjs";
15
15
  export { createDeploymentObserver, mapBounded, MAX_DEPLOYMENT_OBSERVATIONS } from "../../client/deployment-observer.mjs";
16
+ export { createWarmReader } from "../../client/warm-reader.mjs";
16
17
  export { createRefreshLoop } from "../../client/refresh-loop.mjs";
17
- export { rosterRows, livenessInput, livenessAnswers, panelInstances, pendingEntry, failedEntry, observedEntry } from "../../client/deployment-panel.mjs";
18
+ export { rosterRows, kernelLiveness, livenessInput, livenessAnswers, panelInstances, pendingEntry, failedEntry, observedEntry } from "../../client/deployment-panel.mjs";
18
19
  export { panelData, cliReadsRemotes, workspaceChoices, viewModel, listedViews, deployments } from "../../client/panel-views.mjs";
19
20
  export { cliDeploymentIdentity, identityReadable, identityTimedOut } from "../../client/deployment-identity.mjs";
20
21
  export { workspaceStep } from "../../client/workspace-step.mjs";