@awebai/oats 0.69.23 → 0.69.24

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 (74) hide show
  1. package/bin/oats.mjs +56 -17
  2. package/docs/capabilities.md +353 -5
  3. package/docs/capability-manifest.schema.json +36 -0
  4. package/docs/configuration.md +27 -7
  5. package/docs/design/2026-11-19-sandboxes.md +595 -121
  6. package/docs/design/2026-11-20-provider-home-lifecycle.md +320 -0
  7. package/docs/design/README.md +7 -3
  8. package/docs/desktop-cli-api.md +257 -9
  9. package/docs/desktop.md +181 -48
  10. package/docs/execution-targets.md +186 -3
  11. package/docs/first-team.md +11 -0
  12. package/docs/implementation.md +5 -1
  13. package/docs/integrations.md +2 -2
  14. package/docs/knowledge-capability-authoring.md +1 -1
  15. package/docs/knowledge-reference/proposal.md +10 -0
  16. package/docs/knowledge.md +20 -11
  17. package/docs/official-catalog.md +2 -2
  18. package/docs/packages.md +7 -7
  19. package/docs/release-notes/v0.69.24.md +264 -0
  20. package/docs/souls-and-instances.md +45 -0
  21. package/docs/tui.md +21 -1
  22. package/docs/upgrading.md +12 -5
  23. package/docs/workspaces.md +13 -5
  24. package/lib/capability-show.mjs +11 -1
  25. package/lib/command-flags.mjs +2 -2
  26. package/lib/compile-cache.mjs +1 -1
  27. package/lib/core.mjs +1176 -181
  28. package/lib/errors.mjs +4 -1
  29. package/lib/hook-env.mjs +106 -0
  30. package/lib/host-run.mjs +11 -3
  31. package/lib/instance-inspect.mjs +44 -0
  32. package/lib/instance-lifecycle.mjs +15 -3
  33. package/lib/instance-listing.mjs +97 -8
  34. package/lib/kernel-features.mjs +10 -1
  35. package/lib/node-version.mjs +9 -0
  36. package/lib/provider-call-child.mjs +60 -0
  37. package/lib/provider-resume.mjs +83 -0
  38. package/lib/provider-test-seams.mjs +20 -0
  39. package/lib/read-call.mjs +2 -0
  40. package/lib/reserved-launch-env.mjs +8 -1
  41. package/lib/retire-admission.mjs +5 -1
  42. package/lib/schedule.mjs +14 -4
  43. package/lib/servers.mjs +28 -4
  44. package/lib/session-inspect.mjs +104 -13
  45. package/lib/session-providers.mjs +528 -0
  46. package/lib/session-resume.mjs +68 -15
  47. package/lib/stable-node.mjs +3 -0
  48. package/lib/triggers.mjs +3 -1
  49. package/package-catalog.json +2 -2
  50. package/package.json +2 -1
  51. package/packages/client/capability-list.mjs +21 -0
  52. package/packages/client/cli-adapter.mjs +19 -4
  53. package/packages/client/cli-locator.mjs +5 -1
  54. package/packages/client/deployment-data.mjs +23 -1
  55. package/packages/client/deployment-panel.mjs +25 -3
  56. package/packages/client/home-board.mjs +33 -19
  57. package/packages/client/inspect-boundary.mjs +18 -8
  58. package/packages/client/instance-acts.mjs +30 -3
  59. package/packages/client/instance-board.mjs +206 -0
  60. package/packages/client/instance-presentation.mjs +55 -0
  61. package/packages/client/liveness.mjs +15 -4
  62. package/packages/client/own-codes.mjs +5 -1
  63. package/packages/client/remote-roster.mjs +6 -1
  64. package/packages/client/session-backends.mjs +31 -0
  65. package/packages/client/session-start.mjs +18 -6
  66. package/packages/client/spawn-apply-cli.mjs +5 -3
  67. package/packages/client/spawn-apply-contract.mjs +25 -2
  68. package/packages/client/spawn-apply.mjs +5 -1
  69. package/packages/client/spawn-messages.mjs +3 -0
  70. package/packages/client/terminal-contract.mjs +4 -0
  71. package/packages/client/waiting-on-you.mjs +12 -2
  72. package/packages/tui/lib/model.mjs +14 -3
  73. package/packages/tui/lib/store.mjs +12 -3
  74. package/skills/oats-getting-started/SKILL.md +3 -3
