@awebai/oats 0.51.0 → 0.53.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (166) hide show
  1. package/README.md +3 -1
  2. package/bin/oats.mjs +407 -123
  3. package/docs/capabilities.md +75 -6
  4. package/docs/configuration.md +200 -91
  5. package/docs/desktop-cli-api.md +1563 -113
  6. package/docs/desktop-instance-start.md +69 -0
  7. package/docs/desktop.md +10 -7
  8. package/docs/execution-targets.md +145 -58
  9. package/docs/first-team.md +3 -1
  10. package/docs/harness-trust.md +50 -2
  11. package/docs/implementation.md +238 -17
  12. package/docs/integrations.md +13 -9
  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 +25 -2
  18. package/docs/launch-prompt-completion.md +50 -48
  19. package/docs/macos-test-runs.md +246 -0
  20. package/docs/oats-local.schema.json +4 -3
  21. package/docs/official-catalog.md +5 -5
  22. package/docs/packages.md +14 -14
  23. package/docs/release-lane.md +225 -11
  24. package/docs/release-notes/v0.44.0.md +1 -1
  25. package/docs/release-notes/v0.52.0.md +933 -0
  26. package/docs/release-notes/v0.53.0.md +1274 -0
  27. package/docs/schedules.md +97 -4
  28. package/docs/souls-and-instances.md +332 -40
  29. package/docs/tui.md +584 -0
  30. package/docs/upgrading.md +298 -0
  31. package/docs/workspaces.md +3 -3
  32. package/lib/automations.mjs +22 -22
  33. package/lib/claim.mjs +278 -49
  34. package/lib/config-data.mjs +4 -1
  35. package/lib/core.mjs +1282 -289
  36. package/lib/errors.mjs +170 -0
  37. package/lib/harness-trust-write.mjs +68 -27
  38. package/lib/harness-trust.mjs +34 -16
  39. package/lib/instance-events.mjs +19 -1
  40. package/lib/instance-git.mjs +39 -3
  41. package/lib/instance-inspect.mjs +45 -17
  42. package/lib/instance-lifecycle.mjs +306 -57
  43. package/lib/instance-resolution.mjs +59 -6
  44. package/lib/launch-preference.mjs +236 -9
  45. package/lib/launch-prompt-completion.mjs +7 -43
  46. package/lib/launch-prompt-evidence.mjs +14 -7
  47. package/lib/launch-prompt-fixtures/README.md +86 -152
  48. package/lib/launch-prompt-fixtures/dev-channel-confirmation.json +50 -0
  49. package/lib/launch-prompt-fixtures.mjs +122 -109
  50. package/lib/launch-prompt-transport.mjs +2 -56
  51. package/lib/launch-prompts.mjs +102 -100
  52. package/lib/local-edit.mjs +118 -0
  53. package/lib/packages.mjs +13 -4
  54. package/lib/pi-bridge.mjs +308 -0
  55. package/lib/refused-text.mjs +11 -0
  56. package/lib/remote.mjs +190 -25
  57. package/lib/resolve.mjs +2 -1
  58. package/lib/retained-after-retire.mjs +2 -2
  59. package/lib/retire-output.mjs +12 -1
  60. package/lib/schedule-host.mjs +125 -22
  61. package/lib/schedule.mjs +73 -24
  62. package/lib/shell-word.mjs +13 -0
  63. package/lib/soul-launch-verbs.mjs +153 -0
  64. package/lib/stable-node.mjs +62 -0
  65. package/lib/system-tools.mjs +39 -0
  66. package/lib/teams-verbs.mjs +18 -46
  67. package/lib/tmux-server-scope.mjs +62 -0
  68. package/lib/triggers.mjs +4 -4
  69. package/lib/workspace.mjs +54 -30
  70. package/lib/worktree-hooks.mjs +98 -20
  71. package/lib/worktree.mjs +83 -24
  72. package/package-catalog.json +4 -4
  73. package/package.json +8 -2
  74. package/packages/client/attach-exit.mjs +25 -0
  75. package/packages/client/capability-show-contract.mjs +230 -0
  76. package/packages/client/capability-warnings-contract.mjs +57 -0
  77. package/packages/client/cli-adapter.mjs +561 -0
  78. package/packages/client/cli-environment.mjs +53 -0
  79. package/packages/client/cli-locator.mjs +253 -0
  80. package/packages/client/cli-probe-contract.mjs +47 -0
  81. package/packages/client/client-terms.mjs +60 -0
  82. package/packages/client/deployment-contract.mjs +72 -0
  83. package/packages/client/deployment-data.mjs +483 -0
  84. package/packages/client/deployment-facts.mjs +95 -0
  85. package/packages/client/deployment-label.mjs +76 -0
  86. package/packages/client/deployment-observer.mjs +89 -0
  87. package/packages/client/deployment-panel.mjs +180 -0
  88. package/packages/client/deployment-read-cli.mjs +57 -0
  89. package/packages/client/display-text.mjs +50 -0
  90. package/packages/client/harness-names.mjs +30 -0
  91. package/packages/client/inspect-contract.mjs +62 -0
  92. package/packages/client/instance-acts.mjs +90 -0
  93. package/packages/client/instance-admission.mjs +45 -0
  94. package/packages/client/instance-events-contract.mjs +76 -0
  95. package/packages/client/instance-git-contract.mjs +80 -0
  96. package/packages/client/instance-presentation.mjs +86 -0
  97. package/packages/client/instance-tree.mjs +462 -0
  98. package/packages/client/kernel-environment.mjs +11 -0
  99. package/packages/client/kernel-lines.mjs +31 -0
  100. package/packages/client/kernel-made.mjs +23 -0
  101. package/packages/client/launch-contract.mjs +51 -0
  102. package/packages/client/launch-prompt-outcome.mjs +200 -0
  103. package/packages/client/lifecycle-cli.mjs +61 -0
  104. package/packages/client/lifecycle-contract.mjs +413 -0
  105. package/packages/client/liveness-main.mjs +10 -0
  106. package/packages/client/liveness.mjs +48 -0
  107. package/packages/client/machine-contract.mjs +123 -0
  108. package/packages/client/own-codes.mjs +31 -0
  109. package/packages/client/own-environment.mjs +22 -0
  110. package/packages/client/panel-views.mjs +293 -0
  111. package/packages/client/readiness-contract.mjs +174 -0
  112. package/packages/client/refresh-loop.mjs +52 -0
  113. package/packages/client/remote-address.mjs +151 -0
  114. package/packages/client/remote-identity-memory.mjs +94 -0
  115. package/packages/client/remote-roster.mjs +153 -0
  116. package/packages/client/roster-sections.mjs +80 -0
  117. package/packages/client/session-attach.mjs +175 -0
  118. package/packages/client/spawn-apply-cli.mjs +104 -0
  119. package/packages/client/spawn-apply-contract.mjs +195 -0
  120. package/packages/client/spawn-decision.mjs +46 -0
  121. package/packages/client/spawn-messages.mjs +142 -0
  122. package/packages/client/spawn-preview-cli.mjs +38 -0
  123. package/packages/client/spawn-preview-contract.mjs +318 -0
  124. package/packages/client/team-members.mjs +41 -0
  125. package/packages/client/team-rows.mjs +45 -0
  126. package/packages/client/terminal-contract.mjs +57 -0
  127. package/packages/client/terminal-exec.mjs +21 -0
  128. package/packages/client/tmux-status.mjs +66 -0
  129. package/packages/client/waiting-on-you.mjs +88 -0
  130. package/packages/client/workspace-admission.mjs +45 -0
  131. package/packages/client/workspace-choices.mjs +95 -0
  132. package/packages/client/workspace-cli.mjs +142 -0
  133. package/packages/client/workspace-views.mjs +183 -0
  134. package/packages/record/README.md +21 -0
  135. package/packages/record/bin/setup.mjs +108 -15
  136. package/packages/tui/README.md +64 -0
  137. package/packages/tui/bin/tui.mjs +7 -0
  138. package/packages/tui/lib/actions.mjs +44 -0
  139. package/packages/tui/lib/client.mjs +35 -0
  140. package/packages/tui/lib/config.mjs +151 -0
  141. package/packages/tui/lib/main.mjs +176 -0
  142. package/packages/tui/lib/model.mjs +392 -0
  143. package/packages/tui/lib/read.mjs +473 -0
  144. package/packages/tui/lib/store.mjs +364 -0
  145. package/packages/tui/lib/term/keys.mjs +367 -0
  146. package/packages/tui/lib/term/screen.mjs +134 -0
  147. package/packages/tui/lib/term/style.mjs +43 -0
  148. package/packages/tui/lib/term/text.mjs +109 -0
  149. package/packages/tui/lib/term/tty.mjs +178 -0
  150. package/packages/tui/lib/term/width.mjs +124 -0
  151. package/packages/tui/lib/views/detail.mjs +46 -0
  152. package/packages/tui/lib/views/frame.mjs +256 -0
  153. package/packages/tui/lib/views/help.mjs +140 -0
  154. package/packages/tui/lib/views/instances.mjs +137 -0
  155. package/packages/tui/lib/views/scroll.mjs +19 -0
  156. package/packages/tui/lib/views/switcher.mjs +97 -0
  157. package/packages/tui/package.json +8 -0
  158. package/skills/oats-getting-started/SKILL.md +30 -23
  159. package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/frame-05-channel-seeded.txt +0 -35
  160. package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/frame-06-first-after-channel.txt +0 -35
  161. package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/frame-07-after-channel-200ms.txt +0 -35
  162. package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/frame-08-installed-after-channel-200ms.txt +0 -35
  163. package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/manifest.json +0 -77
  164. package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/max-bypass-source.json +0 -88
  165. package/lib/launch-prompt-fixtures/structural-completion.json +0 -205
  166. package/lib/launch-prompt-policy.mjs +0 -87
