@awebai/oats 0.68.1 → 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 (67) 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 +108 -10
  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.69.0.md +658 -0
  15. package/docs/release-notes/v0.69.1.md +25 -0
  16. package/docs/servers.md +44 -5
  17. package/docs/souls-and-instances.md +11 -7
  18. package/docs/tui.md +77 -12
  19. package/docs/upgrading.md +12 -7
  20. package/docs/workspaces.md +1 -1
  21. package/lib/core.mjs +345 -89
  22. package/lib/file-pieces.mjs +49 -0
  23. package/lib/instance-events.mjs +25 -4
  24. package/lib/launch-prompt-fixtures/README.md +62 -0
  25. package/lib/launch-prompt-fixtures/resume-confirmation.json +32 -0
  26. package/lib/launch-prompt-fixtures.mjs +49 -0
  27. package/lib/launch-prompt-resume.mjs +55 -0
  28. package/lib/login-environment.mjs +27 -9
  29. package/lib/schedule.mjs +3 -3
  30. package/lib/servers.mjs +117 -23
  31. package/lib/session-end.mjs +82 -0
  32. package/lib/session-input.mjs +43 -9
  33. package/lib/session-resume-contract.mjs +32 -0
  34. package/lib/session-resume.mjs +310 -0
  35. package/lib/session-seen.mjs +163 -0
  36. package/lib/session-viewer.mjs +147 -44
  37. package/lib/soul-composition.mjs +2 -1
  38. package/lib/start-env.mjs +110 -0
  39. package/lib/tmux-server-scope.mjs +139 -14
  40. package/lib/workspace.mjs +38 -4
  41. package/package-catalog.json +10 -4
  42. package/package.json +1 -1
  43. package/packages/client/cli-adapter.mjs +9 -0
  44. package/packages/client/cli-locator.mjs +3 -2
  45. package/packages/client/deployment-data.mjs +7 -0
  46. package/packages/client/deployment-panel.mjs +3 -0
  47. package/packages/client/file-output-exec.mjs +98 -0
  48. package/packages/client/launch-prompt-outcome.mjs +25 -13
  49. package/packages/client/own-codes.mjs +2 -0
  50. package/packages/client/session-attach.mjs +35 -5
  51. package/packages/client/session-resume-cli.mjs +64 -0
  52. package/packages/client/session-resume-trigger.mjs +167 -0
  53. package/packages/client/session-resume.mjs +332 -0
  54. package/packages/client/tmux-status.mjs +30 -7
  55. package/packages/client/waiting-on-you.mjs +11 -4
  56. package/packages/client/workspace-step.mjs +17 -5
  57. package/packages/record/lib/last-conversation.mjs +123 -0
  58. package/packages/record/lib/session-roots.mjs +10 -1
  59. package/packages/tui/lib/client.mjs +1 -1
  60. package/packages/tui/lib/main.mjs +5 -3
  61. package/packages/tui/lib/model.mjs +45 -12
  62. package/packages/tui/lib/store.mjs +8 -7
  63. package/packages/tui/lib/term/text.mjs +12 -9
  64. package/packages/tui/lib/views/frame.mjs +72 -7
  65. package/packages/tui/lib/views/help.mjs +8 -3
  66. package/packages/tui/lib/views/instances.mjs +3 -2
  67. package/skills/oats-getting-started/SKILL.md +117 -4
package/lib/servers.mjs CHANGED
@@ -17,7 +17,7 @@
17
17
  */
18
18
 
19
19
  import { execFile, execFileSync, spawnSync } from "node:child_process";
20
- import { createHash } from "node:crypto";
20
+ import { createHash, randomBytes } from "node:crypto";
21
21
  import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
22
22
  import { homedir } from "node:os";
23
23
  import { basename, join, resolve } from "node:path";
@@ -29,6 +29,7 @@ import { paletteColor } from "./instance-color.mjs";
29
29
  import { withDirLock } from "./dir-lock.mjs";
30
30
  import { shellWord } from "./core.mjs";
31
31
  import { DETACH_KEY_FEATURE, requireDetachKey } from "./session-viewer.mjs";
32
+ import { LOGIN_CAPTURE_MAX_BYTES, LOGIN_SHELLS, loginPathEmitter, quoteFor, readLoginFrame } from "./login-environment.mjs";
32
33
 
33
34
  const OATS_HOME_DIR = () => process.env.OATS_HOME_DIR || join(homedir(), ".oats");
34
35
  export const SERVERS_FILE = () => join(OATS_HOME_DIR(), "servers.json");
