@awebai/oats 0.68.1 → 0.69.2

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 (99) hide show
  1. package/bin/oats.mjs +180 -36
  2. package/docs/capabilities.md +73 -10
  3. package/docs/capability-manifest.schema.json +1 -1
  4. package/docs/configuration.md +68 -2
  5. package/docs/design/2026-09-23-workspace-module-contracts.md +6 -4
  6. package/docs/design/2026-10-22-module-upgrade.md +1 -1
  7. package/docs/desktop-cli-api.md +600 -25
  8. package/docs/desktop-instance-start.md +59 -3
  9. package/docs/desktop.md +175 -10
  10. package/docs/execution-targets.md +536 -62
  11. package/docs/harness-trust.md +3 -1
  12. package/docs/implementation.md +33 -15
  13. package/docs/integrations.md +2 -2
  14. package/docs/knowledge.md +25 -16
  15. package/docs/oats-local.schema.json +2 -2
  16. package/docs/official-catalog.md +6 -5
  17. package/docs/packages.md +14 -14
  18. package/docs/release-notes/v0.69.0.md +658 -0
  19. package/docs/release-notes/v0.69.1.md +25 -0
  20. package/docs/release-notes/v0.69.2.md +259 -0
  21. package/docs/servers.md +51 -7
  22. package/docs/soul.schema.json +1 -0
  23. package/docs/souls-and-instances.md +46 -9
  24. package/docs/tui.md +177 -21
  25. package/docs/upgrading.md +16 -7
  26. package/docs/workspaces.md +2 -2
  27. package/injects/instance-boundary.md +19 -33
  28. package/injects/work-attached.md +8 -13
  29. package/injects/work-checkout.md +16 -30
  30. package/injects/work-directory.md +9 -15
  31. package/injects/work-workspace.md +8 -19
  32. package/injects/work-worktree.md +18 -33
  33. package/lib/capability-contract.mjs +2 -2
  34. package/lib/core.mjs +496 -127
  35. package/lib/file-pieces.mjs +49 -0
  36. package/lib/instance-background.mjs +54 -0
  37. package/lib/instance-events.mjs +25 -4
  38. package/lib/instance-inspect.mjs +3 -0
  39. package/lib/instance-lifecycle.mjs +35 -0
  40. package/lib/instance-resolution.mjs +3 -2
  41. package/lib/instance-same-work.mjs +67 -0
  42. package/lib/instance-upgrade.mjs +18 -0
  43. package/lib/launch-prompt-fixtures/README.md +62 -0
  44. package/lib/launch-prompt-fixtures/resume-confirmation.json +32 -0
  45. package/lib/launch-prompt-fixtures.mjs +49 -0
  46. package/lib/launch-prompt-resume.mjs +55 -0
  47. package/lib/login-environment.mjs +27 -9
  48. package/lib/materialize.mjs +23 -2
  49. package/lib/resolve.mjs +32 -5
  50. package/lib/schedule.mjs +3 -3
  51. package/lib/servers.mjs +136 -27
  52. package/lib/session-end.mjs +82 -0
  53. package/lib/session-input.mjs +43 -9
  54. package/lib/session-resume-contract.mjs +33 -0
  55. package/lib/session-resume.mjs +337 -0
  56. package/lib/session-seen.mjs +163 -0
  57. package/lib/session-viewer.mjs +147 -44
  58. package/lib/soul-composition.mjs +15 -11
  59. package/lib/start-env.mjs +110 -0
  60. package/lib/tmux-server-scope.mjs +139 -14
  61. package/lib/workspace.mjs +41 -6
  62. package/package-catalog.json +11 -5
  63. package/package.json +1 -1
  64. package/packages/client/cli-adapter.mjs +39 -8
  65. package/packages/client/cli-locator.mjs +3 -2
  66. package/packages/client/deployment-data.mjs +16 -0
  67. package/packages/client/deployment-panel.mjs +7 -0
  68. package/packages/client/file-output-exec.mjs +98 -0
  69. package/packages/client/instance-tree.mjs +64 -14
  70. package/packages/client/launch-prompt-outcome.mjs +25 -13
  71. package/packages/client/own-codes.mjs +2 -0
  72. package/packages/client/panel-views.mjs +11 -3
  73. package/packages/client/remote-roster.mjs +5 -1
  74. package/packages/client/roster-sections.mjs +50 -6
  75. package/packages/client/same-work.mjs +49 -0
  76. package/packages/client/session-attach.mjs +35 -5
  77. package/packages/client/session-resume-cli.mjs +64 -0
  78. package/packages/client/session-resume-trigger.mjs +167 -0
  79. package/packages/client/session-resume.mjs +332 -0
  80. package/packages/client/soul-rows.mjs +2 -0
  81. package/packages/client/spawn-apply-contract.mjs +2 -1
  82. package/packages/client/spawn-decision.mjs +4 -1
  83. package/packages/client/spawn-preview-contract.mjs +12 -1
  84. package/packages/client/spawn-preview.mjs +2 -0
  85. package/packages/client/tmux-status.mjs +30 -7
  86. package/packages/client/waiting-on-you.mjs +11 -4
  87. package/packages/client/workspace-step.mjs +17 -5
  88. package/packages/record/lib/last-conversation.mjs +123 -0
  89. package/packages/record/lib/session-roots.mjs +10 -1
  90. package/packages/tui/README.md +2 -2
  91. package/packages/tui/lib/client.mjs +7 -3
  92. package/packages/tui/lib/main.mjs +49 -14
  93. package/packages/tui/lib/model.mjs +146 -55
  94. package/packages/tui/lib/store.mjs +84 -27
  95. package/packages/tui/lib/term/text.mjs +12 -9
  96. package/packages/tui/lib/views/frame.mjs +74 -7
  97. package/packages/tui/lib/views/help.mjs +10 -3
  98. package/packages/tui/lib/views/instances.mjs +41 -3
  99. package/skills/oats-getting-started/SKILL.md +117 -4