@@ -0,0 +1,57 @@
1
+ /** Private Desktop terminal wire v2. No numeric compatibility/owner inference. */
2
+ export const TERMINAL_API = 2;
3
+ export const TERM_WRITE_BYTES = 64 * 1024;
4
+ export const TERM_CALLER_BYTES = 1024 * 1024;
5
+ export const TERM_READY_BYTES = 64 * 1024;
6
+ export const TERM_READY_MS = 5000;
7
+ export const TERM_CLOSE_MS = 2000;
8
+ export const TERM_PREPARE_MS = 30000;
9
+ export const TERM_ATTACHMENTS_MAX = 4;
10
+ export function terminalHandle(v) {
11
+ return !!v && typeof v === 'object' && !Array.isArray(v) && Number.isSafeInteger(v.id) && v.id > 0
12
+ && typeof v.lease === 'string' && /^[a-f0-9]{64}$/.test(v.lease) ? Object.freeze({ id: v.id, lease: v.lease }) : null;
13
+ }
14
+ /** The E_HERDR_REMOVED stem the kernel and the Desktop share (OATS 0.31.0). */
15
+ export const HERDR_REMOVED = 'Herdr is no longer supported by OATS (removed in 0.31.0); tmux is the only session backend.';
16
+ export const terminalGeometry = (cols, rows) => Number.isInteger(cols) && cols >= 1 && cols <= 1000 && Number.isInteger(rows) && rows >= 1 && rows <= 1000;
17
+ /** Remote failures whose message names the server; the static message says "the server". */
18
+ const serverMessages = {
19
+ E_TERM_REMOTE_UNREACHABLE: server => `Couldn't reach ${server}.`,
20
+ E_TERM_REMOTE_GONE: server => `The session is no longer running on ${server}.`,
21
+ E_TERM_REMOTE_NO_ANSWER: server => `OATS on this computer gave no answer while connecting to ${server}.`,
22
+ E_TERM_REMOTE_NO_SSH: server => `ssh isn't available on this computer, so ${server} can't be reached. Install OpenSSH on this computer.`,
23
+ };
24
+ const messages = {
25
+ E_TERM_FORBIDDEN_FRAME: 'This document cannot access terminals.',
26
+ E_TERM_LEASE: 'This terminal handle is no longer owned by this document.',
27
+ E_TERM_BAD_ARGS: 'Invalid terminal request.', E_TERM_CAP: 'Terminal limit reached. Close a terminal first.',
28
+ E_TERM_CONTEXT_CHANGED: 'The terminal owner or preparation context changed.',
29
+ E_TERM_OPEN_FAILED: 'Could not attach to the requested terminal.',
30
+ E_TERM_NOT_READY: 'The terminal has not acknowledged readiness.',
31
+ E_TERM_REUSED: 'This terminal is already open.',
32
+ E_TERM_READY_TIMEOUT: 'terminal did not become ready; closed',
33
+ E_TERM_OUTPUT_LIMIT: 'Terminal readiness output exceeded its safe limit; closed.',
34
+ E_TERM_PREPARE_TIMEOUT: 'Terminal preparation timed out.',
35
+ E_TERM_CLOSING: 'closing… not yet confirmed', E_TERM_CLOSE_PENDING: 'closing… not yet confirmed',
36
+ E_TERM_BUSY: 'This terminal operation is already in progress.',
37
+ E_TERM_ATTACHMENT_FAILED: 'Could not prepare these attachments.',
38
+ E_TERM_ATTACHMENT_INTERRUPTED: 'Attachment interrupted; some file copies may already exist. No input was inserted.',
39
+ E_TERM_INPUT_LIMIT: 'Terminal input exceeds the safe write limit. Nothing was sent.',
40
+ E_TERM_TRANSPORT: 'The terminal service did not confirm the operation.',
41
+ E_HERDR_REMOVED: HERDR_REMOVED,
42
+ E_TERM_REMOTE_UNREACHABLE: serverMessages.E_TERM_REMOTE_UNREACHABLE('the server'),
43
+ E_TERM_REMOTE_GONE: serverMessages.E_TERM_REMOTE_GONE('the server'),
44
+ E_TERM_REMOTE_NO_ANSWER: serverMessages.E_TERM_REMOTE_NO_ANSWER('the server'),
45
+ E_TERM_REMOTE_NO_SSH: serverMessages.E_TERM_REMOTE_NO_SSH('the server'),
46
+ };
47
+ export function terminalFailure(code) {
48
+ if (typeof code !== 'string' || !Object.hasOwn(messages, code)) code = 'E_TERM_OPEN_FAILED';
49
+ return { terminalApi: TERMINAL_API, ok: false, code, message: messages[code] };
50
+ }
51
+ /** A failure's message for display, naming the server where the message has one. */
52
+ export function terminalMessage(code, server) {
53
+ const failure = terminalFailure(code);
54
+ return server && Object.hasOwn(serverMessages, failure.code) ? serverMessages[failure.code](server) : failure.message;
55
+ }
56
+ export const terminalSuccess = (status, extra = {}) => ({ terminalApi: TERMINAL_API, ok: true, status, ...extra });
57
+ export const terminalSameHandle = (a, b) => !!a && !!b && a.id === b.id && a.lease === b.lease;
@@ -0,0 +1,21 @@
1
+ // Cancellation is a request, not process-exit evidence. In particular Node's
2
+ // AbortError can precede child close. Hold the caller's reservation until BOTH
3
+ // execFile's bounded result and the owned child's close have arrived. A failed
4
+ // command keeps its bounded stdout on the rejection: the CLI prints its JSON
5
+ // refusal and exits nonzero.
6
+ import { execFile } from 'node:child_process';
7
+ export function runTerminalCommand(binary, args, options, exec = execFile) {
8
+ return new Promise((resolve, reject) => {
9
+ let result, closed = false;
10
+ const settle = () => {
11
+ if (!closed || !result) return;
12
+ if (result.error) reject(Object.assign(result.error, { stdout: result.stdout })); else resolve({ stdout: result.stdout, stderr: result.stderr });
13
+ };
14
+ try {
15
+ const child = exec(binary, args, { ...options, shell: false }, (error, stdout, stderr) => {
16
+ result = { error, stdout, stderr }; settle();
17
+ });
18
+ child.once('close', () => { closed = true; settle(); });
19
+ } catch (error) { reject(error); } // spawn did not return an owned child
20
+ });
21
+ }
@@ -0,0 +1,66 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { basename } from "node:path";
3
+
4
+ /** The session a home without a recorded tmux session is looked for in: the kernel's default (0.31),
5
+ * mirrored from the kernel's DEFAULT_TMUX_SESSION (its core module; the Desktop never imports it) — change both. */
6
+ export const DEFAULT_TMUX_SESSION = process.env.OATS_TMUX_SESSION || process.env.PI_AGENTS_TMUX_SESSION || "oats-agents";
7
+
8
+ const shells = new Set(["sh", "bash", "zsh", "fish", "dash", "ksh", "login"]);
9
+
10
+ /** One read per socket, and at most one process snapshot per roster collection. */
11
+ export function createTmuxStatusReader({ exec = execFileSync } = {}) {
12
+ const sockets = new Map();
13
+ let processes;
14
+ const run = (bin, args) => exec(bin, args, {
15
+ encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], timeout: 4000, maxBuffer: 4 * 1024 * 1024,
16
+ });
17
+ function readSocket(socket) {
18
+ if (!sockets.has(socket)) {
19
+ try {
20
+ const text = run("tmux", ["-u", ...(socket ? ["-S", socket] : []), "list-panes", "-a", "-F",
21
+ "#{session_name}\t#{window_name}\t#{window_id}\t#{pane_dead}\t#{pane_current_command}\t#{pane_pid}"]);
22
+ const panes = text.trim().split("\n").filter(Boolean).map((line) => {
23
+ const [session, window, id, dead, command, pid] = line.split("\t");
24
+ if (!session || !window || !/^@\d+$/.test(id) || !/^[01]$/.test(dead) || !/^\d+$/.test(pid)) throw new Error("Invalid tmux status response");
25
+ return { session, window, id, dead: dead === "1", command, pid };
26
+ });
27
+ sockets.set(socket, { panes });
28
+ } catch (e) {
29
+ const absent = /no server running|error connecting.*No such file or directory/i.test(String(e.stderr || ""));
30
+ sockets.set(socket, absent ? { panes: [] } : { error: e.message || "Cannot reach terminal server" });
31
+ }
32
+ }
33
+ return sockets.get(socket);
34
+ }
35
+ function hasHarness(pid) {
36
+ if (!processes) {
37
+ processes = run("ps", ["-axo", "pid=,ppid=,comm="]).split("\n")
38
+ .map((line) => line.trim().match(/^(\d+)\s+(\d+)\s+(.+)$/)).filter(Boolean);
39
+ }
40
+ const descendants = new Set([pid]);
41
+ for (let changed = true; changed;) {
42
+ changed = false;
43
+ for (const [, child, parent, name] of processes) {
44
+ if (!descendants.has(parent) || descendants.has(child)) continue;
45
+ descendants.add(child); changed = true;
46
+ if (!shells.has(basename(name).replace(/^-/, ""))) return true;
47
+ }
48
+ }
49
+ return false;
50
+ }
51
+ return (meta, defaultSession = DEFAULT_TMUX_SESSION) => {
52
+ const tmux = { ...meta.tmux, session: meta.tmux?.session || defaultSession, window: meta.tmux?.window || meta.instance };
53
+ const status = readSocket(tmux.socket || "");
54
+ const unknown = (error) => ({ tmux, running: null, runtimeState: "unreachable", runtimeError: error });
55
+ if (status.error) return unknown(status.error);
56
+ const panes = status.panes.filter((p) => p.session === tmux.session && p.window === tmux.window);
57
+ if (panes.length > 1) return unknown("Instance window has multiple panes; check its terminal before starting");
58
+ const pane = panes[0];
59
+ if (!pane || pane.dead) return { tmux, running: false, runtimeState: "stopped" };
60
+ tmux.id = pane.id;
61
+ try {
62
+ const running = !shells.has(pane.command.replace(/^-/, "")) || hasHarness(pane.pid);
63
+ return { tmux, running, runtimeState: running ? "running" : "shell", paneCommand: pane.command };
64
+ } catch (e) { return unknown(e.message); }
65
+ };
66
+ }
@@ -0,0 +1,88 @@
1
+ /** "Needs input" (Spec D): the kernel's `waitingOnYou` claim on an `oats status --json` row, validated
2
+ * once here and read through one liveness gate by every surface (row mark, card, description, collapsed
3
+ * roll-up: instance-tree.mjs's waitingRollup). Pure, no DOM, never throws. `null` (or absent) means
4
+ * unknown, never "not waiting". Display-only: nothing in Desktop acts on a claim.
5
+ * The claim contract only: the server imports it (deployment-data, remote-roster), so it imports
6
+ * contract modules and nothing else — no tree traversal, no loading UI. */
7
+ import { record } from './readiness-contract.mjs';
8
+ import { eventsTimestamp, eventsId, eventsUnsafe, EVENTS_WITHHELD } from './instance-events-contract.mjs';
9
+ import { NOT_NOTE_TEXT } from './display-text.mjs';
10
+
11
+ /** A claim's note: a non-empty string of at most 200 code points (not UTF-16 units: 101 emoji is a valid
12
+ * note), with none of NOT_NOTE_TEXT (the set's one definition is in display-text.mjs); unsafe text is
13
+ * withheld (the activity view's house rule: it shows EVENTS_WITHHELD). Anything else → null: the claim
14
+ * itself is kept. Not null is the validity answer the kernel's validWaitingMessage gives (a withheld note
15
+ * is a valid note). Never throws (no length-throwing detail helper on this path). */
16
+ export function waitingMessage(v) {
17
+ if (typeof v !== 'string' || !v || [...v].length > 200 || NOT_NOTE_TEXT.test(v)) return null;
18
+ return eventsUnsafe.test(v) ? EVENTS_WITHHELD : v;
19
+ }
20
+
21
+ /** The sidebar's claim: `{ since, producer, reason, message }` or null. Only `since` and `producer` can
22
+ * drop a claim: a missing or malformed reason (never rendered) is null, a malformed message is null, and
23
+ * so is a withheld one (#584): the row, the card and the tab then show the reason in words (waitingLabel),
24
+ * never the withheld marker. Extra keys are ignored (forward compatible). */
25
+ export function waitingOnYouData(v) {
26
+ if (!record(v) || !eventsTimestamp(v.since) || !eventsId(v.producer)) return null;
27
+ const reason = typeof v.reason === 'string' && v.reason.length <= 64 ? v.reason : null;
28
+ const message = waitingMessage(v.message);
29
+ return { since: v.since, producer: v.producer, reason, message: message === EVENTS_WITHHELD ? null : message };
30
+ }
31
+
32
+ /** The claim a row may show, or null. The only gate: liveness says running (`running === true`, and no
33
+ * reported `runtimeState` other than `running`: a tmux `shell`, a stopped pane, an unreachable or
34
+ * unsupported session never shows it), and the row is current: a remote row whose server was not reached,
35
+ * or a row the roster holds stale (`stale`: its last re-read failed), carries a last-known claim, which is
36
+ * unknown. A null or absent `runtimeState` is "not reported", never "not running" (#582): the kernel's
37
+ * remote roster sends null on every row, so a remote row is gated on the `running` its host reported; a
38
+ * local row always carries the concrete state Desktop liveness observed. */
39
+ export function waitingClaim(row, { stale = false } = {}) {
40
+ if (stale || !record(row) || row.running !== true || row.serverUnreached === true) return null;
41
+ if (row.runtimeState != null && row.runtimeState !== 'running') return null;
42
+ return waitingOnYouData(row.waitingOnYou);
43
+ }
44
+
45
+ const LABELS = Object.freeze({ permission: 'Waiting for a tool approval', question: 'Asked you a question', attention: 'Asked for your attention' });
46
+ /** The reason in words. The raw reason is never rendered: an unknown one reads "Needs input". */
47
+ export const waitingLabel = claim => Object.hasOwn(LABELS, claim?.reason ?? '') ? LABELS[claim.reason] : 'Needs input';
48
+
49
+ /** How long it has waited (floor): "under a minute", "N min", "N h", "N d". A future `since` (clock skew)
50
+ * reads "under a minute". Computed when shown, never painted into the row. */
51
+ export function waitedText(since, now = Date.now()) {
52
+ const ms = now - Date.parse(since);
53
+ if (!Number.isFinite(ms) || ms < 60000) return 'under a minute';
54
+ const min = Math.floor(ms / 60000); if (min < 60) return `${min} min`;
55
+ const h = Math.floor(min / 60); if (h < 24) return `${h} h`;
56
+ return `${Math.floor(h / 24)} d`;
57
+ }
58
+
59
+ // The app's copy is English; a fixed table keeps the date deterministic (no locale lookup).
60
+ const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
61
+ const pad = n => String(n).padStart(2, '0');
62
+ /** The claim's start in local time, as precise as it needs to be next to `now`: "14:03" on now's local
63
+ * calendar day, "Oct 2, 14:03" on another day of the same year, "2025-10-02 14:03" in another year. */
64
+ export function waitingClock(since, now = Date.now()) {
65
+ const at = new Date(since), today = new Date(now);
66
+ if (!Number.isFinite(at.getTime())) return '';
67
+ const time = `${pad(at.getHours())}:${pad(at.getMinutes())}`;
68
+ if (at.getFullYear() !== today.getFullYear()) return `${at.getFullYear()}-${pad(at.getMonth() + 1)}-${pad(at.getDate())} ${time}`;
69
+ return at.getMonth() === today.getMonth() && at.getDate() === today.getDate() ? time : `${MONTHS[at.getMonth()]} ${at.getDate()}, ${time}`;
70
+ }
71
+
72
+ /** "dev-a, dev-b" — up to 3 names, then "and N more". */
73
+ export function waitingNames(rows) {
74
+ const names = rows.map(r => r.instance);
75
+ return names.length > 3 ? `${names.slice(0, 3).join(', ')} and ${names.length - 3} more` : names.join(', ');
76
+ }
77
+
78
+ /** The card's "Below" fact: "2 need input: dev-a, dev-b". */
79
+ export const waitingBelowText = rows => `${rows.length} ${rows.length === 1 ? 'needs' : 'need'} input: ${waitingNames(rows)}`;
80
+
81
+ /** What an unavailable row (no card) appends to its title/aria-description sentence. Absolute time only:
82
+ * the sentence is painted once; `now` is the paint time (it decides whether the start needs a date). */
83
+ export function waitingSentence(claim, below = [], now = Date.now()) {
84
+ const parts = [];
85
+ if (claim) parts.push(`Needs input: ${claim.message ?? waitingLabel(claim)} since ${waitingClock(claim.since, now)}`);
86
+ if (below.length) parts.push(`${below.length} below need input: ${waitingNames(below)}`);
87
+ return parts.map(p => ` · ${p}`).join('');
88
+ }
@@ -0,0 +1,45 @@
1
+ /** Whether a directory is an OATS deployment, and which deployments a directory holds: the rule a
2
+ * client applies before it serves or offers a directory. Existence only: the deployment's content is
3
+ * the kernel's to read (`oats workspace status`), and nothing here parses it. The filesystem is the
4
+ * caller's: every function takes its `io`. */
5
+ import { join } from "node:path";
6
+
7
+ /** The most directory entries one look inside a folder reads. */
8
+ export const PICK_SCAN_LIMIT = 200;
9
+
10
+ /** `io.isDeployment` as a predicate that never throws: a path it cannot answer for is not a deployment. */
11
+ export const deploymentCheck = (io) => (p) => { try { return io.isDeployment(p) === true; } catch { return false; } };
12
+
13
+ /** The deployments directly inside `dir`, sorted by name: at most PICK_SCAN_LIMIT entries read, a
14
+ * link never followed, nothing parsed. An unreadable or missing `dir` holds none. Used for a picked
15
+ * parent folder, and for ~/Agents, whose deployments the switcher offers unasked (#518).
16
+ * @param {string} dir
17
+ * @param {object} io
18
+ * @param {(dir: string, limit: number) => { entries: Array<{ name: string, isDirectory: boolean }>, limited: boolean }} io.list
19
+ * at most `limit` entries, `isDirectory` from the entry itself (a link is not a directory)
20
+ * @param {(p: string) => boolean} io.isDeployment a regular oats-local.yaml (lstat)
21
+ * @returns {{ paths: string[], limited: boolean }} */
22
+ export function deploymentsInside(dir, io) {
23
+ let listed = { entries: [], limited: false };
24
+ try { listed = io.list(dir, PICK_SCAN_LIMIT) || listed; } catch { /* unreadable: no children offered */ }
25
+ const paths = listed.entries.filter((e) => e?.isDirectory && typeof e.name === "string" && !e.name.includes("/"))
26
+ .map((e) => e.name).sort((a, b) => a.localeCompare(b)).map((name) => join(dir, name)).filter(deploymentCheck(io));
27
+ return { paths, limited: !!listed.limited };
28
+ }
29
+
30
+ /**
31
+ * Validate a directory as a workspace-model v2 deployment and derive its
32
+ * identity: the canonical deployment directory itself.
33
+ * @param {string} path canonicalized absolute path
34
+ * @param {object} io
35
+ * @param {(p: string) => boolean} io.isDeployment the directory holds its
36
+ * deployment file (a regular, non-symlink oats-local.yaml); existence
37
+ * only — the kernel reads and validates it
38
+ * @returns {{ id: string, name: string, team: null, path: string } | null}
39
+ */
40
+ export function validateWorkspace(path, io) {
41
+ if (typeof path !== "string" || !path.startsWith("/")) return null;
42
+ let deployment = false;
43
+ try { deployment = io.isDeployment(path) === true; } catch { return null; }
44
+ return deployment ? { id: path, name: path.split("/").pop() || path, team: null, path } : null;
45
+ }
@@ -0,0 +1,95 @@
1
+ /** The words a workspace switcher shows for a view (UI spec, #482; #855, 3a): its name, its one muted
2
+ * line, how many of its deployments are not live, its tooltip, and whether a typed filter keeps it.
3
+ * From what panel-views.mjs `workspaceChoices` answers. Words only: a client draws them (the Desktop's
4
+ * menu is packages/desktop/renderer/workspace-switcher.mjs).
5
+ *
6
+ * No state: arguments in, values out, and no argument is changed.
7
+ * A page loads this module: it imports no Node builtin, and must not. */
8
+ import { pathTail } from "./deployment-label.mjs";
9
+
10
+ /** A choice id that is this computer's folder (a deployment from an older server, an unattached
11
+ * one): its path may be shown, as a tooltip. Any other id (a view's `ws:…`, a remote's `remote:…`)
12
+ * is never shown (#482). */
13
+ export const isLocalPath = (id) => typeof id === "string" && id.startsWith("/");
14
+ const short = (value, max = 256) => typeof value === "string" && value.length > 0 && value.length <= max ? value : "";
15
+
16
+ const machinesOf = (choice) => Array.isArray(choice?.machines) ? choice.machines.filter((m) => short(m)) : [];
17
+
18
+ /** The machines a choice's deployments are on, as one line (UI spec, #482): "This Mac · altair", from
19
+ * the server's `machines`. Never a path or an id: without `machines` (an older server), nothing. */
20
+ export function workspaceChoicePlace(choice) {
21
+ return machinesOf(choice).join(" · ");
22
+ }
23
+
24
+ /** Each choice's name, in order. Two choices of one name are told apart by a suffix. */
25
+ export function workspaceChoiceLabels(choices) {
26
+ const base = choices.map((choice) => choice.name
27
+ || (isLocalPath(choice.id) ? String(choice.id).split("/").filter(Boolean).at(-1) : "")
28
+ || "Workspace");
29
+ const counts = new Map();
30
+ for (const name of base) counts.set(name, (counts.get(name) || 0) + 1);
31
+ return choices.map((choice, index) => {
32
+ if (counts.get(base[index]) === 1) return base[index];
33
+ // Two choices of one name: their workspace keys tell them apart, else a folder's last two
34
+ // segments or the machines; never a ws: or remote: id, never a full path.
35
+ const which = short(choice.key, 512) || (isLocalPath(choice.id) ? pathTail(choice.id, 2) : workspaceChoicePlace(choice));
36
+ const suffix = [short(choice.team?.name), which].filter(Boolean).join(" · ");
37
+ return suffix ? `${base[index]} — ${suffix}` : base[index];
38
+ });
39
+ }
40
+
41
+ /** The tooltip of a choice: its deployments' labels (machine and short path) when the server sends
42
+ * them, else a local folder's path; never an id. */
43
+ function choiceTooltip(choice) {
44
+ const deployments = Array.isArray(choice?.deployments) ? choice.deployments : [];
45
+ const labels = Array.isArray(choice?.deploymentLabels) && choice.deploymentLabels.length === deployments.length
46
+ && choice.deploymentLabels.every((l) => short(l, 512)) ? choice.deploymentLabels : [];
47
+ return labels.join(", ") || (isLocalPath(choice?.id) ? choice.id : "");
48
+ }
49
+
50
+ /** The section a switcher lists unattached views under (#482, expert decision Q4). */
51
+ export const UNMATCHED_SECTION = "Not matched to a workspace";
52
+
53
+ /**
54
+ * What a switcher says for each choice, in the same order. Every entry is its name and ONE muted line
55
+ * (UI spec, #482): a view's machines, an unattached view's machine and short reason.
56
+ *
57
+ * id the choice's id
58
+ * label its name (`workspaceChoiceLabels`)
59
+ * place the muted line. A matched view: its machines, joined by " · ". An unattached one: its
60
+ * machine, unless the label already is that machine (a remote group is named by its
61
+ * server), then its short reason, joined the same way
62
+ * notLive for a matched view, how many of its deployments are not live when that is a positive
63
+ * integer; else 0
64
+ * notLiveText "1 deployment not live", "N deployments not live", or ""
65
+ * unattached whether no workspace identity matched it: such a view goes under UNMATCHED_SECTION
66
+ * tooltip its deployments' labels when there is one label per deployment, else a local folder's
67
+ * path, else ""
68
+ * deployment for an unattached view, its first deployment's id (where its full reason and its fix
69
+ * are shown); else null
70
+ *
71
+ * @param {Array<object>} choices what `workspaceChoices` (panel-views.mjs) answers
72
+ */
73
+ export function workspaceChoiceRows(choices) {
74
+ const labels = workspaceChoiceLabels(choices);
75
+ return choices.map((choice, index) => {
76
+ const label = labels[index], unattached = !!choice.unattached;
77
+ const place = unattached
78
+ // The machine, unless the entry is already named by it (a remote group is named by its server).
79
+ ? [machinesOf(choice)[0] === label ? "" : machinesOf(choice)[0] || "", short(choice.short)].filter(Boolean).join(" · ")
80
+ : workspaceChoicePlace(choice);
81
+ const notLive = !unattached && Number.isInteger(choice.notLive) && choice.notLive > 0 ? choice.notLive : 0;
82
+ return { id: choice.id, label, place, notLive,
83
+ notLiveText: notLive ? `${notLive} ${notLive === 1 ? "deployment" : "deployments"} not live` : "",
84
+ unattached, tooltip: choiceTooltip(choice),
85
+ deployment: (unattached && Array.isArray(choice.deployments) ? choice.deployments[0] : null) || null };
86
+ });
87
+ }
88
+
89
+ /** A switcher's filter: whether a row is kept for what was typed. The query is trimmed and lower-cased
90
+ * here; it is looked for in the row's label and place, joined by a space and lower-cased, so what is not
91
+ * shown (a tooltip, a full reason) is never matched. No query keeps every row. */
92
+ export function choiceMatches(row, query) {
93
+ const wanted = String(query ?? "").trim().toLocaleLowerCase();
94
+ return !wanted || `${row.label} ${row.place}`.toLocaleLowerCase().includes(wanted);
95
+ }
@@ -0,0 +1,142 @@
1
+ /** Workspace model v2 verbs the Desktop drives: fixed argv, bounded output,
2
+ * scrubbed instance environment. Only the kernel's JSON crosses back; a
3
+ * refusal is its bounded error envelope (code + message, plus onboarding's
4
+ * rolledBack flag), never stderr, argv, stacks or details objects.
5
+ * capabilities → `oats capabilities --dir D [--max-age S] --json` (capabilitiesApi 1)
6
+ * souls → `oats souls --dir D [--max-age S] --json` (soulsApi 1, the spawn catalog)
7
+ * capability-show → `oats capabilities show NAME (--member KEY | --package ID) [--file PATH]
8
+ * --dir D [--max-age S] --json` (capabilityShowApi 1, feature capability-show:
9
+ * what one capability ships, read at the commit the catalog reports)
10
+ * sync → `oats sync --dir D --json` (syncApi 1)
11
+ * onboard → `oats onboard DIR --workspace REF --json` (onboardApi 2)
12
+ * There is no package approval (packages-no-approval): declaring a package
13
+ * is the trust decision, so every success exits 0. `--max-age` (feature
14
+ * observe-max-age) belongs to the three reads only and reaches argv only when
15
+ * the probe declares the feature; cliWorkspace drops it otherwise. */
16
+ import { execFile } from 'node:child_process';
17
+ import { isAbsolute, resolve } from 'node:path';
18
+ import { OBSERVE_MAX_AGE_FEATURE, validMaxAge } from './deployment-contract.mjs';
19
+ import { capabilityShowSupported, validCapabilityName, validPackageId, validRelativePath, validRepoKey } from './capability-show-contract.mjs';
20
+ import { cliEnvironment } from './cli-environment.mjs';
21
+ import { withoutInstanceVariables } from './kernel-environment.mjs';
22
+ import { requireTerms } from './client-terms.mjs';
23
+
24
+ export const WORKSPACE_READ_TIMEOUT = 60_000;
25
+ export const WORKSPACE_WRITE_TIMEOUT = 300_000; // discovery reads every member remote
26
+ export const WORKSPACE_MAX_BUFFER = 4 * 1024 * 1024;
27
+ export const WORKSPACE_ACTIONS = Object.freeze(['capabilities', 'souls', 'sync', 'onboard', 'capability-show']);
28
+ /** The read-only verbs: the ones `--max-age` may reach. */
29
+ const READS = ['capabilities', 'souls', 'capability-show'];
30
+ /** The kernel line this Desktop drives: workspace model v2 without package approval. */
31
+ export const WORKSPACE_FEATURES = Object.freeze(['workspace-v2', 'packages-no-approval']);
32
+ const absolute = path => typeof path === 'string' && !path.includes('\0') && isAbsolute(path) && resolve(path) === path;
33
+ const record = value => value !== null && typeof value === 'object' && !Array.isArray(value);
34
+ /** A repository reference is the kernel's to parse (E_REPO_REF); the Desktop
35
+ * only refuses what could not be one argv value: empty, huge, control
36
+ * characters or an option-looking token. */
37
+ export const validWorkspaceRef = ref => typeof ref === 'string' && ref.length > 0 && ref.length <= 2048
38
+ && ref.trim() === ref && !/[\u0000-\u001f\u007f]/.test(ref) && !ref.startsWith('-');
39
+
40
+ /** The sentence for each failure this adapter raises itself; one names the client, in its terms (client-terms.mjs). */
41
+ const messages = Object.freeze({
42
+ E_CLI_UNAVAILABLE: 'Choose a compatible installed OATS CLI first.',
43
+ E_WORKSPACE_FEATURE: terms => `The installed OATS CLI is older than ${terms.self} (it does not advertise workspace-v2 and packages-no-approval). Update OATS and retry.`,
44
+ E_BAD_ARGS: 'The workspace request was not valid.',
45
+ E_CLI_FAILED: 'The installed OATS CLI could not complete this workspace command.',
46
+ E_CLI_PROTOCOL: 'The installed OATS CLI returned an invalid workspace result.',
47
+ E_CLI_TIMEOUT: 'The workspace command exceeded its time limit.',
48
+ E_CLI_OUTPUT_LIMIT: 'The workspace command exceeded its size limit.',
49
+ E_CAPABILITY_SHOW_FEATURE: "The installed OATS CLI can't show what a capability ships. Update OATS and retry.",
50
+ });
51
+ /** Every code workspaceFailure has a sentence for. */
52
+ export const WORKSPACE_FAILURE_CODES = Object.freeze(Object.keys(messages));
53
+
54
+ export function workspaceFailure(code, terms, message) {
55
+ requireTerms(terms, 'workspaceFailure');
56
+ const known = Object.hasOwn(messages, code) ? code : 'E_CLI_FAILED', fixed = messages[known];
57
+ return { ok: false, reason: { code: known, message: message || (typeof fixed === 'function' ? fixed(terms) : fixed) } };
58
+ }
59
+
60
+ /** Probe facts only (version --json): the API integer and the feature. */
61
+ export function workspaceGate(cli, terms) {
62
+ requireTerms(terms, 'workspaceGate');
63
+ if (cli?.ok !== true || !absolute(cli.bin)) return workspaceFailure('E_CLI_UNAVAILABLE', terms);
64
+ if (cli.workspaceApi !== 2 || !Array.isArray(cli.features) || !WORKSPACE_FEATURES.every(name => cli.features.includes(name))) return workspaceFailure('E_WORKSPACE_FEATURE', terms);
65
+ return null;
66
+ }
67
+
68
+ export function workspaceArgv(options) {
69
+ if (!record(options) || !WORKSPACE_ACTIONS.includes(options.action)) return null;
70
+ const { action } = options;
71
+ const allowed = { capabilities: ['action', 'context', 'maxAge'], souls: ['action', 'context', 'maxAge'], sync: ['action', 'context'], onboard: ['action', 'dir', 'workspace'],
72
+ 'capability-show': ['action', 'context', 'name', 'member', 'package', 'path', 'maxAge'] }[action];
73
+ if (Object.keys(options).some(key => !allowed.includes(key))) return null;
74
+ if (action === 'onboard') {
75
+ if (!absolute(options.dir) || !validWorkspaceRef(options.workspace)) return null;
76
+ return { argv: ['onboard', options.dir, '--workspace', options.workspace, '--json'], cwd: options.dir, timeout: WORKSPACE_WRITE_TIMEOUT };
77
+ }
78
+ if (!absolute(options.context)) return null;
79
+ if (action === 'capability-show') {
80
+ // Exactly one selector, each value one argv token the kernel parses (never option-looking);
81
+ // the file path is plain, relative and inside the capability (no `..`, no leading `/` or `-`).
82
+ const member = Object.hasOwn(options, 'member'), pkg = Object.hasOwn(options, 'package');
83
+ if (!validCapabilityName(options.name) || member === pkg || !validMaxAge(options.maxAge)) return null;
84
+ if (member ? !validRepoKey(options.member) : !validPackageId(options.package)) return null;
85
+ if (Object.hasOwn(options, 'path') && !validRelativePath(options.path)) return null;
86
+ return { argv: ['capabilities', 'show', options.name, ...(member ? ['--member', options.member] : ['--package', options.package]),
87
+ ...(Object.hasOwn(options, 'path') ? ['--file', options.path] : []), '--dir', options.context,
88
+ ...(options.maxAge === undefined ? [] : ['--max-age', String(options.maxAge)]), '--json'], cwd: options.context, timeout: WORKSPACE_READ_TIMEOUT };
89
+ }
90
+ if (action === 'capabilities' || action === 'souls') {
91
+ if (!validMaxAge(options.maxAge)) return null;
92
+ const maxAge = options.maxAge === undefined ? [] : ['--max-age', String(options.maxAge)];
93
+ return { argv: [action, '--dir', options.context, ...maxAge, '--json'], cwd: options.context, timeout: WORKSPACE_READ_TIMEOUT };
94
+ }
95
+ return { argv: ['sync', '--dir', options.context, '--json'], cwd: options.context, timeout: WORKSPACE_WRITE_TIMEOUT };
96
+ }
97
+
98
+ /** `io.exec` is a client's own `execFile` (the rule is at cli-adapter.mjs `runJson`). */
99
+ export function cliWorkspace(cli, options, terms, io = {}) {
100
+ requireTerms(terms, 'cliWorkspace');
101
+ const gate = workspaceGate(cli, terms);
102
+ if (gate) return Promise.resolve(gate);
103
+ // `capabilities show` is its own feature on top of the workspace line (the feature AND the API integer).
104
+ if (record(options) && options.action === 'capability-show' && !capabilityShowSupported(cli)) return Promise.resolve(workspaceFailure('E_CAPABILITY_SHOW_FEATURE', terms));
105
+ // An invalid value is a bad request whatever the kernel. A valid one on a kernel without
106
+ // observe-max-age names a flag that does not exist there: drop it (on a copy; the caller's
107
+ // request is not ours to edit) so the read runs flagless. Only the reads take it, so the
108
+ // drop never lets a mutating verb past workspaceArgv's allowlist.
109
+ if (record(options) && Object.hasOwn(options, 'maxAge')) {
110
+ if (!validMaxAge(options.maxAge)) return Promise.resolve(workspaceFailure('E_BAD_ARGS', terms));
111
+ if (!cli.features.includes(OBSERVE_MAX_AGE_FEATURE) && READS.includes(options.action)) { const { maxAge, ...rest } = options; options = rest; }
112
+ }
113
+ const plan = workspaceArgv(options);
114
+ if (!plan) return Promise.resolve(workspaceFailure('E_BAD_ARGS', terms));
115
+ const env = withoutInstanceVariables(cliEnvironment(io.env ?? process.env)); // main's own environment is not cleaned; in the backend this changes nothing
116
+ return new Promise(done => {
117
+ const fail = code => done(workspaceFailure(code, terms));
118
+ try {
119
+ (io.exec ?? execFile)(cli.bin, plan.argv, { cwd: plan.cwd, env, shell: false, encoding: 'utf8', timeout: plan.timeout, maxBuffer: WORKSPACE_MAX_BUFFER }, (error, stdout) => {
120
+ if (error?.code === 'ERR_CHILD_PROCESS_STDIO_MAXBUFFER') return fail('E_CLI_OUTPUT_LIMIT');
121
+ if (error?.killed) return fail('E_CLI_TIMEOUT');
122
+ if (typeof stdout !== 'string') return fail(error ? 'E_CLI_FAILED' : 'E_CLI_PROTOCOL');
123
+ if (Buffer.byteLength(stdout, 'utf8') > WORKSPACE_MAX_BUFFER) return fail('E_CLI_OUTPUT_LIMIT');
124
+ let document;
125
+ try { document = JSON.parse(stdout); } catch { return fail(error ? 'E_CLI_FAILED' : 'E_CLI_PROTOCOL'); }
126
+ if (!record(document) || document.schemaVersion !== 1 || typeof document.ok !== 'boolean') return fail('E_CLI_PROTOCOL');
127
+ if (document.ok === false) {
128
+ const reason = document.error;
129
+ if (!record(reason) || typeof reason.code !== 'string' || !/^[A-Z][A-Z0-9_]{0,63}$/.test(reason.code)
130
+ || typeof reason.message !== 'string' || reason.message.length > 8192) return fail('E_CLI_PROTOCOL');
131
+ // A refusal cannot become success, and a success exit cannot carry one.
132
+ if (!error) return fail('E_CLI_PROTOCOL');
133
+ const out = { code: reason.code, message: reason.message };
134
+ if (options.action === 'onboard' && reason.details?.rolledBack === true) out.rolledBack = true;
135
+ return done({ ok: false, reason: out });
136
+ }
137
+ if (error) return fail('E_CLI_FAILED'); // success is exit 0 only
138
+ done({ ok: true, document });
139
+ });
140
+ } catch { fail('E_CLI_FAILED'); }
141
+ });
142
+ }