@@ -268,6 +269,12 @@ export function sshArgv(target, oatsArgs, { cwd, control = false } = {}) {
268
269
  // Sharing is on only when the caller checked the control directory
269
270
  // (controlUsable); otherwise ControlPath=none.
270
271
  const cmd = (cwd ? `cd ${remoteQuote(cwd)} && ` : "") + prefix + [target.oatsPath, ...oatsArgs].map(remoteQuote).join(" ");
272
+ return sshLineArgv(target, cmd, { control });
273
+ }
274
+
275
+ /** argv for the local ssh process that hands one command line, as it is, to the host user's login
276
+ * shell: the caller has quoted every word of it for that shell. */
277
+ function sshLineArgv(target, cmd, { control = false } = {}) {
271
278
  return ["ssh", ...SSH_OPTS, ...(control && !controlPathProblem() ? controlOpts() : NO_CONTROL_OPTS), "--", target.sshHost, cmd];
272
279
  }
273
280
 
@@ -912,6 +919,15 @@ export function hostFeatures(result) {
912
919
  }
913
920
  return [...list];
914
921
  }
922
+ /** The host's viewer fact from its `status --json` result (feature session-attach-prefix-scroll,
923
+ * lib/session-viewer.mjs readSessionViewer), or null when unknown. Untrusted, like the features:
924
+ * relayed as a copy of `{ prefixScroll }` only when that is a boolean; anything else, or a host
925
+ * whose kernel predates the field, is null. */
926
+ export function hostSessionViewer(result) {
927
+ const viewer = result && typeof result === "object" ? result.sessionViewer : undefined;
928
+ if (!viewer || typeof viewer !== "object" || Array.isArray(viewer) || typeof viewer.prefixScroll !== "boolean") return null;
929
+ return { prefixScroll: viewer.prefixScroll };
930
+ }
915
931
 
916
932
  /** `workspaceKeys` (feature roster-workspace-key): when given, only the groups that can belong to
917
933
  * one of those workspaces are probed and returned. A group is judged by its registration: kept
@@ -964,9 +980,10 @@ export async function rosterGroups({ server, workspaceKeys, io = {} } = {}) {
964
980
  // A success envelope whose result is null or missing reads as an empty answer, never a crash
965
981
  // that would sink every other group.
966
982
  const result = status.result ?? {};
967
- // The host's own kernel features (feature server-probe-features), relayed from the same status
968
- // answer, never probed: null when the host does not report a valid list.
969
- g.probe = { ok: true, features: hostFeatures(result) };
983
+ // The host's own kernel features (feature server-probe-features) and its viewer fact (feature
984
+ // session-attach-prefix-scroll), relayed from the same status answer, never probed: null when
985
+ // the host does not report a valid one.
986
+ g.probe = { ok: true, features: hostFeatures(result), sessionViewer: hostSessionViewer(result) };
970
987
  g.agentsRoot = result.root;
971
988
  // The host's own workspace identity (feature workspace-identity), relayed as it answered it: never
972
989
  // derived here, null when the host reports none.
@@ -1267,7 +1284,7 @@ export function scheduleRemote(serverId, oatsArgs, io = {}) {
1267
1284
  return { envelope: envelope.ok ? { ...envelope, result: { ...envelope.result, server: serverId } } : envelope, stderr, target };
1268
1285
  }
1269
1286
 
1270
- export function attachArgv(serverId, { instance, home, detachKey } = {}, io = {}) {
1287
+ export function attachArgv(serverId, { instance, home, detachKey, statusLine = true } = {}, io = {}) {
1271
1288
  io = { ...io, serverId };
1272
1289
  const keyed = detachKey !== undefined;
1273
1290
  // A detach key is checked before anything is asked of the host.
@@ -1284,7 +1301,8 @@ export function attachArgv(serverId, { instance, home, detachKey } = {}, io = {}
1284
1301
  const { target, home: remoteHome } = resolveRoute(serverId, { instance, home }, "session attach", keyed ? { ...io, beforeRoster: requireDetachKeyRemote } : io);
1285
1302
  if (keyed) requireDetachKeyRemote(target);
1286
1303
  if (!io.skipVersionCheck) requireSessionRemote(target, io, remoteHome);
1287
- const [bin, ...rest] = sshArgv(target, ["session", "attach", "--home", remoteHome, ...(detachKey !== undefined ? ["--detach-key", detachKey] : [])], { control: controlUsable(target, io) });
1304
+ // --no-status-line asks for no probe: a host that does not know it ignores it, and shows its line.
1305
+ const [bin, ...rest] = sshArgv(target, ["session", "attach", "--home", remoteHome, ...(detachKey !== undefined ? ["--detach-key", detachKey] : []), ...(statusLine ? [] : ["--no-status-line"])], { control: controlUsable(target, io) });
1288
1306
  // -t: allocate a PTY; placed before `--` with the other ssh options.
1289
1307
  return { argv: [bin, "-t", ...rest], target, home: remoteHome };
1290
1308
  }
@@ -1305,14 +1323,67 @@ const INSTALL_TIMEOUT_MS = 600000;
1305
1323
  /** One host command that is not the oats CLI (`true`, `npm`): its exit status and output, never an
1306
1324
  * envelope. The registration's --path applies as for oats; stdin is closed. */