@@ -0,0 +1,83 @@
1
+ /** The resume cap of a home on a session provider (lib/session-providers.mjs;
2
+ * docs/execution-targets.md, "Lost sessions, and the resume"). A
3
+ * provider home's session that is gone, and that OATS did not stop, is a lost session, and whatever
4
+ * brings it back is a resume: the machine sweep's notice (`oats session resume`), `session start
5
+ * --resume`, and any input to it (a mail the broker delivers, a scheduled wake, a person's
6
+ * `session input`), since the provider restarts the session on that input. The cap is the kernel's
7
+ * own, counted here BEFORE the provider's input is called, so no path to the provider bypasses it:
8
+ * at most RESUME_LIMIT resumes of one home in RESUME_WINDOW_MS, in one boot, as the sweep bounds a
9
+ * tmux home's starts (lib/session-resume.mjs). At the cap the resume is refused
10
+ * E_SESSION_NOT_RUNNING, nothing is sent, and a mail stays unread.
11
+ *
12
+ * One file per home under OATS_HOME_DIR (`session-resume/provider-resumes/<sha256 of the home's
13
+ * real path>.json`): `{ bootId, home, resumes: [<ISO time>] }`. Another boot's file counts
14
+ * nothing. Without a boot id (neither Linux nor macOS) nothing is counted, as for the sweep.
15
+ * Kernel-private, not a contract. A leaf: `session input` reads it without loading the sweep. */
16
+ import { createHash } from "node:crypto";
17
+ import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
18
+ import { join } from "node:path";
19
+ import { oatsError } from "./errors.mjs";
20
+ import { bootId, homeKey, resumeStateDir, sameBoot } from "./session-seen.mjs";
21
+
22
+ /** The resume notice of a home on a session provider: one line that asserts only what holds for
23
+ * every such instance, whatever ended its session. It is sent as the session's input. */
24
+ export const PROVIDER_RESUME_NOTICE = "OATS resumed this session after it was interrupted. Continue from where you were.";
25
+ /** How long the resume of a lost session waits for the processes of its last run to leave the home,
26
+ * before it refuses: `waitMs` is the caller's (150 s for a start, none for an input). */
27
+ export const RESUME_QUIET_WAIT_MS = 150_000;
28
+ /** That wait as this process runs it. OATS_TEST_PROVIDER_RESUME_WAIT_MS (a test's seam) shortens a
29
+ * resume that waits: a value above the caller's own wait is that wait, so the seam never makes a
30
+ * resume wait longer; and a resume that does not wait (an input) still does not. */
31
+ export function resumeQuietWait(waitMs = RESUME_QUIET_WAIT_MS) {
32
+ const seam = Number(process.env.OATS_TEST_PROVIDER_RESUME_WAIT_MS);
33
+ return waitMs > 0 && seam > 0 ? Math.min(seam, waitMs) : waitMs;
34
+ }
35
+ /** At most this many resumes of one home in RESUME_WINDOW_MS. */
36
+ export const RESUME_LIMIT = 3;
37
+ /** The span over which a home's resumes are counted. */
38
+ export const RESUME_WINDOW_MS = 60 * 60_000;
39
+
40
+ const fileOf = (home) => join(resumeStateDir(), "provider-resumes", `${createHash("sha256").update(homeKey(home)).digest("hex").slice(0, 32)}.json`);
41
+ /** The lock a resume of `home` is counted under (lib/dir-lock.mjs): the caller's to take around
42
+ * countProviderResume and its `undo`, so two counts never read the same file. Not taken here:
43
+ * this module is a leaf the hot reads load. */
44
+ export const resumeCountLock = (home) => `${fileOf(home)}.lock`;
45
+ function readResumes(home, boot, now) {
46
+ let doc;
47
+ try { doc = JSON.parse(readFileSync(fileOf(home), "utf8")); } catch { return []; }
48
+ if (!doc || typeof doc !== "object" || !sameBoot(doc.bootId, boot) || !Array.isArray(doc.resumes)) return [];
49
+ return doc.resumes.filter((t) => typeof t === "string" && Number.isFinite(Date.parse(t)) && now - Date.parse(t) < RESUME_WINDOW_MS).sort();
50
+ }
51
+ function writeResumes(home, boot, resumes) {
52
+ const path = fileOf(home), tmp = `${path}.${process.pid}.tmp`;
53
+ mkdirSync(join(resumeStateDir(), "provider-resumes"), { recursive: true, mode: 0o700 });
54
+ try { writeFileSync(tmp, JSON.stringify({ bootId: boot, home: homeKey(home), resumes }, null, 2) + "\n", { mode: 0o600 }); renameSync(tmp, path); }
55
+ catch (e) { rmSync(tmp, { force: true }); throw e; }
56
+ }
57
+
58
+ /** How many resumes of `home` are counted now → `{ count, limit, nextAttemptAt }`: `nextAttemptAt`
59
+ * (an ISO time) when the cap is reached, the instant its oldest counted resume leaves the window. */
60
+ export function providerResumes(home, { boot = bootId(), now = Date.now() } = {}) {
61
+ const resumes = boot ? readResumes(home, boot, now) : [];
62
+ return { count: resumes.length, limit: RESUME_LIMIT, nextAttemptAt: resumes.length >= RESUME_LIMIT ? new Date(Date.parse(resumes[0]) + RESUME_WINDOW_MS).toISOString() : null };
63
+ }
64
+
65
+ /** Count one resume of the provider home `home`, before the provider's input is called → `{ undo }`:
66
+ * `undo()` takes the count back, only for an input the provider itself then refused (nothing was
67
+ * sent: a notice that was not sent is no resume). An input whose call failed, or answered outside
68
+ * the rules, keeps its count: the provider may have restarted the session on it. Throws E_SESSION_NOT_RUNNING at the cap, having counted nothing;
69
+ * `details.resumeCap` is `{ limit, windowMs, nextAttemptAt }`. `instance` names the home in the
70
+ * refusal. A count that cannot be written refuses the resume (E_SESSION_NOT_RUNNING too): an
71
+ * uncounted resume would be one the cap never sees. */
72
+ export function countProviderResume(home, instance, { boot = bootId(), now = Date.now() } = {}) {
73
+ if (!boot) return { undo() {} };
74
+ const resumes = readResumes(home, boot, now);
75
+ if (resumes.length >= RESUME_LIMIT) {
76
+ const nextAttemptAt = new Date(Date.parse(resumes[0]) + RESUME_WINDOW_MS).toISOString();
77
+ throw Object.assign(oatsError("E_SESSION_NOT_RUNNING", `${instance} lost its session and was resumed ${resumes.length} times in the last hour, and was lost again each time: it is not resumed again before ${nextAttemptAt}, and nothing was sent. Start it by hand (oats session restart --home ${home}) if it should run`), { details: { resumeCap: { limit: RESUME_LIMIT, windowMs: RESUME_WINDOW_MS, nextAttemptAt } } });
78
+ }
79
+ const at = new Date(now).toISOString();
80
+ try { writeResumes(home, boot, [...resumes, at]); }
81
+ catch (e) { throw oatsError("E_SESSION_NOT_RUNNING", `${instance} lost its session, and its resume could not be counted (${e?.code ?? e?.message ?? e}); nothing was sent`); }
82
+ return { undo() { try { const kept = readResumes(home, boot, now); const i = kept.lastIndexOf(at); if (i >= 0) { kept.splice(i, 1); writeResumes(home, boot, kept); } } catch { /* the count stands: a resume too many is counted, never one too few */ } } };
83
+ }
@@ -0,0 +1,20 @@
1
+ /** Test seams for the lifecycle of a provider home (docs/design/2026-11-20-provider-home-lifecycle.md,
2
+ * "The holder died" and "A provider's command outlives the kernel that ran it"). No effect unless
3
+ * OATS_TEST_PROVIDER_DIE_AT is set; reserved launch environment (lib/reserved-launch-env.mjs):
4
+ * never a launch's to set.
5
+ *
6
+ * OATS_TEST_PROVIDER_DIE_AT names one point, and the kernel dies there, by SIGKILL, as a killed
7
+ * command does:
8
+ * - a point between two writes (`mark:receipt-written`, `stop:stoppedAt-written`, …: lib/core.mjs);
9
+ * - `call:<verb>:before` and `call:<verb>:after`: right before and right after a provider's
10
+ * command (lib/session-providers.mjs callSessionProvider);
11
+ * - `call:<verb>:during`: while the provider's command runs. The kernel cannot kill itself
12
+ * inside a synchronous wait, so the leader of the command's process group does it, before it
13
+ * runs the provider (lib/provider-call-child.mjs, OATS_TEST_PROVIDER_KILL_KERNEL). */
14
+ export function dieAt(point) {
15
+ if (process.env.OATS_TEST_PROVIDER_DIE_AT !== point) return;
16
+ process.kill(process.pid, "SIGKILL");
17
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 10_000); // the signal is on its way
18
+ }
19
+ /** Whether this kernel is to die while the provider's `verb` command runs. */
20
+ export const diesDuring = (verb) => process.env.OATS_TEST_PROVIDER_DIE_AT === `call:${verb}:during`;
package/lib/read-call.mjs CHANGED
@@ -25,6 +25,7 @@ import { resetRuntimeNames, runtimeNameWarning } from "./deprecation.mjs";
25
25
  import { OWN_NAME_FAILURES } from "./errors.mjs";
