@awebai/oats 0.69.23 → 0.70.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) hide show
  1. package/bin/oats.mjs +112 -20
  2. package/docs/capabilities.md +697 -11
  3. package/docs/capability-manifest.schema.json +66 -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 +322 -0
  7. package/docs/design/README.md +7 -3
  8. package/docs/desktop-cli-api.md +330 -9
  9. package/docs/desktop.md +181 -48
  10. package/docs/execution-targets.md +210 -4
  11. package/docs/first-team.md +11 -0
  12. package/docs/implementation.md +24 -3
  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/release-notes/v0.70.0.md +155 -0
  21. package/docs/souls-and-instances.md +57 -0
  22. package/docs/trust-model.md +8 -1
  23. package/docs/tui.md +21 -1
  24. package/docs/upgrading.md +19 -5
  25. package/docs/workspaces.md +13 -5
  26. package/lib/automation-scope.mjs +1 -1
  27. package/lib/capability-show.mjs +20 -1
  28. package/lib/command-flags.mjs +2 -2
  29. package/lib/compile-cache.mjs +1 -1
  30. package/lib/core.mjs +1455 -203
  31. package/lib/errors.mjs +4 -1
  32. package/lib/home-integrity.mjs +329 -0
  33. package/lib/hook-env.mjs +107 -0
  34. package/lib/host-run.mjs +11 -3
  35. package/lib/instance-events.mjs +32 -5
  36. package/lib/instance-git.mjs +9 -0
  37. package/lib/instance-inspect.mjs +107 -9
  38. package/lib/instance-lifecycle.mjs +15 -3
  39. package/lib/instance-listing.mjs +101 -8
  40. package/lib/instance-resolution.mjs +85 -2
  41. package/lib/instance-upgrade.mjs +170 -14
  42. package/lib/kernel-features.mjs +10 -1
  43. package/lib/node-version.mjs +9 -0
  44. package/lib/provider-call-child.mjs +60 -0
  45. package/lib/provider-resume.mjs +83 -0
  46. package/lib/provider-test-seams.mjs +20 -0
  47. package/lib/read-call.mjs +2 -0
  48. package/lib/remote.mjs +33 -1
  49. package/lib/reserved-launch-env.mjs +8 -1
  50. package/lib/retire-admission.mjs +12 -1
  51. package/lib/sandbox-allowances.mjs +329 -0
  52. package/lib/schedule.mjs +14 -4
  53. package/lib/servers.mjs +38 -5
  54. package/lib/session-inspect.mjs +123 -87
  55. package/lib/session-providers.mjs +575 -0
  56. package/lib/session-receipt.mjs +93 -0
  57. package/lib/session-resume.mjs +68 -15
  58. package/lib/stable-node.mjs +3 -0
  59. package/lib/triggers.mjs +3 -1
  60. package/lib/upgrade-state.mjs +6 -1
  61. package/lib/worktree-hooks.mjs +18 -2
  62. package/lib/worktree.mjs +21 -7
  63. package/package-catalog.json +2 -2
  64. package/package.json +2 -1
  65. package/packages/client/capability-list.mjs +21 -0
  66. package/packages/client/cli-adapter.mjs +19 -4
  67. package/packages/client/cli-locator.mjs +5 -1
  68. package/packages/client/deployment-data.mjs +23 -1
  69. package/packages/client/deployment-panel.mjs +25 -3
  70. package/packages/client/home-board.mjs +33 -19
  71. package/packages/client/inspect-boundary.mjs +18 -8
  72. package/packages/client/instance-acts.mjs +30 -3
  73. package/packages/client/instance-board.mjs +206 -0
  74. package/packages/client/instance-presentation.mjs +55 -0
  75. package/packages/client/liveness.mjs +15 -4
  76. package/packages/client/own-codes.mjs +5 -1
  77. package/packages/client/remote-roster.mjs +6 -1
  78. package/packages/client/session-backends.mjs +31 -0
  79. package/packages/client/session-start.mjs +18 -6
  80. package/packages/client/spawn-apply-cli.mjs +5 -3
  81. package/packages/client/spawn-apply-contract.mjs +25 -2
  82. package/packages/client/spawn-apply.mjs +5 -1
  83. package/packages/client/spawn-messages.mjs +3 -0
  84. package/packages/client/terminal-contract.mjs +4 -0
  85. package/packages/client/waiting-on-you.mjs +12 -2
  86. package/packages/tui/lib/model.mjs +14 -3
  87. package/packages/tui/lib/store.mjs +12 -3
  88. package/skills/oats-getting-started/SKILL.md +3 -3