1307
1325
  function runHostCommand(target, argv, io = {}) {
1326
+ return runSsh(sshArgv({ ...target, oatsPath: argv[0] }, argv.slice(1), { control: controlUsable(target, io) }), io);
1327
+ }
1328
+
1329
+ /** One ssh call, its stdin closed: `{ status, stdout, stderr }`, plus `timedOut` when `io.timeoutMs`
1330
+ * ended it and `overflow` when its stdout passed `io.maxBuffer`. `io.encoding` "buffer" keeps
1331
+ * stdout as bytes. */
1332
+ function runSsh([bin, ...rest], io = {}) {
1308
1333
  const exec = io.execFileSync || execFileSync;
1309
- const [bin, ...rest] = sshArgv({ ...target, oatsPath: argv[0] }, argv.slice(1), { control: controlUsable(target, io) });
1334
+ const encoding = io.encoding || "utf8";
1310
1335
  try {
1311
- return { status: 0, stdout: String(exec(bin, rest, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], maxBuffer: 16 * 1024 * 1024, timeout: io.timeoutMs || 300000 }) ?? ""), stderr: "" };
1336
+ const stdout = exec(bin, rest, { encoding, stdio: ["ignore", "pipe", "pipe"], maxBuffer: io.maxBuffer || 16 * 1024 * 1024, timeout: io.timeoutMs || 300000 });
1337
+ return { status: 0, stdout: encoding === "buffer" ? Buffer.from(stdout ?? "") : String(stdout ?? ""), stderr: "" };
1312
1338
  } catch (e) {
1313
- return { status: typeof e.status === "number" ? e.status : 255, stdout: String(e.stdout || ""), stderr: String(e.stderr ?? e.message ?? "") };
1339
+ return { status: typeof e.status === "number" ? e.status : 255, stdout: encoding === "buffer" ? Buffer.from(e.stdout || "") : String(e.stdout || ""), stderr: String(e.stderr ?? e.message ?? ""), ...(e.code === "ETIMEDOUT" ? { timedOut: true } : {}), ...(e.code === "ENOBUFS" ? { overflow: true } : {}) };
1314
1340
  }
1315
1341
  }
1342
+
1343
+ /** How long the host's login shell has to print its PATH, the ssh round trip included. */
1344
+ export const HOST_LOGIN_SHELL_TIMEOUT_MS = 15000;
1345
+ const SHELL_PATH_RE = /^\/[A-Za-z0-9._\/+-]+$/;
1346
+
1347
+ /**
1348
+ * The PATH the host user's own login shell sets up (lib/login-environment.mjs has the rules): the
1349
+ * shell is the host's $SHELL, which sshd sets from the host's password database; only bash, zsh or
1350
+ * fish, at an absolute path, is run, as `<shell> -l -i -c`, printing its PATH as one nonce frame,
1351
+ * within `io.loginShellTimeoutMs` and 1 MiB. → `{ path, shell }` (the PATH's absolute directories,
1352
+ * colon-separated, each once) or `{ failure }`, in words that hold no value but the shell's name.
1353
+ * ssh's own failure (exit 255) asking for the shell's name throws.
1354
+ */
1355
+ function readHostLoginPath(target, io) {
1356
+ const control = controlUsable(target, io);
1357
+ const asked = runSsh(sshLineArgv(target, `printf '%s\\n' "$SHELL"`, { control }), { ...io, timeoutMs: 60000 });
1358
+ if (asked.status === 255) throw sshFailed(target, asked);
1359
+ const shell = asked.stdout.replace(/\n$/, "");
1360
+ if (asked.status !== 0 || shell === "") return { failure: "ssh gave no SHELL" };
1361
+ if (!SHELL_PATH_RE.test(shell)) return { failure: "its SHELL is not an absolute path" };
1362
+ if (!LOGIN_SHELLS.includes(basename(shell))) return { failure: `its login shell (${basename(shell)}) is not bash, zsh or fish` };
1363
+ const timeoutMs = io.loginShellTimeoutMs || HOST_LOGIN_SHELL_TIMEOUT_MS;
1364
+ const nonce = randomBytes(16).toString("hex");
1365
+ const r = runSsh(sshLineArgv(target, `exec ${shell} -l -i -c ${quoteFor(shell)(loginPathEmitter(nonce))}`, { control }), { ...io, timeoutMs, maxBuffer: LOGIN_CAPTURE_MAX_BYTES, encoding: "buffer" });
1366
+ if (r.timedOut) return { failure: `its login shell did not answer within ${Math.round(timeoutMs / 1000)} s` };
1367
+ if (r.overflow) return { failure: "its answer was larger than 1 MiB" };
1368
+ if (r.status !== 0) return { failure: `its login shell exited with status ${r.status}` };
1369
+ const frame = readLoginFrame(r.stdout, nonce);
1370
+ if (frame.none) return { failure: "its login shell gave no answer" };
1371
+ if (frame.ambiguous) return { failure: "its answer was not exactly one complete frame" };
1372
+ let text;
1373
+ try { text = new TextDecoder("utf-8", { fatal: true }).decode(frame.data); } catch { text = null; }
1374
+ if (!text || /[\0\n\r]/.test(text)) return { failure: "its answer was not one PATH" };
1375
+ const dirs = [...new Set(text.split(":").filter((d) => d.startsWith("/")))];
1376
+ if (!dirs.length) return { failure: "its PATH holds no absolute directory" };
1377
+ return { path: dirs.join(":"), shell };
1378
+ }
1379
+
1380
+ /** Where the host's `name` is on the target's PATH, by `command -v` in sh: its absolute path, or null. */
1381
+ function hostCommandPath(target, name, io) {
1382
+ const r = runHostCommand(target, ["sh", "-c", `command -v ${name}`], { ...io, timeoutMs: 60000 });
1383
+ if (r.status === 255) throw sshFailed(target, r);
1384
+ const found = r.stdout.replace(/\n$/, "");
1385
+ return r.status === 0 && found.startsWith("/") && !/[\0\n\r]/.test(found) ? found : null;
1386
+ }
1316
1387
  const tail = (text) => String(text || "").trim().slice(-400) || "(no output)";