@@ -7,6 +7,29 @@ export const DEFAULT_TMUX_SESSION = process.env.OATS_TMUX_SESSION || process.env
7
7
 
8
8
  const shells = new Set(["sh", "bash", "zsh", "fish", "dash", "ksh", "login"]);
9
9
 
10
+ const paneNumber = (paneId) => Number(paneId.slice(1));
11
+
12
+ /** The agent's pane of one window's panes, [{ paneId: "%N", mark, ...rest }] (`mark`: the pane's
13
+ * `@oats-agent`, "" when unset): the kernel's rule, lib/session-input.mjs `resolveAgentPane`, which
14
+ * a client cannot import. This copy is for this computer's tmux only (the status reader below and
15
+ * the Desktop's terminal open, packages/desktop/tmux-target.mjs), and test/desktop-tmux-status.test.mjs
16
+ * pins it to the kernel's, sentences included. `name` is the window's recorded name, which is what
17
+ * OATS marks the agent's pane with. One pane is the agent's, mark or not. Of several: the one marked
18
+ * `name`; else the lowest pane id of those with no mark (the window's own: an OATS split comes
19
+ * later), as another instance's mark is never this one's; two or more marked `name`, or no
20
+ * candidate, it can't tell. { pane } (the element, null for no pane) or { error }. */
21
+ export function agentPane(panes, name) {
22
+ if (panes.length <= 1) return { pane: panes[0] ?? null };
23
+ const byId = [...panes].sort((a, b) => paneNumber(a.paneId) - paneNumber(b.paneId));
24
+ const ids = (list) => list.map((p) => p.paneId).join(", ");
25
+ const ours = byId.filter((p) => p.mark === name);
26
+ if (ours.length === 1) return { pane: ours[0] };
27
+ if (ours.length > 1) return { error: `the window has ${ours.length} panes marked as ${name}'s agent pane (${ids(ours)}); close all but the agent's with tmux kill-pane -t <id>, or close the window and start the instance` };
28
+ const unmarked = byId.find((p) => !p.mark);
29
+ if (unmarked) return { pane: unmarked };
30
+ return { error: `the window has ${byId.length} panes and none is ${name}'s agent pane (${ids(byId)}); close the panes that aren't, or close the window and start the instance` };
31
+ }
32
+
10
33
  /** One read per socket, and at most one process snapshot per roster collection. */
11
34
  export function createTmuxStatusReader({ exec = execFileSync } = {}) {
12
35
  const sockets = new Map();
@@ -18,11 +41,12 @@ export function createTmuxStatusReader({ exec = execFileSync } = {}) {
18
41
  if (!sockets.has(socket)) {
19
42
  try {
20
43
  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}"]);
44
+ "#{session_name}\t#{window_name}\t#{window_id}\t#{pane_id}\t#{pane_dead}\t#{pane_current_command}\t#{pane_pid}\t#{@oats-agent}"]);
22
45
  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 };
46
+ // The mark is last: whatever it holds, the fields before it are where they should be.
47
+ const [session, window, id, paneId, dead, command, pid, ...mark] = line.split("\t");
48
+ if (!session || !window || !/^@\d+$/.test(id) || !/^%\d+$/.test(paneId) || !/^[01]$/.test(dead) || !/^\d+$/.test(pid)) throw new Error("Invalid tmux status response");
49
+ return { session, window, id, paneId, dead: dead === "1", command, pid, mark: mark.join("\t") };
26
50
  });
27
51
  sockets.set(socket, { panes });