26
26
  import { activateLocalInputs, localRevision, resetLocalInputs } from "./local-inputs.mjs";
27
27
  import { createReadSession, MAX_AGE_LIMIT, READ_REMOTE_BUDGET_MS, resetGitProbes, resetSshCommand } from "./remote.mjs";
28
+ import { resetKernelNode } from "./stable-node.mjs";
28
29
  import { observeResolvedDeployment, resetResolvedDeployment, settleResolvedDeployment } from "./resolved-deployment.mjs";
29
30
 
30
31
  /** Every module-level binding the reads' import closure writes, and what a call does with it: `reset`
@@ -38,6 +39,7 @@ export const READ_STATE = [
38
39
  { module: "lib/remote.mjs", binding: "gitVersions", how: "reset", reset: resetGitProbes },
39
40
  { module: "lib/remote.mjs", binding: "protocolPins", how: "reset", reset: resetGitProbes },
40
41
  { module: "lib/resolved-deployment.mjs", binding: "reported", how: "reset", reset: resetResolvedDeployment },
42
+ { module: "lib/stable-node.mjs", binding: "kernel", how: "reset", reset: resetKernelNode },
41
43
  { module: "lib/resolved-deployment.mjs", binding: "observer", how: "scoped", why: "set and settled by the call when it is given `deployments`; else the CLI's own, settled at exit" },
42
44
  { module: "lib/remote.mjs", binding: "liveChildren", how: "safe", why: "a registry of live git process groups, each leaving on 'close': empty once a call's session is closed, never cleared (that would lose exit reaping)" },
43
45
  { module: "lib/remote.mjs", binding: "cacheLocks", how: "safe", why: "an in-process mutex per cache repo; an entry is removed when its holder releases it" },
@@ -21,4 +21,11 @@ export const RESERVED_LAUNCH_ENV = new Set(["OATS_INSTANCE", "OATS_INSTANCE_HOME
21
21
  // lib/system-tools.mjs).
22
22
  "OATS_TEST_CGROUP", "OATS_TEST_SYSTEMD_BOOTED", "OATS_TEST_SYSTEM_TOOL_DIRS",
23
23
  // The test seam of #1421 §3: the naming call's time limit (lib/instance-naming.mjs NAMING_TIMEOUT_MS).
24
- "OATS_TEST_NAMING_TIMEOUT_MS"]);
24
+ "OATS_TEST_NAMING_TIMEOUT_MS",
25
+ // The test seams of the session-provider contract: the timeout of every provider call
26
+ // (lib/session-providers.mjs sessionProviderTimeout) and how long a lost session's resume waits
27
+ // for its last run's processes to leave the home (lib/provider-resume.mjs resumeQuietWait). Each
28
+ // only shortens: a value above the kernel's own limit is that limit.
29
+ "OATS_TEST_SESSION_PROVIDER_TIMEOUT_MS", "OATS_TEST_PROVIDER_RESUME_WAIT_MS",
30
+ // The test seam of a provider home's write orders: the point at which the kernel dies (lib/core.mjs dieAt).
31
+ "OATS_TEST_PROVIDER_DIE_AT", "OATS_TEST_PROVIDER_LEADER_DELAY_MS", "OATS_TEST_PROVIDER_KILL_KERNEL"]);
@@ -4,6 +4,7 @@ import { existsSync, readFileSync } from "node:fs";
4
4
  import { join } from "node:path";
5
5
  import { directoryRollbackPath, isCapturedHome, readHomeRecord, unreadableRecordSaid } from "./instance-listing.mjs";
6
6
  import { isPlainObject } from "./session-inspect.mjs";
7
+ import { recordsSessionProvider } from "./session-providers.mjs";
7
8
  import { processLiveness } from "./worktree-hooks.mjs";
8
9
  import { lifecycleBusy, oatsError } from "./errors.mjs";
9
10
 
@@ -160,7 +161,10 @@ export function retireCleanupAdmission(home, name, { force = false } = {}, readW
160
161
  // Compensation metadata is the SPAWN's, from whichever record survived — never
161
162
  // a failed retry's report, which says nothing about what still needs undoing.
162
163
  if (!liveMeta?.capabilityMeta && quarantine?.cleanup?.capabilityMeta) meta.capabilityMeta = quarantine.cleanup.capabilityMeta;
163
- if (quarantine && typeof quarantine.cleanup.launched === "boolean") {
164
+ // A home on a session provider keeps what its own record says of its launch: its receipt is the
165
+ // authority for it, and a rollback marker is written `launched: false` whatever the provider had
166
+ // answered by then, which would set the record against the receipt and refuse every retire.
167
+ if (quarantine && typeof quarantine.cleanup.launched === "boolean" && !recordsSessionProvider(liveMeta)) {
164
168
  meta.launched = quarantine.cleanup.launched;
165
169
  meta.tmux = quarantine.cleanup.tmux;
166
170
  meta.sessionTarget = quarantine.cleanup.sessionTarget;
package/lib/schedule.mjs CHANGED
@@ -35,6 +35,7 @@ import { herdrSettingRemoved } from "./errors.mjs";
35
35
  import { withDirLock as withSharedDirLock } from "./dir-lock.mjs";
36
36
  import { pollSourced, tickTriggers } from "./triggers.mjs";
37
37
  import { SCHEDULE_NAME_RE, HOST_NAME_RE, readSnapshot, hostOf, trusted, parseOwner, MODEL_RE, automationError, baseRow, localEntry, localId, soulOriginOf, splitId, validateDescription } from "./automations.mjs";
38
+ import { SESSION_PROVIDER_NAME_RE } from "./kernel-features.mjs";
38
39
  import { MAX_INSTANCE_NAME, shq, shellWord, findAgent, findInstanceHomes, inspectInstanceSession, inputInstanceSession, sessionServerGone, startInstanceSession, retirePendingMarkerPath } from "./core.mjs";
39
40
  import { writeThroughPrivateFile } from "./write-through-private-file.mjs";
40
41
  import { readStartExited } from "./session-end.mjs";
@@ -487,7 +488,9 @@ export function validateDefinition(ws, def, { checkAgent = true, backendSource,
487
488
  }
488
489
  if (def.repo !== undefined) { if (typeof def.repo !== "string" || !def.repo.trim() || def.repo.startsWith("-")) throw scheduleError("E_SCHEDULE_INVALID", "repo: the work repository path, as oats spawn --repo", { field: "repo" }); out.repo = def.repo; }
489
490
  if (def.backend === "herdr") throw herdrBackendRefusal(backendSource ?? `${definitionsPath(ws)} sets jobs.${id}.backend`);
490
- if (def.backend !== undefined) { if (def.backend !== "tmux") throw scheduleError("E_SCHEDULE_INVALID", "backend: tmux", { field: "backend" }); out.backend = def.backend; }
491
+ // tmux, or a session provider of the soul's capabilities (lib/session-providers.mjs): a name here;
492
+ // the run's spawn resolves it against the instance's modules (E_BACKEND_UNKNOWN, E_BACKEND_HARNESS).
493
+ if (def.backend !== undefined) { if (typeof def.backend !== "string" || !SESSION_PROVIDER_NAME_RE.test(def.backend)) throw scheduleError("E_SCHEDULE_INVALID", "backend: tmux, or a session provider's name (1 to 40 lowercase letters, digits and dashes)", { field: "backend" }); out.backend = def.backend; }
491
494
  if (def.purpose !== undefined) { if (typeof def.purpose !== "string" || !/^[a-z0-9-]{1,40}$/.test(def.purpose)) throw scheduleError("E_SCHEDULE_INVALID", "purpose: lowercase letters, digits and dashes", { field: "purpose" }); out.purpose = def.purpose; }
492
495
  // A run spawns <agent>-<purpose|id>-<YYYYMMDDHHMM>; instance names are at most
493
496
  // MAX_INSTANCE_NAME characters, so refuse here what would fail at every firing.
@@ -646,8 +649,12 @@ export function observeHome(home, io) {
646
649
  const retiring = existsSync(retirePendingMarkerPath(home));
647
650
  try {
648
651
  const s = (io?.inspect || inspectInstanceSession)(home);
649
- if (s.present && s.state !== "shell") return { outcome: "active", ...(retiring ? { note: "retiring" } : {}) };
652
+ // A home on a session provider (its inspect answer carries `session`): a wake never starts it
653
+ // (performWake). Its session in error (`shell`) is no startup phase: an input recovers it.
654
+ const provider = s.session !== undefined && s.session !== null ? { provider: true } : {};
655
+ if (s.present && s.state !== "shell") return { outcome: "active", ...provider, ...(retiring ? { note: "retiring" } : {}) };
650
656
  if (retiring) return { outcome: "active", note: "retiring: home present, teardown pending" };
657
+ if (provider.provider) return { outcome: "stopped", ...provider };
651
658
  // A shell right after `session start` is that launch's startup phase
652
659
  // until its wrapper writes the exit marker for the launch id; only then
653
660
  // (or with no start receipt at all) is a shell a finished harness.
@@ -915,7 +922,10 @@ function performWake(def, io, { startIfStopped = true, canStart = true, reserve,
915
922
  if (seen.outcome === "ended") return { kind: "wake", action: "skipped", reason: "home is gone", pending: false };
916
923
  if (seen.outcome === "unknown") return { kind: "wake", action: "skipped", reason: `cannot observe the session: ${seen.error}`, pending: true };
917
924
  if (seen.outcome === "starting") return { kind: "wake", action: "skipped", reason: "session is starting; delivery pending", pending: true };
918
- if (seen.outcome === "stopped") {
925
+ // A home on a session provider is never started by a wake: the wake is its session's input, which
926
+ // the kernel refuses (E_SESSION_NOT_RUNNING, before any provider call) for a home OATS stopped,
927
+ // and which the provider answers for any other.
928
+ if (seen.outcome === "stopped" && !seen.provider) {
919
929
  if (!startIfStopped) return { kind: "wake", action: "skipped", reason: "session stopped; it is started again only at the next due minute; delivery pending", pending: true };
920
930
  if (!canStart) return { kind: "wake", action: "skipped", reason: "host busy: starting this session needs a launch slot; delivery pending", pending: true };
921
931
  // The slot is persisted BEFORE the start call and kept on a start
@@ -945,7 +955,7 @@ function performWake(def, io, { startIfStopped = true, canStart = true, reserve,
945
955
  // Delivery custody: name the instance ONLY when the input result names it; the home's current incarnation at record time.
946
956
  return { kind: "wake", action: "delivered", pending: false, ...(typeof r?.instance === "string" ? { instance: r.instance } : {}), home: def.home, incarnation: incarnationOfHome(def.home) };
947
957
  }
948
- catch (e) { return { kind: "wake", action: "skipped", reason: `input refused: ${e.message}`, pending: true }; }
958
+ catch (e) { return { kind: "wake", action: "skipped", reason: `input refused: ${e.message}`, ...(seen.provider && typeof e?.code === "string" ? { errorCode: e.code } : {}), pending: true }; }
949
959
  }
950
960
 
951
961
  /** A held run as the tick records it: `held.since` is the first skip's time, kept on
package/lib/servers.mjs CHANGED
@@ -35,7 +35,8 @@ import { shellWord } from "./shell-word.mjs";
35
35
  import { DETACH_KEY_FEATURE, requireDetachKey } from "./session-viewer.mjs";
36
36
  import { LOGIN_CAPTURE_MAX_BYTES, LOGIN_SHELLS, loginPathEmitter, quoteFor, readLoginFrame } from "./login-environment.mjs";
37
37
  import { compareSemver } from "./semver.mjs";
38
- import { SPAWN_TASK_STDIN_FEATURE } from "./kernel-features.mjs";
38
+ import { SESSION_PROVIDERS_FEATURE, SPAWN_TASK_STDIN_FEATURE } from "./kernel-features.mjs";
39
+ import { relayedProviderRow, withoutRelayedEndpoint } from "./session-providers.mjs";
39
40
  import { sameRepo } from "./repo-moves.mjs";
40
41
  import { OATS_PACKAGE_NAME } from "./version.mjs";
41
42
  import { readRemoteBoard } from "./instance-board.mjs";
@@ -330,9 +331,24 @@ export function operatorSshArgv(alias, words) {
330
331
 
331
332
  // ------------------------------------------------------------------ running
332
333
 
334
+ /** A host's envelope without a session provider's locator (feature session-providers): a provider
335
+ * home's endpoint, and the thread id a status row carries on its own host, are for the host where
336
+ * the home lives, and are never relayed. An answer's own `session` (a spawn's, a start's, an
337
+ * inspect's) and every roster row's are cut to `{ provider }`, whatever the host sent. */
338
+ function withoutProviderLocators(envelope) {
339
+ const result = envelope?.result;
340
+ if (envelope?.ok !== true || !result || typeof result !== "object") return envelope;
341
+ const rows = (agents) => agents.map((a) => (a && Array.isArray(a.instances) ? { ...a, instances: a.instances.map(withoutRelayedEndpoint) } : a));
342
+ const roster = (doc) => (doc && Array.isArray(doc.agents) ? { ...doc, agents: rows(doc.agents) } : doc);
343
+ const cut = Array.isArray(result.roots) ? { ...result, roots: result.roots.map(roster) } : roster(withoutRelayedEndpoint(result));
344
+ return { ...envelope, result: cut };
345
+ }
333
346
  /** Parse the remote kernel's JSON envelope; anything else on stdout is a
334
347
  * routing failure with the raw text attached, never a guess. */