1317
1388
 
1318
1389
  /** A command a person copies out of a remedy: every argument quoted for a POSIX shell (remoteQuote),
@@ -1363,6 +1434,9 @@ export function connectServer(options, io = {}) {
1363
1434
  if (typeof dir !== "string" || !(dir === "~" || dir.startsWith("~/") || dir.startsWith("/"))) throw serverError("E_BAD_ARGS", `--dir must be an absolute path or ~/… on the host (got ${JSON.stringify(dir)})`);
1364
1435
  io = { ...io, serverId: id, input: undefined };
1365
1436
  const target = { sshHost, workspace: dir, oatsPath: oatsPath || "oats", ...(path ? { path } : {}) };
1437
+ // What this run found on the host for what was not given: the login shell's PATH, and oats on it.
1438
+ const found = {};
1439
+ let login = null;
1366
1440
  const steps = [], human = [];
1367
1441
  let blockedBy = null, check = null, reportedKey = null, registration = null, registeredAs = id;
1368
1442
 
@@ -1377,25 +1451,38 @@ export function connectServer(options, io = {}) {
1377
1451
  if (step.status === "failed") throw Object.assign(serverError(step.code, step.detail), { details: { ...(step.details || {}), steps } });
1378
1452
  };
1379
1453
 
1454
+ // Without --path, every later step runs with the PATH of the host user's own login shell.
1380
1455
  run("ssh", () => {
1381
1456
  const r = runHostCommand(target, ["true"], { ...io, timeoutMs: 60000 });
1382
1457
  if (r.status !== 0) throw sshFailed(target, r);
1383
- return { status: "ok" };
1458
+ if (path) return { status: "ok" };
1459
+ const read = readHostLoginPath(target, io);
1460
+ if (read.failure) return { status: "ok", detail: `could not read ${sshHost}'s login-shell PATH (${read.failure}); using ssh's own PATH` };
1461
+ login = read;
1462
+ target.path = found.path = read.path;
1463
+ return { status: "ok", detail: `PATH from ${sshHost}'s login shell (${basename(read.shell)} -l -i), used by every later step` };
1384
1464
  });
1385
1465
 
1386
1466
  // A kernel the rest of connect can use: this version or newer AND advertising server-connect (the
1387
1467
  // commands connect runs there); a build of the same version without them is not taken for one.
1388
1468
  run("oats", () => {
1389
- const found = probeHostOats(target, io);
1390
1469
  const older = (p) => compareSemver(p.version, localVersion) < 0;
1391
1470
  const usable = (p) => !!p.version && !older(p) && p.features.includes("server-connect");
1392
- if (usable(found)) return { status: "ok", detail: `oats ${found.version}${found.version === localVersion ? "" : ` (this kernel ${localVersion})`}` };
1471
+ // oats found on the login shell's PATH is recorded by its absolute path.
1472
+ const recordOats = () => { if (login && !oatsPath) { const at = hostCommandPath(target, "oats", io); if (at) target.oatsPath = found.oatsPath = at; } };
1473
+ const host = probeHostOats(target, io);
1474
+ if (usable(host)) { recordOats(); return { status: "ok", detail: `oats ${host.version}${host.version === localVersion ? "" : ` (this kernel ${localVersion})`}` }; }
1393
1475
  const npm = runHostCommand(target, ["npm", "--version"], { ...io, timeoutMs: 60000 });
1394
1476
  if (npm.status === 255) throw sshFailed(target, npm);
1395
- const what = !found.version ? `no oats at ${target.oatsPath} on ${sshHost}`
1396
- : older(found) ? `oats ${found.version} at ${target.oatsPath} is older than this kernel (${localVersion})`
1397
- : `oats ${found.version} at ${target.oatsPath} on ${sshHost} does not advertise server-connect, which connect needs there`;
1398
- if (npm.status !== 0) return { status: "needs-human", detail: `${what}, and no npm on its PATH`, remedy: `install Node.js 22+ (npm) on ${sshHost}, or pass --path <the directory holding npm>` };
1477
+ const what = !host.version ? `no oats at ${target.oatsPath} on ${sshHost}`
1478
+ : older(host) ? `oats ${host.version} at ${target.oatsPath} is older than this kernel (${localVersion})`
1479
+ : `oats ${host.version} at ${target.oatsPath} on ${sshHost} does not advertise server-connect, which connect needs there`;
1480
+ if (npm.status !== 0) {
1481
+ const searched = login ? `the PATH of ${sshHost}'s login shell (${basename(login.shell)} -l -i)` : path ? "--path and ssh's PATH" : "ssh's PATH";
1482
+ const where = login ? `so that its login shell finds it (there, ${runnable([login.shell, "-l", "-i", "-c", "command -v npm"])} prints its path)`
1483
+ : path ? "where --path or a non-interactive ssh command finds it" : "where a non-interactive ssh command finds it";
1484
+ return { status: "needs-human", detail: `${what}, and no npm on ${searched}`, remedy: `install Node.js 22+ (npm) on ${sshHost} ${where}, then check again (run the same connect); from the CLI, --path <the directory holding npm> names it instead` };
1485
+ }
1399
1486
  const install = ["npm", "install", "-g", `@awebai/oats@${localVersion}`];
1400
1487
  if (!installOats) return { status: "needs-human", detail: what, remedy: `on ${sshHost}: ${runnable(install)} (or pass --install-oats)` };
1401
1488
  const r = runHostCommand(target, install, { ...io, timeoutMs: INSTALL_TIMEOUT_MS });
@@ -1406,7 +1493,8 @@ export function connectServer(options, io = {}) {
1406
1493
  const still = !after.version ? "is still not found" : older(after) ? `still answers ${after.version}` : `still does not advertise server-connect (${after.version})`;
1407
1494
  throw serverError("E_REMOTE_INSTALL", `npm installed @awebai/oats@${localVersion} on ${sshHost}, but ${target.oatsPath} there ${still}; pass --oats <the installed oats> or --path <npm's global bin directory>`);
1408
1495
  }
1409
- const was = !found.version ? "was missing" : older(found) ? `was ${found.version}` : `was ${found.version} without server-connect`;
1496
+ recordOats();
1497
+ const was = !host.version ? "was missing" : older(host) ? `was ${host.version}` : `was ${host.version} without server-connect`;
1410
1498
  return { status: "done", detail: `installed @awebai/oats ${localVersion} (${was})` };
1411
1499
  });
1412
1500
 
@@ -1445,21 +1533,27 @@ export function connectServer(options, io = {}) {
1445
1533
  // another target is refused (or replaced), never quietly answered by a twin that serves this target.
1446
1534
  run("register", () => updateServers((servers) => {
1447
1535
  const abs = check.dir;
1448
- const entry = { sshHost, workspace: abs, ...(oatsPath ? { oatsPath } : {}), ...(path ? { path } : {}), ...(label ? { label } : {}), workspaceKey: reportedKey };
1536
+ const given = { ...(oatsPath ? { oatsPath } : {}), ...(path ? { path } : {}), ...(label ? { label } : {}) };
1537
+ const entry = { sshHost, workspace: abs, ...found, ...given, workspaceKey: reportedKey };
1449
1538
  const sameTarget = (s) => s.sshHost === sshHost && s.workspace === abs;
1450
- /** A registration of this very target: its key confirmed, or recorded; never contradicted. */
1539
+ /** A registration of this very target: its key confirmed, or recorded; never contradicted. What
1540
+ * this run found on the host fills only what it lacks. */
1451
1541
  const keep = (regId, detail) => {
1452
1542
  const existing = servers[regId];
1453
1543
  if (existing.workspaceKey && existing.workspaceKey !== reportedKey) throw workspaceMismatch(regId, existing, reportedKey);
1454
1544
  registeredAs = regId;
1455
1545
  registration = existing;
1456
- if (existing.workspaceKey) return { status: "ok", ...(detail ? { detail } : {}) };
1457
- existing.workspaceKey = reportedKey;
1458
- return { status: "done", detail: [detail, `recorded workspace ${reportedKey}`].filter(Boolean).join("; ") };
1546
+ const filled = Object.keys(found).filter((k) => existing[k] === undefined || existing[k] === null).sort();
1547
+ for (const k of filled) existing[k] = found[k];
1548
+ const keyed = !existing.workspaceKey;
1549
+ if (keyed) existing.workspaceKey = reportedKey;
1550
+ if (!filled.length && !keyed) return { status: "ok", ...(detail ? { detail } : {}) };
1551
+ return { status: "done", detail: [detail, filled.length ? `recorded ${filled.join(", ")}` : null, keyed ? `recorded workspace ${reportedKey}` : null].filter(Boolean).join("; ") };
1459
1552
  };
