@awebai/oats 0.68.0 → 0.69.1

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 (72) hide show
  1. package/bin/oats.mjs +102 -22
  2. package/docs/capabilities.md +49 -5
  3. package/docs/configuration.md +68 -2
  4. package/docs/desktop-cli-api.md +355 -12
  5. package/docs/desktop-instance-start.md +88 -3
  6. package/docs/desktop.md +147 -13
  7. package/docs/execution-targets.md +514 -62
  8. package/docs/harness-trust.md +3 -1
  9. package/docs/implementation.md +28 -11
  10. package/docs/integrations.md +1 -1
  11. package/docs/oats-local.schema.json +2 -2
  12. package/docs/official-catalog.md +4 -3
  13. package/docs/packages.md +7 -7
  14. package/docs/release-notes/v0.68.1.md +102 -0
  15. package/docs/release-notes/v0.69.0.md +658 -0
  16. package/docs/release-notes/v0.69.1.md +25 -0
  17. package/docs/servers.md +44 -5
  18. package/docs/souls-and-instances.md +11 -7
  19. package/docs/tui.md +114 -31
  20. package/docs/upgrading.md +14 -5
  21. package/docs/workspaces.md +1 -1
  22. package/lib/core.mjs +345 -89
  23. package/lib/file-pieces.mjs +49 -0
  24. package/lib/instance-events.mjs +25 -4
  25. package/lib/launch-prompt-fixtures/README.md +62 -0
  26. package/lib/launch-prompt-fixtures/resume-confirmation.json +32 -0
  27. package/lib/launch-prompt-fixtures.mjs +49 -0
  28. package/lib/launch-prompt-resume.mjs +55 -0
  29. package/lib/login-environment.mjs +27 -9
  30. package/lib/schedule.mjs +3 -3
  31. package/lib/servers.mjs +117 -23
  32. package/lib/session-end.mjs +82 -0
  33. package/lib/session-input.mjs +43 -9
  34. package/lib/session-resume-contract.mjs +32 -0
  35. package/lib/session-resume.mjs +310 -0
  36. package/lib/session-seen.mjs +163 -0
  37. package/lib/session-viewer.mjs +147 -44
  38. package/lib/soul-composition.mjs +2 -1
  39. package/lib/start-env.mjs +110 -0
  40. package/lib/tmux-server-scope.mjs +139 -14
  41. package/lib/workspace.mjs +38 -4
  42. package/package-catalog.json +10 -4
  43. package/package.json +1 -1
  44. package/packages/client/cli-adapter.mjs +9 -0
  45. package/packages/client/cli-locator.mjs +3 -2
  46. package/packages/client/deployment-data.mjs +7 -0
  47. package/packages/client/deployment-panel.mjs +3 -0
  48. package/packages/client/file-output-exec.mjs +98 -0
  49. package/packages/client/instance-display-name.mjs +18 -0
  50. package/packages/client/launch-prompt-outcome.mjs +25 -13
  51. package/packages/client/own-codes.mjs +2 -0
  52. package/packages/client/session-attach.mjs +35 -5
  53. package/packages/client/session-resume-cli.mjs +64 -0
  54. package/packages/client/session-resume-trigger.mjs +167 -0
  55. package/packages/client/session-resume.mjs +332 -0
  56. package/packages/client/tmux-status.mjs +30 -7
  57. package/packages/client/waiting-on-you.mjs +11 -4
  58. package/packages/client/workspace-step.mjs +17 -5
  59. package/packages/record/lib/last-conversation.mjs +123 -0
  60. package/packages/record/lib/session-roots.mjs +10 -1
  61. package/packages/tui/README.md +1 -1
  62. package/packages/tui/lib/client.mjs +2 -1
  63. package/packages/tui/lib/main.mjs +5 -3
  64. package/packages/tui/lib/model.mjs +57 -15
  65. package/packages/tui/lib/store.mjs +8 -7
  66. package/packages/tui/lib/term/text.mjs +12 -9
  67. package/packages/tui/lib/views/capabilities.mjs +6 -6
  68. package/packages/tui/lib/views/frame.mjs +72 -7
  69. package/packages/tui/lib/views/help.mjs +9 -4
  70. package/packages/tui/lib/views/instances.mjs +46 -29
  71. package/packages/tui/lib/views/souls.mjs +9 -8
  72. package/skills/oats-getting-started/SKILL.md +117 -4
@@ -6,6 +6,10 @@ import { inspectSessionTarget } from "./session-input.mjs";
6
6
  /** The kernel feature of `session attach --detach-key` (docs/execution-targets.md, "Inspect,
7
7
  * input and attach"): a routed attach sends the flag only to a host that advertises it. */
8
8
  export const DETACH_KEY_FEATURE = "session-attach-detach-key";
9
+ /** The kernel feature of `session attach --no-status-line`: a locked viewer without its status
10
+ * line (the caller shows the scroll keys itself, as `oats tui` does). A routed attach sends the
11
+ * flag to any host: a kernel without the feature ignores it and shows the line. */
12
+ export const NO_STATUS_LINE_FEATURE = "session-attach-no-status-line";
9
13
  /** The status of an attach its detach key ended. Answered only when the key's own binding ran. */
10
14
  export const SESSION_DETACHED_EXIT = 20;