@@ -0,0 +1,575 @@
1
+ /** Session providers (docs/capabilities.md "Session providers"; docs/execution-targets.md "Backends"):
2
+ * a session backend a capability supplies. tmux is the kernel's built-in backend; a provider is a
3
+ * capability whose manifest declares `sessionProviders.<name>`, four of its own commands the kernel
4
+ * calls for an instance on that backend: `launch`, `inspect`, `input`, `stop` (and, optionally,
5
+ * `inspectMany` and `check`). The kernel keeps what a backend must not own: the receipts, the authority check,
6
+ * the lifecycle claims, the refusals and the JSON answers. This module is the manifest's validator,
7
+ * the wire and the answers' rules. A leaf: the hot reads (`session inspect`, `status`) call a
8
+ * provider without loading core.mjs.
9
+ *
10
+ * Containment, as for `triggerSources`: a malformed `sessionProviders` never refuses the capability.
11
+ * It is validated where a provider is used; a problem inside one provider disables that provider
12
+ * only, a malformed top level every provider of the manifest.
13
+ *
14
+ * The wire. Each call runs the KERNEL'S copy of the home's module, kept outside the home
15
+ * (lib/home-integrity.mjs: `node <instances>/.oats-retirement/modules/…/<capability>/<script>
16
+ * <args>`; never the home's own copy), with its working directory OUTSIDE the home (the filesystem root: a call is
17
+ * never one of the processes that "work in the home", which a resume and a retire look for; the
18
+ * home is in the request), with the environment a lifecycle hook of that capability gets
19
+ * there (lib/hook-env.mjs), `OATS_EVENT=session` and `OATS_BACKEND=<name>`; one JSON request on
20
+ * stdin; exactly one JSON document on stdout; SIGKILL at the verb's timeout. The request is
21
+ * `{ schemaVersion: 1, phase: "session", capability, provider, verb, input }`; the answer echoes
22
+ * those five and carries `ok: true, result` or `ok: false, error: { code, message? }`, and no other
23
+ * key. A call that does not end that way (another exit status, a signal, the timeout, no or
24
+ * malformed JSON, a wrong envelope, a result that breaks its verb's rules) is a FAILED call, which
25
+ * is never read as an answer: an inspect that failed is never "stopped". stderr is never read. */
26
+ import { spawnSync } from "node:child_process";
27
+ import { fileURLToPath } from "node:url";
28
+ import { readFileSync, realpathSync, statSync } from "node:fs";
29
+ import { basename, dirname, isAbsolute, join, parse, relative, resolve, sep } from "node:path";
30
+ import { canonicalJson, parseStrictJson } from "./canonical-json.mjs";
31
+ import { oatsError } from "./errors.mjs";
32
+ import { instanceSoulDir, lifecycleHookEnv } from "./hook-env.mjs";
33
+ import { capabilityRuntimeOf, moduleCopyProblem, providerHomeTrust, recordsModule, runDirOf } from "./home-integrity.mjs";
34
+ import { BUILTIN_SESSION_BACKENDS, SESSION_PROVIDERS_FEATURE, SESSION_PROVIDER_NAME_RE } from "./kernel-features.mjs";
35
+ import { REFUSED_TEXT, safeText } from "./refused-text.mjs";
36
+ import { dieAt, diesDuring } from "./provider-test-seams.mjs";
37
+ import { recordedTeams } from "./teams.mjs";
38
+
39
+ export { BUILTIN_SESSION_BACKENDS, SESSION_PROVIDERS_FEATURE, SESSION_PROVIDER_NAME_RE };
40
+ /** Names no provider may take: the built-in backend; the word a `requires` row's `backends` uses for
41
+ * any session provider (SESSION_PROVIDER_ANY); and the backend that was removed (`--backend herdr` is
42
+ * read only to be refused). */
43
+ export const SESSION_PROVIDER_ANY = "session-provider";
44
+ const RESERVED_NAMES = new Set(["tmux", SESSION_PROVIDER_ANY, "herdr"]);
45
+ /** Whether `name` is one a session provider can have: the one rule for a manifest's key, a
46
+ * receipt's or a record's `backend`, and a row another host relays. */
47
+ export const isSessionProviderName = (name) => typeof name === "string" && SESSION_PROVIDER_NAME_RE.test(name) && !RESERVED_NAMES.has(name);
48
+ const REQUIRED_VERBS = ["launch", "inspect", "input", "stop"];
49
+ const OPTIONAL_VERBS = ["inspectMany", "check"];
50
+ const PROVIDER_KEYS = ["commands", "harnesses", "description", "wire"];
51
+ /** The version of the wire this kernel speaks with a session provider (docs/capabilities.md "The
52
+ * call"). One version: a provider declares it (`sessionProviders.<name>.wire`), and one that
53
+ * declares none, or another, is never called (wireRefusal); every request carries it, so a
54
+ * provider can refuse a kernel that speaks another. */
55
+ export const SESSION_PROVIDER_WIRE = "1.3";
56
+ /** Why a provider is not called: it speaks another wire than this kernel → `{ code:
57
+ * "E_BACKEND_WIRE", message, details }` naming both versions, or null when they agree. A provider
58
+ * that declares no `wire` is one from before the key: wire 1.2. */
59
+ export function wireRefusal(capability, provider) {
60
+ if (provider.wire === SESSION_PROVIDER_WIRE) return null;
61
+ const theirs = provider.wire ?? "1.2 (it declares none)";
62
+ return { code: "E_BACKEND_WIRE", message: `${capability}'s session provider ${provider.name} speaks wire ${theirs}, and this kernel speaks ${SESSION_PROVIDER_WIRE}: they must be the same. Use the release of ${capability} that goes with this OATS`, details: { backend: provider.name, capability, wire: { provider: provider.wire ?? null, kernel: SESSION_PROVIDER_WIRE } } };
63
+ }
64
+ const HARNESS_NAME_RE = /^[a-z][a-z0-9-]{0,39}$/;
65
+ const MAX_PROVIDERS = 16, MAX_HARNESSES = 16, DESCRIPTION_MAX = 200;
66
+ /** An endpoint is a JSON object of at most this many bytes of canonical JSON (4 KiB). */
67
+ export const ENDPOINT_MAX_BYTES = 4096;
68
+ /** A capability id as a home's module directory is named (lib/package-catalog.mjs PACKAGE_ID_RE). */
69
+ const CAPABILITY_ID_RE = /^[a-z0-9][a-z0-9._-]*$/;
70
+ const WIRE_LIMITS = Object.freeze({ maxBytes: 1024 * 1024, maxDepth: 32, maxEntries: 16384 });
71
+ const CODE_RE = /^E_[A-Z0-9_]{1,60}$/;
72
+ const MESSAGE_MAX = 500;
73
+ /** At most this many homes in one `inspectMany` call. */
74
+ export const INSPECT_MANY_MAX = 200;
75
+
76
+ const isObject = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
77
+ const pointerOf = (...tokens) => tokens.map((t) => `/${String(t).replaceAll("~", "~0").replaceAll("/", "~1")}`).join("");
78
+ const oneLine = (v, max) => typeof v === "string" && v.length > 0 && [...v].length <= max && !REFUSED_TEXT.test(v);
79
+
80
+ // ------------------------------------------------------------------------------------- the manifest
81
+
82
+ function checkProvider(manifest, name, decl, problems) {
83
+ const at = (...tokens) => pointerOf("sessionProviders", name, ...tokens);
84
+ const bad = (pointer, message) => problems.push({ provider: name, pointer, message: `session provider ${JSON.stringify(name)}: ${message}` });
85
+ const sound = problems.length;
86
+ if (!SESSION_PROVIDER_NAME_RE.test(name)) bad(at(), "the name must be 1 to 40 lowercase letters, digits and dashes, starting with a letter or digit");
87
+ else if (RESERVED_NAMES.has(name)) bad(at(), `the name ${name} is reserved for the kernel`);
88
+ if (!isObject(decl)) { bad(at(), "must be an object { commands, harnesses, description? }"); return null; }
89
+ for (const k of Object.keys(decl)) if (!PROVIDER_KEYS.includes(k)) bad(at(k), `unknown key ${JSON.stringify(k)} (allowed: ${PROVIDER_KEYS.join(", ")})`);
90
+ if (decl.description !== undefined && !oneLine(decl.description, DESCRIPTION_MAX)) bad(at("description"), `description must be one line of at most ${DESCRIPTION_MAX} characters`);
91
+ // Any version is a sound declaration: one that is not this kernel's is refused where the provider is used (wireRefusal).
92
+ if (decl.wire !== undefined && !(typeof decl.wire === "string" && /^[0-9]{1,3}\.[0-9]{1,3}$/.test(decl.wire))) bad(at("wire"), 'wire must be the wire version the provider speaks, as "<major>.<minor>"');
93
+
94
+ const harnesses = decl.harnesses;
95
+ if (!Array.isArray(harnesses) || harnesses.length < 1 || harnesses.length > MAX_HARNESSES) bad(at("harnesses"), `harnesses must list 1 to ${MAX_HARNESSES} harness names`);
96
+ else harnesses.forEach((h, i) => {
97
+ if (typeof h !== "string" || !HARNESS_NAME_RE.test(h)) bad(at("harnesses", i), "a harness name is 1 to 40 lowercase letters, digits and dashes, starting with a letter");
98
+ else if (harnesses.indexOf(h) !== i) bad(at("harnesses", i), `harness ${JSON.stringify(h)} is listed twice`);
99
+ });
100
+
101
+ const manifestCommands = isObject(manifest.commands) ? manifest.commands : {};
102
+ const commands = {};
103
+ if (!isObject(decl.commands)) bad(at("commands"), `commands must be an object naming ${REQUIRED_VERBS.join(", ")} (and optionally ${OPTIONAL_VERBS.join(", ")})`);
104
+ else {
105
+ for (const k of Object.keys(decl.commands)) if (![...REQUIRED_VERBS, ...OPTIONAL_VERBS].includes(k)) bad(at("commands", k), `unknown verb ${JSON.stringify(k)} (verbs: ${[...REQUIRED_VERBS, ...OPTIONAL_VERBS].join(", ")})`);
106
+ for (const verb of [...REQUIRED_VERBS, ...OPTIONAL_VERBS]) {
107
+ const command = decl.commands[verb];
108
+ if (command === undefined) { if (REQUIRED_VERBS.includes(verb)) bad(at("commands", verb), `commands.${verb} is required`); continue; }
109
+ const spec = typeof command === "string" && Object.hasOwn(manifestCommands, command) ? manifestCommands[command] : undefined;
110
+ if (typeof command !== "string" || !command) bad(at("commands", verb), `commands.${verb} must name one of the manifest's commands`);
111
+ else if (typeof spec !== "string" || !spec.trim()) bad(at("commands", verb), `commands.${verb}: ${JSON.stringify(command)} is not one of the manifest's commands`);
112
+ else { const [script, ...args] = spec.trim().split(/\s+/); commands[verb] = { command, script, args }; }
113
+ }
114
+ }
115
+ if (problems.length > sound) return null;
116
+ return { name, description: decl.description ?? null, harnesses: [...harnesses], commands, wire: decl.wire ?? null };
117
+ }
118
+
119
+ /** A manifest's session providers, validated where they are used. Never throws, whatever `manifest`
120
+ * is. → { providers: { <name>: { name, description, harnesses, commands: { <verb>: { command, script,
121
+ * args } } } }, problems: [{ provider, pointer, message }] }: `providers` holds only the well-formed
122
+ * ones; `provider` is null for a top-level problem. */
123
+ export function sessionProvidersOf(manifest) {
124
+ const out = { providers: {}, problems: [] };
125
+ const decl = isObject(manifest) ? manifest.sessionProviders : undefined;
126
+ if (decl === undefined) return out;
127
+ if (!isObject(decl)) { out.problems.push({ provider: null, pointer: "/sessionProviders", message: "sessionProviders must be an object of named session providers" }); return out; }
128
+ const names = Object.keys(decl);
129
+ if (names.length > MAX_PROVIDERS) { out.problems.push({ provider: null, pointer: "/sessionProviders", message: `sessionProviders declares ${names.length} providers; at most ${MAX_PROVIDERS}` }); return out; }
130
+ for (const name of names) {
131
+ const problems = [];
132
+ const provider = checkProvider(manifest, name, decl[name], problems);
133
+ if (provider) out.providers[name] = provider;
134
+ else out.problems.push(...problems);
135
+ }
136
+ return out;
137
+ }
138
+
139
+ /** The session backends a set of capabilities offers: [{ name, capability, harnesses, description }],
140
+ * sorted by name then capability, with the problems of the malformed ones. `capabilities`:
141
+ * [{ id, manifest }]. A name two capabilities declare is listed twice: `--backend` refuses it. */
142
+ export function offeredSessionProviders(capabilities) {
143
+ const providers = [], problems = [];
144
+ for (const cap of capabilities || []) {
145
+ const found = sessionProvidersOf(cap?.manifest);
146
+ for (const p of Object.values(found.providers)) providers.push({ name: p.name, capability: cap.id, harnesses: p.harnesses, description: p.description });
147
+ for (const problem of found.problems) problems.push({ capability: cap.id, ...problem });
148
+ }
149
+ providers.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : a.capability < b.capability ? -1 : a.capability > b.capability ? 1 : 0));
150
+ return { providers, problems };
151
+ }
152
+
153
+ /** E_BACKEND_AMBIGUOUS: two or more capabilities of one instance declare the provider `name`. */
154
+ export function ambiguousBackend(name, capabilities, nothing) {
155
+ return Object.assign(oatsError("E_BACKEND_AMBIGUOUS", `session backend ${JSON.stringify(name)} is declared by ${capabilities.join(" and ")}; one name has one meaning in an instance: compose only one of them; ${nothing}`), { details: { backend: name, capabilities } });
156
+ }
157
+ /** What `--backend <name>` selects among `capabilities` ([{ id, manifest }]), for `harness`:
158
+ * `{ backend: "tmux" }` for the built-in one, else `{ backend: name, capability, provider }`.
159
+ * Refused before anything is created: E_BACKEND_UNKNOWN (no capability of this instance declares
160
+ * it, or declares it malformed; the message names the backends available), E_BACKEND_AMBIGUOUS
161
+ * (two capabilities declare the name), E_BACKEND_HARNESS (the provider does not list the harness).
162
+ * `nothing` ends each refusal: what the caller has not done ("nothing was created", a spawn's). */
163
+ export function selectSessionBackend(name, capabilities, harness, nothing = "nothing was created") {
164
+ if (name === undefined || name === null || BUILTIN_SESSION_BACKENDS.includes(name)) return { backend: "tmux" };
165
+ const { providers, problems } = offeredSessionProviders(capabilities);
166
+ const matches = providers.filter((p) => p.name === name);
167
+ if (matches.length > 1) throw ambiguousBackend(name, matches.map((p) => p.capability), nothing);
168
+ if (!matches.length) {
169
+ const available = [...BUILTIN_SESSION_BACKENDS, ...new Set(providers.map((p) => p.name))];
170
+ const broken = problems.find((p) => p.provider === name || p.provider === null);
171
+ throw Object.assign(oatsError("E_BACKEND_UNKNOWN", safeText(`unknown session backend ${JSON.stringify(name)}: ${broken ? `capability ${broken.capability} declares it malformed: ${broken.message} (at ${broken.pointer})` : "no capability of this instance declares it as a session provider"}; the backends available here: ${available.join(", ")}; ${nothing}`, 2000)), { details: { backend: String(name).slice(0, 80), available } });
172
+ }
173
+ const [match] = matches;
174
+ const provider = sessionProvidersOf((capabilities || []).find((c) => c.id === match.capability).manifest).providers[name];
175
+ const wire = wireRefusal(match.capability, provider);
176
+ if (wire) throw Object.assign(oatsError(wire.code, `${wire.message}; ${nothing}`), { details: wire.details });
177
+ if (harness !== undefined && !match.harnesses.includes(harness)) throw Object.assign(oatsError("E_BACKEND_HARNESS", `session backend ${name} (${match.capability}) does not run the ${harness} harness; it runs ${match.harnesses.join(", ")}; ${nothing}`), { details: { backend: name, capability: match.capability, harness, harnesses: match.harnesses } });
178
+ return { backend: name, capability: match.capability, provider };
179
+ }
180
+
181
+ // --------------------------------------------------------------------------------------- the records
182
+
183
+ /** Whether `endpoint` is one the kernel records: a JSON object whose canonical JSON (sorted keys, no
184
+ * whitespace; its final line feed not counted) is at most ENDPOINT_MAX_BYTES. */
185
+ export function validEndpoint(endpoint) {
186
+ if (!isObject(endpoint)) return false;
187
+ try { return Buffer.byteLength(canonicalJson(endpoint, WIRE_LIMITS)) - 1 <= ENDPOINT_MAX_BYTES; } catch { return false; }
188
+ }
189
+ /** Two endpoints are the same JSON. */
190
+ export function sameEndpoint(a, b) {
191
+ try { return canonicalJson(a, WIRE_LIMITS) === canonicalJson(b, WIRE_LIMITS); } catch { return false; }
192
+ }
193
+ /** A launch that was SENT to a provider and whose outcome OATS has not recorded: the instant it was
194
+ * sent (`runtime.launchSent`, in the home's receipt, outside the home), or null. The kernel writes
195
+ * it right before it calls the provider's launch and takes it away when the endpoint is recorded
196
+ * or the launch is known to have started nothing. One that is still there afterwards is a spawn or
197
+ * a start that ended first (killed, its host stopped): a session may run that no record names, so
198
+ * every verb that acts on the home first asks the provider to stop whatever session is rooted at
199
+ * it (`stop` with `endpoint: null`), and its reads are unknown, never "not launched". undefined
200
+ * when the field is there and is no instant.
201
+ *
202
+ * On a home that was never launched the receipt reads `{ launched: true, backend, provider,
203
+ * launchSent }` meanwhile, with no endpoint: a kernel from before session providers refuses such
204
+ * a receipt (a launch with no tmux endpoint) instead of reading the home as one it may retire. */
205
+ export function launchSentOf(runtime) {
206
+ const sent = runtime?.launchSent ?? null;
207
+ return sent === null ? null : typeof sent === "string" && Number.isFinite(Date.parse(sent)) ? sent : undefined;
208
+ }
209
+ /** What a read says of a home whose provider was sent a launch that has no recorded outcome. True
210
+ * of both cases, which a read does not tell apart: the launch is in progress, or its command ended. */
211
+ export function unsettledLaunchSaid(name, backend, sent) {
212
+ return `a launch of ${name} was sent to session backend ${backend} at ${sent} and its outcome is not recorded: a spawn or a start is launching it now, or ended before recording it, and whether a session runs is not known. If no such command is running, a stop (oats instance stop ${name} --plan, then --apply) or a start (oats session start --home) first asks the backend to stop whatever session that launch started`;
213
+ }
214
+ /** A receipt's `runtime` as a launched provider home's authority, or undefined when it is not one:
215
+ * `{ launched: true, backend, provider, endpoint, stoppedAt, launchSent }`. `backend` is the provider's name,
216
+ * `provider` the capability that supplies it; `stoppedAt` is an instant or null (OATS stopped this
217
+ * session, and no start has cleared it). Which stop wrote it (an operator's, or the host's
218
+ * shutdown, which a resume brings back) is the home's stop receipt's to say (lib/session-end.mjs),
219
+ * as for a tmux home, never a second field here. */
220
+ export function providerRuntimeOf(runtime) {
221
+ if (!isObject(runtime) || runtime.launched !== true || runtime.tmux !== undefined || runtime.sessionTarget !== undefined) return undefined;
222
+ if (!isSessionProviderName(runtime.backend)) return undefined;
223
+ if (typeof runtime.provider !== "string" || !CAPABILITY_ID_RE.test(runtime.provider) || !validEndpoint(runtime.endpoint)) return undefined;
224
+ const stoppedAt = runtime.stoppedAt ?? null;
225
+ if (stoppedAt !== null && !(typeof stoppedAt === "string" && Number.isFinite(Date.parse(stoppedAt)))) return undefined;
226
+ const launchSent = launchSentOf(runtime);
227
+ if (launchSent === undefined) return undefined;
228
+ return { launched: true, backend: runtime.backend, provider: runtime.provider, endpoint: runtime.endpoint, stoppedAt, launchSent };
229
+ }
230
+ /** The receipt's `runtime` for a launched provider home (`launchSent`: only while a launch that was
231
+ * sent has no recorded outcome, launchSentOf). */
232
+ export function providerRuntimeRecord({ backend, provider, endpoint, stoppedAt = null, launchSent = null }) {
233
+ return { launched: true, backend, provider, endpoint, stoppedAt, ...(launchSent ? { launchSent } : {}) };
234
+ }
235
+ /** The fields of instance.json's session that differ from the one the receipt authorises, as fixed
236
+ * labels in a fixed order: `backend`, `session.provider`, `session.endpoint`. */
237
+ export function providerEndpointDifferences(meta, authority) {
238
+ return [
239
+ ...(meta?.backend === authority.backend ? [] : ["backend"]),
240
+ ...(meta?.session?.provider === authority.provider ? [] : ["session.provider"]),
241
+ ...(isObject(meta?.session?.endpoint) && sameEndpoint(meta.session.endpoint, authority.endpoint) ? [] : ["session.endpoint"]),
242
+ ];
243
+ }
244
+
245
+ // ------------------------------------------------------------------------------------------ the wire
246
+
247
+ /** A verb's timeout in ms: launch 120 s, the others 20 s; a stop also gets the grace it gives its
248
+ * session. OATS_TEST_SESSION_PROVIDER_TIMEOUT_MS (a test's seam) shortens every one: a value
249
+ * above the kernel's own limit is that limit, so the seam never makes a call wait longer. */
250
+ export function sessionProviderTimeout(verb, { graceSeconds = 0 } = {}) {
251
+ const own = verb === "launch" ? 120_000 : verb === "stop" ? 20_000 + graceSeconds * 1000 : 20_000;
252
+ const seam = Number(process.env.OATS_TEST_SESSION_PROVIDER_TIMEOUT_MS);
253
+ return seam > 0 ? Math.min(seam, own) : own;
254
+ }
255
+
256
+ /** A provider as one home runs it → `{ binding }`, or `{ problem }` (one sentence) when the home
257
+ * cannot: its module copy or manifest is missing or unreadable (a capability an upgrade removed),
258
+ * or the manifest no longer declares the provider soundly. `meta`: the home's record (instance.json)
259
+ * as the caller holds it; `capability` and `name` come from the receipt, never from the record alone.
260
+ * binding: `{ home, meta, capability, name, provider, moduleDir, cap, digest }`: `cap` the
261
+ * capability's runtime row (its captured settings), `digest` what tells its module copy from
262
+ * another home's (for a provider home, the module's source as its receipt records it).
263
+ *
264
+ * A home whose receipt names a session provider is bound from that receipt
265
+ * (lib/home-integrity.mjs): `moduleDir` is the KERNEL's copy of the capability, outside the home,
266
+ * whose manifest is read and whose commands are run, never the home's own copy; with no such
267
+ * copy `{ problem }` names the module (a read then shows the home unavailable, never stopped);
268
+ * and `cap` is the receipt's row, never the home's own record's. A home with no receipt yet (a
269
+ * spawn, before it writes one) is bound from its own fresh copy and the rows the spawn holds. */
270
+ export function homeSessionProvider(home, meta, capability, name) {
271
+ if (typeof capability !== "string" || !CAPABILITY_ID_RE.test(capability)) return { problem: `the session provider's capability id ${JSON.stringify(capability)} is not a capability id` };
272
+ const trust = providerHomeTrust(home);
273
+ const moduleDir = runDirOf(home, capability, trust);
274
+ const gone = () => `capability ${capability}, which supplies this home's session backend ${name}, is not among the home's modules (${moduleDir}); respawn the instance from a deployment that composes it`;
275
+ // (A capability an upgrade removed: the receipt records no copy of it any more.)
276
+ if (trust?.composition && !recordsModule(trust, capability)) return { problem: gone() };
277
+ const untrusted = moduleCopyProblem(home, capability, trust);
278
+ if (untrusted) return { problem: untrusted };
279
+ let manifest;
280
+ try { manifest = parseStrictJson(readFileSync(join(moduleDir, "oats.json")), WIRE_LIMITS); }
281
+ catch (e) { return { problem: e?.code === "ENOENT" ? gone() : `the manifest of capability ${capability} in ${moduleDir} cannot be read (${safeText(e?.message ?? e, 200)})` }; }
282
+ if (!isObject(manifest) || manifest.capability !== capability) return { problem: `${join(moduleDir, "oats.json")} is not the manifest of capability ${capability}` };
283
+ const { providers, problems } = sessionProvidersOf(manifest);
284
+ const provider = Object.hasOwn(providers, name) ? providers[name] : null;
285
+ if (!provider) {
286
+ const broken = problems.find((p) => p.provider === name || p.provider === null);
287
+ return { problem: safeText(broken ? `capability ${capability} declares session provider ${name} malformed: ${broken.message} (at ${broken.pointer})` : `capability ${capability} no longer declares session provider ${name}`, 1000) };
288
+ }
289
+ const row = capabilityRuntimeOf(home, meta, trust).find((c) => c?.id === capability);
290
+ // (`providers`: what a home from before `capabilityRuntime` recorded; never read for a provider home.)
291
+ const settings = isObject(row?.settings) ? row.settings : !trust && isObject(meta?.providers?.[capability]) ? meta.providers[capability] : {};
292
+ const cap = { id: capability, layer: row?.layer ?? manifest.layer ?? "", level: row?.level ?? "", settings, settingsOrigins: isObject(row?.settingsOrigins) ? row.settingsOrigins : {} };
293
+ // (`digest`: what tells two homes' copies of a provider apart, for one inspectMany call. For a
294
+ // provider home, whose own record is not read: the module's source, and with none recorded the
295
+ // store of the kernel's copy, which is this home's alone.)
296
+ const source = trust ? trust.composition.modules[capability] : null;
297
+ const digest = trust ? (source.from || source.commit ? canonicalJson(source) : `store:${trust.composition.store}`) : typeof meta?.modules?.[capability]?.digest === "string" ? meta.modules[capability].digest : null;
298
+ return { binding: { home, meta: meta ?? {}, capability, name, provider, moduleDir, cap, digest } };
299
+ }
300
+
301
+ /** An executable inside the module copy: both sides realpath'd (a symlink out of the module is an
302
+ * escape), a regular file; null otherwise. */
303
+ function moduleExecutable(dir, script) {
304
+ let root, file;
305
+ try { root = realpathSync(dir); file = realpathSync(resolve(dir, script)); } catch { return null; }
306
+ const rel = relative(root, file);
307
+ if (!rel || rel === ".." || rel.startsWith(`..${sep}`) || isAbsolute(rel)) return null;
308
+ try { return statSync(file).isFile() ? file : null; } catch { return null; }
309
+ }
310
+
311
+ /** The environment a provider's command runs with in its home: a lifecycle hook's (lib/hook-env.mjs),
312
+ * as the home's launch hooks get it, with OATS_EVENT=session and OATS_BACKEND. */
313
+ function providerEnvironment({ home, meta, cap, name, soulId }) {
314
+ const workspace = isObject(meta.workspace) ? meta.workspace : null;
315
+ return lifecycleHookEnv("session", cap, {
316
+ home, instance: typeof meta.instance === "string" ? meta.instance : basename(home), agentName: typeof meta.agent === "string" ? meta.agent : "",
317
+ // (`soulId`: a spawn's, for a call it makes before the home's record names its soul.)
318
+ soulDir: instanceSoulDir(home, meta), ...(typeof soulId === "string" && soulId ? { soulId } : {}), contextDir: home, rootDir: dirname(dirname(dirname(home))),
319
+ resolved: { workspace, ...recordedTeams(meta), teamsSource: "recorded" },
320
+ priorMeta: isObject(meta.capabilityMeta) ? meta.capabilityMeta : {},
321
+ extraEnv: { OATS_BACKEND: name, ...(typeof meta.harness === "string" ? { OATS_HARNESS: meta.harness } : {}) },
322
+ });
323
+ }
324
+
325
+ /** A provider's refusal as it gives it (`{ code, message? }`: an envelope's `error`, an inspectMany
326
+ * entry's) → `{ code, message }`, the message made safe to print and cut (`fallback` when it gives
327
+ * none), or null when it is no refusal in the wire's shape. */
328
+ function refusalOf(e, fallback) {
329
+ if (!isObject(e) || typeof e.code !== "string" || !CODE_RE.test(e.code) || (e.message !== undefined && typeof e.message !== "string") || Object.keys(e).some((k) => k !== "code" && k !== "message")) return null;
330
+ return { code: e.code, message: safeText(e.message ?? fallback, MESSAGE_MAX) };
331
+ }
332
+ /** What runs a provider's command: the kernel's own process, the leader of a process group made
333
+ * for the call (lib/provider-call-child.mjs). */
334
+ const PROVIDER_CALL_CHILD = fileURLToPath(new URL("./provider-call-child.mjs", import.meta.url));
335
+ /** One call of a provider's verb → `{ ok: true, result }` (the result as answered, not yet judged
336
+ * by its verb's rules), `{ ok: false, refused: { code, message } }` (the provider's own refusal,
337
+ * made safe to print) or `{ ok: false, failed: "<why, one sentence>" }` (a failed call). Never
338
+ * throws. `io.spawnSync` is the process seam.
339
+ *
340
+ * The command runs in a process group of its own, which a timeout ends whole. `groupFile`: where
341
+ * the group's leader records who it is before the provider runs (a path outside the home, of a
342
+ * file that does not exist yet), for a call whose effects must be ended if this kernel is killed
343
+ * while it waits: a launch, an input, a stop (lib/core.mjs markProviderCall). */
344
+ export function callSessionProvider(binding, verb, input, { timeoutMs = sessionProviderTimeout(verb), io, groupFile = null } = {}) {
345
+ // `binding.home` is null, with `binding.env`, for a soul's readiness check: no home exists yet.
346
+ const { capability, name, provider, moduleDir, home } = binding;
347
+ const said = `${capability}'s session provider ${name}`;
348
+ // A provider that speaks another wire is never called: every read of its session is unavailable.
349
+ const wire = wireRefusal(capability, provider);
350
+ if (wire) return { ok: false, failed: wire.message };
351
+ const declared = provider.commands[verb];
352
+ if (!declared) return { ok: false, failed: `${said} declares no ${verb} command` };
353
+ const file = moduleExecutable(moduleDir, declared.script);
354
+ if (!file) return { ok: false, failed: `${said}: the ${verb} command ${declared.command} (${declared.script}) is not a file inside ${home ? "the home's" : "this"} copy of ${capability}` };
355
+ const request = { schemaVersion: 1, wire: SESSION_PROVIDER_WIRE, phase: "session", capability, provider: name, verb, input };
356
+ let r;
357
+ try {
358
+ // (SIGTERM at the timeout: the group's leader answers it by ending the whole group, by SIGKILL.)
359
+ // Tests' seams, for the leader (lib/provider-call-child.mjs): it starts late; it kills this kernel.
360
+ const lateLeader = groupFile ? process.env.OATS_TEST_PROVIDER_LEADER_DELAY_MS : undefined;
361
+ const seams = { ...(lateLeader ? { OATS_TEST_PROVIDER_LEADER_DELAY_MS: lateLeader } : {}), ...(diesDuring(verb) ? { OATS_TEST_PROVIDER_KILL_KERNEL: "1" } : {}) };
362
+ dieAt(`call:${verb}:before`);
363
+ r = (io?.spawnSync || spawnSync)(process.execPath, [PROVIDER_CALL_CHILD, groupFile ?? "-", file, ...declared.args], { cwd: parse(file).root, env: { ...(binding.env ?? providerEnvironment(binding)), ...seams }, input: JSON.stringify(request), encoding: "utf8", timeout: Math.max(1, timeoutMs), killSignal: "SIGTERM", detached: true, maxBuffer: WIRE_LIMITS.maxBytes, stdio: ["pipe", "pipe", "ignore"] });
364
+ } catch (e) { return { ok: false, failed: `${said}: the ${verb} command could not be run (${safeText(e?.code ?? e?.message ?? e, 120)})` }; }
365
+ dieAt(`call:${verb}:after`);
366
+ if (r.error?.code === "ETIMEDOUT") return { ok: false, timedOut: true, failed: `${said} did not answer ${verb} within ${Math.round(timeoutMs / 1000)} s and was killed` };
367
+ if (r.error?.code === "ENOBUFS") return { ok: false, failed: `${said} answered ${verb} with more than the wire's 1 MiB` };
368
+ if (r.error) return { ok: false, failed: `${said}: the ${verb} command could not be run (${safeText(r.error.code ?? r.error.message, 120)})` };
369
+ if (r.signal) return { ok: false, failed: `${said}: the ${verb} command ended on signal ${r.signal}` };
370
+ if (r.status === 125) return { ok: false, failed: `${said}: the ${verb} command was not run (the call could not be recorded, or was ended before it began)` };
371
+ if (r.status !== 0) return { ok: false, failed: `${said}: the ${verb} command exited ${r.status}` };
372
+ let doc;
373
+ try { doc = parseStrictJson(r.stdout || "", WIRE_LIMITS); } catch { return { ok: false, failed: `${said} did not answer ${verb} with exactly one JSON document` }; }
374
+ const malformed = (why) => ({ ok: false, failed: `${said} answered ${verb} with a malformed envelope: ${why}` });
375
+ if (!isObject(doc)) return malformed("not a JSON object");
376
+ const keys = doc.ok === true ? ["schemaVersion", "phase", "capability", "provider", "verb", "ok", "result"] : doc.ok === false ? ["schemaVersion", "phase", "capability", "provider", "verb", "ok", "error"] : null;
377
+ if (!keys) return malformed("ok must be true or false");
378
+ if (Object.keys(doc).some((k) => !keys.includes(k)) || keys.some((k) => !Object.hasOwn(doc, k))) return malformed(`its keys must be exactly ${keys.join(", ")}`);
379
+ for (const k of ["schemaVersion", "phase", "capability", "provider", "verb"]) if (doc[k] !== request[k]) return malformed(`${k} must echo the request's ${JSON.stringify(request[k])}`);
380
+ if (doc.ok === false) {
381
+ const refused = refusalOf(doc.error, `${said} refused ${verb}`);
382
+ return refused ? { ok: false, refused } : malformed("error must be { code, message? }, its code E_ and capitals, digits or underscores");
383
+ }
384
+ return { ok: true, result: doc.result };
385
+ }
386
+ /** What a call that gave no result says, in one sentence: the failure, or the provider's refusal. */
387
+ export const providerSaid = (answer) => answer.failed ?? `${answer.refused.code}: ${answer.refused.message}`;
388
+
389
+ // ------------------------------------------------------------------------------ the answers' rules
390
+
391
+ const exactKeys = (v, required, optional = []) => isObject(v) && required.every((k) => Object.hasOwn(v, k)) && Object.keys(v).every((k) => required.includes(k) || optional.includes(k));
392
+ const STATES = ["unknown", "shell", "stopped"];
393
+ /** `open`: what a client may show instead of a terminal, `{ label, url }`: a one-line label of at
394
+ * most 100 characters and an http(s) URL of at most 2000, printable ASCII, without credentials. */
395
+ function validOpen(open) {
396
+ if (!exactKeys(open, ["label", "url"]) || !oneLine(open.label, 100)) return false;
397
+ if (typeof open.url !== "string" || open.url.length > 2000 || !/^[\x21-\x7e]+$/.test(open.url)) return false;
398
+ let u; try { u = new URL(open.url); } catch { return false; }
399
+ return (u.protocol === "https:" || u.protocol === "http:") && !u.username && !u.password;
400
+ }
401
+ /** A status row's session-provider facts as ANOTHER host reports them (a remote roster's relay,
402
+ * lib/servers.mjs), each kept only in the shape this kernel itself answers: `backend` a provider's
403
+ * name, `session` `{ provider }` and nothing more, `open` `{ label, url }` or null, `runtimeState`
404
+ * one of the row's words. A provider's own locator never leaves its host: no endpoint and no thread
405
+ * id is relayed, whatever the host sent. → those keys, or null when the row is not a session
406
+ * provider's (a tmux row, or a host that does not send these). */
407
+ export function relayedProviderRow(row) {
408
+ if (!isObject(row) || row.tmux || !isSessionProviderName(row.backend)) return null;
409
+ const session = row.session;
410
+ if (!isObject(session) || typeof session.provider !== "string" || !CAPABILITY_ID_RE.test(session.provider) || session.provider.length > 128) return null;
411
+ return {
412
+ backend: row.backend, session: { provider: session.provider },
413
+ open: row.open !== null && row.open !== undefined && validOpen(row.open) ? { label: row.open.label, url: row.open.url } : null,
414
+ ...(["unknown", "shell", "stopped", "unreachable"].includes(row.runtimeState) ? { runtimeState: row.runtimeState } : {}),
415
+ };
416
+ }
417
+ /** An answer of a routed command (`--server`: a spawn's, a start's, an inspect's result) with a
418
+ * provider home's `session` cut to `{ provider }`: the endpoint is for the host where the home
419
+ * lives. Any other answer is returned as it is. */
420
+ export function withoutRelayedEndpoint(result) {
421
+ if (!isObject(result) || !isObject(result.session) || typeof result.session.provider !== "string") return result;
422
+ return { ...result, session: { provider: result.session.provider } };
423
+ }
424
+ /** Whether a home's record (instance.json) says it is on a session provider: it records the
425
+ * provider's `session` and a backend that is no built-in one. The receipt, never this, is the authority. */
426
+ export const recordsSessionProvider = (meta) => isObject(meta?.session) && isSessionProviderName(meta.backend);
427
+ /** Whether a status row is a provider home's. */
428
+ export const isProviderRow = (row) => isObject(row?.session) && isSessionProviderName(row.backend);
429
+ /** A local status row's `session` for a provider home: the capability and, when the recorded
430
+ * endpoint names one (`threadId`, a string of at most 200 characters), the thread id alone, so a
431
+ * tool on the same host can match a session to its instance. Never the endpoint. */
432
+ export function rowSession(provider, endpoint) {
433
+ const threadId = isObject(endpoint) && typeof endpoint.threadId === "string" && endpoint.threadId.length > 0 && endpoint.threadId.length <= 200 && !REFUSED_TEXT.test(endpoint.threadId) ? endpoint.threadId : null;
434
+ return { provider, ...(threadId !== null ? { threadId } : {}) };
435
+ }
436
+ /** An inspect result by the contract's words → `{ present, state, running, open }` (`open` null when
437
+ * the provider offers none), or null when it breaks them. */
438
+ export function judgeInspect(result) {
439
+ if (!exactKeys(result, ["present", "state", "running"], ["open"])) return null;
440
+ if (typeof result.present !== "boolean" || !STATES.includes(result.state) || ![true, false, null].includes(result.running)) return null;
441
+ // Only a row of the contract's table: a session that is not there is stopped and runs nothing.
442
+ if (!result.present && (result.state !== "stopped" || result.running !== false)) return null;
443
+ if (result.open !== undefined && !validOpen(result.open)) return null;
444
+ return { present: result.present, state: result.state, running: result.running, open: result.open ? { label: result.open.label, url: result.open.url } : null };
445
+ }
446
+
447
+ /** Inspect one home's session → `{ observed: { present, state, running, open } }`, or
448
+ * `{ unavailable: "<why>" }`: a refusal, a failed call and a result that breaks the words are all
449
+ * unknown, never stopped. */
450
+ export function inspectProviderSession(binding, endpoint, { io, timeoutMs = sessionProviderTimeout("inspect") } = {}) {
451
+ const answer = callSessionProvider(binding, "inspect", { home: binding.home, endpoint }, { io, timeoutMs });
452
+ if (!answer.ok) return { unavailable: providerSaid(answer) };
453
+ const observed = judgeInspect(answer.result);
454
+ return observed ? { observed } : { unavailable: `${binding.capability}'s session provider ${binding.name} answered inspect with a result that is not { present, state, running, open? } in the contract's words` };
455
+ }
456
+
457
+ /** The key of the homes one `inspectMany` call may hold: one module copy's content (capability and
458
+ * digest), one provider, one set of settings (the call's environment is the first home's). */
459
+ export function inspectManyGroup(binding) {
460
+ if (!binding.provider.commands.inspectMany || !binding.digest) return null;
461
+ try { return canonicalJson([binding.capability, binding.digest, binding.name, binding.cap.settings], WIRE_LIMITS); } catch { return null; }
462
+ }
463
+ /** Inspect the sessions of `entries` ([{ binding, endpoint }], one inspectManyGroup, at most
464
+ * INSPECT_MANY_MAX) with one call → one inspectProviderSession answer per entry, in order. Each
465
+ * entry of the batch is judged as one inspect's answer would be. A batch that fails or is
466
+ * malformed (a failed call, `results` that are not one per home), and an entry that is neither an
467
+ * inspect result in the contract's words nor a well-formed refusal, fall back to that home's own
468
+ * `inspect`: a bad batch is never read as "stopped", and never as an answer for another home.
469
+ * A batch that TIMED OUT is not asked again home by home: a provider that does not answer one call
470
+ * would cost its timeout once more per home, so every entry is `unavailable`. `timeoutFor()` gives
471
+ * each call's timeout in ms (a listing's remaining time), 0 or less meaning none is left. */
472
+ export function inspectProviderSessions(entries, { io, timeoutFor = () => sessionProviderTimeout("inspect") } = {}) {
473
+ const [first] = entries;
474
+ const spent = "the time this listing gives its session providers was spent before this one was asked";
475
+ const own = ({ binding, endpoint }) => { const timeoutMs = timeoutFor(); return timeoutMs > 0 ? inspectProviderSession(binding, endpoint, { io, timeoutMs }) : { unavailable: spent }; };
476
+ const batchMs = timeoutFor();
477
+ if (!(batchMs > 0)) return entries.map(() => ({ unavailable: spent }));
478
+ const answer = callSessionProvider(first.binding, "inspectMany", { homes: entries.map(({ binding, endpoint }) => ({ home: binding.home, instance: typeof binding.meta.instance === "string" ? binding.meta.instance : basename(binding.home), endpoint })) }, { io, timeoutMs: batchMs });
479
+ if (answer.timedOut) return entries.map(() => ({ unavailable: answer.failed }));
480
+ const results = answer.ok && exactKeys(answer.result, ["results"]) && Array.isArray(answer.result.results) && answer.result.results.length === entries.length ? answer.result.results : null;
481
+ if (!results) return entries.map(own);
482
+ return results.map((result, i) => {
483
+ if (exactKeys(result, ["error"])) {
484
+ const refused = refusalOf(result.error, `${first.binding.capability}'s session provider ${first.binding.name} refused inspect`);
485
+ return refused ? { unavailable: `${refused.code}: ${refused.message}` } : own(entries[i]);
486
+ }
487
+ const observed = judgeInspect(result);
488
+ return observed ? { observed } : own(entries[i]);
489
+ });
490
+ }
491
+
492
+ /** The four statuses of a provider's readiness (`check`), the binding check's own. */
493
+ export const CHECK_STATUSES = Object.freeze(["ready", "needs-configuration", "authorization-required", "unavailable"]);
494
+ const codeMessages = (list) => Array.isArray(list) && list.every((x) => exactKeys(x, ["code", "message"]) && typeof x.code === "string" && x.code.length > 0 && x.code.length <= 128 && !/[\x00-\x1f\x7f]/.test(x.code) && typeof x.message === "string");
495
+ /** A provider's readiness, where it declares the optional `check` command (docs/capabilities.md,
496
+ * "check (optional)"): for a
497
+ * home (`{ home, soul: null, settings }`) or, before any home exists, a soul (`{ home: null, soul,
498
+ * settings }`). → `{ result: { status, problems, warnings } }` in the readiness `providers` shape
499
+ * (`status` one of CHECK_STATUSES; `problems` and `warnings` `[{ code, message }]`, messages made
500
+ * safe to print; no problem on `ready`), `{ unavailable: "<why>" }` when the provider failed,
501
+ * refused or answered outside those rules, or null when the provider declares no check. */
502
+ export function checkProviderSession(binding, input, { io, timeoutMs = sessionProviderTimeout("check") } = {}) {
503
+ if (!binding.provider.commands.check) return null;
504
+ const answer = callSessionProvider(binding, "check", input, { io, timeoutMs });
505
+ if (!answer.ok) return { unavailable: providerSaid(answer) };
506
+ const r = answer.result;
507
+ const sound = exactKeys(r, ["status", "problems"], ["warnings"]) && CHECK_STATUSES.includes(r.status) && codeMessages(r.problems) && (r.warnings === undefined || codeMessages(r.warnings)) && !(r.status === "ready" && r.problems.length);
508
+ if (!sound) return { unavailable: `${binding.capability}'s session provider ${binding.name} answered check with a result that is not { status, problems, warnings? } in the readiness words` };
509
+ const safe = (list) => list.map((x) => ({ code: x.code, message: safeText(x.message, MESSAGE_MAX) }));
510
+ return { result: { status: r.status, problems: safe(r.problems), warnings: safe(r.warnings ?? []) } };
511
+ }
512
+ /** The refusal of a launch whose provider is not ready, or null when it is (or declares no check):
513
+ * the kernel asks a provider's readiness for the home right before every launch, so a launch is
514
+ * never sent to a backend that says it cannot take it. `{ code, message }`: the first problem's
515
+ * own code when it is an E_BACKEND_* one, else E_BACKEND_NOT_READY; the message carries every
516
+ * problem the provider named, or why its readiness could not be read. `launch`: the launch that
517
+ * is planned, `{ harness, yolo, args, sandbox }` as its launch input will carry them, so a provider
518
+ * can refuse HERE what it would refuse at the launch (a session it would sandbox whose allowances
519
+ * are `unavailable` or have `missing` entries: only it knows its mode), before a restart stops
520
+ * anything. */
521
+ export function launchReadinessRefusal(binding, { io, launch } = {}) {
522
+ const checked = checkProviderSession(binding, { home: binding.home, soul: null, settings: binding.cap.settings, ...(launch ? { launch } : {}) }, { io });
523
+ if (checked === null || checked.result?.status === "ready") return null;
524
+ const said = `${binding.capability}'s session provider ${binding.name}`;
525
+ if (checked.unavailable) return { code: "E_BACKEND_NOT_READY", message: `${said} is not ready: its readiness could not be read (${checked.unavailable})` };
526
+ const own = checked.result.problems.find((x) => /^E_BACKEND_[A-Z0-9_]{1,50}$/.test(x.code));
527
+ return { code: own?.code ?? "E_BACKEND_NOT_READY", message: `${said} is not ready (${checked.result.status})${checked.result.problems.length ? `: ${checked.result.problems.map((x) => `${x.code}: ${x.message}`).join("; ")}` : ""}` };
528
+ }
529
+ /** The provider's refusals of an input that the kernel relays as its own codes: nothing was sent. */
530
+ const INPUT_REFUSALS = new Set(["E_SESSION_PROMPT_OPEN", "E_SESSION_INPUT_QUEUED"]);
531
+ /** An input error's mark that the provider itself refused the input, so nothing was sent
532
+ * (inputWasRefused). Without it the input's fate is not known: the call failed, or answered
533
+ * outside the rules, and the provider may have dispatched it. */
534
+ const INPUT_NOT_SENT = Symbol("oats.inputNotSent");
535
+ /** Whether an error of inputProviderSession says the provider refused the input: nothing was sent. */
536
+ export const inputWasRefused = (error) => error?.[INPUT_NOT_SENT] === true;
537
+ /** Send `text` to one home's session → `{ submitted: true, verified }`. Throws E_SESSION_PROMPT_OPEN
538
+ * or E_SESSION_INPUT_QUEUED as the provider gives them, else E_SESSION_INPUT_FAILED. An error for
539
+ * the provider's own refusal says nothing was sent (inputWasRefused); any other leaves it unknown. */
540
+ export function inputProviderSession(binding, endpoint, text, { io, groupFile } = {}) {
541
+ const answer = callSessionProvider(binding, "input", { home: binding.home, endpoint, text }, { io, groupFile });
542
+ if (!answer.ok) {
543
+ if (answer.refused) throw Object.assign(INPUT_REFUSALS.has(answer.refused.code) ? oatsError(answer.refused.code, answer.refused.message) : oatsError("E_SESSION_INPUT_FAILED", `cannot submit session input: ${providerSaid(answer)}`), { [INPUT_NOT_SENT]: true });
544
+ throw oatsError("E_SESSION_INPUT_FAILED", `cannot submit session input: ${providerSaid(answer)}; whether the input was sent is not known`);
545
+ }
546
+ if (!exactKeys(answer.result, ["submitted", "verified"]) || answer.result.submitted !== true || typeof answer.result.verified !== "boolean") {
547
+ throw oatsError("E_SESSION_INPUT_FAILED", `cannot submit session input: ${binding.capability}'s session provider ${binding.name} answered input with a result that is not { submitted: true, verified }; whether the input was sent is not known`);
548
+ }
549
+ return { submitted: true, verified: answer.result.verified };
550
+ }
551
+
552
+ /** Stop one home's session, giving it `graceSeconds` → `{ stopped: true }`, or `{ failed: "<why>" }`.
553
+ * `endpoint` null: whatever live session is rooted at the home (a launch whose answer was lost, or
554
+ * one that was sent and never recorded). `launchSent`, then: the instant the kernel recorded for
555
+ * that launch, so the provider can tell what the launch started from what was there before. */
556
+ export function stopProviderSession(binding, endpoint, graceSeconds, { io, launchSent = null, groupFile } = {}) {
557
+ const answer = callSessionProvider(binding, "stop", { home: binding.home, endpoint, graceSeconds, ...(endpoint === null && launchSent ? { launchSent } : {}) }, { timeoutMs: sessionProviderTimeout("stop", { graceSeconds }), io, groupFile });
558
+ if (!answer.ok) return { failed: providerSaid(answer) };
559
+ if (!exactKeys(answer.result, ["stopped"]) || answer.result.stopped !== true) return { failed: `${binding.capability}'s session provider ${binding.name} answered stop with a result that is not { stopped: true }` };
560
+ return { stopped: true };
561
+ }
562
+
563
+ /** Launch one home's session → `{ endpoint }`, or `{ refused: { code, message } }` (the provider's
564
+ * own E_BACKEND_* refusal: nothing was launched) or `{ failed: "<why>", uncertain }`: `uncertain`
565
+ * when the call did not end with an answer, so a session may have been started. */
566
+ export function launchProviderSession(binding, input, { io, groupFile } = {}) {
567
+ const answer = callSessionProvider(binding, "launch", input, { io, groupFile });
568
+ if (!answer.ok) {
569
+ if (answer.refused) return /^E_BACKEND_[A-Z0-9_]+$/.test(answer.refused.code) ? { refused: answer.refused } : { failed: providerSaid(answer), uncertain: false };
570
+ return { failed: answer.failed, uncertain: true };
571
+ }
572
+ if (!exactKeys(answer.result, ["endpoint"]) || !validEndpoint(answer.result.endpoint)) return { failed: `${binding.capability}'s session provider ${binding.name} answered launch with an endpoint that is not a JSON object of at most ${ENDPOINT_MAX_BYTES} bytes`, uncertain: true };
573
+ // A plain copy: the strict decoder's objects have no prototype, and the endpoint is recorded as JSON.
574
+ return { endpoint: JSON.parse(JSON.stringify(answer.result.endpoint)) };
575
+ }