335
348
  export function parseRemoteEnvelope(stdout) {
349
+ return withoutProviderLocators(parseRemoteEnvelopeAsSent(stdout));
350
+ }
351
+ function parseRemoteEnvelopeAsSent(stdout) {
336
352
  const text = String(stdout || "").trim();
337
353
  let doc;
338
354
  try {
@@ -499,6 +515,7 @@ export function dropRemoteProbes(serverId) {
499
515
 
500
516
  function probeRemote(target, io) {
501
517
  const { envelope } = runRemote(target, ["version", "--json"], { ...io, timeoutMs: 60000 });
518
+ if (!envelope.ok) throw relayedFailure(envelope, "version --json");
502
519
  const probe = envelope.result || {};
503
520
  if (probe.desktopApi !== 1 || typeof probe.version !== "string") {
504
521
  throw serverError("E_REMOTE_INCOMPATIBLE", `remote oats at ${target.sshHost} answered an unknown version payload: ${JSON.stringify(probe).slice(0, 200)}`);
@@ -561,7 +578,10 @@ export function checkRemoteSupport(remote, target, oatsArgs, roster) {
561
578
  // A wake schedule at spawn is saved by the host: it must advertise schedules.
562
579
  if (["--wake-json", "--wake-every", "--wake-cron"].some((f) => oatsArgs.includes(f)) && !remote.features.includes("schedule")) refuse("a wake schedule at spawn (the host must advertise the schedule feature)");
563
580
  const backend = flagOf("--backend");
564
- if (backend && !remote.sessionBackends.includes(backend)) refuse(`session backend ${backend}`);
581
+ // A backend that is none of the host's built-in ones is a session provider (a capability's, resolved
582
+ // against the instance's modules there): relayed only to a host that lists the feature. A host
583
+ // without it knows tmux alone, and is never asked for another.
584
+ if (backend && !remote.sessionBackends.includes(backend) && !remote.features.includes(SESSION_PROVIDERS_FEATURE)) refuse(`session backend ${backend} (a session provider: the host must advertise ${SESSION_PROVIDERS_FEATURE})`);
565
585
  if (oatsArgs.includes("--yolo") && !remote.launchOptions.includes("yolo")) refuse("the yolo launch option");
566
586
  return { harness, backend, yolo: oatsArgs.includes("--yolo") };
567
587
  }
@@ -1246,7 +1266,9 @@ export async function rosterGroups({ server, workspaceKeys, io = {} } = {}) {
1246
1266
  const snap = routeOf(i);
1247
1267
  g.instances.push({
1248
1268
  server: g.server, instance: i.instance, agent: a.name, home: i.home || snap?.home, agentsRoot: result.root,
1249
- harness: i.harness || i.runtime || null, backend: i.tmux ? "tmux" : null,
1269
+ // A session provider's row (feature session-providers): its backend's name, `session`, `open`
1270
+ // and `runtimeState`, relayed in the kernel's own shapes only (relayedProviderRow).
1271
+ harness: i.harness || i.runtime || null, backend: i.tmux ? "tmux" : null, ...(relayedProviderRow(i) ?? {}),
1250
1272
  ...(i.sessionTarget ? { sessionTarget: i.sessionTarget } : {}), ...(i.tmux ? { tmux: i.tmux } : {}),
1251
1273
  running: typeof i.running === "boolean" ? i.running : null, ...(i.runtimeError ? { runtimeError: i.runtimeError } : {}),
1252
1274
  ...rowFacts(i), ...rowWaiting(i), ...rowRetire(i), ...rowBackground(i), ...rowPinned(i), ...rowBoard(i), ...rowRelatedWork(i, g.probe.features), ...rowSessionEnd(i),
@@ -1663,7 +1685,9 @@ function probeHostOats(target, io) {
1663
1685
  const r = runHostCommand(target, [target.oatsPath, "version", "--json"], { ...io, timeoutMs: 60000 });
1664
1686
  if (r.status === 255) throw sshFailed(target, r);
1665
1687
  if (r.status === 126 || r.status === 127) return { missing: true };
1666
- const probe = parseRemoteEnvelope(r.stdout).result || {};
1688
+ const envelope = parseRemoteEnvelope(r.stdout);
1689
+ if (!envelope.ok) throw relayedFailure(envelope, "version --json");
1690
+ const probe = envelope.result || {};
1667
1691
  if (probe.desktopApi !== 1 || typeof probe.version !== "string") throw serverError("E_REMOTE_INCOMPATIBLE", `${target.oatsPath} at ${target.sshHost} answered an unknown version payload: ${JSON.stringify(probe).slice(0, 200)}`);
1668
1692
  return { version: probe.version, features: Array.isArray(probe.features) ? probe.features.map(String) : [] };
1669
1693
  }
@@ -1,6 +1,7 @@
1
- /** inspectInstanceSession: what a home's tmux session is, read under the home's runtime authority (its
2
- * recorded launch and receipts, the retirement baseline, the Herdr refusal) and the agent pane's
3
- * liveness. A leaf (awebai/oats#1630): `oats session inspect` reads it without loading core.mjs, which
1
+ /** inspectInstanceSession: what a home's session is, read under the home's runtime authority (its
2
+ * recorded launch and receipts, the retirement baseline, the Herdr refusal): a tmux session's agent
3
+ * pane and its liveness, or, for a home on a session provider (lib/session-providers.mjs), the
4
+ * provider's own answer. A leaf (awebai/oats#1630): `oats session inspect` reads it without loading core.mjs, which
4
5
  * imports these helpers and re-exports what it exported. */
5
6
  import { realPathOrNearest, canonicalHomePath } from "./real-path.mjs";
6
7
  import { existsSync, readFileSync, lstatSync } from "node:fs";
@@ -9,6 +10,7 @@ import { createHash } from "node:crypto";
9
10
  import { inspectSessionTarget } from "./session-input.mjs";
10
11
  import { liveWaiting } from "./instance-events.mjs";
11
12
  import { oatsError, herdrInstanceRemoved } from "./errors.mjs";
13
+ import { homeSessionProvider, isSessionProviderName, inspectProviderSession, launchSentOf, providerEndpointDifferences, providerRuntimeOf, unsettledLaunchSaid } from "./session-providers.mjs";
12
14
 
13
15
  /** A cleanup descriptor is usable only if it can DRIVE the retry, so it is checked
14
16
  * as the strict contract its one producer writes — the rollback above — and to the
@@ -112,15 +114,53 @@ function refuseHerdrHome(home) {
112
114
  if (recordsHerdr(readJsonOrUndefined(join(home, "instance.json")), readJsonOrUndefined(findRetirementBaseline(home)))) throw herdrInstanceRemoved(basename(home));
113
115
  }
114
116
 
117
+ /** What a receipt authorises: `{ launched: false }` (with `planned: { backend, provider }` for a home
118
+ * that will launch on a session provider), `{ launched: true, tmux }` for a tmux session, or
119
+ * `{ launched: true, session }` for a session provider's (`session`: providerRuntimeOf's
120
+ * `{ backend, provider, endpoint, stoppedAt }`); undefined when it is none of these. */
115
121
  function runtimeAuthorityOf(baseline) {
116
122
  const runtime = baseline?.runtime;
117
123
  if (!isPlainObject(runtime) || typeof runtime.launched !== "boolean") return undefined;
118
- if (!runtime.launched) return { launched: false };
124
+ if (!runtime.launched) {
125
+ if (runtime.backend === undefined && runtime.provider === undefined) return { launched: false };
126
+ if (!isSessionProviderName(runtime.backend) || typeof runtime.provider !== "string" || !runtime.provider || runtime.launchSent !== undefined) return undefined;
127
+ return { launched: false, planned: { backend: runtime.backend, provider: runtime.provider, launchSent: null } };
128
+ }
119
129
  if (runtime.sessionTarget !== undefined) return undefined;
130
+ // A launch that was sent for a home never launched, and has no recorded outcome (lib/session-providers.mjs
131
+ // launchSentOf): no endpoint yet. The home is still a planned one, whose record says not launched.
132
+ if (runtime.tmux === undefined && runtime.endpoint === undefined) {
133
+ const launchSent = launchSentOf(runtime);
134
+ if (!launchSent || !isSessionProviderName(runtime.backend) || typeof runtime.provider !== "string" || !runtime.provider) return undefined;
135
+ return { launched: false, planned: { backend: runtime.backend, provider: runtime.provider, launchSent } };
136
+ }
137
+ if (runtime.tmux === undefined) {
138
+ const session = providerRuntimeOf(runtime);
139
+ return session ? { launched: true, session: { backend: session.backend, provider: session.provider, endpoint: session.endpoint, stoppedAt: session.stoppedAt, launchSent: session.launchSent } } : undefined;
140
+ }
120
141
  const tmux = runtime.tmux;
121
142
  if (!isPlainObject(tmux) || ![tmux.session, tmux.window, tmux.socket].every((v) => typeof v === "string" && v.length > 0)) return undefined;
122
143
  return { launched: true, tmux: { session: tmux.session, window: tmux.window, socket: resolve(tmux.socket) } };
123
144
  }
145
+ /** The fields of instance.json's session that differ from the receipt's, for a home on a session
146
+ * provider, launched (`authority.session`) or planned (`authority.planned`: no endpoint yet). */
147
+ function providerDifferences(meta, authority) {
148
+ // While the receipt says a launch is unsettled, the record's endpoint is not compared: the
149
+ // launch that would have written it may have ended at any point (docs/design/2026-11-20-provider-home-lifecycle.md).
150
+ if (authority.session && !authority.session.launchSent) return providerEndpointDifferences(meta, authority.session);
151
+ const named = authority.session ?? authority.planned;
152
+ return [
153
+ ...(meta?.backend === named.backend ? [] : ["backend"]),
154
+ ...(meta?.session?.provider === named.provider ? [] : ["session.provider"]),
155
+ ];
156
+ }
157
+ /** The fields of instance.json's endpoint, of whichever backend the receipt records, that differ
158
+ * from the receipt's: tmux's labels, or a session provider's. A receipt that records no endpoint
159
+ * (never launched, planned on tmux) has none to differ from. */
160
+ function endpointDifferences(meta, authority) {
161
+ if (authority.session || authority.planned) return providerDifferences(meta, authority);
162
+ return authority.launched ? tmuxEndpointDifferences(meta, authority) : [];
163
+ }
124
164
 
125
165
  /** The fields of instance.json's tmux endpoint that differ from the one the independent receipt
126
166
  * authorises, as fixed labels in a fixed order: `tmux.session`, `tmux.window`, `tmux.socket`. */
@@ -133,6 +173,8 @@ function tmuxEndpointDifferences(meta, authority) {
133
173
  }
134
174
  /** instance.json's tmux endpoint is the one the independent receipt authorises. */
135
175
  function tmuxEndpointAgrees(meta, authority) { return tmuxEndpointDifferences(meta, authority).length === 0; }
176
+ /** instance.json's endpoint, of whichever backend the receipt records, is the one it authorises. */
177
+ function endpointAgrees(meta, authority) { return endpointDifferences(meta, authority).length === 0; }
136
178
 
137
179
  /** Whether a blocked or incomplete launch prompt explains metadata's `launched: false` beside a
138
180
  * launched receipt. */
@@ -142,18 +184,23 @@ function promptRetained(meta, authority) {
142
184
  /** A blocked prompt is a retained runtime, not evidence that no process exists.
143
185
  * The independent launched receipt and exact endpoint agreement remain mandatory. */
144
186
  function launchStateAgrees(meta, authority) {
145
- return meta.launched === authority.launched || (promptRetained(meta, authority) && tmuxEndpointAgrees(meta, authority));
187
+ // A launch that was sent for a home never launched (lib/session-providers.mjs launchSentOf): the
188
+ // record says `launched: true` meanwhile, so that a kernel from before session providers refuses
189
+ // the home; the two files are written one after the other, so either value agrees.
190
+ if ((authority.session ?? authority.planned)?.launchSent) return true;
191
+ return meta.launched === authority.launched || (promptRetained(meta, authority) && !authority.session && tmuxEndpointAgrees(meta, authority));
146
192
  }
147
193
 
148
194
  /** The refusal for instance.json that disagrees with the independent receipt. `details.fields` names
149
195
  * what differs, from a fixed vocabulary in a fixed order: `launched` (unless a blocked or incomplete
150
- * launch prompt explains metadata's `launched: false`), then, for a launched receipt, each differing
151
- * tmux endpoint field. Labels only: never a path, a value or the receipt. Callers throw it only once
196
+ * launch prompt explains metadata's `launched: false`), then each differing endpoint field: for a
197
+ * launched tmux receipt `tmux.session`, `tmux.window`, `tmux.socket`; for a session provider's
198
+ * `backend`, `session.provider`, `session.endpoint`. Labels only: never a path, a value or the receipt. Callers throw it only once
152
199
  * their own comparison has refused, so these labels diagnose a refusal and never decide one. */
153
200
  function authorityMismatch(message, meta, authority) {
154
201
  const fields = [
155
- ...(meta.launched === authority.launched || promptRetained(meta, authority) ? [] : ["launched"]),
156
- ...(authority.launched ? tmuxEndpointDifferences(meta, authority) : []),
202
+ ...(meta.launched === authority.launched || promptRetained(meta, authority) || (authority.session ?? authority.planned)?.launchSent ? [] : ["launched"]),
203
+ ...endpointDifferences(meta, authority),
157
204
  ];
158
205
  return Object.assign(oatsError("E_RUNTIME_AUTHORITY_MISMATCH", message), { details: { fields } });
159
206
  }
@@ -194,9 +241,17 @@ function instanceSessionTarget(home, { absentMeta } = {}) {
194
241
  if (!isPlainObject(meta)) throw oatsError("E_RUNTIME_ENDPOINT_UNKNOWN", `cannot read ${recordPath}: it holds no JSON object`);
195
242
  const authority = baseline.version === RETIRE_BASELINE_VERSION && receiptRecordsHome(baseline, canonicalHomePath(home)) && runtimeAuthorityOf(baseline);
196
243
  if (!authority) throw oatsError("E_RUNTIME_ENDPOINT_UNKNOWN", `independent session receipt is missing or invalid for ${home}`);
197
- if (!launchStateAgrees(meta, authority) || (authority.launched && !tmuxEndpointAgrees(meta, authority))) throw authorityMismatch("instance metadata disagrees with independent session receipt", meta, authority);
198
- return { home, target: authority.launched ? { backend: "tmux", ...authority.tmux } : undefined, meta };
244
+ if (!launchStateAgrees(meta, authority) || !endpointAgrees(meta, authority)) throw authorityMismatch("instance metadata disagrees with independent session receipt", meta, authority);
245
+ // `unsettled`: a launch that was sent to the home's provider and never recorded, whether the home
246
+ // was launched before or not: `{ backend, provider, launchSent }`, or null. The one place that says so.
247
+ const recorded = authority.session ?? authority.planned ?? null;
248
+ return { home, target: authority.tmux ? { backend: "tmux", ...authority.tmux } : undefined, meta,
249
+ ...(authority.session ? { session: authority.session } : {}), ...(authority.planned ? { planned: authority.planned } : {}),
250
+ unsettled: recorded?.launchSent ? { backend: recorded.backend, provider: recorded.provider, launchSent: recorded.launchSent } : null };
199
251
  }
252
+ /** The answer for a tmux-only path that meets a home on a session provider (`s`: instanceSessionTarget's
253
+ * answer): the home has no tmux endpoint to read or act on. Undefined for any other home. */
254
+ function providerHomeOf(s) { return s.session ?? s.planned; }
200
255
 
201
256
  /** `wakeHold` (feature wake-hold): whether this home's capabilities said its dialogs become the claims
202
257
  * a wake holds on, from the home's record (instance.json `dialogClaims`): `on-claims` if any entry is
@@ -207,11 +262,47 @@ function wakeHoldOf(meta) {
207
262
  return answers.includes("reported") ? "on-claims" : answers.includes("none") ? "not-exposed" : "unknown";
208
263
  }
209
264
 
210
- /** `io` (`{ exec }`) is the tmux and process-table seam inspectSessionTarget takes. */
265
+ /** What a provider home's `session` is in an answer: the capability that supplies its backend and
266
+ * the endpoint the kernel recorded (null before the first launch). */
267
+ export function sessionOf(session) { return { provider: session.provider, endpoint: session.endpoint ?? null }; }
268
+ /** A launched provider home's session, as inspect answers it (docs/desktop-cli-api.md): the
269
+ * provider's own `{ present, state, running, open }`, with the kernel's `backend`, `session`,
270
+ * `waitingOnYou` and `wakeHold`; no pane and no size. Kernel-owned: a home OATS stopped (`stoppedAt`)
271
+ * answers stopped WITHOUT calling the provider, so a session the provider would restart on the next
272
+ * input reads as OATS left it. A provider that fails, refuses or answers outside the contract's
273
+ * words is E_SESSION_UNAVAILABLE, never stopped. `waitingOnYou` is a producer's claim, read
274
+ * whenever the session is not stopped (providerMayWait): an idle session can be the one waiting
275
+ * on a person. */
276
+ function inspectProviderHome(s, wakeHold, io) {
277
+ const answer = { home: s.home, backend: s.session.backend };
278
+ const kernel = { wakeHold, session: sessionOf(s.session) };
279
+ if (s.session.stoppedAt !== null) return { ...answer, present: false, state: "stopped", running: false, waitingOnYou: null, ...kernel, open: null };
280
+ const found = homeSessionProvider(s.home, s.meta, s.session.provider, s.session.backend);
281
+ if (found.problem) throw oatsError("E_SESSION_UNAVAILABLE", `cannot inspect session: ${found.problem}`);
282
+ const inspected = inspectProviderSession(found.binding, s.session.endpoint, { io });
283
+ if (inspected.unavailable) throw oatsError("E_SESSION_UNAVAILABLE", `cannot inspect session: ${inspected.unavailable}`);
284
+ const { present, state, running, open } = inspected.observed;
285
+ return { ...answer, present, state, running, waitingOnYou: providerMayWait(inspected.observed) ? liveWaiting(s.home) : null, ...kernel, open };
286
+ }
287
+ /** Whether a provider's session, as observed, can be waiting on a human: whenever it is not stopped
288
+ * (`running` true or null). An agent that waits on a question is idle where its provider runs it,
289
+ * so it reads `running: null`: the claim is shown then too. Never for a session that is gone (a
290
+ * lost one included) or in error, nor for a home OATS stopped, which is never observed. */
291
+ function providerMayWait(observed) { return observed.present === true && observed.running !== false; }
292
+
293
+ /** `io` (`{ exec }`) is the tmux and process-table seam inspectSessionTarget takes; for a home on a
294
+ * session provider, `io.spawnSync` is the provider call's. */
211
295
  export function inspectInstanceSession(home, { io, absentMeta } = {}) {
212
296
  if (typeof home === "string" && isAbsolute(home) && !existsSync(home)) return { home: realPathOrNearest(home), backend: null, present: false, state: "stopped", running: false, waitingOnYou: null, wakeHold: wakeHoldOf(null) };
213
297
  const s = instanceSessionTarget(home, { absentMeta });
214
298
  const wakeHold = wakeHoldOf(s.meta);
299
+ // A launch that was sent and never recorded (launchSentOf), on a home launched before or not: a
300
+ // session may run that no record names. Unknown, never "not launched" or "stopped", until a stop
301
+ // or a start has settled it.
302
+ if (s.unsettled) throw oatsError("E_SESSION_UNAVAILABLE", unsettledLaunchSaid(basename(s.home), s.unsettled.backend, s.unsettled.launchSent));
303
+ if (s.session) return inspectProviderHome(s, wakeHold, io);
304
+ // A home that will launch on a session provider says which: nothing was launched yet.
305
+ if (s.planned) return { home: s.home, backend: s.planned.backend, present: false, state: "not-launched", running: false, waitingOnYou: null, wakeHold, session: sessionOf(s.planned), open: null };
215
306
  if (!s.target) return { home: s.home, backend: null, present: false, state: "not-launched", running: false, waitingOnYou: null, wakeHold };
216
307
  let observed;
217
308
  try { observed = inspectSessionTarget(s.target, io, { includeSize: true }); }
@@ -226,4 +317,4 @@ export function inspectInstanceSession(home, { io, absentMeta } = {}) {
226
317
  * fallback shell nor a dead pane. Only such a session can be waiting on a human. */
227
318
  function harnessRunning(observed) { return observed?.present === true && observed.state !== "shell" && observed.state !== "stopped"; }
228
319
 
229
- export { RETIRE_BASELINE_VERSION, authorityMismatch, harnessRunning, instanceSessionTarget, instancesRetirementRoot, isPlainObject, launchStateAgrees, missingSessionReceipt, readJsonOrUndefined, receiptHomeIdentity, receiptRecordsHome, recordsHerdr, refuseHerdrHome, runtimeAuthorityOf, tmuxEndpointAgrees };
320
+ export { RETIRE_BASELINE_VERSION, authorityMismatch, endpointAgrees, harnessRunning, providerHomeOf, providerMayWait, instanceSessionTarget, instancesRetirementRoot, isPlainObject, launchStateAgrees, missingSessionReceipt, readJsonOrUndefined, receiptHomeIdentity, receiptRecordsHome, recordsHerdr, refuseHerdrHome, runtimeAuthorityOf, tmuxEndpointAgrees };