28
52
  } catch (e) {
@@ -53,9 +77,8 @@ export function createTmuxStatusReader({ exec = execFileSync } = {}) {
53
77
  const status = readSocket(tmux.socket || "");
54
78
  const unknown = (error) => ({ tmux, running: null, runtimeState: "unreachable", runtimeError: error });
55
79
  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];
80
+ const { pane, error } = agentPane(status.panes.filter((p) => p.session === tmux.session && p.window === tmux.window), tmux.window);
81
+ if (error) return unknown(error);
59
82
  if (!pane || pane.dead) return { tmux, running: false, runtimeState: "stopped" };
60
83
  tmux.id = pane.id;
61
84
  try {
@@ -20,13 +20,14 @@ export function waitingMessage(v) {
20
20
 
21
21
  /** The sidebar's claim: `{ since, producer, reason, message }` or null. Only `since` and `producer` can
22
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). */
23
+ * so is a withheld one (#584) or one with no character but white space (#1502): the row, the card and the
24
+ * tab then show the reason in words (waitingLabel), never the withheld marker or a blank line. Extra keys
25
+ * are ignored (forward compatible). */
25
26
  export function waitingOnYouData(v) {
26
27
  if (!record(v) || !eventsTimestamp(v.since) || !eventsId(v.producer)) return null;
27
28
  const reason = typeof v.reason === 'string' && v.reason.length <= 64 ? v.reason : null;
28
29
  const message = waitingMessage(v.message);
29
- return { since: v.since, producer: v.producer, reason, message: message === EVENTS_WITHHELD ? null : message };
30
+ return { since: v.since, producer: v.producer, reason, message: message === EVENTS_WITHHELD || !message?.trim() ? null : message };
30
31
  }
31
32
 
32
33
  /** The claim a row may show, or null. The only gate: liveness says running (`running === true`, and no
@@ -45,6 +46,9 @@ export function waitingClaim(row, { stale = false } = {}) {
45
46
  const LABELS = Object.freeze({ permission: 'Waiting for a tool approval', question: 'Asked you a question', attention: 'Asked for your attention' });
46
47
  /** The reason in words. The raw reason is never rendered: an unknown one reads "Needs input". */
47
48
  export const waitingLabel = claim => Object.hasOwn(LABELS, claim?.reason ?? '') ? LABELS[claim.reason] : 'Needs input';
49
+ /** What a surface that already says "Needs input" adds after it: the message, else the reason in words,
50
+ * else null, when the claim names no reason of its own and the tag's words say it all (#1502). */
51
+ export const waitingDetail = claim => claim?.message ?? (Object.hasOwn(LABELS, claim?.reason ?? '') ? LABELS[claim.reason] : null);
48
52
 
49
53
  /** How long it has waited (floor): "under a minute", "N min", "N h", "N d". A future `since` (clock skew)
50
54
  * reads "under a minute". Computed when shown, never painted into the row. */
@@ -82,7 +86,10 @@ export const waitingBelowText = rows => `${rows.length} ${rows.length === 1 ? 'n
82
86
  * the sentence is painted once; `now` is the paint time (it decides whether the start needs a date). */
83
87
  export function waitingSentence(claim, below = [], now = Date.now()) {
84
88
  const parts = [];
85
- if (claim) parts.push(`Needs input: ${claim.message ?? waitingLabel(claim)} since ${waitingClock(claim.since, now)}`);
89
+ if (claim) {
90
+ const detail = waitingDetail(claim);
91
+ parts.push(`Needs input${detail ? `: ${detail}` : ''} since ${waitingClock(claim.since, now)}`);
92
+ }
86
93
  if (below.length) parts.push(`${below.length} below need input: ${waitingNames(below)}`);
87
94
  return parts.map(p => ` · ${p}`).join('');
88
95
  }
@@ -1,23 +1,35 @@
1
1
  /** The workspace the leader's ↑ and ↓ move to (keymap.mjs `workspace-previous`, `workspace-next`): the
2
2
  * next openable row of the sidebar's list of workspaces, as each client draws it, in one direction. Both
3
- * clients read it; each draws its own list and opens what this answers.
3
+ * clients read it; each draws its own list and opens what this answers. Both clients' moves wrap.
4
4
  *
5
5
  * Pure: arguments in, a key out, nothing changed. A page loads this module: it imports nothing. */
6
6
 
7
7
  /**
8
8
  * The key of the next row with `openable` true from the row `currentKey`, in the direction `step`
9
- * (+1, down the list; −1, up it), or null at an end: the list does not wrap. Rows that are not
10
- * openable are passed over. With `currentKey` not among the rows (null included: nothing is open, or
11
- * what is open is not listed), the first openable row for +1 and the last for −1, or null when none is.
9
+ * (+1, down the list; −1, up it). Rows that are not openable are passed over. Without `wrap` (the TUI
10
+ * list's own cursor) the list does not wrap: null at an end. With `wrap` (both clients' moves) it goes
11
+ * on from the other end, and
12
+ * when no other row can be opened it answers `currentKey` itself (an openable current row: the only
13
+ * one), so a caller can tell "only this one" from "none". With `currentKey` not among the rows (null
14
+ * included: nothing is open, or what is open is not listed), the first openable row for +1 and the
15
+ * last for −1, or null when none is, wrapping or not.
12
16
  * @param {{ key: string, openable: boolean }[]} rows the list as drawn, in its order
13
17
  * @param {string | null} currentKey the row the client is on
14
18
  * @param {1 | -1} step
19
+ * @param {{ wrap?: boolean }} [options]
15
20
  * @returns {string | null}
16
21
  */
17
- export function workspaceStep(rows, currentKey, step) {
22
+ export function workspaceStep(rows, currentKey, step, { wrap = false } = {}) {
18
23
  const list = Array.isArray(rows) ? rows : [];
19
24
  const at = currentKey === null || currentKey === undefined ? -1 : list.findIndex((row) => row?.key === currentKey);
20
25
  const dir = step < 0 ? -1 : 1;
26
+ if (wrap && at !== -1) {
27
+ for (let n = 1; n < list.length; n++) {
28
+ const row = list[(((at + dir * n) % list.length) + list.length) % list.length];
29
+ if (row?.openable === true) return row.key;
30
+ }
31
+ return list[at]?.openable === true ? list[at].key : null;
32
+ }
21
33
  for (let i = at === -1 ? (dir === 1 ? 0 : list.length - 1) : at + dir; i >= 0 && i < list.length; i += dir) {
22
34
  if (list[i]?.openable === true) return list[i].key;
23
35
  }
@@ -0,0 +1,123 @@
1
+ // lastConversation — the conversation a restarted instance should reopen.
2
+ //
3
+ // The roots come from the home's own native-record receipts (what each managed
4
+ // start of this harness actually recorded), never from an observer's HOME. A
5
+ // transcript is the instance's conversation only when it was STARTED in the
6
+ // home itself: a session started in <home>/work is a helper's, not the
7
+ // instance's. `since` (the home's createdAt) drops an earlier incarnation of a
8
+ // reused name: its receipts started, and its transcripts last changed, before
9
+ // this home existed.
10
+ //
11
+ // Unlike capture, this is a best-effort lookup, so it never certifies complete
12
+ // history: a home made before the recorder has receipts only for later starts,
13
+ // and those are enough. Unexpected I/O failures throw.
14
+
15
+ import { closeSync, fstatSync, openSync, readFileSync, readdirSync, realpathSync, statSync } from "node:fs";
16
+ import { basename, dirname, isAbsolute, join, resolve } from "node:path";
17
+ import { isUtf8 } from "node:buffer";
18
+
19
+ import { SESSION_FORMATS } from "./formats.mjs";
20
+ import { bufferLines, fileChunks } from "./file-lines.mjs";
21
+ import { nativeHistoryPath } from "./native-history.mjs";
22
+ import { CWD_SCAN_BOUND_BYTES, cwdOfLine } from "./sessions-for-home.mjs";
23
+
24
+ const SOURCE = { claude: "cc", pi: "pi", codex: "codex" };
25
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
26
+ const RECEIPT = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.json$/;
27
+ // What pi's `--session` resolves as an id, not a path (pi treats `/`, `\` and
28
+ // a `.jsonl` suffix as a path). The recorder accepts the same bare form.
29
+ const PI_ID = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
30
+
31
+ function canonical(p) {
32
+ try { return realpathSync(p); }
33
+ catch (err) { if (err.code !== "ENOENT") throw err; return resolve(p); }
34
+ }
35
+
36
+ function sinceMs(since) {
37
+ const t = since instanceof Date ? since.getTime() : typeof since === "number" ? since : typeof since === "string" ? Date.parse(since) : NaN;
38
+ if (!Number.isFinite(t)) throw new TypeError("lastConversation needs a valid `since` (the home's createdAt)");
39
+ return t;
40
+ }
41
+
42
+ function readJson(path) { return JSON.parse(readFileSync(path, "utf8")); }
43
+
44
+ // The locations this harness's started launches (since `since`) recorded.
45
+ // null: there is no v1 receipt custody to trust for this harness.
46
+ function receiptRoots(home, runtime, since) {
47
+ const dir = nativeHistoryPath(home);
48
+ let names;
49
+ try { names = readdirSync(dir); }
50
+ catch (err) { if (err.code === "ENOENT") return null; throw err; }
51
+ let header;
52
+ try { header = readJson(join(dir, "history.json")); }
53
+ catch (err) { if (err.code === "ENOENT") return null; throw err; }
54
+ if (header?.version !== 1) return null; // a captured (v2) home keeps protected custody
55
+ const roots = [];
56
+ for (const name of names.sort()) {
57
+ if (!RECEIPT.test(name)) continue; // history.json, temp files, strays
58
+ const row = readJson(join(dir, name));
59
+ if (row?.version !== 1 || row.runtime !== runtime || row.state !== "started") continue;
60
+ if (!(Date.parse(row.startedAt) >= since)) continue;
61
+ if (row.id !== basename(name, ".json") || !Array.isArray(row.locations)) throw new Error(`invalid native record receipt: ${name}`);
62
+ for (const path of row.locations) {
63
+ if (typeof path !== "string" || !isAbsolute(path) || path.includes("\0") || resolve(path) !== path) throw new Error(`invalid native record location in ${name}`);
64
+ if (!roots.includes(path)) roots.push(path);
65
+ }
66
+ }
67
+ return roots.length ? roots : null;
68
+ }
69
+
70
+ // The first native header in the file's complete lines (cwd, and pi's id).
71
+ // A tolerant read: other instances' transcripts in a shared root may be
72
+ // growing while we look, and only their already-terminated prefix is read.
73
+ function header(source, path) {
74
+ let fd;
75
+ try { fd = openSync(path, "r"); }
76
+ catch (err) { if (err.code === "ENOENT") return null; throw err; } // removed since listing
77
+ try {
78
+ const end = Math.min(CWD_SCAN_BOUND_BYTES, fstatSync(fd).size);
79
+ for (const bytes of bufferLines(fileChunks(fd, { end, size: 64 * 1024 }))) {
80
+ if (bytes[bytes.length - 1] !== 10) break; // an unterminated fragment is not a record
81
+ const line = isUtf8(bytes) ? bytes.toString("utf8") : null;
82
+ const cwd = cwdOfLine(source, line);
83
+ if (!cwd) continue;
84
+ return { cwd, id: source === "pi" ? JSON.parse(line).id : undefined };
85
+ }
86
+ return null;
87
+ } finally { closeSync(fd); }
88
+ }
89
+
90
+ /** The harness's last conversation started in `home` since `since`.
91
+ * `harness`: "claude" | "pi" | "codex"; `since`: ISO string, Date or ms.
92
+ * Returns { sessionId, path } (sessionId is what the harness's resume flag
93
+ * takes), or { none: "no-receipts" } / { none: "no-conversation" }. */
94
+ export function lastConversation(home, { harness, since } = {}) {
95
+ const source = SOURCE[harness];
96
+ if (!source) throw new Error(`unsupported harness for lastConversation: ${harness}`);
97
+ const after = sinceMs(since);
98
+ const roots = receiptRoots(home, harness, after);
99
+ if (!roots) return { none: "no-receipts" };
100
+ const format = SESSION_FORMATS[source], target = canonical(home);
101
+ let best = null;
102
+ // Non-strict: a recorded root nothing has written to yet is simply empty.
103
+ for (const path of new Set(format.listFiles(roots, { strict: false }))) {
104
+ let sessionId = format.sessionId(path);
105
+ // Claude: never a subagent or sidechain transcript; `claude --resume`
106
+ // takes the parent session's UUID, which is its file's name.
107
+ if (source === "cc" && (basename(dirname(path)) === "subagents" || !UUID.test(sessionId))) continue;
108
+ let mtimeMs;
109
+ try { mtimeMs = statSync(path).mtimeMs; }
110
+ catch (err) { if (err.code === "ENOENT") continue; throw err; }
111
+ // Cheap before any read: shared roots hold every other home's transcripts.
112
+ if (mtimeMs < after || (best && (mtimeMs < best.mtimeMs || (mtimeMs === best.mtimeMs && path > best.path)))) continue;
113
+ const found = header(source, path);
114
+ if (!found || canonical(found.cwd) !== target) continue;
115
+ if (source === "pi") {
116
+ // pi's --session matches the header id; the filename carries the same id.
117
+ if (typeof found.id === "string") sessionId = found.id;
118
+ if (!PI_ID.test(sessionId) || sessionId.endsWith(".jsonl")) continue;
119
+ }
120
+ best = { sessionId, path, mtimeMs };
121
+ }
122
+ return best ? { sessionId: best.sessionId, path: best.path } : { none: "no-conversation" };
123
+ }
@@ -81,7 +81,16 @@ export function nativeLaunchLocations(harness, { cwd, env = process.env, args =
81
81
  let sessionDir = env.PI_CODING_AGENT_SESSION_DIR;
82
82
  for (let i = 0; i < args.length; i++) {
83
83
  const arg = args[i];
84
- if (arg === "--session" || arg.startsWith("--session=")) throw new Error("explicit Pi --session has no supported directory custody; capture explicit roots instead");
84
+ if (arg === "--session" || arg.startsWith("--session=")) {
85
+ // A resumed launch names its session by bare id; pi looks an id up in the
86
+ // session directory below, so that directory is still where it writes.
87
+ // pi opens anything with `/`, `\` or a `.jsonl` suffix as a file path,
88
+ // which may live anywhere: that has no directory custody.
89
+ const id = arg === "--session" ? args[++i] : arg.slice("--session=".length);
90
+ if (!id || id.startsWith("-")) throw new Error("invalid native --session");
91
+ if (/[/\\\0]/.test(id) || /^[.~]/.test(id) || id.endsWith(".jsonl")) throw new Error("explicit Pi --session has no supported directory custody; capture explicit roots instead");
92
+ continue;
93
+ }
85
94
  if (arg === "--session-dir" || arg.startsWith("--session-dir=")) {
86
95
  sessionDir = arg === "--session-dir" ? args[++i] : arg.slice("--session-dir=".length);
87
96
  if (!sessionDir || sessionDir.startsWith("--")) throw new Error("invalid native --session-dir");
@@ -20,7 +20,7 @@ never does.
20
20
  | path | contents |
21
21
  |---|---|
22
22
  | `bin/tui.mjs` | the entry `bin/oats.mjs` loads: it imports the whole module graph, then runs `main()` |
23
- | `lib/main.mjs` | the start (arguments, environment, terminal, `tui.json`, deployment, kernel, and outside every deployment this computer's list of deployments) and the loop: events through `reduce`, effects out, the frame drawn; the list's reads, the add of the deployment the run starts in and the switcher's Remove, through the shared `cliDeploymentList`; a resize and the keys typed to an agent told to the store (`passed`), which ends a line of one key |
23
+ | `lib/main.mjs` | the start (arguments, environment, terminal, `tui.json`, deployment, kernel, and outside every deployment this computer's list of deployments) and the loop: events through `reduce`, effects out, the frame drawn; the list's reads, the add of the deployment the run starts in and the switcher's Remove, through the shared `cliDeploymentList`; the kernel's machine sweep of lost sessions (`oats session resume --json`), when the shared resume trigger says (after that add has settled, and when a read shows a lost session), through `changeExec`; a resize and the keys typed to an agent told to the store (`passed`), which ends a line of one key |
24
24
  | `lib/actions.mjs` | the action table and its default keys: the reducer, the cheat sheet and the help read the effective one. The keys shared with the Desktop are not written here: the leader's table and the plain keys of the list come from `packages/client/keymap.mjs`, and `test/keymap.test.mjs` fails on a row of the shared table the TUI does not handle |
25
25
  | `lib/config.mjs` | `tui.json` (`~/.oats/config/tui.json`): moved once from where earlier versions read it, read once, checked, and the effective action table; the default leader is the shared one (`keymap.mjs` `leaderKey`, Ctrl+X on every platform) |
26
26
  | `lib/client.mjs` | the one module that imports the shared readers (`packages/client/`), and the client's terms |
@@ -77,7 +77,7 @@ Rules the tests pin (`test/tui-boundary.test.mjs` reads the files):
77
77
  a block that says what its command never says ends that client (THE
78
78
  CAPTURE in `lib/panel.mjs`). A
79
79
  change (`lib/read.mjs` `changeExec`: the apply of a stop or a retire, a
80
- start, a restart, a spawn's apply) is never signalled on the way out: it
80
+ start, a restart, a spawn's apply, the machine sweep) is never signalled on the way out: it
81
81
  is let go, and its output goes to files, so it never meets a closed pipe.
82
82
  Only a spawn's apply has a deadline, the shared apply's, at which it is
83
83
  sent its signal (`timeout`, `killSignal`), and only while the run lasts:
@@ -22,14 +22,14 @@ export { remoteRosterState } from "../../client/remote-roster.mjs";
22
22
  export { observeIdentities, identityMemory } from "../../client/remote-identity-memory.mjs";
23
23
  export { workspaceChoiceRows, choiceMatches, UNMATCHED_SECTION } from "../../client/workspace-choices.mjs";
24
24
  export { shortPath, deploymentLabel, machineLabels } from "../../client/deployment-label.mjs";
25
- export { instanceId, instanceVisibleInTree, waitingRollup, collapseKey, filterInstanceTree, hasInstanceChildren, heldHome, instanceSiblings } from "../../client/instance-tree.mjs";
26
- export { rosterSections, deploymentState, rowStale, primaryDeployment, isMultiDeployment } from "../../client/roster-sections.mjs";
25
+ export { instanceId, instanceVisibleInTree, waitingRollup, collapseKey, filterInstanceTree, hasInstanceChildren, heldHome, instanceSiblings, backgroundPlacement, BACKGROUND_FEATURE } from "../../client/instance-tree.mjs";
26
+ export { rosterSections, deploymentState, rowStale, primaryDeployment, isMultiDeployment, rosterSectionKey, sidebarSections } from "../../client/roster-sections.mjs";
27
27
  export { runtimeState, runtimeCounts, originLead, siblingText, instanceColor } from "../../client/instance-presentation.mjs";
28
28
  export { instanceDisplayName } from "../../client/instance-display-name.mjs";
29
29
  export { waitingClaim, waitingLabel, waitedText, waitingClock, waitingBelowText } from "../../client/waiting-on-you.mjs";
30
30
  export { instanceActs, openAct } from "../../client/instance-acts.mjs";
31
31
  export { rowReason } from "../../client/remote-address.mjs";
32
- export { sessionAttachArgv, prepareRemoteTerm, detachKeySupported, hostDetachKeySupported, preflightFailure, DETACH_KEY_FEATURE } from "../../client/session-attach.mjs";
32
+ export { sessionAttachArgv, prepareRemoteTerm, detachKeySupported, hostDetachKeySupported, preflightFailure, DETACH_KEY_FEATURE, PREFIX_SCROLL_FEATURE, localScrollKeys, hostScrollKeys } from "../../client/session-attach.mjs";
33
33
  export { attachExit } from "../../client/attach-exit.mjs";
34
34
  export { kernelLines } from "../../client/kernel-lines.mjs";
35
35
  export { createLifecycleBoundary } from "../../client/instance-lifecycle.mjs";
@@ -38,6 +38,10 @@ export { createRetiresInFlight, retiringRows } from "../../client/retire-in-flig
38
38
  export { startGate, startInstance } from "../../client/session-start.mjs";
39
39
  export { retainedStartMessage, launchFlagIgnored, flagIgnoredNotice } from "../../client/launch-prompt-outcome.mjs";
40
40
  export { INSTANCE_VARIABLES } from "../../client/kernel-environment.mjs";
41
+ // #1559: the kernel's machine sweep, run when the TUI opens and when a read shows a lost session
42
+ // (lib/main.mjs): the shared trigger decides when, the runner runs it, and the reader words what it did.
43
+ export { runResumeSweep } from "../../client/session-resume-cli.mjs";
44
+ export { createResumeTrigger, localDeploymentIds } from "../../client/session-resume-trigger.mjs";
41
45
  export { validateWorkspace } from "../../client/workspace-admission.mjs";
42
46
  export { createSoulCatalog, soulCatalogKey } from "../../client/soul-catalog.mjs";
43
47
  export { soulRows } from "../../client/soul-rows.mjs";
@@ -12,9 +12,9 @@
12
12
  import { homedir } from "node:os";
13
13
  import { resolve } from "node:path";
14
14
  import { bindings } from "./actions.mjs";
15
- import { TERMS, capabilityCatalogKey, cliDeploymentList, deploymentsListSupported, createCapabilityCatalog, createLifecycleBoundary, createLifecycleConfirmation, createRetiresInFlight, createSoulCatalog, createSpawnApplyBoundary, createSpawnPreview, createSpawnTransaction, displayLine, heldHome, pendingEntry, prepareRemoteTerm, sessionAttachArgv, soulCatalogKey, startInstance } from "./client.mjs";
15
+ import { TERMS, capabilityCatalogKey, cliDeploymentList, deploymentsListSupported, createCapabilityCatalog, createLifecycleBoundary, createLifecycleConfirmation, createRetiresInFlight, createSoulCatalog, createSpawnApplyBoundary, createSpawnPreview, createSpawnTransaction, createResumeTrigger, displayLine, heldHome, pendingEntry, prepareRemoteTerm, runResumeSweep, sessionAttachArgv, soulCatalogKey, startInstance } from "./client.mjs";
16
16
  import { loadConfig, loadKeys } from "./config.mjs";
17
- import { ACT_WORDS, LIST_WORDS, actContext, actCwd, listRowsOf, localDeployments, model, outcomeOf, reachedMachines, roster, spawnContext } from "./model.mjs";
17
+ import { ACT_WORDS, LIST_WORDS, actContext, actCwd, listRowsOf, localDeployments, model, outcomeOf, reachedMachines, resumeObservation, roster, spawnContext } from "./model.mjs";
18
18
  import { createPanel, sweep } from "./panel.mjs";
19
19
  import { CHANGE_FILES, admitDeployment, createIdentityReads, createReader, findDeployment, leaveInstance, probeKernel, realpath, startExec, tellable } from "./read.mjs";
20
20
  import { initialState, reduce } from "./store.mjs";
@@ -72,6 +72,9 @@ export function parseArgs(argv) {
72
72
 
73
73
  /** The label of a change to this computer's deployments list (an add or a remove), for the line after leaving. */
74
74
  const LIST_CHANGE = Object.freeze({ verb: "list" });
75
+ /** The label of the kernel's machine sweep (`oats session resume --json`), every one the run starts: a
76
+ * change, never signalled, and never named after leaving (the TUI says nothing of a sweep). */
77
+ const RESUME_CHANGE = Object.freeze({ verb: "resume" });
75
78
  /** Why a call to this computer's deployments list has no answer at all: it threw before the kernel
76
79
  * could answer. The shared adapter's own code for a kernel call that failed (deployment-list-cli.mjs). */
77
80
  const NOT_ASKED = Object.freeze({ code: "E_CLI_FAILED", message: "the kernel could not be asked" });
@@ -94,10 +97,11 @@ function errorLines(error) {
94
97
  * can answer them. `deploymentList` is the shared cliDeploymentList (this computer's deployments
95
98
  * list, through the kernel: awebai/oats#1390), and `startExec` the exec it is handed before the
96
99
  * terminal is taken; replaceable so a test can answer the list. `loadKeys` reads keys.json, the
97
- * chord family (lib/config.mjs), replaceable so no test reads a user's file. */
100
+ * chord family (lib/config.mjs), replaceable so no test reads a user's file. `createResumeTrigger`
101
+ * is the shared trigger of the kernel's machine sweep (packages/client session-resume-trigger.mjs). */
98
102
  const EFFECTS = Object.freeze({ loadConfig, loadKeys, findDeployment, probeKernel, createReader, createIdentityReads, deploymentList: cliDeploymentList, startExec, admitDeployment, prepareRemoteTerm, createPanel, sweep,
99
103
  runDir: CHANGE_FILES.dir, removeDir: CHANGE_FILES.remove, realpath, tellable, startInstance, createLifecycleConfirmation, createLifecycleBoundary, createSoulCatalog,
100
- createCapabilityCatalog, createSpawnPreview, createSpawnApplyBoundary, createSpawnTransaction });
104
+ createCapabilityCatalog, createSpawnPreview, createSpawnApplyBoundary, createSpawnTransaction, createResumeTrigger });
101
105
 
102
106
  /** The timers a run lends the shared spawn: the apply's deadline and its grace (the boundary's
103
107
  * `applyTimer`), the boundary's wait for an answer (`timer`) and the transaction's polls
@@ -214,7 +218,13 @@ export async function main({ argv, stdin, stdout, stderr, env, proc = process, n
214
218
  * covers nothing, whatever entry it kept. */
215
219
  function entered(event) {
216
220
  heard(event);
217
- if (event.read === true && state.numbers.get(event.id) === event.number) retires.landed(event.number, (t) => !t.server && t.workspace === event.id);
221
+ if (event.read !== true || state.numbers.get(event.id) !== event.number) return;
222
+ retires.landed(event.number, (t) => !t.server && t.workspace === event.id);
223
+ // The rows of the view that holds it, with its deployments of this machine: a lost row of one of those
224
+ // sweeps again; another machine's row never does (the shared trigger's locality).
225
+ if (ended) return;
226
+ const { rows, localDeploymentIds } = resumeObservation(state, event.id, clock());
227
+ resume.observed(rows, { localDeploymentIds });
218
228
  }
219
229
  /** An event of the roster read: taken, then an outcome covers the rows of each machine it reached
220
230
  * (a read that failed marks every machine not reached, and covers none). */
@@ -235,6 +245,22 @@ export async function main({ argv, stdin, stdout, stderr, env, proc = process, n
235
245
  onEntry: entered, onRoster: rostered,
236
246
  files: { ...CHANGE_FILES, dir: runDir },
237
247
  });
248
+ // LOST SESSIONS RESUMED (docs/tui.md, "Resuming lost sessions"; #1559): the kernel's machine sweep,
249
+ // `oats session resume --json`, which resumes every lost session of every local deployment of this
250
+ // computer. The shared trigger decides when: once the run has started (`launch`, after the add of the
251
+ // deployment it started in has settled, so the sweep's registry holds it), then whenever a read of a
252
+ // served deployment shows a row of a deployment of this machine whose session was lost (`observed`,
253
+ // given the view's rows and its local deployment ids: lib/model.mjs resumeObservation), never two at
254
+ // a time nor more often than its floor, and only with a kernel that has the sweep. The TUI decides nothing of what
255
+ // resumes. The sweep is a change of the run (the reader's changeExec: detached, its output in files,
256
+ // never signalled), which outlives the TUI and is let go in silence on the way out; what it read goes
257
+ // to the store as `{ resumed }`, which says nothing of it and at most reads the rows live.
258
+ const resume = effects.createResumeTrigger({
259
+ cli: () => probe.cli,
260
+ run: (cli) => runResumeSweep(cli, { exec: (bin, argv, options, callback) => reader.changeExec(bin, argv, { ...options, label: RESUME_CHANGE }, callback), env }),
261
+ now,
262
+ onReading: (reading) => heard({ resumed: reading }),
263
+ });
238
264
  // THE TABS AND THE SPLIT (docs/tui.md, "Tabs", "Splits"): the terminals open in the panel, at
239
265
  // most the store's TAB_LIMIT across its groups. `viewers` maps each tab's instanceId to its
240
266
  // viewer, `{ id, panel, cols, rows }` (the panel's own id once the window exists, null before,
@@ -521,10 +547,11 @@ export async function main({ argv, stdin, stdout, stderr, env, proc = process, n
521
547
  }
522
548
  /** The deployment the run started in (from where it was started, or `--dir`), added to the list
523
549
  * once, as the TUI's: best effort. A failure opens nothing less, and is said once, in the line
524
- * under the sidebar's title. A row opened from the switcher is on the list already. */
550
+ * under the sidebar's title. A row opened from the switcher is on the list already. Settles once
551
+ * the add has, whatever it answered; at once without one. */
525
552
  function listStart(path) {
526
- if (!listing) return;
527
- Promise.resolve()
553
+ if (!listing) return Promise.resolve();
554
+ return Promise.resolve()
528
555
  .then(() => effects.deploymentList(probe.cli, { action: "add", path, via: "tui" }, { exec: listChange, env }))
529
556
  .then((answer) => { if (!answer.ok) heard({ notListed: answer.reason }); }, () => heard({ notListed: NOT_ASKED }));
530
557
  }
@@ -579,19 +606,21 @@ export async function main({ argv, stdin, stdout, stderr, env, proc = process, n
579
606
  * starts in the panel at once. On another, the shared preflight runs first over the reader's
580
607
  * exec (a read like any other, ended on every way out), and what it prepared waits for the
581
608
  * store's `panel`, which comes only if the open was not given up and the row is still there.
582
- * The viewer is given no key of its own: the TUI takes the back key before the pane sees it. */
609
+ * The viewer is given no key of its own: the TUI takes the back key before the pane sees it.
610
+ * Nor its status line, where the kernel can leave it out (--no-status-line): the cheat sheet
611
+ * names the scroll keys. */
583
612
  function open(decision) {
584
613
  if (!decision.routed) {
585
614
  let args;
586
615
  // A target the shared home refuses (no absolute home) starts nothing; the line after says
587
616
  // the viewer ended without saying why.
588
- try { args = sessionAttachArgv(probe.cli, decision.target); } catch { return void heard({ returned: { id: decision.id, status: null, stderr: "" } }); }
617
+ try { args = sessionAttachArgv(probe.cli, decision.target, { statusLine: false }); } catch { return void heard({ returned: { id: decision.id, status: null, stderr: "" } }); }
589
618
  return view(decision.id, probe.cli.bin, args);
590
619
  }
591
620
  giveUpPreflight();
592
621
  const mine = preflight = { id: decision.id, controller: new AbortController(), prepared: null };
593
622
  Promise.resolve()
594
- .then(() => effects.prepareRemoteTerm(probe.cli, decision.target, { exec: reader.exec, signal: mine.controller.signal }))
623
+ .then(() => effects.prepareRemoteTerm(probe.cli, decision.target, { exec: reader.exec, signal: mine.controller.signal, statusLine: false }))
595
624
  .then((prepared) => { if (preflight === mine) { mine.prepared = prepared; heard({ prepared: { id: mine.id } }); } },
596
625
  (error) => { if (preflight === mine) { preflight = null; heard({ prepared: { id: mine.id, error } }); } });
597
626
  }
@@ -811,7 +840,8 @@ export async function main({ argv, stdin, stdout, stderr, env, proc = process, n
811
840
  // The run's directory goes last, made for whichever of the two needed it first: the reader
812
841
  // removes it only when it wrote a change there, and one it cannot remove (a change still
813
842
  // writing) stays.
814
- onEnd() { ended = true; spawnTimers.end(); dismiss(confirmation?.n); panel.end(); identities.stop(); reader.stop(); if (dir !== null) { try { effects.removeDir(dir); } catch { /* not empty, or gone */ } } },
843
+ // The machine sweep in flight is let go with the other changes: its answer is no longer shown.
844
+ onEnd() { ended = true; resume.dispose(); spawnTimers.end(); dismiss(confirmation?.n); panel.end(); identities.stop(); reader.stop(); if (dir !== null) { try { effects.removeDir(dir); } catch { /* not empty, or gone */ } } },
815
845
  });
816
846
  function refresh(how) { Promise.resolve(reader.request(how)).catch(() => {}); }
817
847
  /** A preflight under way when the process stops: given up, and the store told. Its state alone is
@@ -853,7 +883,11 @@ export async function main({ argv, stdin, stdout, stderr, env, proc = process, n
853
883
  // At the wait's end what the key parser kept as a possible beginning of the answer is read as typed.
854
884
  if (kb === "asking" && !ended) kbTimer = setTimer(() => { kbTimer = null; guard.attempt(() => { const released = parser.giveUp(); answered(null); if (released.length && !typing()) act(released); watchEscape(); }); }, Math.max(0, answerBy - now()));
855
885
  guard.attempt(() => { if (!ended) Promise.resolve(reader.start()).catch(() => {}); });
856
- if (found.ok) guard.attempt(() => { if (!ended) listStart(found.deployment); });
886
+ // The machine sweep, once the add of the deployment the run started in has settled (a start in the
887
+ // switcher has none): after the first frame and the first read cycle have begun, never before them.
888
+ let added = Promise.resolve();
889
+ if (found.ok) guard.attempt(() => { if (!ended) added = listStart(found.deployment); });
890
+ added.then(() => { if (!ended) guard.attempt(() => { resume.launch(); }); });
857
891
  // Once a run, at the start: the identities of this computer's listed deployments, the list read first
858
892
  // when the run did not read it before the terminal was taken.
859
893
  guard.attempt(() => { if (!ended) { if (listedAtStart) identify(); else readList({ identify: true }); } });
@@ -867,7 +901,8 @@ export async function main({ argv, stdin, stdout, stderr, env, proc = process, n
867
901
  if (kbTimer !== null) clearTimer(kbTimer);
868
902
  // After the alternate screen is left, so the message stays on the screen the user returns to.
869
903
  // One line per change still running, to a terminal or a file only; the status never depends on it.
870
- const running = reader.changes?.() ?? [];
904
+ // The machine sweep is no change of the person's: none for it.
905
+ const running = (reader.changes?.() ?? []).filter(({ label }) => label !== RESUME_CHANGE);
871
906
  if (running.length && effects.tellable(stderr)) {
872
907
  try { stderr.write(running.map(({ label }) => `${label === LIST_CHANGE ? LIST_WORDS.leaving : ACT_WORDS.leaving(label?.verb ?? "change", displayLine(label?.name) ?? "an instance")}\n`).join("")); } catch { /* nothing to tell it to */ }
873
908
  }