11
15
  /** The closed grammar of a detach key: Control with a letter other than h, i and m, or one of
@@ -23,14 +27,57 @@ export function requireDetachKey(value) {
23
27
  throw Object.assign(new Error(`--detach-key must be one key: C-<a letter except h, i and m, or one of \\ ] ^ _>, M-<a lowercase letter or digit>, or F1 to F12 with at most one of C-, M-, S- (got ${JSON.stringify(value)})`), { code: "E_BAD_ARGS" });
24
28
  }
25
29
 
26
- /** The table of a viewer without a detach key: one for the whole tmux server, emptied and bound
27
- * again by each such viewer. */
28
- const LOCKED_TABLE = "oatsview-locked";
29
- /** The mouse bindings of a viewer's key table, the locked one or a keyed viewer's own. */
30
- const MOUSE_BINDINGS = [
31
- ["WheelUpPane", "if-shell", "-F", "#{||:#{pane_in_mode},#{mouse_any_flag}}", "send-keys -M", "copy-mode -e; send-keys -M"],
32
- ["MouseDrag1Pane", "if-shell", "-F", "#{||:#{pane_in_mode},#{mouse_any_flag}}", "send-keys -M", "copy-mode -M"],
33
- ];
30
+ /** Whether a mouse event is the pane's to read: in copy mode already, or the app there asked
31
+ * for mouse reports. */
32
+ const VIEWER_MOUSE = "#{||:#{pane_in_mode},#{mouse_any_flag}}";
33
+ /** The bindings of a viewer's key table (every viewer has its own, named as its session), each the
34
+ * arguments of a `bind-key -T <table>` after the table: data a caller that builds its own viewer
35
+ * (the Desktop's local one) pins its table to. The mouse ones
36
+ * pass the event to the pane when the app there has grabbed the mouse, as Claude Code does; the
37
+ * scrollback key then still enters copy mode, a page up (#1476). In copy mode, tmux's own
38
+ * copy-mode table takes the keys: PageUp, PageDown and q. A table's unbind (`unbind-key -a`)
39
+ * removes them all. */
40
+ export const VIEWER_BINDINGS = Object.freeze([
41
+ Object.freeze(["WheelUpPane", "if-shell", "-F", VIEWER_MOUSE, "send-keys -M", "copy-mode -e; send-keys -M"]),
42
+ Object.freeze(["MouseDrag1Pane", "if-shell", "-F", VIEWER_MOUSE, "send-keys -M", "copy-mode -M"]),
43
+ Object.freeze(["S-PageUp", "copy-mode -u"]),
44
+ ]);
45
+ /** The locked viewer's C-b table (#1502 part D): a table of its own, named as its session with
46
+ * PREFIX_TABLE_SUFFIX. Its locked table binds PREFIX_KEY to `switch-client -T <that table>`: the
47
+ * client reads its next key there, and tmux takes it back to its own table after that key, with
48
+ * no timeout. Here:
49
+ * - `[` enters copy mode, as a tmux prefix does; the agent reads nothing.
50
+ * - The viewer's own wheel, drag and S-PageUp send the C-b, then do what the locked table does.
51
+ * - Any other key (`Any`, which tmux runs for every key with no binding of its own):
52
+ * send-keys C-b ; if-shell -F '#{!=:#{mouse_x},}' 'send-keys -M' 'send-keys'
53
+ * The C-b goes to the agent first. Then a mouse event (only a mouse event sets mouse_x) goes
54
+ * as one with -M, and any other key goes with a `send-keys` that names no key, which sends
55
+ * the key the command is bound to: tmux(1), 3.8, send-keys: "If no keys are given and the
56
+ * command is bound to a key, then that key is used." So C-b n, C-b C-b, C-b Up and a paste
57
+ * after C-b reach the agent as both keys, as typed.
58
+ * Both tables are the viewer's alone: bound once, when the viewer is made and before a client
59
+ * reads them, and removed with its session. No other viewer touches them.
60
+ * A tmux limitation remains: setting ANY session's key-table option returns every client of the
61
+ * server to its default table (tmux options.c, the "key-table" case: TAILQ_FOREACH(loop,
62
+ * &clients, entry) server_client_set_key_table(loop, NULL), the same in 3.3, 3.4 and 3.8), and
63
+ * every new viewer sets its own. So a C-b pressed in the instant another viewer opens is lost,
64
+ * and the key after it reaches the agent alone. */
65
+ export const PREFIX_TABLE_SUFFIX = "-prefix";
66
+ export const PREFIX_KEY = "C-b";
67
+ /** The bindings of a locked viewer's C-b table, as VIEWER_BINDINGS are (data a caller pins its own to). */
68
+ export const LOCKED_PREFIX_BINDINGS = Object.freeze([
69
+ Object.freeze(["[", "copy-mode"]),
70
+ Object.freeze(["WheelUpPane", `send-keys C-b ; if-shell -F '${VIEWER_MOUSE}' 'send-keys -M' 'copy-mode -e; send-keys -M'`]),
71
+ Object.freeze(["MouseDrag1Pane", `send-keys C-b ; if-shell -F '${VIEWER_MOUSE}' 'send-keys -M' 'copy-mode -M'`]),
72
+ Object.freeze(["S-PageUp", "send-keys C-b ; copy-mode -u"]),
73
+ Object.freeze(["Any", "send-keys C-b ; if-shell -F '#{!=:#{mouse_x},}' 'send-keys -M' 'send-keys'"]),
74
+ ]);
75
+ /** The locked viewer's status line: its scroll keys, where the person reading the agent sees
76
+ * them, unless its caller asks for none (`statusLine: false`, NO_STATUS_LINE_FEATURE). It names
77
+ * only the keys that work: C-b [ only where the C-b table is bound (VIEWER_PREFIX_MIN_TMUX). A
78
+ * keyed viewer has no status line: its caller shows its own keys. */
79
+ export const VIEWER_SCROLL_HINT = "Shift+PgUp or C-b [ to scroll back";
80
+ export const VIEWER_SCROLL_HINT_WITHOUT_PREFIX = "Shift+PgUp to scroll back";
34
81
  /** What a detach key runs, as ONE bind-key argument (a bare `;` argument would end bind-key and
35
82
  * run the rest at once): mark the viewer session, keep it past its last client (its
36
83
  * client-detached hook, below, would remove it, and the mark with it, before the attach reads the
@@ -49,10 +96,11 @@ export const VIEWER_CLOSED_HOOK_INDEX = 900;
49
96
  * key table of that name. A key table belongs to the server and outlives its session. The
50
97
  * viewer's own client-detached hook (the attach, below) unbinds it when it ends the session; a
51
98
  * session can also end with no client detaching from it (its window ended, a kill-session), and
52
- * only a global session-closed hook runs then: a session's own hooks are gone with it. The name is matched before it reaches a command. `run-shell -C`
99
+ * only a global session-closed hook runs then: a session's own hooks are gone with it. Its C-b
100
+ * table (`<name>-prefix`) goes too. The name is matched before it reaches a command. `run-shell -C`
53
101
  * expands the name; tmux before 3.2 has no -C, the entry does nothing there, and the next attach's
54
102
  * sweep removes the table. A constant: setting it again leaves the server as it was. */
55
- const VIEWER_CLOSED_HOOK = `if-shell -F '#{m/r:${VIEWER_NAME_PATTERN},#{hook_session_name}}' "run-shell -C 'unbind-key -a -q -T #{hook_session_name}'"`;
103
+ const VIEWER_CLOSED_HOOK = `if-shell -F '#{m/r:${VIEWER_NAME_PATTERN},#{hook_session_name}}' "run-shell -C 'unbind-key -a -q -T #{hook_session_name} ; unbind-key -a -q -T #{hook_session_name}${PREFIX_TABLE_SUFFIX}'"`;
56
104
  /** Whether a process exists: kill(pid, 0), and EPERM (another user's) exists too. */