1460
1553
  const mine = servers[id];
1461
1554
  if (mine && sameTarget(mine)) {
1462
- const differ = ["oatsPath", "path", "label"].filter((k) => entry[k] !== undefined && entry[k] !== mine[k]);
1555
+ // A value given differs; one only found here differs only under --replace.
1556
+ const differ = ["oatsPath", "path", "label"].filter((k) => entry[k] !== undefined && entry[k] !== mine[k] && (Object.hasOwn(given, k) || replace));
1463
1557
  if (!differ.length || !replace) return keep(id, differ.length ? `${differ.join(", ")} differ from the registration and were not changed (--replace rewrites it)` : undefined);
1464
1558
  if (mine.workspaceKey && mine.workspaceKey !== reportedKey) throw workspaceMismatch(id, mine, reportedKey);
1465
1559
  servers[id] = entry; registration = entry;
@@ -0,0 +1,82 @@
1
+ /** How a launched home's last session ended (feature session-resume): `lost`, `stopped` or
2
+ * `exited`, derived from what the kernel already writes in the home. Kernel-private files, not a
3
+ * contract:
4
+ * - `.oats-start-exited`: the window a spawn or a start made writes it when the harness exits,
5
+ * `{"startId":"<id>","status":<n>}` (the harness's exit status). A kernel before 0.69 wrote the
6
+ * start id alone on one line, and only from a start's window.
7
+ * - `.oats-stop.json`: `oats instance stop` / `oats session stop`, `{ instance, at, stop, retained,
8
+ * startId }`; `startId` (0.69) is the start the stop ended, null when the home had none.
9
+ * A reboot or a killed tmux server leaves neither file for the start that was running: that is a
10
+ * lost session, the one a resume brings back. Dependency-free: status, start --resume and the
11
+ * schedule runner read the files through here. */
12
+ import { join } from "node:path";
13
+ import { readFileHead } from "./bounded-read.mjs";
14
+ import { SESSION_END } from "./session-resume-contract.mjs";
15
+
16
+ export const START_EXITED_FILE = ".oats-start-exited";
17
+ export const STOP_RECEIPT_FILE = ".oats-stop.json";
18
+ const RECORD_MAX = 64 * 1024;
19
+ /** A shell's exit status from 128 up is a signal's (128 + n): the harness was killed, not ended. */
20
+ const SIGNALLED = 128;
21
+
22
+ function readText(path) {
23
+ try {
24
+ const { bytes, size } = readFileHead(path, RECORD_MAX + 1);
25
+ return size > RECORD_MAX ? null : bytes.toString("utf8");
26
+ } catch { return null; }
27
+ }
28
+
29
+ /** The exit marker of `home` → `{ startId, status }` (status null for the legacy one-line form), or
30
+ * null when there is none or it reads as neither form. Never throws. */
31
+ export function readStartExited(home) {
32
+ const text = readText(join(home, START_EXITED_FILE));
33
+ if (text === null) return null;
34
+ const trimmed = text.trim();
35
+ if (trimmed.startsWith("{")) {
36
+ try {
37
+ const v = JSON.parse(trimmed);
38
+ if (!v || typeof v !== "object" || Array.isArray(v) || typeof v.startId !== "string" || !v.startId) return null;
39
+ return { startId: v.startId, status: Number.isInteger(v.status) && v.status >= 0 ? v.status : null };
40
+ } catch { return null; }
41
+ }
42
+ // A start id as a start's pending receipt accepts one.
43
+ return /^[a-zA-Z0-9-]{1,80}$/.test(trimmed) ? { startId: trimmed, status: null } : null;
44
+ }
45
+
46
+ /** The stop receipt of `home` (`.oats-stop.json`), or null. Never throws. */
47
+ export function readStopReceipt(home) {
48
+ const text = readText(join(home, STOP_RECEIPT_FILE));
49
+ if (text === null) return null;
50
+ try { const v = JSON.parse(text); return v && typeof v === "object" && !Array.isArray(v) ? v : null; } catch { return null; }
51
+ }
52
+
53
+ /** When the home's current start began: the last restart's `startedAt`, else the spawn's `createdAt`;
54
+ * as ms, or NaN when the record names neither. */
55
+ export function currentStartTime(meta) {
56
+ const restarts = Array.isArray(meta?.restarts) ? meta.restarts : [];
57
+ const last = restarts.length ? restarts[restarts.length - 1]?.startedAt : undefined;
58
+ return Date.parse(typeof last === "string" ? last : meta?.createdAt);
59
+ }
60
+
61
+ /** How the session of `meta`'s current start (`meta.startId`) ended, from the home's files alone:
62
+ * - `stopped`: the stop receipt names this start (`startId` equal), or, a receipt without a start
63
+ * id, was written after this start began;
64
+ * - `exited`: the exit marker names this start with a status below 128, or in its legacy form
65
+ * (no status: a kernel before 0.69 wrote it only when the harness ended on its own window);
66
+ * - `lost`: anything else — a marker with a signal's status (128 and up), or no file naming this
67
+ * start (the host went down, or the tmux server died, under a live harness).
68
+ * A home that records no start id (spawned before 0.69, never restarted) can be named by no marker:
69
+ * only a stop after its `createdAt` reads `stopped`, otherwise `lost` (the documented legacy gap).
70
+ * The caller reads it only for a launched home that does not run. */
71
+ export function sessionEndOf(home, meta) {
72
+ const startId = typeof meta?.startId === "string" && meta.startId ? meta.startId : null;
73
+ const since = currentStartTime(meta);
74
+ const stop = readStopReceipt(home);
75
+ if (stop) {
76
+ if (typeof stop.startId === "string" && stop.startId) { if (stop.startId === startId) return SESSION_END.STOPPED; }
77
+ else if (Date.parse(stop.at) > since) return SESSION_END.STOPPED;
78
+ }
79
+ const exited = startId ? readStartExited(home) : null;
80
+ if (exited && exited.startId === startId) return exited.status !== null && exited.status >= SIGNALLED ? SESSION_END.LOST : SESSION_END.EXITED;
81
+ return SESSION_END.LOST;
82
+ }
@@ -14,11 +14,35 @@ function tmux(target, args, { exec = execFileSync, input, timeout = 10000, killS
14
14
  stdio: ["pipe", "pipe", "pipe"],
15
15
  });
16
16
  }
