@awebai/oats 0.69.5 → 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.
- package/bin/oats.mjs +78 -320
- package/docs/design/2026-09-26-okf-knowledge-operations.md +2 -0
- package/docs/design/2026-10-29-warm-reader.md +261 -0
- package/docs/design/README.md +4 -0
- package/docs/desktop-cli-api.md +250 -12
- package/docs/execution-targets.md +11 -2
- package/docs/implementation.md +26 -8
- package/docs/integrations.md +1 -1
- package/docs/knowledge.md +14 -7
- package/docs/named-test-runs.md +4 -0
- package/docs/official-catalog.md +3 -3
- package/docs/packages.md +12 -12
- package/docs/release-notes/v0.69.6.md +165 -0
- package/docs/schedules.md +8 -1
- package/docs/tui.md +21 -4
- package/docs/upgrading.md +9 -5
- package/docs/workspaces.md +2 -2
- package/lib/argv.mjs +41 -0
- package/lib/automation-scope.mjs +6 -4
- package/lib/automations.mjs +61 -11
- package/lib/captured-context.mjs +12 -0
- package/lib/hot-reads.mjs +21 -15
- package/lib/install-stamp.mjs +61 -0
- package/lib/instance-events.mjs +8 -6
- package/lib/instance-listing.mjs +13 -5
- package/lib/kernel-features.mjs +10 -0
- package/lib/local-edit.mjs +1 -1
- package/lib/local-inputs.mjs +3 -0
- package/lib/member-clone.mjs +15 -11
- package/lib/read-call.mjs +143 -0
- package/lib/reader.mjs +203 -0
- package/lib/remote.mjs +47 -6
- package/lib/resolved-deployment.mjs +12 -4
- package/lib/roster-read.mjs +199 -0
- package/lib/session-input.mjs +35 -11
- package/lib/workspace-read.mjs +160 -0
- package/package-catalog.json +2 -2
- package/package.json +1 -1
- package/packages/client/cli-locator.mjs +1 -0
- package/packages/client/cli-probe-contract.mjs +4 -2
- package/packages/client/deployment-observer.mjs +8 -3
- package/packages/client/deployment-panel.mjs +17 -1
- package/packages/client/deployment-read-cli.mjs +48 -27
- package/packages/client/own-codes.mjs +3 -0
- package/packages/client/warm-reader.mjs +241 -0
- package/packages/tui/lib/client.mjs +2 -1
- package/packages/tui/lib/read.mjs +59 -11
- package/skills/oats-getting-started/SKILL.md +2 -2
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
/** lib/workspace-read.mjs — `oats workspace status`, the workspace read (awebai/oats#1630): the
|
|
2
|
+
* membership table, the locked and declared packages, the automations placed on this host, and the
|
|
3
|
+
* desktop facts. One implementation behind the CLI (bin/oats.mjs workspaceCmd) and a process that answers
|
|
4
|
+
* it many times (lib/read-call.mjs, whose header describes the context and the answer).
|
|
5
|
+
* `workspaceStatusAnswer(ctx)` is the `--json` answer, an envelope; `workspaceStatusView(ctx)` the data
|
|
6
|
+
* bin's text renderer reads. Beside them, the rows `oats sync` reports too. A leaf a hot read loads
|
|
7
|
+
* (lib/hot-reads.mjs): never core.mjs. Kernel-private, not exported from `./core`. */
|
|
8
|
+
import { dirname, join } from "node:path";
|
|
9
|
+
import { scopeAutomations } from "./automation-scope.mjs";
|
|
10
|
+
import { GH_LOGIN_DISPLAY_TIMEOUT_MS, ghLoginParts, staleTrust, trustRemedy } from "./automations.mjs";
|
|
11
|
+
import { LAYERS, officialCapabilityAliases, officialCatalogFile, officialPackageCatalog } from "./package-catalog.mjs";
|
|
12
|
+
import { classifyPackageValue, LOCK_FILE, readLock } from "./packages.mjs";
|
|
13
|
+
import { answerWarnings, refuse, runRead } from "./read-call.mjs";
|
|
14
|
+
import { browseUrl, factObservation } from "./remote.mjs";
|
|
15
|
+
import { loadLocal } from "./workspace.mjs";
|
|
16
|
+
|
|
17
|
+
/** `oats workspace status --json`: → `{ exit, answer, stderr }` (lib/read-call.mjs), `answer` the envelope. */
|
|
18
|
+
export function workspaceStatusAnswer(ctx) {
|
|
19
|
+
return runRead(ctx, async (call) => {
|
|
20
|
+
const { result } = await workspaceStatusFacts(call, ctx);
|
|
21
|
+
return { answer: { schemaVersion: 1, ok: true, result: call.withObservation(result), ...answerWarnings() } };
|
|
22
|
+
});
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** `oats workspace status` in text mode: → `{ exit, answer, view, stderr }`, `view` `{ result, discovery,
|
|
26
|
+
* localPath }` when it did not refuse, `answer` the failure envelope when it did. */
|
|
27
|
+
export function workspaceStatusView(ctx) {
|
|
28
|
+
return runRead(ctx, async (call) => ({ view: await workspaceStatusFacts(call, ctx) }));
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** The facts of `oats workspace status` (contract §6) at the deployment `dir` names. */
|
|
32
|
+
async function workspaceStatusFacts(call, { dir }) {
|
|
33
|
+
let found;
|
|
34
|
+
try { found = loadLocal(dir); }
|
|
35
|
+
catch (e) { refuse(e.code || "E_LOCAL_MISSING", e.message, e.details); }
|
|
36
|
+
// `remotes`: each member clone's remotes, asked of git once for the whole read (lib/member-clone.mjs).
|
|
37
|
+
const ctx = { dir, localPath: found.path, local: found.local, deploymentDir: dirname(found.path), remoteOptions: call.remoteOptions(), remotes: new Map() };
|
|
38
|
+
// The standalone case (decisions 10/25) is a discovery too: the repo's own view
|
|
39
|
+
// plus the kernel's oats.core default — discoverOrStandalone decides.
|
|
40
|
+
let discovery;
|
|
41
|
+
try { const { discoverOrStandalone } = await import("./member-clone.mjs"); discovery = await discoverOrStandalone(ctx.local, { deployment: ctx.deploymentDir, remoteOptions: ctx.remoteOptions }); }
|
|
42
|
+
catch (e) { if (typeof e?.code === "string" && e.code.startsWith("E_")) refuse(e.code, e.message, e.details ?? e.provenance); throw e; }
|
|
43
|
+
let lock;
|
|
44
|
+
try { lock = readLock(ctx.deploymentDir); } catch (e) { refuse(e.code || "E_LOCK_SCHEMA", e.message, e.details); }
|
|
45
|
+
const members = memberRows(discovery);
|
|
46
|
+
const packages = packageRows(lock);
|
|
47
|
+
// Standalone (decision 10): there is no workspace file — the declared packages are the
|
|
48
|
+
// kernel's own default (decision 25) and there are no teams.
|
|
49
|
+
const standalone = discovery.standalone === true;
|
|
50
|
+
const declared = Object.keys(standalone ? standalonePackages(catalogForStatus()).packages : (discovery.workspace?.packages || {})).sort();
|
|
51
|
+
const locked = new Set(packages.map((p) => p.id));
|
|
52
|
+
const unsynced = declared.filter((id) => !locked.has(id));
|
|
53
|
+
const stale = packages.filter((p) => !declared.includes(p.id)).map((p) => p.id);
|
|
54
|
+
const result = { workspaceStatusApi: 1, standalone: standalone || undefined, workspace: { name: workspaceName(discovery), key: discovery.key, url: discovery.url, commit: discovery.commit, observedAt: discovery.observedAt, local: ctx.localPath, teams: sharedTeamRows(discovery) }, members, packages, declaredPackages: declared, unsynced, stale, external: (discovery.external || []).map((e) => ({ source: e.source, soul: e.soul.name })), problems: discovery.problems, warnings: [...(discovery.warnings ?? [])] };
|
|
55
|
+
// Workspace automations (0.29.0), from the snapshot `oats sync` took, placed on this host.
|
|
56
|
+
// A display: under --max-age the placement may reuse a recent gh login, as the read reuses heads, and a hung gh
|
|
57
|
+
// costs it GH_LOGIN_DISPLAY_TIMEOUT_MS. An act that places or fires an automation always asks gh live. Without
|
|
58
|
+
// --max-age the session reuses nothing (maxAge 0), but the lookup still records a login and, failing, ends the
|
|
59
|
+
// reuse of the one before it, as every live display does.
|
|
60
|
+
const lookup = {
|
|
61
|
+
timeoutMs: GH_LOGIN_DISPLAY_TIMEOUT_MS,
|
|
62
|
+
observe: (ghHost) => { const parts = ghLoginParts(ghHost); return parts ? factObservation(ctx.remoteOptions, "gh-login", parts) : null; },
|
|
63
|
+
};
|
|
64
|
+
const actx = scopeAutomations(ctx.deploymentDir, { remotes: ctx.remotes, lookup });
|
|
65
|
+
result.automations = { host: actx.host.name, snapshot: actx.snapshot ? { takenAt: actx.snapshot.takenAt, problems: actx.snapshot.problems.length } : null, rows: [...actx.triggers, ...actx.schedules].map((a) => ({ kind: a.kind, id: a.id, runsOn: a.runsOn, owner: a.owner, runsHere: a.placement.runsHere, reason: a.placement.reason, enabledHere: a.placement.enabledHere, origin: a.origin, ...(a.invalid ? { invalid: a.invalid } : {}) })) };
|
|
66
|
+
// Automation trust (0.30): a workspace automation placed here but not trusted, and a trust entry
|
|
67
|
+
// that names none, are warnings the operator acts on in oats-local.yaml.
|
|
68
|
+
for (const a of [...actx.triggers, ...actx.schedules].filter((x) => x.placement.reason === "untrusted")) {
|
|
69
|
+
result.warnings.push({ code: "automation-untrusted", kind: a.kind, id: a.id, message: `${a.kind} ${a.id} is declared for this host (${a.runsOn}, as ${a.owner}) but not trusted here, so it does not run`, remedy: trustRemedy(a.id) });
|
|
70
|
+
}
|
|
71
|
+
for (const entry of staleTrust(actx.host, [...actx.triggers, ...actx.schedules])) {
|
|
72
|
+
result.warnings.push({ code: "automation-trust-stale", entry, message: `oats-local.yaml automations.trust names ${entry}, which is no workspace trigger or schedule${actx.snapshot ? "" : " (no automations snapshot yet: run oats sync)"}; its member may not have synced yet` });
|
|
73
|
+
}
|
|
74
|
+
await desktopFacts(result, discovery, lock, ctx);
|
|
75
|
+
return { result, discovery, localPath: ctx.localPath };
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** The official catalog's package map (package-catalog.json; OATS_PACKAGE_CATALOG overrides). */
|
|
79
|
+
function catalogForStatus() {
|
|
80
|
+
try { return officialPackageCatalog(); }
|
|
81
|
+
catch (e) { refuse(e.code || "E_PACKAGE_MISSING", e.message); }
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** The committed (shared) teams as `workspace status` reports them: rows in label order (team model v2). */
|
|
85
|
+
function sharedTeamRows(discovery) {
|
|
86
|
+
const teams = discovery.standalone === true ? {} : discovery.workspace?.teams || {};
|
|
87
|
+
return Object.keys(teams).sort((a, b) => (a < b ? -1 : a > b ? 1 : 0)).map((label) => ({ label, team: typeof teams[label]?.team === "string" ? teams[label].team : null, description: typeof teams[label]?.description === "string" ? teams[label].description : null }));
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** `oats workspace status` facts (feature desktop-facts): the workspace defaults as rows; this
|
|
91
|
+
* computer (member clones and the rule that found each, disabled souls, the lock); file locations with
|
|
92
|
+
* browsable urls; each catalog package's newer version, when the official catalog has one. */
|
|
93
|
+
async function desktopFacts(result, discovery, lock, ctx) {
|
|
94
|
+
const { memberCloneOf } = await import("./member-clone.mjs");
|
|
95
|
+
const defaults = discovery.standalone === true ? {} : (discovery.workspace?.defaults ?? {});
|
|
96
|
+
const rows = (entries) => Object.entries(entries && typeof entries === "object" ? entries : {}).map(([name, v]) => ({ name, from: v === "off" ? null : v?.from ?? null, off: v === "off" })).sort((a, b) => (a.name < b.name ? -1 : 1));
|
|
97
|
+
const slot = (d) => (d && typeof d === "object" ? Object.entries(d).map(([name, v]) => ({ name, from: v?.from ?? null }))[0] ?? null : d ?? null);
|
|
98
|
+
result.defaults = {
|
|
99
|
+
slots: Object.fromEntries(LAYERS.map((l) => [l, slot(defaults[l])])),
|
|
100
|
+
capabilities: rows(defaults.capabilities),
|
|
101
|
+
};
|
|
102
|
+
result.workspace.file = discovery.standalone === true ? null : { path: "oats-workspace.yaml", url: browseUrl(discovery.key, discovery.commit, "oats-workspace.yaml") };
|
|
103
|
+
for (const m of result.members) Object.assign(m, { url: browseUrl(m.key, m.commit), membershipFile: { path: "oats-membership.yaml", url: browseUrl(m.key, m.commit, "oats-membership.yaml") } });
|
|
104
|
+
result.clones = result.members.map((m) => {
|
|
105
|
+
try { return { key: m.key, name: m.name, ...memberCloneOf(ctx.deploymentDir, ctx.local, m.key, { remotes: ctx.remotes }) }; }
|
|
106
|
+
catch (e) { if (e?.code === "E_CLONE_MISMATCH") return { key: m.key, name: m.name, path: null, rule: null, problem: { code: e.code, message: e.message } }; throw e; }
|
|
107
|
+
});
|
|
108
|
+
result.disabledSouls = [...(Array.isArray(ctx.local?.souls?.disabled) ? ctx.local.souls.disabled : [])];
|
|
109
|
+
result.lock = { path: join(ctx.deploymentDir, LOCK_FILE), lockfileVersion: lock.lockfileVersion ?? null };
|
|
110
|
+
const { compareSemver } = await import("./semver.mjs");
|
|
111
|
+
let catalog = null; try { catalog = officialPackageCatalog(); } catch { catalog = null; }
|
|
112
|
+
const cat = catalog && typeof catalog === "object" ? (catalog.packages && typeof catalog.packages === "object" && !("url" in catalog.packages) ? catalog.packages : catalog) : {};
|
|
113
|
+
for (const p of result.packages) {
|
|
114
|
+
const ref = p.source === `catalog:${p.id}` ? cat[p.id]?.ref : undefined;
|
|
115
|
+
const tag = standaloneCatalogVersion(ref);
|
|
116
|
+
const version = tag ? tag.replace(/^v/, "") : null;
|
|
117
|
+
p.latest = version && typeof p.version === "string" && compareSemver(version, p.version) > 0 ? { version, ref } : null;
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** The package requests of a standalone view: the catalog's own pin of the package
|
|
122
|
+
* providing oats.core (decision 25) — nothing else, since the version list lives in
|
|
123
|
+
* the workspace file we cannot read. The request is written as resolvePackages
|
|
124
|
+
* expects a CATALOG entry: the bare version (`v1.1.3`), never the catalog's raw ref
|
|
125
|
+
* (`oats-framework/v1.1.3` is a tag PATH the one grammar refuses); parsePackageRequest
|
|
126
|
+
* recomposes the tag from the catalog's own convention.
|
|
127
|
+
* → { packages: { <id>: <version> }, problems: [ { code: "E_PACKAGE_MISSING", … } ] } */
|
|
128
|
+
export function standalonePackages(catalog) {
|
|
129
|
+
let id = "oats.framework";
|
|
130
|
+
const file = officialCatalogFile();
|
|
131
|
+
try { const alias = officialCapabilityAliases()["oats.core"]; id = (typeof alias === "string" ? alias : alias?.package) ?? id; } catch { /* the catalog is diagnosed below */ }
|
|
132
|
+
const version = standaloneCatalogVersion(catalog?.[id]?.ref);
|
|
133
|
+
if (version) return { packages: { [id]: version }, problems: [] };
|
|
134
|
+
const why = catalog?.[id] ? `its ref ${JSON.stringify(catalog[id].ref)} carries no version` : `it has no entry ${JSON.stringify(id)}`;
|
|
135
|
+
return { packages: {}, problems: [{ code: "E_PACKAGE_MISSING", id, reason: "no-catalog", catalog: file, path: `/packages/${id}`, message: `the catalog has no package providing oats.core (OATS_PACKAGE_CATALOG=${file}): ${why}; standalone spawns will be refused until it does` }] };
|
|
136
|
+
}
|
|
137
|
+
/** The bare version of a catalog ref: its LAST path segment when that is a version
|
|
138
|
+
* (`v1.1.3` → `v1.1.3`; `oats-framework/v1.1.3` → `v1.1.3`; `main` → null). */
|
|
139
|
+
export function standaloneCatalogVersion(ref) {
|
|
140
|
+
if (typeof ref !== "string" || !ref.trim()) return null;
|
|
141
|
+
const tail = ref.trim().split("/").filter(Boolean).pop() ?? "";
|
|
142
|
+
return classifyPackageValue(tail).kind === "catalog" ? tail : null;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** Display name of a discovery: the workspace's name, or the standalone label (decision 10). */
|
|
146
|
+
export const workspaceName = (discovery) => discovery.workspace?.name ?? `standalone:${memberLabel(discovery.key)}`;
|
|
147
|
+
export const memberLabel = (key) => String(key).split("/").filter(Boolean).pop()?.replace(/\.git$/, "") || String(key);
|
|
148
|
+
|
|
149
|
+
/** Membership rows for `sync` / `workspace status`. */
|
|
150
|
+
export function memberRows(discovery) {
|
|
151
|
+
return discovery.members.map((m) => ({
|
|
152
|
+
key: m.key, name: memberLabel(m.key), commit: m.commit ?? null, confirmed: m.confirmed, status: m.confirmed ? "confirmed" : m.reason, detail: m.detail ?? null,
|
|
153
|
+
souls: m.souls.map((s) => s.name), capabilities: m.capabilities.map((c) => c.name), publishes: m.publishes ?? null,
|
|
154
|
+
}));
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** Package rows for `sync` / `workspace status` from the lock. */
|
|
158
|
+
export function packageRows(lock) {
|
|
159
|
+
return Object.entries(lock.packages).map(([id, p]) => ({ id, version: p.version, source: p.source, commit: p.commit, integrity: p.integrity, capabilities: p.capabilities, souls: (p.souls ?? []).map((x) => x.name) }));
|
|
160
|
+
}
|
package/package-catalog.json
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
"packages": {
|
|
4
4
|
"oats.okf": {
|
|
5
5
|
"url": "https://github.com/awebai/oats-okf.git",
|
|
6
|
-
"ref": "v5.
|
|
6
|
+
"ref": "v5.7.0",
|
|
7
7
|
"path": "oats-package"
|
|
8
8
|
},
|
|
9
9
|
"oats.aweb": {
|
|
@@ -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.
|
|
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.
|
|
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
|
-
|
|
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
|
|
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
|
-
|
|
40
|
-
|
|
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
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
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
|
-
|
|
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";
|