@awebai/oats 0.50.0 → 0.52.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.
Files changed (132) hide show
  1. package/README.md +1 -0
  2. package/bin/oats.mjs +153 -51
  3. package/docs/capabilities.md +11 -3
  4. package/docs/configuration.md +134 -88
  5. package/docs/desktop-cli-api.md +994 -71
  6. package/docs/desktop-instance-start.md +56 -0
  7. package/docs/desktop.md +10 -7
  8. package/docs/execution-targets.md +230 -59
  9. package/docs/first-team.md +3 -1
  10. package/docs/harness-trust.md +50 -2
  11. package/docs/implementation.md +73 -8
  12. package/docs/integrations.md +9 -8
  13. package/docs/knowledge-reference/acceptance.md +1 -0
  14. package/docs/knowledge-reference/harvester.md +5 -3
  15. package/docs/knowledge-reference/model.md +5 -3
  16. package/docs/knowledge-theory.md +1 -1
  17. package/docs/knowledge.md +43 -7
  18. package/docs/launch-prompt-completion.md +50 -48
  19. package/docs/oats-local.schema.json +4 -3
  20. package/docs/official-catalog.md +4 -4
  21. package/docs/packages.md +14 -14
  22. package/docs/release-lane.md +15 -5
  23. package/docs/release-notes/v0.44.0.md +1 -1
  24. package/docs/release-notes/v0.51.0.md +156 -0
  25. package/docs/release-notes/v0.52.0.md +933 -0
  26. package/docs/schedules.md +91 -4
  27. package/docs/servers.md +21 -2
  28. package/docs/souls-and-instances.md +113 -21
  29. package/docs/tui.md +152 -0
  30. package/docs/workspaces.md +2 -2
  31. package/lib/claim.mjs +266 -0
  32. package/lib/core.mjs +845 -166
  33. package/lib/errors.mjs +170 -0
  34. package/lib/harness-trust-write.mjs +68 -27
  35. package/lib/harness-trust.mjs +34 -16
  36. package/lib/instance-inspect.mjs +40 -11
  37. package/lib/instance-lifecycle.mjs +169 -47
  38. package/lib/launch-preference.mjs +16 -0
  39. package/lib/launch-prompt-completion.mjs +7 -43
  40. package/lib/launch-prompt-evidence.mjs +14 -7
  41. package/lib/launch-prompt-fixtures/README.md +86 -152
  42. package/lib/launch-prompt-fixtures/dev-channel-confirmation.json +50 -0
  43. package/lib/launch-prompt-fixtures.mjs +122 -109
  44. package/lib/launch-prompt-transport.mjs +2 -56
  45. package/lib/launch-prompts.mjs +102 -100
  46. package/lib/schedule-host.mjs +154 -22
  47. package/lib/schedule.mjs +73 -24
  48. package/lib/servers.mjs +20 -4
  49. package/lib/session-viewer.mjs +87 -10
  50. package/lib/system-tools.mjs +39 -0
  51. package/lib/tmux-server-scope.mjs +62 -0
  52. package/lib/triggers.mjs +4 -4
  53. package/lib/workspace.mjs +5 -11
  54. package/lib/worktree-hooks.mjs +116 -23
  55. package/lib/worktree.mjs +89 -102
  56. package/package-catalog.json +3 -3
  57. package/package.json +7 -2
  58. package/packages/client/capability-show-contract.mjs +230 -0
  59. package/packages/client/capability-warnings-contract.mjs +57 -0
  60. package/packages/client/cli-adapter.mjs +548 -0
  61. package/packages/client/cli-environment.mjs +53 -0
  62. package/packages/client/cli-locator.mjs +253 -0
  63. package/packages/client/cli-probe-contract.mjs +47 -0
  64. package/packages/client/client-terms.mjs +60 -0
  65. package/packages/client/deployment-contract.mjs +68 -0
  66. package/packages/client/deployment-data.mjs +483 -0
  67. package/packages/client/deployment-facts.mjs +34 -0
  68. package/packages/client/deployment-label.mjs +76 -0
  69. package/packages/client/deployment-observer.mjs +89 -0
  70. package/packages/client/deployment-panel.mjs +142 -0
  71. package/packages/client/deployment-read-cli.mjs +53 -0
  72. package/packages/client/display-text.mjs +44 -0
  73. package/packages/client/harness-names.mjs +30 -0
  74. package/packages/client/inspect-contract.mjs +62 -0
  75. package/packages/client/instance-acts.mjs +54 -0
  76. package/packages/client/instance-admission.mjs +45 -0
  77. package/packages/client/instance-events-contract.mjs +74 -0
  78. package/packages/client/instance-git-contract.mjs +80 -0
  79. package/packages/client/instance-presentation.mjs +22 -0
  80. package/packages/client/instance-tree.mjs +453 -0
  81. package/packages/client/kernel-environment.mjs +11 -0
  82. package/packages/client/launch-contract.mjs +51 -0
  83. package/packages/client/launch-prompt-outcome.mjs +165 -0
  84. package/packages/client/lifecycle-cli.mjs +61 -0
  85. package/packages/client/lifecycle-contract.mjs +372 -0
  86. package/packages/client/liveness-main.mjs +10 -0
  87. package/packages/client/liveness.mjs +35 -0
  88. package/packages/client/machine-contract.mjs +123 -0
  89. package/packages/client/own-environment.mjs +22 -0
  90. package/packages/client/panel-views.mjs +286 -0
  91. package/packages/client/readiness-contract.mjs +172 -0
  92. package/packages/client/refresh-loop.mjs +52 -0
  93. package/packages/client/remote-address.mjs +126 -0
  94. package/packages/client/remote-roster.mjs +67 -0
  95. package/packages/client/roster-sections.mjs +80 -0
  96. package/packages/client/spawn-apply-cli.mjs +104 -0
  97. package/packages/client/spawn-apply-contract.mjs +183 -0
  98. package/packages/client/spawn-decision.mjs +46 -0
  99. package/packages/client/spawn-messages.mjs +119 -0
  100. package/packages/client/spawn-preview-cli.mjs +32 -0
  101. package/packages/client/spawn-preview-contract.mjs +314 -0
  102. package/packages/client/team-members.mjs +41 -0
  103. package/packages/client/team-rows.mjs +45 -0
  104. package/packages/client/terminal-contract.mjs +57 -0
  105. package/packages/client/tmux-status.mjs +66 -0
  106. package/packages/client/waiting-on-you.mjs +88 -0
  107. package/packages/client/workspace-admission.mjs +45 -0
  108. package/packages/client/workspace-cli.mjs +142 -0
  109. package/packages/client/workspace-views.mjs +147 -0
  110. package/packages/tui/README.md +46 -0
  111. package/packages/tui/bin/tui.mjs +7 -0
  112. package/packages/tui/lib/actions.mjs +29 -0
  113. package/packages/tui/lib/client.mjs +4 -0
  114. package/packages/tui/lib/main.mjs +105 -0
  115. package/packages/tui/lib/term/keys.mjs +323 -0
  116. package/packages/tui/lib/term/screen.mjs +122 -0
  117. package/packages/tui/lib/term/style.mjs +43 -0
  118. package/packages/tui/lib/term/text.mjs +49 -0
  119. package/packages/tui/lib/term/tty.mjs +168 -0
  120. package/packages/tui/lib/term/width.mjs +124 -0
  121. package/packages/tui/lib/views/frame.mjs +62 -0
  122. package/packages/tui/lib/views/help.mjs +28 -0
  123. package/packages/tui/package.json +8 -0
  124. package/skills/oats-getting-started/SKILL.md +29 -22
  125. package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/frame-05-channel-seeded.txt +0 -35
  126. package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/frame-06-first-after-channel.txt +0 -35
  127. package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/frame-07-after-channel-200ms.txt +0 -35
  128. package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/frame-08-installed-after-channel-200ms.txt +0 -35
  129. package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/manifest.json +0 -77
  130. package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/max-bypass-source.json +0 -88
  131. package/lib/launch-prompt-fixtures/structural-completion.json +0 -205
  132. package/lib/launch-prompt-policy.mjs +0 -87