17
+ /** The tmux pane option OATS sets on the agent's pane whenever it creates or respawns it, its value
18
+ * the instance's window name (the instance name). Internal: what OATS sets, not an API (#1569). */
19
+ export const AGENT_PANE_OPTION = "@oats-agent";
20
+ const paneNumber = (paneId) => Number(paneId.slice(1));
21
+ /** Which of a window's panes is the agent's (#1569), the one rule every reader applies (the client's
22
+ * tmux-status keeps a copy, held to this one by a parity test). `panes`: the window's panes, each
23
+ * `{ paneId: "%N", mark }` (`mark`: the pane's AGENT_PANE_OPTION, "" when unset; any other field is
24
+ * carried along); `name`: the instance's window name. One pane is the agent's, mark or not. Of
25
+ * several: the one marked with `name`; else, when none is, the unmarked pane with the lowest id
26
+ * (tmux's creation order: the window's own pane, before any split of it). A pane marked with another
27
+ * name is never the agent's. → `{ pane }` (the element itself, null for no panes), or `{ error }`
28
+ * when it cannot tell: the sentence every refusal and status's `runtimeError` carry. */
29
+ export function resolveAgentPane(panes, name) {
30
+ if (panes.length <= 1) return { pane: panes[0] ?? null };
31
+ const byId = [...panes].sort((a, b) => paneNumber(a.paneId) - paneNumber(b.paneId));
32
+ const ids = (list) => list.map((p) => p.paneId).join(", ");
33
+ const ours = byId.filter((p) => p.mark === name);
34
+ if (ours.length === 1) return { pane: ours[0] };
35
+ 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` };
36
+ const unmarked = byId.find((p) => !p.mark);
37
+ if (unmarked) return { pane: unmarked };
38
+ 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` };
39
+ }
17
40
  // Public inspection opts into window geometry; input and other session operations
