@awebai/oats 0.68.1 → 0.69.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/oats.mjs +180 -36
- package/docs/capabilities.md +73 -10
- package/docs/capability-manifest.schema.json +1 -1
- package/docs/configuration.md +68 -2
- package/docs/design/2026-09-23-workspace-module-contracts.md +6 -4
- package/docs/design/2026-10-22-module-upgrade.md +1 -1
- package/docs/desktop-cli-api.md +600 -25
- package/docs/desktop-instance-start.md +59 -3
- package/docs/desktop.md +175 -10
- package/docs/execution-targets.md +536 -62
- package/docs/harness-trust.md +3 -1
- package/docs/implementation.md +33 -15
- package/docs/integrations.md +2 -2
- package/docs/knowledge.md +25 -16
- package/docs/oats-local.schema.json +2 -2
- package/docs/official-catalog.md +6 -5
- package/docs/packages.md +14 -14
- package/docs/release-notes/v0.69.0.md +658 -0
- package/docs/release-notes/v0.69.1.md +25 -0
- package/docs/release-notes/v0.69.2.md +259 -0
- package/docs/servers.md +51 -7
- package/docs/soul.schema.json +1 -0
- package/docs/souls-and-instances.md +46 -9
- package/docs/tui.md +177 -21
- package/docs/upgrading.md +16 -7
- package/docs/workspaces.md +2 -2
- package/injects/instance-boundary.md +19 -33
- package/injects/work-attached.md +8 -13
- package/injects/work-checkout.md +16 -30
- package/injects/work-directory.md +9 -15
- package/injects/work-workspace.md +8 -19
- package/injects/work-worktree.md +18 -33
- package/lib/capability-contract.mjs +2 -2
- package/lib/core.mjs +496 -127
- package/lib/file-pieces.mjs +49 -0
- package/lib/instance-background.mjs +54 -0
- package/lib/instance-events.mjs +25 -4
- package/lib/instance-inspect.mjs +3 -0
- package/lib/instance-lifecycle.mjs +35 -0
- package/lib/instance-resolution.mjs +3 -2
- package/lib/instance-same-work.mjs +67 -0
- package/lib/instance-upgrade.mjs +18 -0
- package/lib/launch-prompt-fixtures/README.md +62 -0
- package/lib/launch-prompt-fixtures/resume-confirmation.json +32 -0
- package/lib/launch-prompt-fixtures.mjs +49 -0
- package/lib/launch-prompt-resume.mjs +55 -0
- package/lib/login-environment.mjs +27 -9
- package/lib/materialize.mjs +23 -2
- package/lib/resolve.mjs +32 -5
- package/lib/schedule.mjs +3 -3
- package/lib/servers.mjs +136 -27
- package/lib/session-end.mjs +82 -0
- package/lib/session-input.mjs +43 -9
- package/lib/session-resume-contract.mjs +33 -0
- package/lib/session-resume.mjs +337 -0
- package/lib/session-seen.mjs +163 -0
- package/lib/session-viewer.mjs +147 -44
- package/lib/soul-composition.mjs +15 -11
- package/lib/start-env.mjs +110 -0
- package/lib/tmux-server-scope.mjs +139 -14
- package/lib/workspace.mjs +41 -6
- package/package-catalog.json +11 -5
- package/package.json +1 -1
- package/packages/client/cli-adapter.mjs +39 -8
- package/packages/client/cli-locator.mjs +3 -2
- package/packages/client/deployment-data.mjs +16 -0
- package/packages/client/deployment-panel.mjs +7 -0
- package/packages/client/file-output-exec.mjs +98 -0
- package/packages/client/instance-tree.mjs +64 -14
- package/packages/client/launch-prompt-outcome.mjs +25 -13
- package/packages/client/own-codes.mjs +2 -0
- package/packages/client/panel-views.mjs +11 -3
- package/packages/client/remote-roster.mjs +5 -1
- package/packages/client/roster-sections.mjs +50 -6
- package/packages/client/same-work.mjs +49 -0
- package/packages/client/session-attach.mjs +35 -5
- package/packages/client/session-resume-cli.mjs +64 -0
- package/packages/client/session-resume-trigger.mjs +167 -0
- package/packages/client/session-resume.mjs +332 -0
- package/packages/client/soul-rows.mjs +2 -0
- package/packages/client/spawn-apply-contract.mjs +2 -1
- package/packages/client/spawn-decision.mjs +4 -1
- package/packages/client/spawn-preview-contract.mjs +12 -1
- package/packages/client/spawn-preview.mjs +2 -0
- package/packages/client/tmux-status.mjs +30 -7
- package/packages/client/waiting-on-you.mjs +11 -4
- package/packages/client/workspace-step.mjs +17 -5
- package/packages/record/lib/last-conversation.mjs +123 -0
- package/packages/record/lib/session-roots.mjs +10 -1
- package/packages/tui/README.md +2 -2
- package/packages/tui/lib/client.mjs +7 -3
- package/packages/tui/lib/main.mjs +49 -14
- package/packages/tui/lib/model.mjs +146 -55
- package/packages/tui/lib/store.mjs +84 -27
- package/packages/tui/lib/term/text.mjs +12 -9
- package/packages/tui/lib/views/frame.mjs +74 -7
- package/packages/tui/lib/views/help.mjs +10 -3
- package/packages/tui/lib/views/instances.mjs +41 -3
- package/skills/oats-getting-started/SKILL.md +117 -4
package/lib/materialize.mjs
CHANGED
|
@@ -107,6 +107,15 @@ function assertResolution(resolution) {
|
|
|
107
107
|
if (resolution.skills !== undefined && !Array.isArray(resolution.skills)) throw bad("/skills", "must be an array when present");
|
|
108
108
|
if (resolution.injects !== undefined && !Array.isArray(resolution.injects)) throw bad("/injects", "must be an array when present");
|
|
109
109
|
if (resolution.payloads !== undefined && !plainObject(resolution.payloads)) throw bad("/payloads", "must be an object when present");
|
|
110
|
+
if (resolution.instructionOrder !== undefined) {
|
|
111
|
+
if (!Array.isArray(resolution.instructionOrder)) throw bad("/instructionOrder", "must be an array of module names when present");
|
|
112
|
+
const listed = new Set();
|
|
113
|
+
resolution.instructionOrder.forEach((name, i) => {
|
|
114
|
+
if (!seen.has(name)) throw bad(`/instructionOrder/${i}`, `names no module (found ${JSON.stringify(name)})`);
|
|
115
|
+
if (listed.has(name)) throw bad(`/instructionOrder/${i}`, `lists module ${JSON.stringify(name)} twice`);
|
|
116
|
+
listed.add(name);
|
|
117
|
+
});
|
|
118
|
+
}
|
|
110
119
|
return resolution;
|
|
111
120
|
}
|
|
112
121
|
|
|
@@ -317,6 +326,14 @@ function moduleInjects(resolution, module, moduleDir) {
|
|
|
317
326
|
return rels;
|
|
318
327
|
}
|
|
319
328
|
|
|
329
|
+
/** Capability blocks (`capability:<module>`, built in module order) in `resolution.instructionOrder`;
|
|
330
|
+
* a module the order does not list keeps its place after the listed ones. Stable within a module. */
|
|
331
|
+
function instructionOrdered(resolution, blocks) {
|
|
332
|
+
const order = Array.isArray(resolution.instructionOrder) ? resolution.instructionOrder : [];
|
|
333
|
+
const rank = (b) => { const i = order.indexOf(b.source.slice("capability:".length)); return i < 0 ? order.length : i; };
|
|
334
|
+
return blocks.map((b, i) => ({ b, i, r: rank(b) })).sort((x, y) => x.r - y.r || x.i - y.i).map(({ b }) => b);
|
|
335
|
+
}
|
|
336
|
+
|
|
320
337
|
/* ───────────────────────────── home ─────────────────────────────── */
|
|
321
338
|
|
|
322
339
|
function assertHome(home) {
|
|
@@ -371,10 +388,14 @@ function ensureOatsDir(home) {
|
|
|
371
388
|
* lock oats-lock.json v3 object: package repo/path/commit for from.kind === "package"
|
|
372
389
|
* catalog { <id>: { url, ref, path } } for lock entries whose source is "catalog:<id>"
|
|
373
390
|
* soulAgentsMd the soul's canonical AGENTS.md text (else read from options.soulDir)
|
|
374
|
-
* blocks pre-rendered blocks [{ source, file, content }] placed
|
|
391
|
+
* blocks pre-rendered blocks [{ source, file, content }] placed AFTER the capability injects
|
|
375
392
|
* (the kernel's own kernel:… and work-mode:… blocks, composed by core.mjs)
|
|
376
393
|
* now() ISO timestamp source (tests)
|
|
377
394
|
*
|
|
395
|
+
* The AGENTS.md is the soul's body, then each module's inject in `resolution.instructionOrder`
|
|
396
|
+
* (the soul's listing, then the workspace defaults' order; a module the order omits follows, in
|
|
397
|
+
* module order), then `blocks`. `outcome.blocks` lists every block in that written order.
|
|
398
|
+
*
|
|
378
399
|
* stageMaterialize adds `replace` (complete roots), `staging` (explicit scratch
|
|
379
400
|
* directory), `existingModules` (name → frozen source path), and `instanceJson`
|
|
380
401
|
* (derived metadata transform). Its commit({preserveOnFailure:true}) retains
|
|
@@ -544,7 +565,7 @@ export async function stageMaterialize(resolution, home, options = {}) {
|
|
|
544
565
|
moduleRows.push({ name: module.name, from, commit: source.commit, digest, files: fetched.files ?? null, bytes: fetched.bytes ?? null, path: finalModule, materializedAt: at });
|
|
545
566
|
}
|
|
546
567
|
|
|
547
|
-
const blocks = [...(Array.isArray(options.blocks) ? options.blocks : [])
|
|
568
|
+
const blocks = [...instructionOrdered(resolution, capabilityBlocks), ...(Array.isArray(options.blocks) ? options.blocks : [])];
|
|
548
569
|
for (const b of blocks) {
|
|
549
570
|
if (!plainObject(b) || typeof b.source !== "string" || typeof b.file !== "string" || typeof b.content !== "string") {
|
|
550
571
|
throw fail("E_MATERIALIZE_RESOLUTION", "options.blocks entries must be { source, file, content } strings", { block: b });
|
package/lib/resolve.mjs
CHANGED
|
@@ -367,6 +367,30 @@ export function composeCapabilities(workspace, soulDefinition, { offs = null } =
|
|
|
367
367
|
return [...map.values()].sort((a, b) => byCodepoint(a.name, b.name));
|
|
368
368
|
}
|
|
369
369
|
|
|
370
|
+
/**
|
|
371
|
+
* The order a soul's capability instructions take in its composed AGENTS.md: the capabilities the soul
|
|
372
|
+
* lists, in its `capabilities:` order, then the workspace defaults it does not list, in the order the
|
|
373
|
+
* workspace's `defaults:` lists them (slot defaults and `defaults.capabilities` entries as they appear in
|
|
374
|
+
* the file). Each capability sits where the entry that composed it (its `via`) lists it, so a soul entry
|
|
375
|
+
* that re-lists a default sits at the soul's position. A name made only of digits comes first in its map
|
|
376
|
+
* (JavaScript orders integer-like keys first): a documented quirk. `declared` is composeCapabilities' output,
|
|
377
|
+
* over the same workspace and soul definition. → [name], every declared name once.
|
|
378
|
+
*/
|
|
379
|
+
export function instructionOrder(workspace, soulDefinition, declared) {
|
|
380
|
+
const viaOf = new Map(declared.map((d) => [d.name, d.via]));
|
|
381
|
+
const order = [];
|
|
382
|
+
const take = (entries, via) => {
|
|
383
|
+
for (const name of Object.keys(isObject(entries) ? entries : {})) if (viaOf.get(name) === via && !order.includes(name)) order.push(name);
|
|
384
|
+
};
|
|
385
|
+
take(soulDefinition?.capabilities, "soul");
|
|
386
|
+
const defaults = isObject(workspace?.defaults) ? workspace.defaults : {};
|
|
387
|
+
for (const key of Object.keys(defaults)) {
|
|
388
|
+
if (key === "capabilities") take(defaults.capabilities, "defaults.capabilities");
|
|
389
|
+
else if (SLOTS.includes(key)) take(defaults[key], `defaults.${key}`);
|
|
390
|
+
}
|
|
391
|
+
return order;
|
|
392
|
+
}
|
|
393
|
+
|
|
370
394
|
/* ───────────────────────────── lookups ────────────────────────────────── */
|
|
371
395
|
|
|
372
396
|
/** A discovery's member row by key (the first with that key; lib/workspace.mjs memberRowByKey). */
|
|
@@ -603,7 +627,7 @@ export function lockedCapability(name, id, entry, capabilities, details = { capa
|
|
|
603
627
|
* options: { local, lock, spawn = { providers? }, catalog, remote, remoteOptions }
|
|
604
628
|
* `catalog` (package-catalog.json shape) tells which repo a `catalog:<id>` lock entry is read from.
|
|
605
629
|
*
|
|
606
|
-
* → Resolution { resolutionApi: 1, soul, modules[], slots, payloads, payloadOrigins, skills[], injects[], revision } — deep-frozen.
|
|
630
|
+
* → Resolution { resolutionApi: 1, soul, modules[], slots, payloads, payloadOrigins, skills[], injects[], instructionOrder[], revision } — deep-frozen.
|
|
607
631
|
* Extra fields beyond the contract (recorded for materialize): module.dir (capability dir, repo-relative)
|
|
608
632
|
* and from.repoKey on package modules.
|
|
609
633
|
*/
|
|
@@ -627,9 +651,9 @@ export async function resolveSoul(discovery, soulEntry, { local = null, lock = n
|
|
|
627
651
|
// What the soul turned off (feature desktop-facts): its own `off` over a lower layer, and a `<slot>: none`
|
|
628
652
|
// that dropped a workspace default below. Provenance, like slotsFrom.
|
|
629
653
|
const offs = [];
|
|
630
|
-
const
|
|
631
|
-
|
|
632
|
-
|
|
654
|
+
const composedWorkspace = discovery?.standalone === true ? null : workspace;
|
|
655
|
+
const composedSoul = discovery?.standalone === true ? { ...definition, capabilities: soulEntry.capabilities ?? definition.capabilities } : definition;
|
|
656
|
+
const declared = composeCapabilities(composedWorkspace, composedSoul, { offs });
|
|
633
657
|
const turnedOff = offs;
|
|
634
658
|
|
|
635
659
|
const modules = [];
|
|
@@ -816,8 +840,11 @@ export async function resolveSoul(discovery, soulEntry, { local = null, lock = n
|
|
|
816
840
|
// `capabilitiesFrom` (the same per composed capability) and `turnedOff` (feature desktop-facts).
|
|
817
841
|
const teams = reportRows(soulTeamsHere.teams), defaultTeam = soulTeamsHere.defaultTeam;
|
|
818
842
|
const capabilitiesFrom = Object.fromEntries(modules.map((m) => [m.name, fromOfVia(viaOf.get(m.name))]));
|
|
843
|
+
// `instructionOrder` (the order the modules' injects take in the composed AGENTS.md: the soul's listing,
|
|
844
|
+
// then the workspace defaults' file order) is provenance too: reordering a soul's list is no composition change.
|
|
845
|
+
const order = instructionOrder(composedWorkspace, composedSoul, declared).filter((name) => moduleNames.has(name));
|
|
819
846
|
turnedOff.sort((a, b) => byCodepoint(a.name, b.name));
|
|
820
|
-
return deepFreeze({ ...decl, payloads, payloadOrigins: origins, teams, defaultTeam, slotsFrom, capabilitiesFrom, turnedOff, declRevision, payloadRevision, revision });
|
|
847
|
+
return deepFreeze({ ...decl, payloads, payloadOrigins: origins, teams, defaultTeam, slotsFrom, capabilitiesFrom, instructionOrder: order, turnedOff, declRevision, payloadRevision, revision });
|
|
821
848
|
}
|
|
822
849
|
|
|
823
850
|
/** Where a composed capability came from, as the Desktop names it (`layers.<layer>.from`): the soul's own
|
package/lib/schedule.mjs
CHANGED
|
@@ -37,6 +37,7 @@ import { resolveMemberClone } from "./instance-resolution.mjs";
|
|
|
37
37
|
import { SCHEDULE_NAME_RE, HOST_NAME_RE, readSnapshot, hostOf, trusted, parseOwner, MODEL_RE, automationContext, automationError, baseRow, localEntry, localId, soulOriginOf, splitId, validateDescription } from "./automations.mjs";
|
|
38
38
|
import { RESERVED_LAUNCH_ENV, MAX_INSTANCE_NAME, shq, shellWord, findAgent, findInstanceHomes, inspectInstanceSession, inputInstanceSession, sessionServerGone, startInstanceSession, retirePendingMarkerPath } from "./core.mjs";
|
|
39
39
|
import { writeThroughPrivateFile } from "./write-through-private-file.mjs";
|
|
40
|
+
import { readStartExited } from "./session-end.mjs";
|
|
40
41
|
|
|
41
42
|
export const SCHEDULE_FILE = "oats-schedules.json";
|
|
42
43
|
export const SCHEDULE_API = 2;
|
|
@@ -518,9 +519,8 @@ function startupInProgress(home) {
|
|
|
518
519
|
const pendingPath = join(home, ".oats-start-pending.json");
|
|
519
520
|
if (!existsSync(pendingPath)) return false;
|
|
520
521
|
let pending; try { pending = JSON.parse(readFileSync(pendingPath, "utf8")); } catch { return true; }
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
try { return readFileSync(exitedPath, "utf8").trim() !== String(pending.id); } catch { return true; }
|
|
522
|
+
// The exit marker in either form (lib/session-end.mjs): the legacy start id, or {startId, status}.
|
|
523
|
+
return readStartExited(home)?.startId !== String(pending?.id);
|
|
524
524
|
}
|
|
525
525
|
|
|
526
526
|
/** All homes for an instance name across the scope's roster (every known
|
package/lib/servers.mjs
CHANGED
|
@@ -17,7 +17,7 @@
|
|
|
17
17
|
*/
|
|
18
18
|
|
|
19
19
|
import { execFile, execFileSync, spawnSync } from "node:child_process";
|
|
20
|
-
import { createHash } from "node:crypto";
|
|
20
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
21
21
|
import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
|
|
22
22
|
import { homedir } from "node:os";
|
|
23
23
|
import { basename, join, resolve } from "node:path";
|
|
@@ -29,6 +29,7 @@ import { paletteColor } from "./instance-color.mjs";
|
|
|
29
29
|
import { withDirLock } from "./dir-lock.mjs";
|
|
30
30
|
import { shellWord } from "./core.mjs";
|
|
31
31
|
import { DETACH_KEY_FEATURE, requireDetachKey } from "./session-viewer.mjs";
|
|
32
|
+
import { LOGIN_CAPTURE_MAX_BYTES, LOGIN_SHELLS, loginPathEmitter, quoteFor, readLoginFrame } from "./login-environment.mjs";
|
|
32
33
|
|
|
33
34
|
const OATS_HOME_DIR = () => process.env.OATS_HOME_DIR || join(homedir(), ".oats");
|
|
34
35
|
export const SERVERS_FILE = () => join(OATS_HOME_DIR(), "servers.json");
|
|
@@ -268,6 +269,12 @@ export function sshArgv(target, oatsArgs, { cwd, control = false } = {}) {
|
|
|
268
269
|
// Sharing is on only when the caller checked the control directory
|
|
269
270
|
// (controlUsable); otherwise ControlPath=none.
|
|
270
271
|
const cmd = (cwd ? `cd ${remoteQuote(cwd)} && ` : "") + prefix + [target.oatsPath, ...oatsArgs].map(remoteQuote).join(" ");
|
|
272
|
+
return sshLineArgv(target, cmd, { control });
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/** argv for the local ssh process that hands one command line, as it is, to the host user's login
|
|
276
|
+
* shell: the caller has quoted every word of it for that shell. */
|
|
277
|
+
function sshLineArgv(target, cmd, { control = false } = {}) {
|
|
271
278
|
return ["ssh", ...SSH_OPTS, ...(control && !controlPathProblem() ? controlOpts() : NO_CONTROL_OPTS), "--", target.sshHost, cmd];
|
|
272
279
|
}
|
|
273
280
|
|
|
@@ -668,6 +675,11 @@ export function routeCommand(serverId, cmd, oatsArgs, io = {}) {
|
|
|
668
675
|
if (oatsArgs.includes("--suggest-name")) requireRemoteFeature(remote, target, preview ? "spawn-suggest-name" : "spawn-apply-suggest-name");
|
|
669
676
|
// An exact name is the host's to take: a host without spawn-name would refuse the flag, or worse.
|
|
670
677
|
if (oatsArgs.includes("--name")) requireRemoteFeature(remote, target, "spawn-name");
|
|
678
|
+
// Feature instance-background: an older host would refuse the flag as unknown, or place the instance
|
|
679
|
+
// in the main list; either is said here, before anything is sent.
|
|
680
|
+
if (oatsArgs.includes("--background") || oatsArgs.includes("--no-background")) requireRemoteFeature(remote, target, "instance-background");
|
|
681
|
+
// A host without instance-same-work would refuse the flag as unknown: it is never sent there.
|
|
682
|
+
if (oatsArgs.includes("--same-work")) requireRemoteFeature(remote, target, "instance-same-work");
|
|
671
683
|
const { envelope, stderr } = runRemote(target, json(withScope(["spawn", ...hostHarnessArgs(remote, oatsArgs)])), io);
|
|
672
684
|
if (preview && envelope.ok && envelope.result?.preview === true && envelope.result.spawnPreviewApi === 2) {
|
|
673
685
|
// The host's preview with the two fields a routed spawn adds; never a
|
|
@@ -812,6 +824,10 @@ const HOST_SURFACES = {
|
|
|
812
824
|
"retire plan": { feature: "lifecycle-plans", api: "lifecycleApi", version: 1 },
|
|
813
825
|
// Feature instance-color: the feature alone (its answer's instanceColorApi is not a probe key).
|
|
814
826
|
"instance color": { feature: "instance-color" },
|
|
827
|
+
// Feature instance-background: the same (its answer's instanceBackgroundApi is not a probe key).
|
|
828
|
+
"instance background": { feature: "instance-background" },
|
|
829
|
+
// Feature instance-same-work: the feature alone, as instance color.
|
|
830
|
+
"instance same-work": { feature: "instance-same-work" },
|
|
815
831
|
};
|
|
816
832
|
|
|
817
833
|
function requireSurface(remote, target, surface) {
|
|
@@ -820,7 +836,7 @@ function requireSurface(remote, target, surface) {
|
|
|
820
836
|
}
|
|
821
837
|
}
|
|
822
838
|
|
|
823
|
-
/** `readiness`, `instance events|git|diff|stop|color` and `retire --plan` on the
|
|
839
|
+
/** `readiness`, `instance events|git|diff|stop|color|background|same-work` and `retire --plan` on the
|
|
824
840
|
* host: the instance is addressed as every routed session command addresses
|
|
825
841
|
* it (its name through a saved route or the host's roster, or an exact
|
|
826
842
|
* --home), the scope is an explicit --dir on the host or the registered
|
|
@@ -829,7 +845,7 @@ function requireSurface(remote, target, surface) {
|
|
|
829
845
|
function routeHostSurface(serverId, cmd, oatsArgs, io) {
|
|
830
846
|
const key = cmd === "instance" ? `instance ${oatsArgs[0]}` : cmd === "retire" ? "retire plan" : cmd;
|
|
831
847
|
const surface = HOST_SURFACES[key];
|
|
832
|
-
if (!surface) throw serverError("E_USAGE", `--server routes instance events, git, diff, stop and
|
|
848
|
+
if (!surface) throw serverError("E_USAGE", `--server routes instance events, git, diff, stop, color, background and same-work only (not ${key})`);
|
|
833
849
|
const args = [...oatsArgs];
|
|
834
850
|
const valueOf = (flag) => { const i = args.indexOf(flag); return i >= 0 && args[i + 1] !== undefined && !args[i + 1].startsWith("--") ? args[i + 1] : undefined; };
|
|
835
851
|
const name = cmd === "readiness" ? undefined : args[cmd === "instance" ? 1 : 0];
|
|
@@ -884,13 +900,19 @@ const rowFacts = (i = {}) => Object.fromEntries(REMOTE_ROW_FACTS.map((k) => [k,
|
|
|
884
900
|
* omits it, and absent ("not reported") must stay distinct from null ("no claim"). The
|
|
885
901
|
* value passes the kernel's own read rule again; anything it refuses is null. */
|
|
886
902
|
const rowWaiting = (i) => (Object.hasOwn(i, "waitingOnYou") ? { waitingOnYou: readWaitingClaim(i.waitingOnYou) } : {});
|
|
887
|
-
/** `
|
|
903
|
+
/** `background` (feature instance-background) only as `true`, relayed ONLY when the host's row says exactly
|
|
904
|
+
* that: absent is the only reading of "not background", so any other value is dropped, never false. */
|
|
905
|
+
const rowBackground = (i) => (i.background === true ? { background: true } : {});
|
|
906
|
+
/** `retire` (feature status-retire-state) as `waitingOnYou` is, relayed ONLY when the host's row has the
|
|
888
907
|
* key: a host whose kernel predates the feature omits it, and its rows say nothing. Absent is the
|
|
889
908
|
* only reading of "no retire", so a value the kernel's own read refuses is dropped, never null. */
|
|
890
909
|
const rowRetire = (i) => {
|
|
891
910
|
const retire = Object.hasOwn(i, "retire") ? readRetireState(i.retire) : undefined;
|
|
892
911
|
return retire ? { retire } : {};
|
|
893
912
|
};
|
|
913
|
+
/** `sameWork` (feature instance-same-work) as `background`: relayed ONLY when the host's row says
|
|
914
|
+
* `sameWork: true`, the one value a row carries; anything else, and a host that omits it, is absent. */
|
|
915
|
+
const rowSameWork = (i) => (i.sameWork === true ? { sameWork: true } : {});
|
|
894
916
|
|
|
895
917
|
/** The bounds a host's `features` list must meet to be relayed (feature server-probe-features). */
|
|
896
918
|
export const HOST_FEATURES_MAX = 256;
|
|
@@ -912,6 +934,15 @@ export function hostFeatures(result) {
|
|
|
912
934
|
}
|
|
913
935
|
return [...list];
|
|
914
936
|
}
|
|
937
|
+
/** The host's viewer fact from its `status --json` result (feature session-attach-prefix-scroll,
|
|
938
|
+
* lib/session-viewer.mjs readSessionViewer), or null when unknown. Untrusted, like the features:
|
|
939
|
+
* relayed as a copy of `{ prefixScroll }` only when that is a boolean; anything else, or a host
|
|
940
|
+
* whose kernel predates the field, is null. */
|
|
941
|
+
export function hostSessionViewer(result) {
|
|
942
|
+
const viewer = result && typeof result === "object" ? result.sessionViewer : undefined;
|
|
943
|
+
if (!viewer || typeof viewer !== "object" || Array.isArray(viewer) || typeof viewer.prefixScroll !== "boolean") return null;
|
|
944
|
+
return { prefixScroll: viewer.prefixScroll };
|
|
945
|
+
}
|
|
915
946
|
|
|
916
947
|
/** `workspaceKeys` (feature roster-workspace-key): when given, only the groups that can belong to
|
|
917
948
|
* one of those workspaces are probed and returned. A group is judged by its registration: kept
|
|
@@ -964,9 +995,10 @@ export async function rosterGroups({ server, workspaceKeys, io = {} } = {}) {
|
|
|
964
995
|
// A success envelope whose result is null or missing reads as an empty answer, never a crash
|
|
965
996
|
// that would sink every other group.
|
|
966
997
|
const result = status.result ?? {};
|
|
967
|
-
// The host's own kernel features (feature server-probe-features)
|
|
968
|
-
//
|
|
969
|
-
|
|
998
|
+
// The host's own kernel features (feature server-probe-features) and its viewer fact (feature
|
|
999
|
+
// session-attach-prefix-scroll), relayed from the same status answer, never probed: null when
|
|
1000
|
+
// the host does not report a valid one.
|
|
1001
|
+
g.probe = { ok: true, features: hostFeatures(result), sessionViewer: hostSessionViewer(result) };
|
|
970
1002
|
g.agentsRoot = result.root;
|
|
971
1003
|
// The host's own workspace identity (feature workspace-identity), relayed as it answered it: never
|
|
972
1004
|
// derived here, null when the host reports none.
|
|
@@ -983,7 +1015,7 @@ export async function rosterGroups({ server, workspaceKeys, io = {} } = {}) {
|
|
|
983
1015
|
harness: i.harness || i.runtime || null, backend: i.tmux ? "tmux" : null,
|
|
984
1016
|
...(i.sessionTarget ? { sessionTarget: i.sessionTarget } : {}), ...(i.tmux ? { tmux: i.tmux } : {}),
|
|
985
1017
|
running: typeof i.running === "boolean" ? i.running : null, ...(i.runtimeError ? { runtimeError: i.runtimeError } : {}),
|
|
986
|
-
...rowFacts(i), ...rowWaiting(i), ...rowRetire(i),
|
|
1018
|
+
...rowFacts(i), ...rowWaiting(i), ...rowRetire(i), ...rowBackground(i), ...rowSameWork(i),
|
|
987
1019
|
// Every row the host reports is addressed by its home, saved
|
|
988
1020
|
// route or not; savedRoute says only that it was spawned from here.
|
|
989
1021
|
retirePending: !!i.retirePending, rollbackIncomplete: !!i.rollbackIncomplete, savedRoute: !!snap, addressable: true, missingRemotely: false,
|
|
@@ -1267,7 +1299,7 @@ export function scheduleRemote(serverId, oatsArgs, io = {}) {
|
|
|
1267
1299
|
return { envelope: envelope.ok ? { ...envelope, result: { ...envelope.result, server: serverId } } : envelope, stderr, target };
|
|
1268
1300
|
}
|
|
1269
1301
|
|
|
1270
|
-
export function attachArgv(serverId, { instance, home, detachKey } = {}, io = {}) {
|
|
1302
|
+
export function attachArgv(serverId, { instance, home, detachKey, statusLine = true } = {}, io = {}) {
|
|
1271
1303
|
io = { ...io, serverId };
|
|
1272
1304
|
const keyed = detachKey !== undefined;
|
|
1273
1305
|
// A detach key is checked before anything is asked of the host.
|
|
@@ -1284,7 +1316,8 @@ export function attachArgv(serverId, { instance, home, detachKey } = {}, io = {}
|
|
|
1284
1316
|
const { target, home: remoteHome } = resolveRoute(serverId, { instance, home }, "session attach", keyed ? { ...io, beforeRoster: requireDetachKeyRemote } : io);
|
|
1285
1317
|
if (keyed) requireDetachKeyRemote(target);
|
|
1286
1318
|
if (!io.skipVersionCheck) requireSessionRemote(target, io, remoteHome);
|
|
1287
|
-
|
|
1319
|
+
// --no-status-line asks for no probe: a host that does not know it ignores it, and shows its line.
|
|
1320
|
+
const [bin, ...rest] = sshArgv(target, ["session", "attach", "--home", remoteHome, ...(detachKey !== undefined ? ["--detach-key", detachKey] : []), ...(statusLine ? [] : ["--no-status-line"])], { control: controlUsable(target, io) });
|
|
1288
1321
|
// -t: allocate a PTY; placed before `--` with the other ssh options.
|
|
1289
1322
|
return { argv: [bin, "-t", ...rest], target, home: remoteHome };
|
|
1290
1323
|
}
|
|
@@ -1305,14 +1338,67 @@ const INSTALL_TIMEOUT_MS = 600000;
|
|
|
1305
1338
|
/** One host command that is not the oats CLI (`true`, `npm`): its exit status and output, never an
|
|
1306
1339
|
* envelope. The registration's --path applies as for oats; stdin is closed. */
|
|
1307
1340
|
function runHostCommand(target, argv, io = {}) {
|
|
1341
|
+
return runSsh(sshArgv({ ...target, oatsPath: argv[0] }, argv.slice(1), { control: controlUsable(target, io) }), io);
|
|
1342
|
+
}
|
|
1343
|
+
|
|
1344
|
+
/** One ssh call, its stdin closed: `{ status, stdout, stderr }`, plus `timedOut` when `io.timeoutMs`
|
|
1345
|
+
* ended it and `overflow` when its stdout passed `io.maxBuffer`. `io.encoding` "buffer" keeps
|
|
1346
|
+
* stdout as bytes. */
|
|
1347
|
+
function runSsh([bin, ...rest], io = {}) {
|
|
1308
1348
|
const exec = io.execFileSync || execFileSync;
|
|
1309
|
-
const
|
|
1349
|
+
const encoding = io.encoding || "utf8";
|
|
1310
1350
|
try {
|
|
1311
|
-
|
|
1351
|
+
const stdout = exec(bin, rest, { encoding, stdio: ["ignore", "pipe", "pipe"], maxBuffer: io.maxBuffer || 16 * 1024 * 1024, timeout: io.timeoutMs || 300000 });
|
|
1352
|
+
return { status: 0, stdout: encoding === "buffer" ? Buffer.from(stdout ?? "") : String(stdout ?? ""), stderr: "" };
|
|
1312
1353
|
} catch (e) {
|
|
1313
|
-
return { status: typeof e.status === "number" ? e.status : 255, stdout: String(e.stdout || ""), stderr: String(e.stderr ?? e.message ?? "") };
|
|
1354
|
+
return { status: typeof e.status === "number" ? e.status : 255, stdout: encoding === "buffer" ? Buffer.from(e.stdout || "") : String(e.stdout || ""), stderr: String(e.stderr ?? e.message ?? ""), ...(e.code === "ETIMEDOUT" ? { timedOut: true } : {}), ...(e.code === "ENOBUFS" ? { overflow: true } : {}) };
|
|
1314
1355
|
}
|
|
1315
1356
|
}
|
|
1357
|
+
|
|
1358
|
+
/** How long the host's login shell has to print its PATH, the ssh round trip included. */
|
|
1359
|
+
export const HOST_LOGIN_SHELL_TIMEOUT_MS = 15000;
|
|
1360
|
+
const SHELL_PATH_RE = /^\/[A-Za-z0-9._\/+-]+$/;
|
|
1361
|
+
|
|
1362
|
+
/**
|
|
1363
|
+
* The PATH the host user's own login shell sets up (lib/login-environment.mjs has the rules): the
|
|
1364
|
+
* shell is the host's $SHELL, which sshd sets from the host's password database; only bash, zsh or
|
|
1365
|
+
* fish, at an absolute path, is run, as `<shell> -l -i -c`, printing its PATH as one nonce frame,
|
|
1366
|
+
* within `io.loginShellTimeoutMs` and 1 MiB. → `{ path, shell }` (the PATH's absolute directories,
|
|
1367
|
+
* colon-separated, each once) or `{ failure }`, in words that hold no value but the shell's name.
|
|
1368
|
+
* ssh's own failure (exit 255) asking for the shell's name throws.
|
|
1369
|
+
*/
|
|
1370
|
+
function readHostLoginPath(target, io) {
|
|
1371
|
+
const control = controlUsable(target, io);
|
|
1372
|
+
const asked = runSsh(sshLineArgv(target, `printf '%s\\n' "$SHELL"`, { control }), { ...io, timeoutMs: 60000 });
|
|
1373
|
+
if (asked.status === 255) throw sshFailed(target, asked);
|
|
1374
|
+
const shell = asked.stdout.replace(/\n$/, "");
|
|
1375
|
+
if (asked.status !== 0 || shell === "") return { failure: "ssh gave no SHELL" };
|
|
1376
|
+
if (!SHELL_PATH_RE.test(shell)) return { failure: "its SHELL is not an absolute path" };
|
|
1377
|
+
if (!LOGIN_SHELLS.includes(basename(shell))) return { failure: `its login shell (${basename(shell)}) is not bash, zsh or fish` };
|
|
1378
|
+
const timeoutMs = io.loginShellTimeoutMs || HOST_LOGIN_SHELL_TIMEOUT_MS;
|
|
1379
|
+
const nonce = randomBytes(16).toString("hex");
|
|
1380
|
+
const r = runSsh(sshLineArgv(target, `exec ${shell} -l -i -c ${quoteFor(shell)(loginPathEmitter(nonce))}`, { control }), { ...io, timeoutMs, maxBuffer: LOGIN_CAPTURE_MAX_BYTES, encoding: "buffer" });
|
|
1381
|
+
if (r.timedOut) return { failure: `its login shell did not answer within ${Math.round(timeoutMs / 1000)} s` };
|
|
1382
|
+
if (r.overflow) return { failure: "its answer was larger than 1 MiB" };
|
|
1383
|
+
if (r.status !== 0) return { failure: `its login shell exited with status ${r.status}` };
|
|
1384
|
+
const frame = readLoginFrame(r.stdout, nonce);
|
|
1385
|
+
if (frame.none) return { failure: "its login shell gave no answer" };
|
|
1386
|
+
if (frame.ambiguous) return { failure: "its answer was not exactly one complete frame" };
|
|
1387
|
+
let text;
|
|
1388
|
+
try { text = new TextDecoder("utf-8", { fatal: true }).decode(frame.data); } catch { text = null; }
|
|
1389
|
+
if (!text || /[\0\n\r]/.test(text)) return { failure: "its answer was not one PATH" };
|
|
1390
|
+
const dirs = [...new Set(text.split(":").filter((d) => d.startsWith("/")))];
|
|
1391
|
+
if (!dirs.length) return { failure: "its PATH holds no absolute directory" };
|
|
1392
|
+
return { path: dirs.join(":"), shell };
|
|
1393
|
+
}
|
|
1394
|
+
|
|
1395
|
+
/** Where the host's `name` is on the target's PATH, by `command -v` in sh: its absolute path, or null. */
|
|
1396
|
+
function hostCommandPath(target, name, io) {
|
|
1397
|
+
const r = runHostCommand(target, ["sh", "-c", `command -v ${name}`], { ...io, timeoutMs: 60000 });
|
|
1398
|
+
if (r.status === 255) throw sshFailed(target, r);
|
|
1399
|
+
const found = r.stdout.replace(/\n$/, "");
|
|
1400
|
+
return r.status === 0 && found.startsWith("/") && !/[\0\n\r]/.test(found) ? found : null;
|
|
1401
|
+
}
|
|
1316
1402
|
const tail = (text) => String(text || "").trim().slice(-400) || "(no output)";
|
|
1317
1403
|
|
|
1318
1404
|
/** A command a person copies out of a remedy: every argument quoted for a POSIX shell (remoteQuote),
|
|
@@ -1363,6 +1449,9 @@ export function connectServer(options, io = {}) {
|
|
|
1363
1449
|
if (typeof dir !== "string" || !(dir === "~" || dir.startsWith("~/") || dir.startsWith("/"))) throw serverError("E_BAD_ARGS", `--dir must be an absolute path or ~/… on the host (got ${JSON.stringify(dir)})`);
|
|
1364
1450
|
io = { ...io, serverId: id, input: undefined };
|
|
1365
1451
|
const target = { sshHost, workspace: dir, oatsPath: oatsPath || "oats", ...(path ? { path } : {}) };
|
|
1452
|
+
// What this run found on the host for what was not given: the login shell's PATH, and oats on it.
|
|
1453
|
+
const found = {};
|
|
1454
|
+
let login = null;
|
|
1366
1455
|
const steps = [], human = [];
|
|
1367
1456
|
let blockedBy = null, check = null, reportedKey = null, registration = null, registeredAs = id;
|
|
1368
1457
|
|
|
@@ -1377,25 +1466,38 @@ export function connectServer(options, io = {}) {
|
|
|
1377
1466
|
if (step.status === "failed") throw Object.assign(serverError(step.code, step.detail), { details: { ...(step.details || {}), steps } });
|
|
1378
1467
|
};
|
|
1379
1468
|
|
|
1469
|
+
// Without --path, every later step runs with the PATH of the host user's own login shell.
|
|
1380
1470
|
run("ssh", () => {
|
|
1381
1471
|
const r = runHostCommand(target, ["true"], { ...io, timeoutMs: 60000 });
|
|
1382
1472
|
if (r.status !== 0) throw sshFailed(target, r);
|
|
1383
|
-
return { status: "ok" };
|
|
1473
|
+
if (path) return { status: "ok" };
|
|
1474
|
+
const read = readHostLoginPath(target, io);
|
|
1475
|
+
if (read.failure) return { status: "ok", detail: `could not read ${sshHost}'s login-shell PATH (${read.failure}); using ssh's own PATH` };
|
|
1476
|
+
login = read;
|
|
1477
|
+
target.path = found.path = read.path;
|
|
1478
|
+
return { status: "ok", detail: `PATH from ${sshHost}'s login shell (${basename(read.shell)} -l -i), used by every later step` };
|
|
1384
1479
|
});
|
|
1385
1480
|
|
|
1386
1481
|
// A kernel the rest of connect can use: this version or newer AND advertising server-connect (the
|
|
1387
1482
|
// commands connect runs there); a build of the same version without them is not taken for one.
|
|
1388
1483
|
run("oats", () => {
|
|
1389
|
-
const found = probeHostOats(target, io);
|
|
1390
1484
|
const older = (p) => compareSemver(p.version, localVersion) < 0;
|
|
1391
1485
|
const usable = (p) => !!p.version && !older(p) && p.features.includes("server-connect");
|
|
1392
|
-
|
|
1486
|
+
// oats found on the login shell's PATH is recorded by its absolute path.
|
|
1487
|
+
const recordOats = () => { if (login && !oatsPath) { const at = hostCommandPath(target, "oats", io); if (at) target.oatsPath = found.oatsPath = at; } };
|
|
1488
|
+
const host = probeHostOats(target, io);
|
|
1489
|
+
if (usable(host)) { recordOats(); return { status: "ok", detail: `oats ${host.version}${host.version === localVersion ? "" : ` (this kernel ${localVersion})`}` }; }
|
|
1393
1490
|
const npm = runHostCommand(target, ["npm", "--version"], { ...io, timeoutMs: 60000 });
|
|
1394
1491
|
if (npm.status === 255) throw sshFailed(target, npm);
|
|
1395
|
-
const what = !
|
|
1396
|
-
: older(
|
|
1397
|
-
: `oats ${
|
|
1398
|
-
if (npm.status !== 0)
|
|
1492
|
+
const what = !host.version ? `no oats at ${target.oatsPath} on ${sshHost}`
|
|
1493
|
+
: older(host) ? `oats ${host.version} at ${target.oatsPath} is older than this kernel (${localVersion})`
|
|
1494
|
+
: `oats ${host.version} at ${target.oatsPath} on ${sshHost} does not advertise server-connect, which connect needs there`;
|
|
1495
|
+
if (npm.status !== 0) {
|
|
1496
|
+
const searched = login ? `the PATH of ${sshHost}'s login shell (${basename(login.shell)} -l -i)` : path ? "--path and ssh's PATH" : "ssh's PATH";
|
|
1497
|
+
const where = login ? `so that its login shell finds it (there, ${runnable([login.shell, "-l", "-i", "-c", "command -v npm"])} prints its path)`
|
|
1498
|
+
: path ? "where --path or a non-interactive ssh command finds it" : "where a non-interactive ssh command finds it";
|
|
1499
|
+
return { status: "needs-human", detail: `${what}, and no npm on ${searched}`, remedy: `install Node.js 22+ (npm) on ${sshHost} ${where}, then check again (run the same connect); from the CLI, --path <the directory holding npm> names it instead` };
|
|
1500
|
+
}
|
|
1399
1501
|
const install = ["npm", "install", "-g", `@awebai/oats@${localVersion}`];
|
|
1400
1502
|
if (!installOats) return { status: "needs-human", detail: what, remedy: `on ${sshHost}: ${runnable(install)} (or pass --install-oats)` };
|
|
1401
1503
|
const r = runHostCommand(target, install, { ...io, timeoutMs: INSTALL_TIMEOUT_MS });
|
|
@@ -1406,7 +1508,8 @@ export function connectServer(options, io = {}) {
|
|
|
1406
1508
|
const still = !after.version ? "is still not found" : older(after) ? `still answers ${after.version}` : `still does not advertise server-connect (${after.version})`;
|
|
1407
1509
|
throw serverError("E_REMOTE_INSTALL", `npm installed @awebai/oats@${localVersion} on ${sshHost}, but ${target.oatsPath} there ${still}; pass --oats <the installed oats> or --path <npm's global bin directory>`);
|
|
1408
1510
|
}
|
|
1409
|
-
|
|
1511
|
+
recordOats();
|
|
1512
|
+
const was = !host.version ? "was missing" : older(host) ? `was ${host.version}` : `was ${host.version} without server-connect`;
|
|
1410
1513
|
return { status: "done", detail: `installed @awebai/oats ${localVersion} (${was})` };
|
|
1411
1514
|
});
|
|
1412
1515
|
|
|
@@ -1445,21 +1548,27 @@ export function connectServer(options, io = {}) {
|
|
|
1445
1548
|
// another target is refused (or replaced), never quietly answered by a twin that serves this target.
|
|
1446
1549
|
run("register", () => updateServers((servers) => {
|
|
1447
1550
|
const abs = check.dir;
|
|
1448
|
-
const
|
|
1551
|
+
const given = { ...(oatsPath ? { oatsPath } : {}), ...(path ? { path } : {}), ...(label ? { label } : {}) };
|
|
1552
|
+
const entry = { sshHost, workspace: abs, ...found, ...given, workspaceKey: reportedKey };
|
|
1449
1553
|
const sameTarget = (s) => s.sshHost === sshHost && s.workspace === abs;
|
|
1450
|
-
/** A registration of this very target: its key confirmed, or recorded; never contradicted.
|
|
1554
|
+
/** A registration of this very target: its key confirmed, or recorded; never contradicted. What
|
|
1555
|
+
* this run found on the host fills only what it lacks. */
|
|
1451
1556
|
const keep = (regId, detail) => {
|
|
1452
1557
|
const existing = servers[regId];
|
|
1453
1558
|
if (existing.workspaceKey && existing.workspaceKey !== reportedKey) throw workspaceMismatch(regId, existing, reportedKey);
|
|
1454
1559
|
registeredAs = regId;
|
|
1455
1560
|
registration = existing;
|
|
1456
|
-
|
|
1457
|
-
existing
|
|
1458
|
-
|
|
1561
|
+
const filled = Object.keys(found).filter((k) => existing[k] === undefined || existing[k] === null).sort();
|
|
1562
|
+
for (const k of filled) existing[k] = found[k];
|
|
1563
|
+
const keyed = !existing.workspaceKey;
|
|
1564
|
+
if (keyed) existing.workspaceKey = reportedKey;
|
|
1565
|
+
if (!filled.length && !keyed) return { status: "ok", ...(detail ? { detail } : {}) };
|
|
1566
|
+
return { status: "done", detail: [detail, filled.length ? `recorded ${filled.join(", ")}` : null, keyed ? `recorded workspace ${reportedKey}` : null].filter(Boolean).join("; ") };
|
|
1459
1567
|
};
|
|
1460
1568
|
const mine = servers[id];
|
|
1461
1569
|
if (mine && sameTarget(mine)) {
|
|
1462
|
-
|
|
1570
|
+
// A value given differs; one only found here differs only under --replace.
|
|
1571
|
+
const differ = ["oatsPath", "path", "label"].filter((k) => entry[k] !== undefined && entry[k] !== mine[k] && (Object.hasOwn(given, k) || replace));
|
|
1463
1572
|
if (!differ.length || !replace) return keep(id, differ.length ? `${differ.join(", ")} differ from the registration and were not changed (--replace rewrites it)` : undefined);
|
|
1464
1573
|
if (mine.workspaceKey && mine.workspaceKey !== reportedKey) throw workspaceMismatch(id, mine, reportedKey);
|
|
1465
1574
|
servers[id] = entry; registration = entry;
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
/** How a launched home's last session ended (feature session-resume): `lost`, `stopped` or
|
|
2
|
+
* `exited`, derived from what the kernel already writes in the home. Kernel-private files, not a
|
|
3
|
+
* contract:
|
|
4
|
+
* - `.oats-start-exited`: the window a spawn or a start made writes it when the harness exits,
|
|
5
|
+
* `{"startId":"<id>","status":<n>}` (the harness's exit status). A kernel before 0.69 wrote the
|
|
6
|
+
* start id alone on one line, and only from a start's window.
|
|
7
|
+
* - `.oats-stop.json`: `oats instance stop` / `oats session stop`, `{ instance, at, stop, retained,
|
|
8
|
+
* startId }`; `startId` (0.69) is the start the stop ended, null when the home had none.
|
|
9
|
+
* A reboot or a killed tmux server leaves neither file for the start that was running: that is a
|
|
10
|
+
* lost session, the one a resume brings back. Dependency-free: status, start --resume and the
|
|
11
|
+
* schedule runner read the files through here. */
|
|
12
|
+
import { join } from "node:path";
|
|
13
|
+
import { readFileHead } from "./bounded-read.mjs";
|
|
14
|
+
import { SESSION_END } from "./session-resume-contract.mjs";
|
|
15
|
+
|
|
16
|
+
export const START_EXITED_FILE = ".oats-start-exited";
|
|
17
|
+
export const STOP_RECEIPT_FILE = ".oats-stop.json";
|
|
18
|
+
const RECORD_MAX = 64 * 1024;
|
|
19
|
+
/** A shell's exit status from 128 up is a signal's (128 + n): the harness was killed, not ended. */
|
|
20
|
+
const SIGNALLED = 128;
|
|
21
|
+
|
|
22
|
+
function readText(path) {
|
|
23
|
+
try {
|
|
24
|
+
const { bytes, size } = readFileHead(path, RECORD_MAX + 1);
|
|
25
|
+
return size > RECORD_MAX ? null : bytes.toString("utf8");
|
|
26
|
+
} catch { return null; }
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** The exit marker of `home` → `{ startId, status }` (status null for the legacy one-line form), or
|
|
30
|
+
* null when there is none or it reads as neither form. Never throws. */
|
|
31
|
+
export function readStartExited(home) {
|
|
32
|
+
const text = readText(join(home, START_EXITED_FILE));
|
|
33
|
+
if (text === null) return null;
|
|
34
|
+
const trimmed = text.trim();
|
|
35
|
+
if (trimmed.startsWith("{")) {
|
|
36
|
+
try {
|
|
37
|
+
const v = JSON.parse(trimmed);
|
|
38
|
+
if (!v || typeof v !== "object" || Array.isArray(v) || typeof v.startId !== "string" || !v.startId) return null;
|
|
39
|
+
return { startId: v.startId, status: Number.isInteger(v.status) && v.status >= 0 ? v.status : null };
|
|
40
|
+
} catch { return null; }
|
|
41
|
+
}
|
|
42
|
+
// A start id as a start's pending receipt accepts one.
|
|
43
|
+
return /^[a-zA-Z0-9-]{1,80}$/.test(trimmed) ? { startId: trimmed, status: null } : null;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** The stop receipt of `home` (`.oats-stop.json`), or null. Never throws. */
|
|
47
|
+
export function readStopReceipt(home) {
|
|
48
|
+
const text = readText(join(home, STOP_RECEIPT_FILE));
|
|
49
|
+
if (text === null) return null;
|
|
50
|
+
try { const v = JSON.parse(text); return v && typeof v === "object" && !Array.isArray(v) ? v : null; } catch { return null; }
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** When the home's current start began: the last restart's `startedAt`, else the spawn's `createdAt`;
|
|
54
|
+
* as ms, or NaN when the record names neither. */
|
|
55
|
+
export function currentStartTime(meta) {
|
|
56
|
+
const restarts = Array.isArray(meta?.restarts) ? meta.restarts : [];
|
|
57
|
+
const last = restarts.length ? restarts[restarts.length - 1]?.startedAt : undefined;
|
|
58
|
+
return Date.parse(typeof last === "string" ? last : meta?.createdAt);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** How the session of `meta`'s current start (`meta.startId`) ended, from the home's files alone:
|
|
62
|
+
* - `stopped`: the stop receipt names this start (`startId` equal), or, a receipt without a start
|
|
63
|
+
* id, was written after this start began;
|
|
64
|
+
* - `exited`: the exit marker names this start with a status below 128, or in its legacy form
|
|
65
|
+
* (no status: a kernel before 0.69 wrote it only when the harness ended on its own window);
|
|
66
|
+
* - `lost`: anything else — a marker with a signal's status (128 and up), or no file naming this
|
|
67
|
+
* start (the host went down, or the tmux server died, under a live harness).
|
|
68
|
+
* A home that records no start id (spawned before 0.69, never restarted) can be named by no marker:
|
|
69
|
+
* only a stop after its `createdAt` reads `stopped`, otherwise `lost` (the documented legacy gap).
|
|
70
|
+
* The caller reads it only for a launched home that does not run. */
|
|
71
|
+
export function sessionEndOf(home, meta) {
|
|
72
|
+
const startId = typeof meta?.startId === "string" && meta.startId ? meta.startId : null;
|
|
73
|
+
const since = currentStartTime(meta);
|
|
74
|
+
const stop = readStopReceipt(home);
|
|
75
|
+
if (stop) {
|
|
76
|
+
if (typeof stop.startId === "string" && stop.startId) { if (stop.startId === startId) return SESSION_END.STOPPED; }
|
|
77
|
+
else if (Date.parse(stop.at) > since) return SESSION_END.STOPPED;
|
|
78
|
+
}
|
|
79
|
+
const exited = startId ? readStartExited(home) : null;
|
|
80
|
+
if (exited && exited.startId === startId) return exited.status !== null && exited.status >= SIGNALLED ? SESSION_END.LOST : SESSION_END.EXITED;
|
|
81
|
+
return SESSION_END.LOST;
|
|
82
|
+
}
|