@@ -0,0 +1,89 @@
1
+ /** Native deployment observations with bounded admission and both-outcome
2
+ * ownership. No cache, queued work, reader fallback or generation conversion. */
3
+ import { isAbsolute, resolve } from 'node:path';
4
+ import { cliDeploymentRead } from './deployment-read-cli.mjs';
5
+ import { deploymentStatusData, workspaceStatusData, observationData } from './deployment-data.mjs';
6
+ import { deploymentReadGate, deploymentFailure, validMaxAge } from './deployment-contract.mjs';
7
+ export const MAX_DEPLOYMENT_OBSERVATIONS = 2; // each owns at most two CLI reads
8
+
9
+ /** Run `fn` over `items` with at most `limit` calls in flight, first come first served; results keep
10
+ * the input order. The observation cycle reads every registered deployment through this, bounded by
11
+ * the observer's own admission: starting them all in one tick left the third and later deployments
12
+ * E_DEPLOYMENT_BUSY on every cycle, never read and shown as "pending" forever (#461). A slow
13
+ * deployment holds one slot while the others go through the rest. */
14
+ export async function mapBounded(items, limit, fn) {
15
+ const results = new Array(items.length);
16
+ let next = 0;
17
+ const worker = async () => { while (next < items.length) { const index = next++; results[index] = await fn(items[index], index); } };
18
+ await Promise.all(Array.from({ length: Math.max(1, Math.min(limit, items.length)) }, worker));
19
+ return results;
20
+ }
21
+ const absolute = value => typeof value === 'string' && !value.includes('\0') && isAbsolute(value) && resolve(value) === value;
22
+
23
+ /** getContext(id) is the owner's registry lookup, not renderer data. revision
24
+ * must change on CLI/registry invalidation. Pending revoked reads retain their
25
+ * slots until settlement; a new epoch cannot bypass the resource bound.
26
+ * `read` is a reader with `cliDeploymentRead`'s signature, `(cli, options)`, and its answer. A client
27
+ * that runs the kernel through its own `exec` passes one that closes over it:
28
+ * `read: (cli, options) => cliDeploymentRead(cli, options, { exec })`. Both reads of an observation
29
+ * go through it, and nothing else of the observer starts a process. */
30
+ export function createDeploymentObserver({ getContext, read = cliDeploymentRead }) {
31
+ const pending = new Map(); let active = 0, alive = true;
32
+ function admit(id) {
33
+ if (!alive) return deploymentFailure('E_DEPLOYMENT_STALE');
34
+ let value;
35
+ try { value = getContext(id); } catch { return deploymentFailure('E_BAD_ARGS'); }
36
+ if (!value || value.deployment !== id || !absolute(id) || !Number.isSafeInteger(value.revision) || value.revision < 0) return deploymentFailure('E_BAD_ARGS');
37
+ const gate = deploymentReadGate(value.cli, 'status');
38
+ 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] };
41
+ const stamp = JSON.stringify([id, value.revision, cli]);
42
+ return { ok: true, deployment: id, cli, stamp };
43
+ }
44
+ const current = captured => { const next = admit(captured.deployment); return next.ok && next.stamp === captured.stamp; };
45
+ /** `maxAge` (feature observe-max-age) rides on both reads; the adapter drops it for a kernel
46
+ * that does not declare the feature. Waiters coalesce on the stamp alone: a live (0) request
47
+ * that joins a background flight accepts that flight's observation rather than doubling it. */
48
+ function observe(id, { maxAge } = {}) {
49
+ const captured = admit(id);
50
+ if (!captured.ok) return Promise.resolve(captured);
51
+ if (!validMaxAge(maxAge)) return Promise.resolve(deploymentFailure('E_BAD_ARGS'));
52
+ let work = pending.get(captured.stamp);
53
+ if (!work) {
54
+ if (active >= MAX_DEPLOYMENT_OBSERVATIONS) return Promise.resolve(deploymentFailure('E_DEPLOYMENT_BUSY'));
55
+ active++; // reserve synchronously, before any dispatch/await
56
+ work = Promise.resolve().then(async () => {
57
+ if (!current(captured)) return deploymentFailure('E_DEPLOYMENT_STALE');
58
+ try {
59
+ const settled = await Promise.allSettled(['status', 'workspace-status'].map(action => Promise.resolve().then(() => {
60
+ if (!current(captured)) return deploymentFailure('E_DEPLOYMENT_STALE');
61
+ return read(captured.cli, { action, context: captured.deployment, ...(maxAge !== undefined ? { maxAge } : {}) });
62
+ })));
63
+ // Even a rejecting invoker keeps this reservation until its sibling
64
+ // read settles. Promise.all would release resources prematurely.
65
+ if (!current(captured)) return deploymentFailure('E_DEPLOYMENT_STALE');
66
+ if (settled.some(result => result.status === 'rejected')) return deploymentFailure('E_CLI_PROTOCOL');
67
+ const [status, header] = settled.map(result => result.value);
68
+ if (!status?.ok) return status || deploymentFailure('E_CLI_PROTOCOL');
69
+ if (!header?.ok) return header || deploymentFailure('E_CLI_PROTOCOL');
70
+ const workspaceStatus = workspaceStatusData(header.document, captured.deployment);
71
+ const roster = deploymentStatusData(status.document, captured.deployment);
72
+ // The observation's age is its OLDEST remote-head observation across both reads; a
73
+ // kernel that reports none observed live, so the completion time is the truth.
74
+ const stamps = [status, header].map(r => observationData(r.document).observedAt).filter(s => typeof s === 'string');
75
+ const observedAt = stamps.length ? stamps.sort()[0] : new Date().toISOString();
76
+ return { ok: true, deployment: captured.deployment, workspaceStatus, roster, observedAt };
77
+ } catch (error) {
78
+ if (!current(captured)) return deploymentFailure('E_DEPLOYMENT_STALE');
79
+ return deploymentFailure(error?.code === 'E_DEPLOYMENT_SCOPE' ? 'E_DEPLOYMENT_SCOPE' : 'E_CLI_PROTOCOL');
80
+ }
81
+ }).finally(() => { pending.delete(captured.stamp); active--; });
82
+ pending.set(captured.stamp, work);
83
+ }
84
+ // Each waiter owns its copy; a renderer/request cannot mutate another's
85
+ // observation or the retained private producer bytes.
86
+ return work.then(result => current(captured) ? structuredClone(result) : deploymentFailure('E_DEPLOYMENT_STALE'));
87
+ }
88
+ return { observe, dispose() { alive = false; } };
89
+ }
@@ -0,0 +1,142 @@
1
+ /** What one deployment's observation becomes for a client's panel (#855, 1d): the kernel's roster as
2
+ * rows, the liveness collector's input and its answers, each row as the panel serves it, and the
3
+ * deployment's entry: before the first probe, after a failed read, and observed.
4
+ *
5
+ * Every function takes what it needs and returns a value. Nothing is kept between calls, and nothing
6
+ * here reads a clock, a file or a process: a client runs the collector itself (liveness-main.mjs, as a
7
+ * child, with its own environment and limits) and gives what it printed to `livenessAnswers`, and it
8
+ * passes the time of its call as `at`, an ISO string. Each client keeps its own store of entries.
9
+ *
10
+ * Not for a page: this module imports `node:path`. What a page shows of a deployment that is not
11
+ * observed is in deployment-facts.mjs (`deploymentUnavailableText`), and the Desktop's
12
+ * test/inventory.test.mjs holds that its page reaches no module that imports a Node builtin. */
13
+ import { dirname } from 'node:path';
14
+
15
+ /** One row per instance of a roster (deployment-data.mjs `deploymentStatusData`): the kernel's row,
16
+ * with `agent`, `description` and `team` from its soul and `agentsRoot` from the roster.
17
+ * Needs input: a row keeps the kernel's `waitingOnYou` only when this CLI advertises waiting-on-you.
18
+ * Gate on the feature, never the version: a pre-feature kernel emitting the field is dropped. A row
19
+ * without the key stays without it. */
20
+ export function rosterRows(roster, cli) {
21
+ const waitingFeature = Array.isArray(cli?.features) && cli.features.includes("waiting-on-you");
22
+ return roster.agents.flatMap((agent) => agent.instances.map(({ waitingOnYou, ...instance }) => ({
23
+ ...instance, ...(waitingFeature && waitingOnYou !== undefined ? { waitingOnYou } : {}),
24
+ agent: instance.agent || agent.name, description: agent.description || "",
25
+ team: agent.team || null, agentsRoot: roster.root,
26
+ })));
27
+ }
28
+
29
+ /** The liveness collector's input (liveness.mjs `observeLiveness`), one per row, in the rows' order.
30
+ * `running` is the kernel's answer: the collector leaves a row it answered `null` as the kernel has it. */
31
+ export function livenessInput(rows) {
32
+ return rows.map((i) => ({ instance: i.instance, running: i.running, tmux: i.tmux, sessionTarget: i.sessionTarget,
33
+ runtimeState: i.runtimeState, runtimeError: i.runtimeError }));
34
+ }
35
+
36
+ /** The collector's answers, one per row. `stdout` is what the collector printed, or `null` when it
37
+ * failed, timed out or could not start. Anything that is not JSON for an array of exactly
38
+ * `rows.length` answers gives every row the unknown answer; no rows give `[]`, whatever was printed. */
39
+ export function livenessAnswers(rows, stdout) {
40
+ if (!rows.length) return [];
41
+ const unknown = () => rows.map(() => ({ running: null, runtimeState: "unreachable", runtimeError: "Terminal status is unavailable" }));
42
+ if (typeof stdout !== "string") return unknown();
43
+ try {
44
+ const parsed = JSON.parse(stdout);
45
+ return Array.isArray(parsed) && parsed.length === rows.length ? parsed : unknown();
46
+ } catch { return unknown(); }
47
+ }
48
+
49
+ /** A row as the panel serves it: the per-instance contract a client's grouping and overview read.
50
+ * A dropped or misspelt field here is a field no view receives. */
51
+ export function panelInstance(i) {
52
+ return {
53
+ instance: i.instance, agent: i.agent, description: i.description,
54
+ // The reported harness only (harness-names.mjs reads a released kernel's runtime); never a guessed default.
55
+ repo: i.repo, work: i.work, branch: i.branch || null, harness: i.harness || null,
56
+ model: i.model || null, running: i.running, createdAt: i.createdAt,
57
+ home: i.home, agentsRoot: i.agentsRoot,
58
+ workspace: dirname(i.agentsRoot), repoName: (i.repo || dirname(i.agentsRoot)).split("/").pop(),
59
+ parentInstance: i.parentInstance || null,
60
+ // Agent relations (kernel contract, final): siblingInstance links a
61
+ // declared sibling to a ROOT anchor; relation/relativeTo record what
62
+ // was declared at spawn. Forwarded for cluster grouping and the
63
+ // cluster-first overview.
64
+ siblingInstance: i.siblingInstance || null,
65
+ relation: i.relation || null,
66
+ relativeTo: i.relativeTo || null,
67
+ ...(i.sessionTarget ? { sessionTarget: i.sessionTarget } : {}),
68
+ runtimeState: i.runtimeState, runtimeError: i.runtimeError,
69
+ tmux: i.tmux, git: null,
70
+ // Workspace-model v2 facts exactly as `oats status --json` reported them:
71
+ // module drift rows (or the recorded map when the workspace is
72
+ // unreachable), the soul source and the served identity. Identity is
73
+ // present only when a provider reported one — never synthesized.
74
+ ...(i.modules !== undefined ? { modules: i.modules } : {}),
75
+ ...(i.soul !== undefined ? { soul: i.soul } : {}),
76
+ ...(i.identity !== undefined ? { identity: i.identity } : {}),
77
+ // desktop-facts: the last session start, where the model came from, the messaging identity's address.
78
+ ...(i.startedAt !== undefined ? { startedAt: i.startedAt } : {}),
79
+ ...(i.modelFrom !== undefined ? { modelFrom: i.modelFrom } : {}),
80
+ ...(i.identityAddress !== undefined ? { identityAddress: i.identityAddress } : {}),
81
+ ...(i.retirePending ? { retirePending: true } : {}),
82
+ ...(i.rollbackIncomplete ? { rollbackIncomplete: true } : {}),
83
+ // #802: a spawn setting up its worktree (deployment-data.mjs keeps it as true only).
84
+ ...(i.spawnInProgress === true ? { spawnInProgress: true } : {}),
85
+ ...(i.captured ? { captured: true } : {}),
86
+ // Needs input (PR K): the validated claim (or null, unknown) as status reported it; absent stays absent.
87
+ // The client's liveness is merged before projection, so running/runtimeState beside it are the probe's.
88
+ ...(i.waitingOnYou !== undefined ? { waitingOnYou: i.waitingOnYou } : {}),
89
+ team: i.team || null,
90
+ };
91
+ }
92
+
93
+ /** The panel's rows: each row merged with its liveness answer and projected, running first, then by name. */
94
+ export function panelInstances(rows, answers) {
95
+ return rows.map((row, index) => panelInstance({ ...row, ...answers[index] }))
96
+ .sort((a, b) => (a.running === b.running ? String(a.instance).localeCompare(b.instance) : a.running ? -1 : 1));
97
+ }
98
+
99
+ /** A deployment's entry before the first CLI probe has settled, when there is no verdict to report:
100
+ * the entry already held, or a pending one. */
101
+ export function pendingEntry(previous, at) {
102
+ return previous || { deployment: { status: "pending" }, instances: [], generatedAt: at };
103
+ }
104
+
105
+ /** A deployment's entry after a read that failed with `reason` (deployment-contract.mjs).
106
+ * A transient busy or stale read keeps the entry held, as it is. A remote the kernel could not read
107
+ * (a cache problem, the network, a timeout) does not erase what was observed: the last observation
108
+ * stays, marked with the failure, the kernel's message and its bounded cause (Spec D); an `error` and
109
+ * an `errorCause` it already carried are replaced, the cause removed when this reason has none.
110
+ * Every other failure, and each of those without an entry to keep, is shown as unavailable with the
111
+ * reason, never as an empty roster. */
112
+ export function failedEntry(previous, reason, at) {
113
+ if (previous && ["E_DEPLOYMENT_BUSY", "E_DEPLOYMENT_STALE"].includes(reason?.code)) return previous;
114
+ if (previous?.deployment?.status === "observed" && reason?.code === "E_REMOTE_UNREADABLE") {
115
+ const { error: _error, errorCause: _cause, ...kept } = previous;
116
+ const cause = reason.cause;
117
+ return { ...kept, error: reason.message, ...(cause ? { errorCause: { code: reason.code, ...cause } } : {}) };
118
+ }
119
+ return { deployment: { status: "unavailable", reason }, instances: [], generatedAt: at };
120
+ }
121
+
122
+ /** An observed deployment's entry: the observer's answer (deployment-observer.mjs: `roster`,
123
+ * `workspaceStatus`, `observedAt`) and the panel's rows (`panelInstances`). `souls` are the roster's
124
+ * souls without their instances. A client adds its own facts to `deployment` after the call. */
125
+ export function observedEntry({ roster, workspaceStatus, observedAt }, instances, at) {
126
+ return {
127
+ deployment: { status: "observed", root: roster.root, workspace: workspaceStatus.workspace, workspaceStatus,
128
+ reachable: roster.workspace ?? null, withheld: roster.withheld,
129
+ souls: roster.agents.map(({ instances: _instances, ...soul }) => soul) },
130
+ instances, generatedAt: at, observedAt,
131
+ };
132
+ }
133
+
134
+ /** The deployment facts a view may show: the header observation, reachability and any unavailable
135
+ * reason. Pending when there is none; as it is when not observed; without the private soul rows
136
+ * (`souls`) and the catalog's key when observed. */
137
+ export function publicDeployment(deployment) {
138
+ if (!deployment) return { status: "pending" };
139
+ if (deployment.status !== "observed") return deployment;
140
+ const { souls: _souls, catalogKey: _catalogKey, ...rest } = deployment;
141
+ return rest;
142
+ }
@@ -0,0 +1,53 @@
1
+ /** Bounded fixed-argv native deployment reads. Private producer documents are
2
+ * projected by the owning observer, never forwarded wholesale to a renderer. */
3
+ import { execFile } from 'node:child_process';
4
+ import { isAbsolute, resolve } from 'node:path';
5
+ import { deploymentReadGate, deploymentFailure, deploymentRecord, validMaxAge, maxAgeArgv, remoteFailureCause } from './deployment-contract.mjs';
6
+ import { withoutInstanceVariables } from './kernel-environment.mjs';
7
+
8
+ export const DEPLOYMENT_READ_TIMEOUT = 30_000;
9
+ export const DEPLOYMENT_READ_MAX_BUFFER = 4 * 1024 * 1024;
10
+ const absolute = path => typeof path === 'string' && !path.includes('\0') && isAbsolute(path) && resolve(path) === path;
11
+
12
+ /** `status` is a raw object; `workspace status` is a schemaVersion:1 envelope.
13
+ * Those are distinct native command contracts, not interchangeable generations.
14
+ * `io.exec` is a client's own `execFile` (the rule is at cli-adapter.mjs `runJson`); `io.env` its environment. */
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'];
24
+ const env = withoutInstanceVariables(io.env ?? process.env);
25
+ return new Promise(done => {
26
+ const fail = code => done(deploymentFailure(code));
27
+ try {
28
+ (io.exec ?? execFile)(bin, argv, { cwd: context, env, shell: false, encoding: 'utf8', timeout: DEPLOYMENT_READ_TIMEOUT, maxBuffer: DEPLOYMENT_READ_MAX_BUFFER }, (error, stdout) => {
29
+ if (error?.code === 'ERR_CHILD_PROCESS_STDIO_MAXBUFFER') return fail('E_CLI_OUTPUT_LIMIT');
30
+ if (error?.killed) return fail('E_CLI_TIMEOUT');
31
+ if (typeof stdout !== 'string') return fail(error ? 'E_CLI_FAILED' : 'E_CLI_PROTOCOL');
32
+ if (Buffer.byteLength(stdout, 'utf8') > DEPLOYMENT_READ_MAX_BUFFER) return fail('E_CLI_OUTPUT_LIMIT');
33
+ let document;
34
+ 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) || typeof reason.code !== 'string' || !/^[A-Z][A-Z0-9_]{0,63}$/.test(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
+ const cause = reason.code === 'E_REMOTE_UNREADABLE' ? remoteFailureCause(reason.details) : null;
43
+ return done({ ok: false, reason: { code: reason.code, message: reason.message, ...(cause ? { cause } : {}) } });
44
+ }
45
+ if (error) return fail('E_CLI_FAILED');
46
+ if (action === 'status') {
47
+ if (Object.hasOwn(document, 'schemaVersion') || !absolute(document.root) || !Array.isArray(document.agents)) return fail('E_CLI_PROTOCOL');
48
+ } else if (document.schemaVersion !== 1 || document.ok !== true || document.result?.workspaceStatusApi !== 1) return fail('E_CLI_PROTOCOL');
49
+ done({ ok: true, document });
50
+ });
51
+ } catch { fail('E_CLI_FAILED'); }
52
+ });
53
+ }
@@ -0,0 +1,44 @@
1
+ /** The one display filter for free text the kernel or a host supplies and Desktop shows: a detail, or a
2
+ * label inside one of Desktop's sentences. The result is lossy and for display only: it is never evidence
3
+ * of identity and never authority for an action, and it is not fit for a name that identifies something.
4
+ * Pure: no DOM, no IO, never throws. A contract module: the server imports it too, so it imports nothing. */
5
+
6
+ /** Not text a one-line note may hold, an exact set (the maintainer's decision for the kernel's
7
+ * validWaitingMessage): control characters (Cc: C0, DEL, C1), the line and paragraph separators, the bidi
8
+ * embeddings and overrides (U+202A–202E) and isolates (U+2066–2069), the zero-width space, the word
9
+ * joiner, the BOM and the tag characters (U+E0000–E007F). Every other format character is text: ZWJ
10
+ * (emoji sequences), ZWNJ (Persian, Urdu), LRM, RLM and ALM (Hebrew, Arabic), the soft hyphen. */
11
+ export const NOT_NOTE_TEXT = /[\p{Cc}\u2028\u2029\u202A-\u202E\u2066-\u2069\u200B\u2060\uFEFF\u{E0000}-\u{E007F}]/u;
12
+ const EVERY_NOT_NOTE_TEXT = new RegExp(NOT_NOTE_TEXT.source, 'gu');
13
+
14
+ /** Text withheld whole: secrets, credentialed URLs, C0 controls other than tab and line feed, DEL. */
15
+ export const UNSAFE = /[\x00-\x08\x0b-\x1f\x7f]|[a-z][a-z0-9+.-]*:\/\/[^\s/]*@|(?:token|authorization|password|secret|api[_ -]?key)\s*[:=]\s*\S+|(?:gh[pousr]_|github_pat_)[A-Za-z0-9_]{16,}/i;
16
+ export const DETAIL_WITHHELD = '[Detail withheld]';
17
+ export const MAX_DISPLAY_LINE = 2048;
18
+
19
+ /** One line: tab, line feed and the line and paragraph separators each become a space, runs of spaces
20
+ * collapse (also a run the text already had: acceptable for free text, not for an identifier) and the
21
+ * ends are trimmed. Every character of NOT_NOTE_TEXT still present becomes U+FFFD:
22
+ * replaced, never dropped, so the reader sees something was withheld. Two different texts can become the
23
+ * same line: the result is for display only, never for comparing, selecting or addressing anything.
24
+ * Bounded to MAX_DISPLAY_LINE UTF-16 units, without splitting a surrogate pair or ending on a space. */
25
+ function oneLine(text) {
26
+ const line = text.replace(/[\t\n\u2028\u2029]/g, ' ').replace(/ {2,}/g, ' ').replace(/^ | $/g, '').replace(EVERY_NOT_NOTE_TEXT, '\uFFFD');
27
+ if (line.length <= MAX_DISPLAY_LINE) return line;
28
+ const last = line.charCodeAt(MAX_DISPLAY_LINE - 1);
29
+ return line.slice(0, last >= 0xD800 && last <= 0xDBFF ? MAX_DISPLAY_LINE - 1 : MAX_DISPLAY_LINE).replace(/ $/, '');
30
+ }
31
+
32
+ /** Kernel or host text as one display line, DETAIL_WITHHELD when it is UNSAFE, or null when there is
33
+ * nothing to show (not a string, empty, or only line breaks and spaces). UNSAFE is tested on the text as
34
+ * given, before any folding, replacement or truncation: what is withheld is withheld whole. The line is
35
+ * what is shown, so it is held to UNSAFE as well; filtering twice therefore equals filtering once. */
36
+ export function displayLine(text) {
37
+ if (typeof text !== 'string' || !text) return null;
38
+ if (UNSAFE.test(text)) return DETAIL_WITHHELD;
39
+ const line = oneLine(text);
40
+ return !line ? null : UNSAFE.test(line) ? DETAIL_WITHHELD : line;
41
+ }
42
+
43
+ /** Already a display line: what a relayed text must be before it is shown again. */
44
+ export const cleanLine = v => typeof v === 'string' && displayLine(v) === v;
@@ -0,0 +1,30 @@
1
+ /** The harness rename (kernel 0.27.0, feature `harness`; docs/desktop-cli-api.md
2
+ * "The harness rename"). The Desktop speaks `harness`. A released kernel without
3
+ * the feature still speaks `runtime`: its payloads are READ in either spelling
4
+ * (a payload carries one; the new name wins), and what the Desktop WRITES to a
5
+ * kernel (flags, definition keys) follows the feature. Drop the old spellings
6
+ * when the accepted range no longer includes a kernel without `harness`. */
7
+ export const HARNESSES = Object.freeze(['pi', 'claude', 'codex']);
8
+ /** Each harness as people read it. */
9
+ export const HARNESS_NAMES = Object.freeze({ pi: 'Pi', claude: 'Claude Code', codex: 'Codex' });
10
+
11
+ export const harnessFeature = cli => Array.isArray(cli?.features) && cli.features.includes('harness');
12
+ /** The spawn/session/launch-config flag for this kernel. */
13
+ export const harnessFlag = cli => harnessFeature(cli) ? '--harness' : '--runtime';
14
+ /** The key a definition written to this kernel uses (launch-config set, schedule spec). */
15
+ export const harnessKey = cli => harnessFeature(cli) ? 'harness' : 'runtime';
16
+
17
+ /** A kernel row's harness: `harness`, else a released kernel's `runtime`. */
18
+ export function harnessOf(row) {
19
+ if (!row || typeof row !== 'object') return undefined;
20
+ if (Object.hasOwn(row, 'harness')) return row.harness;
21
+ if (Object.hasOwn(row, 'runtime')) return row.runtime;
22
+ return undefined;
23
+ }
24
+
25
+ /** The probe's harness list: `harnesses` with the feature, a released kernel's `runtimes` without. */
26
+ export function harnessList(probe) {
27
+ const value = harnessFeature(probe) ? probe?.harnesses : probe?.runtimes;
28
+ return Array.isArray(value) ? value : null;
29
+ }
30
+
@@ -0,0 +1,62 @@
1
+ /** `oats inspect --json` on the workspace model (`operationsApi: 2`; each soul
2
+ * row `soulsApi: 2`). The subject is an instance (`--home`) or a soul
3
+ * (`--soul`), never a scope. Everything shown is the kernel's record: a
4
+ * capability's origin is its module's `from`, its settings the merged payload.
5
+ * Presentation-only; no classic field (scope chain, activation, trust,
6
+ * snapshot drift, sources provenance) is read. */
7
+ import { harnessOf } from './harness-names.mjs';
8
+ import { launchOf, REPORT_FROM, RECORD_FROM } from './launch-contract.mjs';
9
+ import { memberLabel } from './deployment-facts.mjs';
10
+
11
+ export const OPERATIONS_API = 2;
12
+ export const SOULS_API = 2;
13
+ const record = v => !!v && typeof v === 'object' && !Array.isArray(v);
14
+ const str = v => typeof v === 'string';
15
+ const short = v => str(v) && /^[0-9a-f]{7,64}$/.test(v) ? v.slice(0, 7) : null;
16
+
17
+ /** The probe integer is the gate (no feature string). */
18
+ export const inspectSupported = cli => cli?.ok === true && cli.operationsApi === OPERATIONS_API;
19
+
20
+ /** The inspection for this selection, or null when it is not the operationsApi 2
21
+ * document for exactly this subject. */
22
+ export function inspectData(v, selection) {
23
+ if (!record(v) || v.operationsApi !== OPERATIONS_API || !record(v.subject) || !Array.isArray(v.souls) || v.souls.length > 1
24
+ || !Array.isArray(v.capabilities) || !record(v.layers) || !Array.isArray(v.problems)) return null;
25
+ const s = v.subject;
26
+ if (selection?.instance) {
27
+ if (s.kind !== 'instance' || s.home !== selection.selector?.home || !record(v.instance)) return null;
28
+ } else if (selection?.agent) {
29
+ if (s.kind !== 'soul' || s.soul !== selection.agent.name || v.instance !== null) return null;
30
+ } else return null;
31
+ if (v.souls.some(row => !record(row) || row.soulsApi !== SOULS_API)) return null;
32
+ if (v.capabilities.some(cap => !record(cap) || !str(cap.id) || !Array.isArray(cap.operations ?? []))) return null;
33
+ // Launch preferences (0.30, feature launch-preference): a soul's is what a spawn with no flags would
34
+ // decide; a home's is its record (a pre-0.30 home reads `recorded`), with `launchCurrent` (what
35
+ // --reselect-launch would choose now, or null).
36
+ const home = s.kind === 'instance', ok = (x, from) => launchOf(x, from) !== undefined;
37
+ if (Object.hasOwn(v, 'launch') && !ok(v.launch, home ? RECORD_FROM : REPORT_FROM)) return null;
38
+ if (Object.hasOwn(v, 'launchCurrent') && !(home && (v.launchCurrent === null || ok(v.launchCurrent, REPORT_FROM)))) return null;
39
+ if (v.souls.some(row => Object.hasOwn(row, 'launch') && !ok(row.launch, REPORT_FROM))) return null;
40
+ return v;
41
+ }
42
+
43
+ const text = (v, fallback = '—') => v === undefined || v === null || v === '' ? fallback : String(v);
44
+ /** A module's `from`: member commit, or package version + commit. */
45
+ export function originText(from) {
46
+ if (!record(from)) return 'Not reported';
47
+ if (from.kind === 'package') return `package ${text(from.package, '?')} ${text(from.version, '')}`.trimEnd() + (short(from.commit) ? ` @ ${short(from.commit)}` : '');
48
+ if (from.kind === 'member') return `member ${memberLabel(from.repoKey)}${short(from.commit) ? ` @ ${short(from.commit)}` : ''}`;
49
+ return text(from.kind);
50
+ }
51
+ export const inspectFacts = {
52
+ instance: i => [
53
+ ['Harness', text(harnessOf(i))], ['Model', text(i.model, 'Harness default')],
54
+ ['Permissions', i.yolo === true ? 'Unrestricted (yolo)' : i.yolo === false ? 'Restricted' : 'Harness default'],
55
+ ['Launched', i.launched === true ? 'Yes' : i.launched === false ? 'No' : '—'], ['Created', text(i.createdAt)],
56
+ ['Resolution', str(i.resolution) ? i.resolution.slice(0, 12) : '—'],
57
+ ],
58
+ capability: cap => [
59
+ ['Version', text(cap.version)], ['Layer', text(cap.layer, 'None')], ['Origin', originText(cap.from)],
60
+ ['Missing requirements', Array.isArray(cap.missingRequires) && cap.missingRequires.length ? cap.missingRequires.join(', ') : 'None'],
61
+ ],
62
+ };
@@ -0,0 +1,54 @@
1
+ /** Which acts a roster row offers, decided from the kernel's row alone. A client draws its menu, its
2
+ * keys or its buttons from this answer: verbs and reasons, never a label, an icon or a key.
3
+ *
4
+ * instanceActs(instance) -> { blocked: Reason | null, limited: Reason | null, acts: Act[] }
5
+ * Act = { verb, enabled, reason: Reason | null }
6
+ * Reason = { code, sentence } and, by code:
7
+ * { code: 'unaddressable', key, sentence } key: the row reason's own (remote-address.mjs rowReason)
8
+ * { code: 'held', kind, sentence } kind: 'spawning' | 'spawn-incomplete' | 'retire-incomplete'
9
+ * { code: 'unsupported-session', sentence }
10
+ *
11
+ * A client may switch on `code`, and on `key` or `kind` when it needs to; never on the sentence.
12
+ * The sentences are the ones the shared tables already produce. Two of them can be kernel text (an
13
+ * unaddressable row's `runtimeError`, the kernel's reason for a removed session backend): a client
14
+ * shows a sentence only through display-text.mjs `displayLine`.
15
+ *
16
+ * `blocked`: the row offers nothing, and this is why; `acts` is then empty.
17
+ * `limited`: the row offers fewer acts than a home normally does, and this is why. It is about the
18
+ * row, not about one act: **a client adds none of its own acts to a limited row.**
19
+ * `blocked` and `limited` are never both set. An act's own `reason` says why that one act is listed
20
+ * and not enabled; the others stay as they are.
21
+ *
22
+ * In order, the first that applies:
23
+ * a remote row the kernel does not report addressable blocked (unaddressable); no acts
24
+ * a home the kernel holds, spawning blocked (held); no acts
25
+ * a home the kernel holds, spawn or retire incomplete limited (held); retire
26
+ * a session backend OATS no longer has inspect, start (not enabled, unsupported-session), stop, retire
27
+ * running === true inspect, restart, stop, retire
28
+ * running === false inspect, start, stop, retire
29
+ * running unknown inspect, stop, retire
30
+ */
31
+ import { heldHome } from './instance-tree.mjs';
32
+ import { unsupportedSession } from './instance-presentation.mjs';
33
+ import { canAddressRemote, rowReason } from './remote-address.mjs';
34
+
35
+ const act = (verb, reason = null) => ({ verb, enabled: !reason, reason });
36
+
37
+ export function instanceActs(instance) {
38
+ if (!canAddressRemote(instance)) {
39
+ const { key, sentence } = rowReason(instance);
40
+ return { blocked: { code: 'unaddressable', key, sentence }, limited: null, acts: [] };
41
+ }
42
+ // #802: a home the kernel holds starts, stops and opens nothing. Retire only when a spawn or a retire left it
43
+ // half cleaned (the kernel's retire completes it), nothing while its spawn sets up the worktree.
44
+ const held = heldHome(instance);
45
+ if (held) {
46
+ const reason = { code: 'held', kind: held.kind, sentence: held.sentence(instance.instance) };
47
+ return held.retire ? { blocked: null, limited: reason, acts: [act('retire')] } : { blocked: reason, limited: null, acts: [] };
48
+ }
49
+ // A Herdr-recorded row cannot start or restart: Start stays listed, not enabled, with the kernel's reason.
50
+ const unsupported = unsupportedSession(instance);
51
+ const launch = unsupported ? [act('start', { code: 'unsupported-session', sentence: unsupported })]
52
+ : instance.running === true ? [act('restart')] : instance.running === false ? [act('start')] : [];
53
+ return { blocked: null, limited: null, acts: [act('inspect'), ...launch, act('stop'), act('retire')] };
54
+ }
@@ -0,0 +1,45 @@
1
+ /** Shared qualified roster authority. No filesystem, kernel import or process.
2
+ * Individual operations negotiate their own CLI feature/API after admission. */
3
+ import { isAbsolute, basename } from 'node:path';
4
+ import { gitTarget } from './instance-git-contract.mjs';
5
+ import { canAddressRemote, unaddressableSentence, unroutableReason } from './remote-address.mjs';
6
+ export { canAddressRemote };
7
+ export const record = v => !!v && typeof v === 'object' && !Array.isArray(v);
8
+ export const absolute = v => typeof v === 'string' && isAbsolute(v) && !v.includes('\0');
9
+ const name = v => typeof v === 'string' && /^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(v);
10
+ const host = v => v === null || v === undefined || typeof v === 'string' && /^[a-z0-9][a-z0-9-]{0,63}$/.test(v);
11
+ export function instanceSelector(v) {
12
+ return record(v) && Object.keys(v).every(k => ['instance', 'agent', 'agentsRoot', 'server'].includes(k))
13
+ && name(v.instance) && name(v.agent) && absolute(v.agentsRoot) && host(v.server);
14
+ }
15
+ /** Admit one roster row. A remote row is admitted only in its own remote workspace, when the kernel
16
+ * reports it addressable and this machine's probe routes `operation` (a `remote` entry). The
17
+ * admitted `context` is then this machine's cwd (`localCwd`), never a `--dir`: the kernel sends the
18
+ * registered workspace. A remote denial carries a `reason` naming the server. */
19
+ export function admitInstance(selector, { workspace, instances = [], cli, operation, localCwd } = {}) {
20
+ const denied = (code, target = null, reason = undefined) => ({ code, target, ...(reason ? { reason } : {}) });
21
+ if (!instanceSelector(selector)) return denied('E_BAD_ARGS');
22
+ if (!workspace || typeof workspace.id !== 'string' || !workspace.id || !absolute(workspace.scope)) return denied('E_WORKSPACE_UNKNOWN');
23
+ const matches = (Array.isArray(instances) ? instances : []).filter(i => record(i) && host(i.server)
24
+ && i.instance === selector.instance && i.agent === selector.agent && i.agentsRoot === selector.agentsRoot && (i.server ?? null) === (selector.server ?? null));
25
+ if (matches.length !== 1) return denied(matches.length ? 'E_AMBIGUOUS_INSTANCE' : 'E_SESSION_UNKNOWN');
26
+ const instance = matches[0];
27
+ if (!absolute(instance.home) || basename(instance.home) !== instance.instance) return denied('E_HOME_MISMATCH');
28
+ const target = gitTarget({ workspace: workspace.id, instance: instance.instance, agent: instance.agent,
29
+ agentsRoot: instance.agentsRoot, home: instance.home, server: instance.server ?? null });
30
+ if (!target) return denied('E_HOME_MISMATCH');
31
+ const remote = !!(workspace.remote || workspace.server || instance.remote || target.server);
32
+ if (remote) {
33
+ // Never resolve a remote target against a local panel, or the reverse.
34
+ if (!workspace.remote || !host(workspace.server) || !workspace.server || target.server !== workspace.server) return denied('E_SESSION_UNKNOWN', target);
35
+ const label = workspace.name || workspace.server;
36
+ if (!canAddressRemote(instance)) return denied('E_SNAPSHOT_UNKNOWN', target,
37
+ { code: 'E_SNAPSHOT_UNKNOWN', message: unaddressableSentence({ ...instance, repoName: label }), detail: null, remote: true });
38
+ if (typeof operation !== 'string' || !Array.isArray(cli?.remote) || !cli.remote.includes(operation)) return denied('unsupported-remote-operation', target, unroutableReason(label));
39
+ if (cli?.ok !== true || !absolute(cli.bin)) return denied('cli-unavailable', target);
40
+ if (!absolute(localCwd)) return denied('E_WORKSPACE_UNKNOWN', target);
41
+ return { target, context: localCwd, bin: cli.bin, remote: { server: workspace.server, label } };
42
+ }
43
+ if (cli?.ok !== true || !absolute(cli.bin)) return denied('cli-unavailable', target);
44
+ return { target, context: workspace.scope, bin: cli.bin };
45
+ }
@@ -0,0 +1,74 @@
1
+ /** K7 API2 consumer input contract. Pure data validation; no log/kernel IO. */
2
+ import { absolute, record } from './readiness-contract.mjs';
3
+ import { remoteReason } from './remote-address.mjs';
4
+ const exact = (v, keys) => record(v) && Object.keys(v).every(k => keys.includes(k));
5
+ const name = v => typeof v === 'string' && /^[A-Za-z0-9][A-Za-z0-9._-]{0,255}$/.test(v);
6
+ const text = (v, max = 4096) => typeof v === 'string' && !!v && v.length <= max && !/[\x00-\x1f\x7f]/.test(v);
7
+ export const EVENTS_LIMITS = Object.freeze([50, 100, 200]);
8
+ export const EVENTS_DEFAULT_LIMIT = 100;
9
+ export const eventsTimestamp = v => typeof v === 'string' && /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(v)
10
+ && Number.isFinite(Date.parse(v)) && new Date(v).toISOString() === v;
11
+ /** Text the activity view and the roster may show: no control characters, no URL, no token-looking
12
+ * assignment. Shared by packages/desktop/renderer/instance-events-data.mjs and waiting-on-you.mjs. */
13
+ export const eventsUnsafe = /[\x00-\x08\x0b-\x1f\x7f]|[a-z][a-z0-9+.-]*:\/\/\S+|(?:gh[pousr]_|github_pat_)[A-Za-z0-9_]{16,}|(?:token|authorization|password|secret|api[_ -]?key)\s*[:=]\s*\S+/i;
14
+ /** A producer or kind id: non-empty, ≤ 256, no control characters, nothing unsafe. */
15
+ export const eventsId = v => typeof v === 'string' && !!v && v.length <= 256 && !/[\x00-\x1f\x7f]/.test(v) && !eventsUnsafe.test(v);
16
+ /** What stands in for text eventsUnsafe refuses. The one literal: eventsDetail and waitingMessage return it,
17
+ * and the sidebar's claim (waitingOnYouData) reads it as "no note". */
18
+ export const EVENTS_WITHHELD = '[Detail withheld]';
19
+ /** A free-text detail: a string ≤ max (throws otherwise); unsafe text is withheld, never shown. */
20
+ export function eventsDetail(v, max = 2048) {
21
+ if (typeof v !== 'string' || v.length > max) throw Error('invalid event detail');
22
+ return eventsUnsafe.test(v) ? EVENTS_WITHHELD : v;
23
+ }
24
+ export const eventsLimit = v => EVENTS_LIMITS.includes(v) ? v : null;
25
+ export const eventsSupported = cli => cli?.ok === true && absolute(cli.bin) && cli.eventsApi === 2
26
+ && Array.isArray(cli.features) && cli.features.includes('instance-events-2');
27
+ /** Renderer supplies a qualified selector (a server id for a remote row), never a home or log path. */
28
+ export function eventsSelector(v) {
29
+ return exact(v, ['instance', 'agent', 'agentsRoot', 'server']) && name(v.instance) && name(v.agent)
30
+ && absolute(v.agentsRoot) && (v.server === null || typeof v.server === 'string' && /^[a-z0-9][a-z0-9-]{0,63}$/.test(v.server))
31
+ ? { instance: v.instance, agent: v.agent, agentsRoot: v.agentsRoot, server: v.server } : null;
32
+ }
33
+ export function eventsRequest(v) {
34
+ if (!exact(v, ['action', 'selector', 'limit']) || v.action !== 'read') return null;
35
+ const selector = eventsSelector(v.selector);
36
+ const limit = Object.hasOwn(v, 'limit') ? eventsLimit(v.limit) : EVENTS_DEFAULT_LIMIT;
37
+ return selector && limit !== null ? { action: 'read', selector, limit } : null;
38
+ }
39
+ /** Only server admission supplies these paths. Syntactic validation is NOT
40
+ * roster/scope admission, incarnation proof, or authority to open a file. */
41
+ export function eventsTarget(v) {
42
+ const selector = eventsSelector(v?.selector);
43
+ return record(v) && selector && text(v.workspace) && absolute(v.context) && absolute(v.home)
44
+ && v.home.split('/').at(-1) === selector.instance && (v.incarnation == null || eventsTimestamp(v.incarnation))
45
+ ? { workspace: v.workspace, context: v.context, selector, home: v.home, incarnation: v.incarnation ?? null } : null;
46
+ }
47
+ const errors = {
48
+ E_BAD_ARGS: 'Activity requires one qualified local instance and an approved row limit.',
49
+ E_EVENTS_UNAVAILABLE: 'Activity requires advertised instance-events-2 and integer eventsApi 2. API 1 is not invoked.',
50
+ E_WORKSPACE_UNKNOWN: 'Choose an advertised local workspace.',
51
+ E_SESSION_UNKNOWN: 'The selected instance is no longer in the current roster.',
52
+ E_AMBIGUOUS_INSTANCE: 'Choose one exact instance home.',
53
+ E_HOME_MISMATCH: 'The instance home no longer matches the selected address.',
54
+ E_NOT_IN_SCOPE: 'The selected instance is outside this workspace scope.',
55
+ E_TARGET_CHANGED: 'The workspace, instance or CLI changed. Load activity again.',
56
+ 'cli-unavailable': 'Choose a compatible installed OATS CLI.',
57
+ 'unsupported-remote-operation': "This computer's OATS can't route this to the server. Update OATS here.",
58
+ E_UNSUPPORTED_MODE: 'Activity is unavailable for this execution mode; no classic fallback.',
59
+ 'unsupported-action': 'This CLI cannot read activity for the selected execution mode.',
60
+ E_BUSY: 'Two activity reads are already in progress. Retry when one finishes.',
61
+ E_FORBIDDEN_FRAME: 'This frame cannot request activity.',
62
+ E_CLI_TIMEOUT: 'The activity read timed out.',
63
+ E_CLI_OUTPUT_LIMIT: 'The activity response exceeded its output limit.',
64
+ E_CLI_PROTOCOL: 'The CLI returned invalid or mismatched activity data.',
65
+ E_CLI_FAILED: 'The installed CLI could not complete the activity read.',
66
+ };
67
+ /** `reason`: a remote read's reason (remote-address.mjs), kept only when it validates. */
68
+ export function eventsFailure(code, target = null, reason = null) {
69
+ if (!Object.hasOwn(errors, code)) code = 'E_CLI_FAILED';
70
+ return { instanceEventsViewApi: 1, status: 'unavailable', target: eventsTarget(target), data: null,
71
+ reason: remoteReason(reason) || { code, message: errors[code] } };
72
+ }
73
+ /** The fixed sentence for an activity code: the headline of a host refusal outside the remote table. */
74
+ export const eventsMessage = code => eventsFailure(code).reason.message;