18
41
  // retain their existing transport result and do not depend on size parsing.
19
- export function inspectSessionTarget(target, io, { includeSize = false } = {}) {
42
+ // `includePanes` adds `panes`, the window's pane count (the viewer selects the agent's pane in a split window).
43
+ export function inspectSessionTarget(target, io, { includeSize = false, includePanes = false } = {}) {
20
44
  const format = "#{pane_id}\t#{pane_dead}\t#{pane_current_command}\t#{pane_pid}"
21
- + (includeSize ? "\t#{window_width}\t#{window_height}" : "");
45
+ + (includeSize ? "\t#{window_width}\t#{window_height}" : "") + `\t#{${AGENT_PANE_OPTION}}`;
22
46
  let rows;
23
47
  try {
24
48
  const output = tmux(target, ["list-panes", "-t", `=${target.session}:=${target.window}`, "-F", format], io);
@@ -29,10 +53,14 @@ export function inspectSessionTarget(target, io, { includeSize = false } = {}) {
29
53
  if (/can't find (window|session)/i.test(String(e.stderr || ""))) return { backend: "tmux", present: false, state: "stopped" };
30
54
  throw e;
31
55
  }
32
- return createSessionPaneInspector(io)(rows, { includeSize });
56
+ const state = createSessionPaneInspector(io)(rows, { includeSize, name: target.window });
57
+ return includePanes ? { ...state, panes: rows.length } : state;
33
58
  }
34
- /** Interpret one window's panes with the lifecycle's shell/descendant rule. A status read shares
35
- * one inspector across windows so both successful and failed process scans cost one child. */
59
+ /** Interpret one window's panes: resolve the agent's pane (resolveAgentPane, `name` the window's
60
+ * instance name), then judge that pane alone with the lifecycle's shell/descendant rule; the other
61
+ * panes never make it unknown. Each row is `id, dead, command, pid[, cols, rows], mark` (the mark may
62
+ * be missing). A status read shares one inspector across windows so both successful and failed
63
+ * process scans cost one child. */
36
64
  export function createSessionPaneInspector(io) {
37
65
  let processRead;
38
66
  const readProcesses = () => {
@@ -47,11 +75,17 @@ export function createSessionPaneInspector(io) {
47
75
  if (processRead.error) throw processRead.error;
48
76
  return processRead.rows;
49
77
  };
50
- return (rows, { includeSize = false } = {}) => {
78
+ return (rows, { includeSize = false, name } = {}) => {
51
79
  if (!rows.length) return { backend: "tmux", present: false, state: "stopped" };
52
- if (rows.length !== 1) throw new Error("session window has multiple panes; choose an unsplit agent window");
53
- const [paneId, dead, command, panePid, cols, rowsCount] = rows[0].split("\t");
54
- if (!/^%\d+$/.test(paneId) || !["0", "1"].includes(dead)) throw new Error("invalid tmux pane response");
80
+ const panes = rows.map((row) => {
81
+ const fields = row.split("\t");
82
+ if (!/^%\d+$/.test(fields[0])) throw new Error("invalid tmux pane response");
83
+ return { paneId: fields[0], mark: fields[includeSize ? 6 : 4] ?? "", fields };
84
+ });
85
+ const { pane, error } = resolveAgentPane(panes, name);
86
+ if (error) throw new Error(error);
87
+ const [paneId, dead, command, panePid, cols, rowsCount] = pane.fields;
88
+ if (!["0", "1"].includes(dead)) throw new Error("invalid tmux pane response");
55
89
  if (includeSize && ![cols, rowsCount].every(value => /^[1-9]\d*$/.test(value) && Number.isSafeInteger(Number(value)))) {
56
90
  throw new Error("invalid tmux pane response");
57
91
  }
@@ -0,0 +1,32 @@
1
+ /** The names of the session-resume contract (feature session-resume, #1559): the strings a client
2
+ * reads in `sessionEnd`, in a `session start --resume` answer's `resume` object and in the rows of
3
+ * `oats session resume` (docs/desktop-cli-api.md). Both product sides settle them together
4
+ * (awebai/oats#1567): every producer, reader, test and doc takes them from here, so a change is made
5
+ * in one place. Each shape has one producer: `sessionEnd` lib/session-end.mjs `sessionEndOf`; the
6
+ * start's `resume` object lib/core.mjs `resumeAnswer`; the sweep's rows lib/session-resume.mjs
7
+ * (`rowFromStart`, `predicted` and the rows it answers without a start). Dependency-free. */
8
+
9
+ export const SESSION_RESUME_FEATURE = "session-resume";
10
+
11
+ /** `sessionEnd` on an `oats status --json` row of a launched home that does not run. */
12
+ export const SESSION_END = Object.freeze({ LOST: "lost", STOPPED: "stopped", EXITED: "exited" });
13
+
14
+ /** `resume.reason` of a start that opened a fresh conversation instead of continuing one; a sweep
15
+ * row `fresh` carries it as its `reason`. */
16
+ export const FRESH_REASON = Object.freeze({ NO_CONVERSATION: "no-conversation", NO_RECEIPTS: "no-receipts", RESUME_UNPROVEN: "resume-unproven" });
17
+
18
+ /** `resume.waiting` of a start that succeeded and waits for its human. */
19
+ export const RESUME_WAITING = Object.freeze({ RESUME_CONFIRMATION: "resume-confirmation" });
20
+
21
+ /** A sweep row's `outcome`. */
22
+ export const OUTCOME = Object.freeze({ RESUMED: "resumed", FRESH: "fresh", ALREADY_RUNNING: "already-running", SKIPPED: "skipped", BLOCKED: "blocked", REFUSED: "refused" });
23
+
24
+ /** A sweep row's `reason`, beside FRESH_REASON's for `fresh`. */
25
+ export const ROW_REASON = Object.freeze({
26
+ UNKNOWN: "unknown", START_BUSY: "start-busy", NOT_LOST: "not-lost", NOT_SEEN_RECENTLY: "not-seen-recently",
27
+ RESUME_CONFIRMATION: RESUME_WAITING.RESUME_CONFIRMATION, LAUNCH_PROMPT: "launch-prompt",
28
+ START_REFUSED: "start-refused", REFUSED_THIS_BOOT: "refused-this-boot", KEEPS_GETTING_LOST: "keeps-getting-lost",
29
+ });
30
+
31
+ /** `deployments[].reason` of a deployment the sweep did not sweep. */
32
+ export const NOT_SWEPT = Object.freeze({ NOT_OK: "not-ok", UNREADABLE: "unreadable" });