57
105
  function processAlive(pid) {
58
106
  try { process.kill(pid, 0); return true; } catch (e) { return e.code === "EPERM"; }
@@ -63,14 +111,17 @@ function processAlive(pid) {
63
111
  * an attach that is alive may not have attached its client yet, or may be between a leave by its
64
112
  * key and its own cleanup. A key table goes when no session has its name. Keys are listed before
65
113
  * sessions: a viewer makes its session before its table, so a table listed belongs to a session
66
- * that the later list shows, unless that session has ended. Nothing whose name is not a viewer's
67
- * is touched, the shared locked table included. A failed call removes nothing and counts nothing:
114
+ * that the later list shows, unless that session has ended. A viewer's C-b table goes with its
115
+ * session's name (`<name>-prefix`). Nothing whose name is not a viewer's is touched (the server-
116
+ * wide `oatsview-locked` and `oatsview-locked-prefix` of an earlier kernel included). A failed call removes nothing and counts nothing:
68
117
  * the attach goes on, and the next one sweeps again. */
118
+ /** The session a viewer's key table belongs to: its own name, or the name before PREFIX_TABLE_SUFFIX. */
119
+ const sessionOfTable = (table) => (table.endsWith(PREFIX_TABLE_SUFFIX) ? table.slice(0, -PREFIX_TABLE_SUFFIX.length) : table);
69
120
  function sweepViewers(run) {
70
121
  const swept = { sessions: 0, tables: 0 };
71
122
  let tables, sessions;
72
123
  try {
73
- tables = new Set(run(["list-keys"]).split("\n").map((line) => /^bind-key\s+(?:-r\s+)?-T\s+(\S+)\s/.exec(line)?.[1]).filter((t) => VIEWER_NAME.test(t ?? "")));
124
+ tables = new Set(run(["list-keys"]).split("\n").map((line) => /^bind-key\s+(?:-r\s+)?-T\s+(\S+)\s/.exec(line)?.[1]).filter((t) => VIEWER_NAME.test(sessionOfTable(t ?? ""))));
74
125
  sessions = run(["list-sessions", "-F", "#{session_name}\t#{session_attached}"]).split("\n").map((line) => line.split("\t"));
75
126
  } catch { return swept; }
76
127
  const kept = new Set();
@@ -80,7 +131,7 @@ function sweepViewers(run) {
80
131
  try { run(["kill-session", "-t", `=${name}`]); swept.sessions++; } catch { kept.add(name); }
81
132
  }
82
133
  for (const table of tables) {
83
- if (kept.has(table)) continue;
134
+ if (kept.has(sessionOfTable(table))) continue;
84
135
  try { run(["unbind-key", "-a", "-q", "-T", table]); swept.tables++; } catch { /* the next attach sweeps again */ }
85
136
  }
86
137
  return swept;
@@ -95,13 +146,52 @@ export function tmuxHasClientFeatures(versionText) {
95
146
  const [major, minor] = [Number(m[1]), Number(m[2])];
96
147
  return major > 3 || (major === 3 && minor >= 2);
97
148
  }
98
- /** The probe's answer per `exec`: one `tmux -V` per process for the real one, and a fresh probe
99
- * for each fake a test injects. */
100
- const clientFeatures = new WeakMap();
149
+ /** The first tmux whose `send-keys` with no key sends the key it is bound to, which the locked
150
+ * viewer's C-b table needs to forward a key after C-b: tmux 3.3 (its CHANGES, "3.2a to 3.3":
151
+ * "Make send-keys without arguments send the key it is bound to (if bound to a key)", commit
152
+ * 9f6164a05). Before it such a send-keys sends nothing, and the key after C-b would be lost. */
153
+ export const VIEWER_PREFIX_MIN_TMUX = "3.3";
154
+ const [PREFIX_MIN_MAJOR, PREFIX_MIN_MINOR] = VIEWER_PREFIX_MIN_TMUX.split(".").map(Number);
155
+ /** Whether a `tmux -V` answer names a tmux of VIEWER_PREFIX_MIN_TMUX or later: `tmux X.Y` with an
156
+ * optional letter suffix, or a development build `tmux next-X.Y`, which is X.Y in the making and
157
+ * newer than every earlier release. `tmux master`, another vendor's spelling or no answer is not
158
+ * one: the viewer then has no C-b. */
159
+ export function tmuxForwardsBoundKey(versionText) {
160
+ const m = /^tmux (?:next-)?(\d+)\.(\d+)[a-z]*$/.exec(String(versionText ?? "").trim());
161
+ if (!m) return false;
162
+ const [major, minor] = [Number(m[1]), Number(m[2])];
163
+ return major > PREFIX_MIN_MAJOR || (major === PREFIX_MIN_MAJOR && minor >= PREFIX_MIN_MINOR);
164
+ }
165
+ /** The feature that names `sessionViewer` in `oats version --json` and `oats status --json` (and a
166
+ * roster's `probe.sessionViewer`): listed by every kernel that has it, whatever this host's tmux. */
167
+ export const PREFIX_SCROLL_FEATURE = "session-attach-prefix-scroll";
168
+ /** This host's viewer fact, `{ prefixScroll }`: whether a viewer without a detach key binds C-b [
169
+ * here, by the rule its preparation applies (tmuxForwardsBoundKey of the tmux on PATH). It asks
170
+ * `tmux -V` at every call, never keeping an answer: a tmux upgraded under a running Desktop is read
171
+ * as it is now. No answer is false. */
172
+ export function readSessionViewer({ exec = execFileSync } = {}) {
173
+ let text = null;
174
+ try { text = exec("tmux", ["-V"], { encoding: "utf8", timeout: 10000, stdio: ["ignore", "pipe", "pipe"] }); } catch { /* no tmux, or no answer */ }
175
+ return { prefixScroll: tmuxForwardsBoundKey(text) };
176
+ }
177
+ /** The probe's answers per `exec`, `{ sync, forwards }`: one `tmux -V` per process for the real
178
+ * one, and a fresh probe for each fake a test injects. A probe that fails answers no to both:
179
+ * never the attach's failure. */
180
+ const probed = new WeakMap();
181
+ function probeTmux(exec, run) {
182
+ if (!probed.has(exec)) {
183
+ let text = null;
184
+ try { text = run(["-V"]); } catch { /* no answer: today's client, and no C-b */ }
185
+ probed.set(exec, { sync: tmuxHasClientFeatures(text), forwards: tmuxForwardsBoundKey(text) });
186
+ }
187
+ return probed.get(exec);
188
+ }
101
189
 
102
- export function prepareSessionViewer(target, { exec = execFileSync, detachKey } = {}) {
190
+ export function prepareSessionViewer(target, { exec = execFileSync, detachKey, statusLine = true } = {}) {
103
191
  if (detachKey !== undefined) requireDetachKey(detachKey);
104
- if (!inspectSessionTarget(target, { exec }).present) throw new Error("session no longer exists");
192
+ // The agent's pane (lib/session-input.mjs resolveAgentPane): a window it cannot tell refuses here.
193
+ const agent = inspectSessionTarget(target, { exec }, { includePanes: true });
194
+ if (!agent.present) throw new Error("session no longer exists");
105
195
  // UTF-8 mode (-u) like the shared session helper: a service without a
106
196
  // UTF-8 locale (launchd) otherwise mangles tmux output.
107
197
  // Each call in a session and process group of its own (`detached`): a hang-up, termination or
@@ -113,40 +203,58 @@ export function prepareSessionViewer(target, { exec = execFileSync, detachKey }
113
203
  }).trim();
114
204
  const swept = sweepViewers(run);
115
205
  const viewer = `oatsview-${process.pid}-${randomUUID().slice(0, 8)}`;
116
- // A keyed viewer reads a table of its own, named as its session: a binding in the locked table
117
- // would be every viewer's, and the next viewer's unbind would remove it.
118
- const table = detachKey === undefined ? LOCKED_TABLE : viewer;
206
+ // Every viewer reads tables of its own, named as its session: bound once here, before a client
207
+ // reads them, and removed with the session, so no other viewer's preparation ever changes a
208
+ // table a client reads. A locked viewer (no detach key) on a tmux that forwards a key after C-b
209
+ // has a C-b table too (PREFIX_TABLE_SUFFIX).
210
+ const table = viewer, locked = detachKey === undefined, prefixTable = `${viewer}${PREFIX_TABLE_SUFFIX}`;
211
+ let prefixed = false;
119
212
  const cleanup = () => {
120
213
  try { run(["kill-session", "-t", `=${viewer}`]); } catch { /* already detached/ended */ }
121
214
  // A key table belongs to the tmux server and outlives the session; tmux drops it with its
122
215
  // last binding.
123
- if (table !== LOCKED_TABLE) { try { run(["unbind-key", "-a", "-q", "-T", table]); } catch { /* the server is gone */ } }
216
+ try { run(["unbind-key", "-a", "-q", "-T", table]); } catch { /* the server is gone */ }
217
+ if (prefixed) { try { run(["unbind-key", "-a", "-q", "-T", prefixTable]); } catch { /* the server is gone */ } }
124
218
  };
125
219
  try {
126
220
  const placeholder = run(["new-session", "-d", "-s", viewer, "-P", "-F", "#{window_id}"]);
127
221
  if (!/^@\d+$/.test(placeholder)) throw new Error("tmux returned no viewer window id");
128
222
  run(["link-window", "-s", `=${target.session}:=${target.window}`, "-t", `=${viewer}:`]);
129
223
  run(["kill-window", "-t", placeholder]);
224
+ // The viewer shows every pane of the window; its client's keys go to the agent's pane, never to
225
+ // another one a split left behind (a forgotten no-echo prompt). A one-pane window is left alone.
226
+ if (agent.panes > 1) run(["select-pane", "-t", agent.paneId]);
130
227
  // One linked window prevents a stale viewer from selecting a sibling agent
131
228
  // when this agent retires. Disable window navigation in the viewer only.
132
229
  for (const name of ["prefix", "prefix2"]) run(["set-option", "-t", viewer, name, "None"]);
230
+ // One `tmux -V`: whether this tmux forwards a key after C-b (the C-b table and the line that
231
+ // names it), and whether its client takes `-T sync` (below).
232
+ const probe = probeTmux(exec, run);
233
+ prefixed = locked && probe.forwards;
133
234
  run(["set-option", "-t", viewer, "key-table", table]);
134
- // The viewer shows one agent; its status line only repeats that name.
135
- // Session-scoped on the temporary viewer: the agents' own session and
136
- // the operator's tmux settings are untouched.
137
- run(["set-option", "-t", viewer, "status", "off"]);
235
+ // The viewer shows one agent, so a status line would only repeat its name: a keyed viewer has
236
+ // none. The locked viewer's status line is its scroll keys, which a person can find nowhere
237
+ // else (#1502 part D); it takes the client's last row. Session-scoped on the temporary
238
+ // viewer: the agents' own session and the operator's tmux settings are untouched.
239
+ if (locked && statusLine) {
240
+ run(["set-option", "-t", viewer, "status", "on"]);
241
+ run(["set-option", "-t", viewer, "status-format[0]", prefixed ? VIEWER_SCROLL_HINT : VIEWER_SCROLL_HINT_WITHOUT_PREFIX]);
242
+ } else run(["set-option", "-t", viewer, "status", "off"]);
138
243
  // When the agent's window ends (a retire), the viewer has no window left and tmux destroys it.
139
244
  // The viewer's client must then leave, not be moved: under an operator's `detach-on-destroy off`
140
245
  // tmux would switch it to another session, another agent's terminal (#1237).
141
246
  run(["set-option", "-t", viewer, "detach-on-destroy", "on"]);
142
247
  run(["unbind-key", "-a", "-q", "-T", table]);
143
- for (const binding of MOUSE_BINDINGS) run(["bind-key", "-T", table, ...binding]);
144
- // The key is its own argv element, after the grammar admitted it.
145
- if (detachKey !== undefined) {
146
- run(["bind-key", "-T", table, detachKey, DETACH_BINDING]);
147
- // The table goes when the session does, however the session ended; no other index is touched.
148
- run(["set-hook", "-g", `session-closed[${VIEWER_CLOSED_HOOK_INDEX}]`, VIEWER_CLOSED_HOOK]);
248
+ for (const binding of VIEWER_BINDINGS) run(["bind-key", "-T", table, ...binding]);
249
+ if (prefixed) {
250
+ run(["bind-key", "-T", table, PREFIX_KEY, `switch-client -T ${prefixTable}`]);
251
+ run(["unbind-key", "-a", "-q", "-T", prefixTable]);
252
+ for (const binding of LOCKED_PREFIX_BINDINGS) run(["bind-key", "-T", prefixTable, ...binding]);
149
253
  }
254
+ // The key is its own argv element, after the grammar admitted it.
255
+ if (detachKey !== undefined) run(["bind-key", "-T", table, detachKey, DETACH_BINDING]);
256
+ // The tables go when the session does, however the session ended; no other index is touched.
257
+ run(["set-hook", "-g", `session-closed[${VIEWER_CLOSED_HOOK_INDEX}]`, VIEWER_CLOSED_HOOK]);
150
258
  run(["set-option", "-t", viewer, "mouse", "on"]);
151
259
  const env = { ...process.env }; delete env.TMUX;
152
260
  /** Whether the detach key's binding ran: it marks the viewer session before it detaches. A
@@ -162,12 +270,7 @@ export function prepareSessionViewer(target, { exec = execFileSync, detachKey }
162
270
  // one in two reads does not paint the half-drawn state (#1193). A terminal without the mode
163
271
  // ignores it. tmux before 3.2 has no -T, and a probe that fails leaves it out: never the
164
272
  // attach's failure.
165
- if (!clientFeatures.has(exec)) {
166
- let sync = false;
167
- try { sync = tmuxHasClientFeatures(run(["-V"])); } catch { /* no answer: today's client */ }
168
- clientFeatures.set(exec, sync);
169
- }
170
- const features = clientFeatures.get(exec) ? ["-T", "sync"] : [];
273
+ const features = probe.sync ? ["-T", "sync"] : [];
171
274
  // The client sets the viewer session's client-detached hook itself, after its attach succeeded
172
275
  // (a command chained after attach-session runs only then; a viewer whose client never attached
173
276
  // is the cleanup's, or the next attach's sweep's): when a client goes and none is left, the hook
@@ -183,11 +286,11 @@ export function prepareSessionViewer(target, { exec = execFileSync, detachKey }
183
286
  // (any command client) runs server_check_unattached, which destroys the session under it, and
184
287
  // the server's next loop dereferences the session's NULL curw: SIGSEGV, every agent's session
185
288
  // gone (#1336). client-detached fires only once the client has left the server's client list.
186
- // A keyed viewer's hook unbinds its table too: tmux runs no hook for what a hook's own commands
289
+ // The hook unbinds the viewer's tables too: tmux runs no hook for what a hook's own commands
187
290
  // cause, so the session-closed entry does not run for a session this kill-session ends. The
188
- // unbind comes first: a command list stops at a command that fails, as this kill-session does
291
+ // unbinds come first: a command list stops at a command that fails, as this kill-session does
189
292
  // when the session has already ended.
190
- const removal = table === LOCKED_TABLE ? `kill-session -t =${viewer}` : `unbind-key -a -q -T ${table} ; kill-session -t =${viewer}`;
293
+ const removal = `unbind-key -a -q -T ${table} ; ${prefixed ? `unbind-key -a -q -T ${prefixTable} ; ` : ""}kill-session -t =${viewer}`;
191
294
  const attach = ["attach-session", "-t", `=${viewer}`, ";", "set-hook", "-t", `=${viewer}:`, "client-detached", `if-shell -F '#{==:#{session_attached},0}' '${removal}'`];
192
295
  return { binary: "tmux", args: ["-u", "-S", target.socket, ...features, ...attach], env, cleanup, detached, session: viewer, swept };
193
296
  } catch (e) { cleanup(); throw e; }
@@ -209,7 +312,7 @@ function holdQuit() {
209
312
  /** Attach this terminal to a viewer of the target and answer the client's status, or
210
313
  * SESSION_DETACHED_EXIT when `detachKey` was given and ended the attach. `onSwept` is given what
211
314
  * the preparation swept, `{ sessions, tables }`, before the client starts. */
212
- export async function attachSessionTarget(target, { detachKey, onSwept } = {}) {
315
+ export async function attachSessionTarget(target, { detachKey, statusLine, onSwept } = {}) {
213
316
  if (detachKey !== undefined) { requireDetachKey(detachKey); holdQuit(); }
214
317
  // HUP, TERM and INT are held from before the viewer session exists until its cleanup has
215
318
  // finished: one that arrives in between, early or late, finds a listener and not the default
@@ -223,7 +326,7 @@ export async function attachSessionTarget(target, { detachKey, onSwept } = {}) {
223
326
  const signals = ["SIGHUP", "SIGTERM", "SIGINT"];
224
327
  for (const sig of signals) process.on(sig, stop);
225
328
  // A preparation that fails has already removed what it made.
226
- try { viewer = prepareSessionViewer(target, { detachKey }); }
329
+ try { viewer = prepareSessionViewer(target, { detachKey, statusLine }); }
227
330
  catch (e) { for (const sig of signals) process.removeListener(sig, stop); throw e; }
228
331
  // Until the client has exited, a QUIT stops the attach as the other signals do, with status 1.
229
332
  // Unless the key's binding has already run: then the client is on its way out, the QUIT is the
@@ -53,7 +53,8 @@ export async function composeSoulInstructions({ deployment, prepared, soulDir, c
53
53
  const bodyFile = join(soulDir, "AGENTS.md");
54
54
  if (!existsSync(bodyFile)) throw fail("E_SOUL_INCOMPLETE", `soul "${soulName}" has no canonical AGENTS.md (${bodyFile})`);
55
55
  // The work mode and kind as a spawn with no flags derives them (spawnInstance: o.work || agent.work || "checkout").
56
- composition = composeInstanceAgentsMd(soulDir, deployment, agent.name, agent.work || "checkout", agent.kind, prepared);
56
+ // Reported, never launched: the launch configurations stay out, so a broken one does not hide the instructions.
57
+ composition = composeInstanceAgentsMd(soulDir, deployment, agent.name, agent.work || "checkout", agent.kind, prepared, { launchConfigs: false });
57
58
  body = readFileSync(bodyFile, "utf8");
58
59
  } catch (e) {
59
60
  if (systemError(e)) throw fail("E_SOUL_INCOMPLETE", `soul "${soulName}" cannot be read here: ${e.message}`, { cause: e.code });
@@ -0,0 +1,110 @@
1
+ /** What a start's launch environment was (feature session-resume, #1559): the record that lets a
2
+ * resume refuse to start under a `fromEnv` value that changed since the start it brings back.
3
+ * Kernel-private files in the home, not a contract:
4
+ * - `.oats-start-env.key`: 32 random bytes, mode 0600, made once, at the first start that records.
5
+ * It never leaves the home: never logged, answered or put in an event.
6
+ * - `.oats-start-env.json`: `{ startId, digests: { <fromEnv source name>: <hex HMAC-SHA256(key,
7
+ * value)> } }`, written whole (tmp + rename) at every start that renders a recipe, for that
8
+ * start's id; `digests` is `{}` for a launch with no reference. A value is never written: a
9
+ * `fromEnv` value may be a credential, and only its keyed one-way digest is kept.
10
+ * The record is best effort: a write that fails leaves the previous record (for another start) or
11
+ * none, which a resume reads as unverified. A retire's recovery copy of the home leaves both out
12
+ * (lib/core.mjs copyRecoveryHome). Dependency-free: the start, the spawn and the sweep's
13
+ * `--plan` read and write it through here. */
14
+ import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
15
+ import { readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
16
+ import { join } from "node:path";
17
+
18
+ export const START_ENV_FILE = ".oats-start-env.json";
19
+ export const START_ENV_KEY_FILE = ".oats-start-env.key";
20
+ /** A temporary file of either, left by a write that was cut short. */
21
+ export const START_ENV_TMP = /^\.oats-start-env\.(json|key)\.tmp-.+$/;
22
+ const KEY_BYTES = 32;
23
+ const RECORD_MAX = 64 * 1024;
24
+ const DIGEST = /^[0-9a-f]{64}$/;
25
+
26
+ /** The source names of a recipe's `{fromEnv}` references, sorted, each once. */
27
+ export function fromEnvNames(recipeEnv) {
28
+ return [...new Set(Object.values(recipeEnv || {}).filter((v) => v && typeof v === "object" && typeof v.fromEnv === "string" && v.fromEnv).map((v) => v.fromEnv))].sort();
29
+ }
30
+
31
+ /** The message of a resume refused for references that are not set (E_LAUNCH_ENV_MISSING). */
32
+ export function launchEnvMissingMessage(names) {
33
+ return `this home's launch references ${names.join(", ")}, not set on this host; nothing was started`;
34
+ }
35
+ /** The message of a resume refused for a changed value (E_LAUNCH_ENV_CHANGED): names only, sorted. */
36
+ export function launchEnvChangedMessage(names) {
37
+ return `this home's launch environment changed since its last start (${[...names].sort().join(", ")}); nothing was started: start it yourself to use the new values`;
38
+ }
39
+ /** The warning of a resume whose launch environment has no record to check against. */
40
+ export function launchEnvUnverifiedWarning(instance) {
41
+ return `${instance}'s launch environment could not be verified this once (it was last started before OATS recorded it); its next start records it`;
42
+ }
43
+
44
+ /** The home's key, or null when there is none, it cannot be read, or it is not 32 bytes. */
45
+ function readKey(home) {
46
+ try {
47
+ const key = readFileSync(join(home, START_ENV_KEY_FILE));
48
+ return key.length === KEY_BYTES ? key : null;
49
+ } catch { return null; }
50
+ }
51
+ const digestOf = (key, value) => createHmac("sha256", key).update(String(value), "utf8").digest("hex");
52
+
53
+ /** `bytes` to `path` through a new temporary file beside it (O_EXCL, mode 0600), then renamed over
54
+ * it: the file is either the old one or the whole new one. */
55
+ function writeWhole(path, bytes) {
56
+ const tmp = `${path}.tmp-${process.pid}-${randomBytes(6).toString("hex")}`;
57
+ try {
58
+ writeFileSync(tmp, bytes, { mode: 0o600, flag: "wx" });
59
+ renameSync(tmp, path);
60
+ } catch (e) {
61
+ try { rmSync(tmp, { force: true }); } catch { /* the failure is the one to report */ }
62
+ throw e;
63
+ }
64
+ }
65
+
66
+ /** Record the launch environment of start `startId` of `home`: the digest of each of `names` (source
67
+ * names, fromEnvNames) as `env` holds it. A home without a usable key gets a new one first, and its
68
+ * old record goes before the key is replaced, so no record is ever read with a key it was not made
69
+ * with. Never throws: → true when the record was written. */
70
+ export function recordStartEnv(home, startId, names, env) {
71
+ try {
72
+ let key = readKey(home);
73
+ if (!key) {
74
+ rmSync(join(home, START_ENV_FILE), { force: true });
75
+ key = randomBytes(KEY_BYTES);
76
+ writeWhole(join(home, START_ENV_KEY_FILE), key);
77
+ }
78
+ // No prototype: every valid source name, `__proto__` included, is an entry of its own.
79
+ const digests = Object.create(null);
80
+ for (const name of names) if (env[name] !== undefined) digests[name] = digestOf(key, env[name]);
81
+ writeWhole(join(home, START_ENV_FILE), JSON.stringify({ startId, digests }, null, 2) + "\n");
82
+ return true;
83
+ } catch { return false; }
84
+ }
85
+
86
+ /** Whether `env` gives `names` (the references of the launch a resume runs) the values start
87
+ * `startId` of `home` recorded. Reads only: it never makes a key or a record. → `{ ok: true }`;
88
+ * `{ changed: [names] }`, sorted: a name whose value differs, is now unset, or is on one side only;
89
+ * or `{ unverified: true }`: no record, a record of another start, one that does not read, or no
90
+ * usable key. Never throws. */
91
+ export function checkStartEnv(home, startId, names, env) {
92
+ let record;
93
+ try {
94
+ const text = readFileSync(join(home, START_ENV_FILE));
95
+ if (text.length > RECORD_MAX) return { unverified: true };
96
+ record = JSON.parse(text.toString("utf8"));
97
+ } catch { return { unverified: true }; }
98
+ if (!record || typeof record !== "object" || Array.isArray(record) || typeof record.startId !== "string" || !record.startId || record.startId !== startId) return { unverified: true };
99
+ const digests = record.digests;
100
+ if (!digests || typeof digests !== "object" || Array.isArray(digests) || Object.values(digests).some((d) => typeof d !== "string" || !DIGEST.test(d))) return { unverified: true };
101
+ const key = readKey(home);
102
+ if (!key) return { unverified: true };
103
+ const changed = [];
104
+ for (const name of new Set([...Object.keys(digests), ...names])) {
105
+ if (!Object.hasOwn(digests, name) || !names.includes(name) || env[name] === undefined) { changed.push(name); continue; }
106
+ const now = Buffer.from(digestOf(key, env[name]), "hex"), then = Buffer.from(digests[name], "hex");
107
+ if (!timingSafeEqual(now, then)) changed.push(name);
108
+ }
109
+ return changed.length ? { changed: changed.sort() } : { ok: true };
110
+ }
@@ -1,11 +1,17 @@
1
- /** Whether the OATS tmux server starts in a systemd scope of its own (awebai/oats#915).
2
- * A server started by a process inside a systemd service lives in that service's cgroup and dies
3
- * when the unit stops: the schedule tick's oneshot, or a Desktop run as a user service. On Linux,
4
- * from inside a service, on the unified cgroup hierarchy, the server's start runs under
5
- * `systemd-run --user --scope`: the server is then a sibling of the service, not part of it.
6
- * Everything else starts the server as before. */
1
+ /** Where the OATS tmux server and the agents' harnesses run on a systemd host (awebai/oats#915).
2
+ * systemd-oomd ends a whole cgroup under memory pressure, and a unit's stop ends its cgroup: a
3
+ * server started inside a unit of the user manager (the schedule tick's oneshot, a Desktop run as a
4
+ * user service, a client launched from a desktop session in its `app-*.scope`) would share that
5
+ * unit's fate. On Linux, on the unified cgroup hierarchy, from inside a service, or a scope of the
6
+ * user manager, the server's start runs under `systemd-run --user --scope`: the server is then a
7
+ * sibling of that unit, not part of it. Each agent's harness, wherever the server runs, is launched
8
+ * in a scope of its own too (agentScope), so that such a kill ends one agent and never the server
9
+ * or the others. Everything else starts as before. */
10
+ import { execFileSync } from "node:child_process";
7
11
  import { createHash, randomBytes } from "node:crypto";
8
- import { readFileSync } from "node:fs";
12
+ import { readFileSync, statSync } from "node:fs";
13
+ import { canonicalHomePath } from "./real-path.mjs";
14
+ import { systemTool } from "./system-tools.mjs";
9
15
 
10
16
  const HIERARCHY = "the cgroup hierarchy is not the unified one, so there is no unified cgroup path to judge";
11
17
  /** The last component of an absolute cgroup path, when it names a systemd service. */
@@ -14,15 +20,27 @@ function serviceOf(path) {
14
20
  const last = path.split("/").pop();
15
21
  return last.endsWith(".service") ? last : null;
16
22
  }
23
+ /** The user manager's own unit, as a cgroup path component. */
24
+ const USER_MANAGER = /^user@\d+\.service$/;
25
+ /** The unit a unified cgroup path's last component names, when a server started there is to leave
26
+ * it: a service, system or user (as #915 began), or a scope under the user manager (a desktop
27
+ * application's or a terminal's `app-*.scope`, an agent's `oats-agent-*.scope`, the manager's own
28
+ * `init.scope`). A login session's `session-N.scope` sits beside the user manager, not in it: not one. */
29
+ function unitOf(path) {
30
+ const service = serviceOf(path);
31
+ if (service || typeof path !== "string" || !path.startsWith("/")) return service;
32
+ const parts = path.split("/"), last = parts.pop();
33
+ return last.endsWith(".scope") && parts.some((part) => USER_MANAGER.test(part)) ? last : null;
34
+ }
17
35
 
18
- /** → { wrap: true, unit } (inside `unit`, start the server in its own scope), { wrap: false }, or
19
- * { wrap: false, warn: { unit, reason } } (inside a service, known only from INVOCATION_ID, on a
36
+ /** → { wrap: true, unit } (inside `unit`, start the server in its own scope: unitOf), { wrap: false },
37
+ * or { wrap: false, warn: { unit, reason } } (inside a service, known only from INVOCATION_ID, on a
20
38
  * hierarchy this cannot judge). `cgroup` is the text of /proc/self/cgroup, null when unreadable. */
21
39
  export function serverScopePlan({ platform, cgroup, invocationId }) {
22
40
  if (platform !== "linux" || typeof cgroup !== "string") return { wrap: false };
23
41
  const lines = cgroup.split("\n").filter(Boolean);
24
42
  if (lines.length === 1 && lines[0].startsWith("0::") && lines[0].slice(3).startsWith("/")) {
25
- const unit = serviceOf(lines[0].slice(3));
43
+ const unit = unitOf(lines[0].slice(3));
26
44
  return unit ? { wrap: true, unit } : { wrap: false };
27
45
  }
28
46
  if (!invocationId) return { wrap: false };
@@ -31,9 +49,12 @@ export function serverScopePlan({ platform, cgroup, invocationId }) {
31
49
  return { wrap: false, warn: { unit: named || "a systemd service", reason: HIERARCHY } };
32
50
  }
33
51
 
34
- /** Where the creator runs → { platform, cgroup, invocationId }: `io`'s when it says, else for a test only
35
- * OATS_TEST_CGROUP (the text of a /proc/self/cgroup, judged as Linux), else this process's own (null
36
- * cgroup when it cannot be read, or off Linux). */
52
+ /** Where the creator runs → { platform, cgroup, invocationId, systemdBooted }: `io`'s when it says, else
53
+ * for a test only OATS_TEST_CGROUP (the text of a /proc/self/cgroup, judged as Linux), else this
54
+ * process's own (null cgroup when it cannot be read, or off Linux). `systemdBooted` is sd_booted's
55
+ * answer (/run/systemd/system is a directory); for a test, io.systemdBooted or OATS_TEST_SYSTEMD_BOOTED
56
+ * ("1" or "0"), and a test's placement (io.cgroup, OATS_TEST_CGROUP) is a systemd host's unless one of
57
+ * those says otherwise. */
37
58
  export function creatorPlacement(io) {
38
59
  const seam = process.env.OATS_TEST_CGROUP;
39
60
  const platform = io?.platform ?? (seam !== undefined ? "linux" : process.platform);
@@ -44,7 +65,16 @@ export function creatorPlacement(io) {
44
65
  else cgroup = null;
45
66
  }
46
67
  const invocationId = io && "invocationId" in io ? io.invocationId : process.env.INVOCATION_ID;
47
- return { platform, cgroup, invocationId };
68
+ const booted = process.env.OATS_TEST_SYSTEMD_BOOTED;
69
+ const systemdBooted = typeof io?.systemdBooted === "boolean" ? io.systemdBooted
70
+ : booted !== undefined ? booted === "1"
71
+ : seam !== undefined || io?.cgroup !== undefined ? true // a test's placement: a systemd host's
72
+ : platform === "linux" && sdBooted();
73
+ return { platform, cgroup, invocationId, systemdBooted };
74
+ }
75
+ /** sd_booted(3): whether this host was booted with systemd as its init. */
76
+ function sdBooted() {
77
+ try { return statSync("/run/systemd/system").isDirectory(); } catch { return false; }
48
78
  }
49
79
 
50
80
  /** The scope's name, one per start that starts the server: a prefix per server address (the socket
@@ -60,3 +90,98 @@ export function serverScopeUnit({ socket, env }) {
60
90
  export function serverScopeWarning({ unit, reason }) {
61
91
  return `the OATS tmux server was started inside ${unit}: it ends when that unit stops; start the OATS tmux server from your own shell, or enable the user systemd bus (${reason})`;
62
92
  }
93
+
94
+ // ---- the agent's scope ------------------------------------------------------------------------------
95
+
96
+ /** Whether a creator judged at `placement` (creatorPlacement) launches agents' harnesses in scopes of
97
+ * their own: Linux booted with systemd, on the unified hierarchy, whatever unit the creator is in or
98
+ * not in (the harness is the server's child, wherever the server is). A host without systemd (a
99
+ * container's own init, another init system) has no user manager and no systemd-oomd: nothing to
100
+ * keep an agent out of, so nothing is wrapped and nothing said, as off Linux. */
101
+ export function agentScopeHost({ platform, cgroup, systemdBooted }) {
102
+ if (platform !== "linux" || !systemdBooted || typeof cgroup !== "string") return false;
103
+ const lines = cgroup.split("\n").filter(Boolean);
104
+ return lines.length === 1 && lines[0].startsWith("0::/");
105
+ }
106
+
107
+ /** An agent's scope name, one per launch: a prefix per home (the first 12 hex of the sha256 of its
108
+ * canonical path) and a random part. A scope ends with its last process, so a later launch of the
109
+ * same home never reuses its name (as serverScopeUnit). */
110
+ export function agentScopeUnit({ home }) {
111
+ return `oats-agent-${createHash("sha256").update(canonicalHomePath(home)).digest("hex").slice(0, 12)}-${randomBytes(4).toString("hex")}`;
112
+ }
113
+
114
+ /** The names `systemd-run --user` finds the user manager by: the session bus, else the runtime
115
+ * directory's bus and the manager's private socket. The probe runs with the pane's values of these
116
+ * and no others. */
117
+ export const SCOPE_ENV_NAMES = Object.freeze(["XDG_RUNTIME_DIR", "DBUS_SESSION_BUS_ADDRESS"]);
118
+ const PROBE_TIMEOUT_MS = 5000;
119
+ const PROBE_ARGS = Object.freeze(["--user", "--scope", "--collect", "--quiet", "--"]);
120
+ /** The real probe: a scope around the system's `true`, run with `env` → { ok: true } | { reason }. */
121
+ function runScopeProbe({ systemdRun, trueFile, env }) {
122
+ try {
123
+ execFileSync(systemdRun, [...PROBE_ARGS, trueFile], { env, timeout: PROBE_TIMEOUT_MS, stdio: ["ignore", "ignore", "pipe"], encoding: "utf8" });
124
+ return { ok: true };
125
+ } catch (e) {
126
+ if (e?.code === "ETIMEDOUT" || (e?.signal && e?.status == null)) return { reason: `it did not answer within ${PROBE_TIMEOUT_MS / 1000} s` };
127
+ return { reason: String(e?.stderr ?? "").trim().split("\n")[0] || (Number.isInteger(e?.status) ? `exit ${e.status}` : String(e?.message || "failed")) };
128
+ }
129
+ }
130
+ /** The probes' answers, per probe (the real one, or a test's io.scopeProbe), per systemd-run and the
131
+ * pane's SCOPE_ENV_NAMES: one probe per kernel process for each, so a sweep of many starts probes once. */
132
+ const probed = new WeakMap();
133
+ function probeOnce(probe, { systemdRun, trueFile, env }) {
134
+ let answers = probed.get(probe);
135
+ if (!answers) probed.set(probe, answers = new Map());
136
+ const key = JSON.stringify([systemdRun, ...SCOPE_ENV_NAMES.map((name) => env[name] ?? null)]);
137
+ if (!answers.has(key)) answers.set(key, probe({ systemdRun, trueFile, env: { ...env } }));
138
+ return answers.get(key);
139
+ }
140
+
141
+ /**
142
+ * Whether this launch's harness runs in a scope of its own → { wrapper: { systemdRun, env } } (the
143
+ * system's systemd-run and env, absolute: agentScopeArgv), { warning } (a systemd host where it runs in
144
+ * the server's cgroup, and why), or {} (a host where nothing changes: off Linux, not booted with
145
+ * systemd, a cgroup hierarchy other than the unified one; nothing said). `paneEnv()` gives the pane's SCOPE_ENV_NAMES as { env } (a name it does not set
146
+ * is not in `env`) or { reason } (they cannot be read); it is called only on a host that wraps.
147
+ * The probe is the guard: the launch is wrapped only once `systemd-run --user --scope` has started a
148
+ * scope with the pane's own environment. `io` is a test's: its placement (creatorPlacement, with
149
+ * io.systemdBooted), its
150
+ * system directories (io.systemToolDirs) and its probe (io.scopeProbe, given what the real probe is
151
+ * given). An `io` without a scopeProbe judges no scope at all: its tmux is a test's, and the host's
152
+ * user manager is never reached unless a test opts in.
153
+ */
154
+ export function agentScope({ io, paneEnv }) {
155
+ if (!agentScopeHost(creatorPlacement(io))) return {};
156
+ const probe = io ? io.scopeProbe : runScopeProbe;
157
+ if (!probe) return {};
158
+ const unscoped = (reason) => ({ warning: agentScopeWarning(reason) });
159
+ const where = io?.systemToolDirs ? { dirs: io.systemToolDirs } : {};
160
+ const systemdRun = systemTool("systemd-run", where), clean = systemTool("env", where), trueFile = systemTool("true", where);
161
+ const missing = systemdRun.reason ?? clean.reason ?? trueFile.reason;
162
+ if (missing) return unscoped(missing);
163
+ const pane = paneEnv();
164
+ if (pane.reason) return unscoped(pane.reason);
165
+ const answer = probeOnce(probe, { systemdRun: systemdRun.file, trueFile: trueFile.file, env: pane.env });
166
+ if (!answer?.ok) return unscoped(`\`systemd-run --user --scope\` could not start a scope in the pane's environment: ${answer?.reason || "the probe failed"}`);
167
+ return { wrapper: { systemdRun: systemdRun.file, env: clean.file } };
168
+ }
169
+
170
+ /** The words before the harness's own `/bin/sh -c` that run it in a scope named `unit` (agentScopeUnit):
171
+ * systemd-run execs the system's env, which execs what follows with INVOCATION_ID removed (the
172
+ * scope's own, which systemd-run exports to what it runs, as for the server). The process keeps its
173
+ * pid through each exec, so the harness stays the pane's direct child and its exit status is the
174
+ * pane shell's to read. */
175
+ export function agentScopeArgv({ systemdRun, env }, unit) {
176
+ return [systemdRun, "--user", "--scope", "--collect", "--quiet", "--unit", unit, "--", env, "-u", "INVOCATION_ID"];
177
+ }
178
+
179
+ /** The answer's warning when the harness runs in the server's cgroup. */
180
+ const AGENT_SCOPE_PREFIX = "the agent's harness runs in the OATS tmux server's cgroup, not a scope of its own: ";
181
+ export function agentScopeWarning(reason) {
182
+ return `${AGENT_SCOPE_PREFIX}${reason}`;
183
+ }
184
+ /** Whether a warning is agentScopeWarning's: said of the host, not of the one launch that met it. */
185
+ export function isAgentScopeWarning(text) {
186
+ return typeof text === "string" && text.startsWith(AGENT_SCOPE_PREFIX);
187
+ }