@awebai/oats 0.69.3 → 0.69.5
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 +68 -49
- package/docs/configuration.md +12 -0
- package/docs/desktop-cli-api.md +8 -1
- package/docs/execution-targets.md +25 -3
- package/docs/implementation.md +42 -3
- package/docs/integrations.md +2 -2
- package/docs/knowledge.md +9 -6
- package/docs/named-test-runs.md +4 -2
- package/docs/official-catalog.md +6 -6
- package/docs/packages.md +14 -14
- package/docs/release-lane.md +25 -18
- package/docs/release-notes/v0.69.4.md +73 -0
- package/docs/release-notes/v0.69.5.md +146 -0
- package/docs/souls-and-instances.md +2 -2
- package/docs/tui.md +2 -1
- package/docs/upgrading.md +16 -5
- package/docs/workspaces.md +2 -2
- package/lib/agents-root.mjs +51 -0
- package/lib/automation-api.mjs +7 -0
- package/lib/automation-scope.mjs +35 -0
- package/lib/automations.mjs +2 -1
- package/lib/compile-cache.mjs +36 -0
- package/lib/core.mjs +39 -1348
- package/lib/deployment-path.mjs +127 -0
- package/lib/deployments.mjs +2 -2
- package/lib/drift.mjs +95 -0
- package/lib/hot-reads.mjs +131 -0
- package/lib/instance-address.mjs +21 -0
- package/lib/instance-lifecycle.mjs +4 -16
- package/lib/instance-listing.mjs +730 -0
- package/lib/instance-resolution.mjs +5 -166
- package/lib/materialize.mjs +2 -87
- package/lib/member-clone.mjs +188 -0
- package/lib/package-catalog.mjs +93 -0
- package/lib/packages.mjs +4 -24
- package/lib/reserved-launch-env.mjs +20 -0
- package/lib/resolved-deployment.mjs +1 -1
- package/lib/schedule.mjs +5 -29
- package/lib/semver.mjs +12 -0
- package/lib/servers.mjs +10 -12
- package/lib/session-end.mjs +3 -2
- package/lib/session-inspect.mjs +219 -0
- package/lib/soul-listing.mjs +216 -0
- package/lib/status-words.mjs +30 -0
- package/lib/version.mjs +9 -0
- package/lib/write-file-atomic.mjs +28 -0
- package/package-catalog.json +5 -5
- package/package.json +1 -1
- package/packages/tui/lib/store.mjs +7 -3
- package/skills/oats-getting-started/SKILL.md +3 -3
|
@@ -0,0 +1,730 @@
|
|
|
1
|
+
/** listInstances: every home under an agents root as a status row (its record, tmux liveness, retire
|
|
2
|
+
* state, waiting claim, colour, served identity, its launch recipe redacted), and the legacy layouts
|
|
3
|
+
* status warns about. A leaf (awebai/oats#1630): `oats status` lists homes without loading core.mjs,
|
|
4
|
+
* which imports what it still uses from here and re-exports what it exported. */
|
|
5
|
+
import { canonicalHomePath } from "./real-path.mjs";
|
|
6
|
+
import { execFileSync } from "node:child_process";
|
|
7
|
+
import { readFileSync, readdirSync, lstatSync, existsSync, statSync, openSync, constants as fsConstants, fstatSync, closeSync, accessSync, readlinkSync } from "node:fs";
|
|
8
|
+
import { join, dirname, resolve, basename } from "node:path";
|
|
9
|
+
import { noteRuntimeName } from "./deprecation.mjs";
|
|
10
|
+
import { createSessionPaneInspector, AGENT_PANE_OPTION } from "./session-input.mjs";
|
|
11
|
+
import { liveWaiting } from "./instance-events.mjs";
|
|
12
|
+
import { processLiveness } from "./worktree-hooks.mjs";
|
|
13
|
+
import { shownHolder } from "./claim.mjs";
|
|
14
|
+
import { isInstant as isInstantString, readRetireState } from "./retire-state.mjs";
|
|
15
|
+
import { herdrInstanceRemoved, oatsError } from "./errors.mjs";
|
|
16
|
+
import { readInstanceColor } from "./instance-color.mjs";
|
|
17
|
+
import { readInstanceBackground } from "./instance-background.mjs";
|
|
18
|
+
import { sameWorkOf } from "./instance-same-work.mjs";
|
|
19
|
+
import { sessionEndOf } from "./session-end.mjs";
|
|
20
|
+
import { recordSeen } from "./session-seen.mjs";
|
|
21
|
+
import { listAgents, capabilityAgentDirs } from "./soul-listing.mjs";
|
|
22
|
+
import { recordsHerdr, readJsonOrUndefined, findRetirementBaseline, instanceSessionTarget, harnessRunning, isPlainObject, instancesRetirementRoot } from "./session-inspect.mjs";
|
|
23
|
+
|
|
24
|
+
/** OATS 0.25 and earlier homed local souls and capability-defined agents at
|
|
25
|
+
* <scope>/local-agents/ (and <root>/local-agents|tmp-agents). The kernel never reads,
|
|
26
|
+
* spawns into or retires from them; it only detects them: `legacyLocalAgents` names
|
|
27
|
+
* what is left there so status/doctor say so. */
|
|
28
|
+
const LEGACY_LOCAL_AGENTS_DIR = "local-agents";
|
|
29
|
+
/** The names of the non-hidden directories in `d` ([] when it cannot be read). */
|
|
30
|
+
function subdirs(d) {
|
|
31
|
+
try { return readdirSync(d, { withFileTypes: true }).filter((e) => e.isDirectory() && !e.name.startsWith(".")).map((e) => e.name); } catch { return []; }
|
|
32
|
+
}
|
|
33
|
+
/** What OATS 0.25 left under <scope>/local-agents/ (and the nested <root>/local-agents|
|
|
34
|
+
* tmp-agents) for the agents root `root`: one `legacy-local-agents` problem naming the
|
|
35
|
+
* instance homes there, or null. Names only — nothing there is read, spawned into or
|
|
36
|
+
* retired from. */
|
|
37
|
+
export function legacyLocalAgents(root) {
|
|
38
|
+
if (!root) return null;
|
|
39
|
+
const bases = [join(dirname(root), LEGACY_LOCAL_AGENTS_DIR), join(root, LEGACY_LOCAL_AGENTS_DIR), join(root, "tmp-agents")];
|
|
40
|
+
const dirs = [], instances = [];
|
|
41
|
+
for (const base of bases) {
|
|
42
|
+
let st; try { st = lstatSync(base); } catch { continue; }
|
|
43
|
+
if (!st.isDirectory()) continue;
|
|
44
|
+
dirs.push(base);
|
|
45
|
+
for (const agent of subdirs(base)) for (const inst of subdirs(join(base, agent, "instances"))) instances.push(inst);
|
|
46
|
+
}
|
|
47
|
+
if (!dirs.length) return null;
|
|
48
|
+
instances.sort();
|
|
49
|
+
return { code: "legacy-local-agents", dirs, instances,
|
|
50
|
+
message: `${instances.length} instance home${instances.length === 1 ? "" : "s"} under local-agents/ ${instances.length === 1 ? "is" : "are"} from OATS 0.25 and ${instances.length === 1 ? "is" : "are"} not managed by this kernel; retire ${instances.length === 1 ? "it" : "them"} with the 0.25 kernel or delete the directory once ${instances.length === 1 ? "it is" : "they are"} stopped${instances.length ? ` (${instances.join(", ")})` : ""}` };
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** The captured homes (the 0.24–0.25 captured/portable path, removed in 0.26) under the
|
|
54
|
+
* agents root `root`: one `legacy-captured-home` problem naming them, or null. They have
|
|
55
|
+
* no 0.26 runtime (start, inspect and in-home commands refuse them); retire still works. */
|
|
56
|
+
export function legacyCapturedHomes(root) {
|
|
57
|
+
if (!root) return null;
|
|
58
|
+
const homes = [];
|
|
59
|
+
for (const agent of subdirs(root)) for (const inst of subdirs(join(root, agent, "instances"))) {
|
|
60
|
+
const home = join(root, agent, "instances", inst);
|
|
61
|
+
let meta; try { meta = JSON.parse(readFileSync(join(home, "instance.json"), "utf8")); } catch { continue; }
|
|
62
|
+
if (isCapturedHome(meta)) homes.push({ instance: inst, home });
|
|
63
|
+
}
|
|
64
|
+
if (!homes.length) return null;
|
|
65
|
+
homes.sort((a, b) => a.instance.localeCompare(b.instance));
|
|
66
|
+
const one = homes.length === 1;
|
|
67
|
+
return { code: "legacy-captured-home", instances: homes.map((h) => h.instance), homes: homes.map((h) => h.home),
|
|
68
|
+
message: `${homes.length} captured home${one ? "" : "s"} (0.24–0.25; the captured/portable path was removed in 0.26) ${one ? "has" : "have"} no 0.26 runtime: start, inspect and in-home commands refuse ${one ? "it" : "them"}; retire ${one ? "it" : "them"} (\`oats retire\` still works) and re-spawn from the deployment (${homes.map((h) => h.instance).join(", ")})` };
|
|
69
|
+
}
|
|
70
|
+
// The tmux session a new tmux instance opens its window in, when oats-local.yaml session.tmuxSession
|
|
71
|
+
// names none (0.31). PI_AGENTS_TMUX_SESSION is the pre-0.31 variable, still honoured. The Desktop keeps
|
|
72
|
+
// the same default in packages/client/tmux-status.mjs (it does not import lib/): change both.
|
|
73
|
+
export const DEFAULT_TMUX_SESSION = process.env.OATS_TMUX_SESSION || process.env.PI_AGENTS_TMUX_SESSION || "oats-agents";
|
|
74
|
+
|
|
75
|
+
/** tmuxWindows' read, keeping a missing socket file apart (#624): `{ windows }`, with `missingSocket`
|
|
76
|
+
* (tmux's words) when the default server's socket file is missing. Any other failure reads as no
|
|
77
|
+
* session. `has-session` first, as ever: it is the read-only probe a caller may expect for a home
|
|
78
|
+
* that records no socket, and it words a missing socket file as list-windows does. */
|
|
79
|
+
function defaultTmuxWindows(session) {
|
|
80
|
+
const run = (args) => execFileSync("tmux", args, { encoding: "utf8", timeout: 10000, maxBuffer: 1024 * 1024, stdio: ["ignore", "pipe", "pipe"] });
|
|
81
|
+
try {
|
|
82
|
+
run(["has-session", "-t", session]);
|
|
83
|
+
return { windows: run(["list-windows", "-t", session, "-F", "#{window_name}"]).split("\n").filter(Boolean) };
|
|
84
|
+
} catch (e) {
|
|
85
|
+
// Either read: the socket file can go between the two.
|
|
86
|
+
return tmuxServerAbsence(e) === "missing-socket" ? { windows: [], missingSocket: tmuxFailure(e, "tmux failed") } : { windows: [] };
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
const tmuxFailure = (e, fallback) => String(e?.stderr ?? e?.message ?? "").trim() || fallback;
|
|
91
|
+
|
|
92
|
+
/** `name` as an exec looks it up on `path`: the first entry, in order, that holds a regular
|
|
93
|
+
* executable file of that name, as an absolute path; null when none does. A relative entry, and
|
|
94
|
+
* an empty one (an empty PATH is one empty entry), are `cwd`. Nothing is run. */
|
|
95
|
+
function lookupOnPath(name, path, cwd = process.cwd()) {
|
|
96
|
+
for (const dir of path.split(":")) {
|
|
97
|
+
const candidate = resolve(cwd, dir || ".", name);
|
|
98
|
+
try { accessSync(candidate, fsConstants.X_OK); if (statSync(candidate).isFile()) return candidate; } catch { /* not here */ }
|
|
99
|
+
}
|
|
100
|
+
return null;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// ---------- launch recipes ----------
|
|
104
|
+
// What a harness start is made of, recorded in instance.json (`launch`) so a
|
|
105
|
+
// later start or restart can re-render it, select another configuration, or
|
|
106
|
+
// switch harness without guessing from the command string. The rendered
|
|
107
|
+
// command (`command`) stays beside it, byte-identical to what spawn rendered
|
|
108
|
+
// before recipes existed when no configuration is selected. Version 2 (0.27.0)
|
|
109
|
+
// names the harness `harness`; version 1 (0.26.0 homes) said `runtime` and is
|
|
110
|
+
// read as version 2 (upgradeLaunchRecipe); the next start or restart rewrites it.
|
|
111
|
+
export const LAUNCH_RECIPE_VERSION = 2;
|
|
112
|
+
/** A recorded recipe as this kernel reads it: version 1 `{runtime}` (0.26.0) is
|
|
113
|
+
* version 2 `{harness}` (lead call 6: read either, write new). Anything else is
|
|
114
|
+
* returned as it is, for assertLaunchRecipe to judge. */
|
|
115
|
+
export function upgradeLaunchRecipe(recipe) {
|
|
116
|
+
if (!isPlainObject(recipe) || recipe.version !== 1 || Object.hasOwn(recipe, "harness")) return recipe;
|
|
117
|
+
const { runtime, ...rest } = recipe;
|
|
118
|
+
return { ...rest, version: LAUNCH_RECIPE_VERSION, harness: runtime };
|
|
119
|
+
}
|
|
120
|
+
/** A home's instance.json as this kernel reads it: 0.26.0 recorded `runtime` and a
|
|
121
|
+
* version-1 recipe; both read as `harness` (lead call 6). Every reader of a home's
|
|
122
|
+
* harness goes through here; the next start or restart writes the new names. */
|
|
123
|
+
export function upgradeHomeMeta(meta, home) {
|
|
124
|
+
if (!isPlainObject(meta)) return meta;
|
|
125
|
+
const old = Object.hasOwn(meta, "runtime") || (isPlainObject(meta.launch) && meta.launch.version === 1 && !Object.hasOwn(meta.launch, "harness"));
|
|
126
|
+
if (!old) return meta;
|
|
127
|
+
noteRuntimeName(`instance.json of ${home || meta.home || meta.instance} (a 0.26.0 home: its next start or restart records harness)`);
|
|
128
|
+
const { runtime, ...rest } = meta;
|
|
129
|
+
return { ...rest, ...(runtime !== undefined || meta.harness !== undefined ? { harness: meta.harness ?? runtime } : {}), ...(meta.launch !== undefined ? { launch: upgradeLaunchRecipe(meta.launch) } : {}) };
|
|
130
|
+
}
|
|
131
|
+
/** A home's record (`<home>/instance.json`) as it is on disk. Total: it never throws, so that one
|
|
132
|
+
* home's record decides only for that home (awebai/oats#896). One of:
|
|
133
|
+
* - `{ state: "record", path, meta }`: the JSON object the file holds, as written (a reader of
|
|
134
|
+
* the home's harness passes it through upgradeHomeMeta);
|
|
135
|
+
* - `{ state: "absent", path }`: no entry of that name, or a home this process cannot look into,
|
|
136
|
+
* where whether there is one cannot be told (answered as a home without a record, as before);
|
|
137
|
+
* - `{ state: "unreadable", path, reason }`: an entry is there and gives no JSON object: cut off,
|
|
138
|
+
* empty, kept from this user, a directory, a link to nothing, or JSON that is not an object.
|
|
139
|
+
* `reason` is the system's or the parser's, in words, without the path.
|
|
140
|
+
* An unreadable record is never an absent one: the home may be a whole instance with work, and
|
|
141
|
+
* "cannot read" is not "is not there". */
|
|
142
|
+
export function readHomeRecord(home) {
|
|
143
|
+
const path = join(home, "instance.json");
|
|
144
|
+
const unreadable = (reason) => ({ state: "unreadable", path, reason });
|
|
145
|
+
let text;
|
|
146
|
+
try {
|
|
147
|
+
// Only a regular file is read: a read of a directory fails, and one of a pipe would not return.
|
|
148
|
+
const entry = statSync(path);
|
|
149
|
+
if (!entry.isFile()) return unreadable(entry.isDirectory() ? "it is a directory" : "it is not a regular file");
|
|
150
|
+
text = readFileSync(path, "utf8");
|
|
151
|
+
} catch (e) {
|
|
152
|
+
let entry;
|
|
153
|
+
try { entry = lstatSync(path); } catch { return { state: "absent", path }; }
|
|
154
|
+
if (entry.isSymbolicLink() && e?.code === "ENOENT") return unreadable("it is a symbolic link to nothing");
|
|
155
|
+
// The system's words without the path, which the answer already names: `EACCES: permission denied`.
|
|
156
|
+
return unreadable(String(e?.message ?? e).replace(/, [a-z]+ '.*'$/s, ""));
|
|
157
|
+
}
|
|
158
|
+
let value;
|
|
159
|
+
try { value = JSON.parse(text); } catch (e) { return unreadable(String(e?.message ?? e)); }
|
|
160
|
+
if (!isPlainObject(value)) return unreadable(`it holds ${value === null ? "null" : Array.isArray(value) ? "an array" : `a ${typeof value}`}, not a JSON object`);
|
|
161
|
+
return { state: "record", path, meta: value };
|
|
162
|
+
}
|
|
163
|
+
/** What an answer says of a record that cannot be read (readHomeRecord): the file and the reason. */
|
|
164
|
+
const unreadableRecordSaid = (record) => `${record.path} cannot be read (${record.reason})`;
|
|
165
|
+
|
|
166
|
+
/** A persisted command with every environment value withheld (references
|
|
167
|
+
* stay references); a command the parser refuses is withheld whole. */
|
|
168
|
+
/** The identity environment every launch carries: public facts (instance
|
|
169
|
+
* name, home path), shown in public renderings; everything else is withheld. */
|
|
170
|
+
export const IDENTITY_LAUNCH_ENV = new Set(["OATS_INSTANCE", "OATS_INSTANCE_HOME"]);
|
|
171
|
+
export function redactLaunchCommand(command) {
|
|
172
|
+
try { return parseLaunchCommand(command).tokens.map((t) => t.kind === "env" && !IDENTITY_LAUNCH_ENV.has(t.name) ? `${t.name}='<redacted>'` : t.text).join(" "); }
|
|
173
|
+
catch { return "<unparseable launch command withheld>"; }
|
|
174
|
+
}
|
|
175
|
+
/** The recipe as answers carry it: every environment value withheld, and without `kernelBin`
|
|
176
|
+
* (the home's record keeps it; human `oats status` reads it from there). */
|
|
177
|
+
export function redactLaunchRecipe(recipe) {
|
|
178
|
+
const env = Object.fromEntries(Object.keys(recipe.env || {}).sort().map((n) => [n, typeof recipe.env[n] === "string" ? { redacted: true } : { fromEnv: recipe.env[n].fromEnv }]));
|
|
179
|
+
const hooks = recipe.hooks ? { ...recipe.hooks, env: Object.fromEntries(Object.keys(recipe.hooks.env || {}).sort().map((n) => [n, { redacted: true }])) } : undefined;
|
|
180
|
+
const { kernelBin: _recorded, ...answered } = recipe;
|
|
181
|
+
return { ...answered, env, ...(hooks ? { hooks } : {}) };
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/** Decision 27 (K2): the principal an instance ACTS AS, as its messaging-layer provider reported
|
|
185
|
+
* it — a documented layer contract `{ mode: "local"|"global", alias, team, address|null, resident|null,
|
|
186
|
+
* grant?: { id, expiresAt, scopes } }` under `identity` in the provider's hook meta. The kernel copies it
|
|
187
|
+
* through and never interprets `grant`. Preference: the capability whose captured layer is "messaging";
|
|
188
|
+
* else any capability that emitted an `identity` object. Null when none did. */
|
|
189
|
+
export function servedIdentityOf(meta) {
|
|
190
|
+
const cm = meta?.capabilityMeta;
|
|
191
|
+
if (!cm || typeof cm !== "object") return null;
|
|
192
|
+
const harness = Array.isArray(meta.capabilityRuntime) ? meta.capabilityRuntime : [];
|
|
193
|
+
const messaging = harness.filter((c) => c && c.layer === "messaging").map((c) => c.id);
|
|
194
|
+
const pick = (ids) => { for (const id of ids) { const v = cm[id]?.identity; if (v && typeof v === "object" && !Array.isArray(v)) return { ...v, provider: id }; } return null; };
|
|
195
|
+
return pick(messaging) ?? pick(Object.keys(cm));
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/** The window names of `session` on the tmux server at `socket`: `{ windows }`, empty when the server
|
|
199
|
+
* or the session is gone, with `missingSocket` (tmux's words) when the socket file is missing, which
|
|
200
|
+
* alone does not say the server is gone (#624); `{ error }` when the server could not be read. */
|
|
201
|
+
function recordedTmuxWindows(socket, session, io) {
|
|
202
|
+
try { return { windows: tmuxOn(socket, ["list-windows", "-t", `=${session}`, "-F", "#{window_name}"], io).split("\n").filter(Boolean) }; }
|
|
203
|
+
catch (e) {
|
|
204
|
+
const absence = tmuxServerAbsence(e);
|
|
205
|
+
if (absence === "missing-socket") return { windows: [], missingSocket: tmuxFailure(e, "tmux list-windows failed") };
|
|
206
|
+
if (absence || /can't find session/i.test(String(e.stderr ?? ""))) return { windows: [] };
|
|
207
|
+
return { error: String(e.stderr ?? e.message ?? "").trim() || "tmux list-windows failed" };
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
/** A status row's harness liveness from its session's panes: unknown (not false) when the server could not
|
|
211
|
+
* be read, and, for a row whose server holds its endpoint (`endpoint`), when its socket file is
|
|
212
|
+
* missing while a process works in the home or the scan (`scanHome()`, processesInHome's answer for
|
|
213
|
+
* it) cannot tell (#624). */
|
|
214
|
+
function tmuxLiveness({ windows, error, missingSocket, panes, windowIds }, window, scanHome, endpoint, inspectPanes) {
|
|
215
|
+
if (error) return { running: null, runtimeState: "unreachable", runtimeError: error };
|
|
216
|
+
const running = windows.includes(window);
|
|
217
|
+
const why = !running && missingSocket && endpoint ? missingSocketUnestablished(missingSocket, scanHome()) : null;
|
|
218
|
+
if (why) return { running: null, runtimeState: "unreachable", runtimeError: why };
|
|
219
|
+
if (!running) return { running: false };
|
|
220
|
+
try {
|
|
221
|
+
// Two windows of one name: tmux finds neither by name, so no session command reaches this one.
|
|
222
|
+
if (windowIds?.get(window)?.size > 1) throw new Error(`the session has ${windowIds.get(window).size} windows named ${window}`);
|
|
223
|
+
const observed = inspectPanes(panes.get(window) ?? [], { name: window });
|
|
224
|
+
return { running: harnessRunning(observed), ...(observed.state === "shell" ? { runtimeState: "shell" } : {}) };
|
|
225
|
+
} catch (e) { return { running: null, runtimeState: "unreachable", runtimeError: tmuxFailure(e, "tmux pane inspection failed") }; }
|
|
226
|
+
}
|
|
227
|
+
/** One extra read per socket/session, never per row. Keep window discovery's missing-socket
|
|
228
|
+
* handling; a failed pane read after successful discovery is unknown, not proof of a stop. */
|
|
229
|
+
function statusTmuxPanes(snapshot, socket, session, io) {
|
|
230
|
+
if (!snapshot.windows?.length) return snapshot;
|
|
231
|
+
try {
|
|
232
|
+
const args = ["list-panes", "-s", "-t", `=${session}`, "-F", `#{window_name}\t#{window_id}\t#{pane_id}\t#{pane_dead}\t#{pane_current_command}\t#{pane_pid}\t#{${AGENT_PANE_OPTION}}`];
|
|
233
|
+
const output = socket ? tmuxOn(socket, args, io) : (io?.exec || execFileSync)("tmux", ["-u", ...args], {
|
|
234
|
+
encoding: "utf8", timeout: 10000, maxBuffer: 1024 * 1024, stdio: ["ignore", "pipe", "pipe"],
|
|
235
|
+
});
|
|
236
|
+
const panes = new Map(), windowIds = new Map();
|
|
237
|
+
for (const line of output.split("\n").filter(Boolean)) {
|
|
238
|
+
const [window, windowId, ...pane] = line.split("\t");
|
|
239
|
+
if (!pane.length) throw new Error("invalid tmux pane response");
|
|
240
|
+
if (!panes.has(window)) { panes.set(window, []); windowIds.set(window, new Set()); }
|
|
241
|
+
panes.get(window).push(pane.join("\t"));
|
|
242
|
+
windowIds.get(window).add(windowId);
|
|
243
|
+
}
|
|
244
|
+
return { ...snapshot, panes, windowIds };
|
|
245
|
+
} catch (e) { return { error: tmuxFailure(e, "tmux list-panes failed") }; }
|
|
246
|
+
}
|
|
247
|
+
export function listInstances(root, tmuxSession = DEFAULT_TMUX_SESSION, io) {
|
|
248
|
+
// Liveness reads each home's RECORDED endpoint (a pre-0.31 home records pi-agents): the recorded
|
|
249
|
+
// socket, never the ambient $TMUX server: one window read and one pane read per socket/session,
|
|
250
|
+
// plus one lazy process scan for shell descendants, independent of the number of homes.
|
|
251
|
+
// A home without a recorded socket reads the default server.
|
|
252
|
+
// A row whose socket file is missing is checked against one process scan of the host, made the
|
|
253
|
+
// first time a row needs it and shared by every row (`io` reaches it: processesInHome).
|
|
254
|
+
let hostScan;
|
|
255
|
+
const scanOf = (home) => () => {
|
|
256
|
+
hostScan ??= hostProcesses(io);
|
|
257
|
+
return hostScan.ok ? { ok: true, processes: processesWorkingIn(hostScan.processes, home) } : hostScan;
|
|
258
|
+
};
|
|
259
|
+
const inspectPanes = createSessionPaneInspector(io);
|
|
260
|
+
const tmuxByEndpoint = new Map();
|
|
261
|
+
const windowsOf = (session, socket) => {
|
|
262
|
+
const key = JSON.stringify([socket ?? null, session]);
|
|
263
|
+
if (!tmuxByEndpoint.has(key)) tmuxByEndpoint.set(key, statusTmuxPanes(
|
|
264
|
+
socket ? recordedTmuxWindows(socket, session, io) : defaultTmuxWindows(session), socket, session, io));
|
|
265
|
+
return tmuxByEndpoint.get(key);
|
|
266
|
+
};
|
|
267
|
+
const readInstancesOf = (agentDir) => {
|
|
268
|
+
const instancesDir = join(agentDir, "instances");
|
|
269
|
+
// An instance name starts with a letter or digit (INSTANCE_NAME_RE); a
|
|
270
|
+
// dot-directory under instances/ is kernel bookkeeping (.oats-retirement
|
|
271
|
+
// holds baselines and recoveries), never a home (oats-5xl).
|
|
272
|
+
return (existsSync(instancesDir) ? readdirSync(instancesDir, { withFileTypes: true }) : [])
|
|
273
|
+
.filter((e) => e.isDirectory() && !e.name.startsWith("."))
|
|
274
|
+
.map((e) => {
|
|
275
|
+
const home = join(instancesDir, e.name);
|
|
276
|
+
// The record decides for this home only: one that is there and cannot be read gives the
|
|
277
|
+
// row of a home without a record, whose liveness says why (below), never a failed listing.
|
|
278
|
+
const record = readHomeRecord(home);
|
|
279
|
+
const meta = record.state === "record" ? upgradeHomeMeta(record.meta, home) : { instance: e.name, home };
|
|
280
|
+
// A home retained by an incomplete rollback is NOT a live instance: it
|
|
281
|
+
// is preserved state awaiting cleanup, and must read that way.
|
|
282
|
+
const fallback = directoryRollbackPath(home);
|
|
283
|
+
const quarantine = existsSync(fallback) ? fallback : join(home, ".oats-rollback-incomplete.json");
|
|
284
|
+
let rollbackIncomplete, spawnInProgress;
|
|
285
|
+
if (existsSync(quarantine)) {
|
|
286
|
+
try { rollbackIncomplete = JSON.parse(readFileSync(quarantine, "utf8")); }
|
|
287
|
+
catch { rollbackIncomplete = { reason: "rollback incomplete" }; }
|
|
288
|
+
// #796: a spawn still running its worktree hooks keeps a marker that names it
|
|
289
|
+
// (`inProgress`). While that process is verifiably alive the home is a spawn in
|
|
290
|
+
// progress, not a failed one; otherwise the marker reads as the quarantine. A process whose
|
|
291
|
+
// start cannot be read is not shown in progress either: on a host that never reads it, the
|
|
292
|
+
// row would say "setting up" forever. It reads as the quarantine (its `inProgress` names
|
|
293
|
+
// the pid), and retire, which never takes it for gone, refuses it with the way out.
|
|
294
|
+
if (rollbackIncomplete?.inProgress && processLiveness(rollbackIncomplete.inProgress).state === "alive") { rollbackIncomplete = undefined; spawnInProgress = true; }
|
|
295
|
+
}
|
|
296
|
+
// A self-retire that has been requested but not completed: the home is
|
|
297
|
+
// owed a retirement, not live work. Read-only here — completion is the
|
|
298
|
+
// detached child's or an operator's `oats retire`, never status.
|
|
299
|
+
const { retirePending, marker } = readRetirePending(home);
|
|
300
|
+
const retire = retireStateOf(home, marker);
|
|
301
|
+
// A home opened in Herdr (removed in 0.31.0) is listed, never observed: its row says so.
|
|
302
|
+
// A home whose record cannot be read is listed, never observed: where its session is, is in the record.
|
|
303
|
+
const liveness = record.state === "unreadable" ? { running: null, runtimeState: "unreachable", runtimeError: `E_UNIDENTIFIED_INSTANCE_HOME: ${unreadableRecordSaid(record)}` }
|
|
304
|
+
: recordsHerdr(meta, readJsonOrUndefined(findRetirementBaseline(home)))
|
|
305
|
+
? { running: null, runtimeState: "unsupported", runtimeError: `E_HERDR_REMOVED: ${herdrInstanceRemoved(e.name).message}` }
|
|
306
|
+
: tmuxLiveness(windowsOf(meta.tmux?.session || tmuxSession, meta.tmux?.socket), meta.tmux?.window || meta.instance || e.name, scanOf(home),
|
|
307
|
+
// A home that records no socket and no launch (--no-launch) reads the default server only
|
|
308
|
+
// by default: that server's missing socket says nothing about it, and stays "not running".
|
|
309
|
+
!!meta.tmux?.socket || meta.launched === true, inspectPanes);
|
|
310
|
+
const identity = servedIdentityOf(meta);
|
|
311
|
+
// Feature desktop-facts: `startedAt` — the last session start or restart (the receipt's restarts[]),
|
|
312
|
+
// else the spawn's own launch (createdAt), else null (never launched); `identityAddress` — the
|
|
313
|
+
// messaging identity's address (or alias) its capability recorded, null otherwise; `modelFrom` — null
|
|
314
|
+
// for a home spawned before it was recorded.
|
|
315
|
+
const lastStart = Array.isArray(meta.restarts) && meta.restarts.length ? meta.restarts[meta.restarts.length - 1]?.startedAt ?? null : null;
|
|
316
|
+
const facts = { startedAt: lastStart ?? (meta.launched ? meta.createdAt ?? null : null), identityAddress: identity ? identity.address ?? identity.alias ?? null : null, modelFrom: meta.modelFrom ?? null };
|
|
317
|
+
// The home IS the directory enumerated here, and the instance its name:
|
|
318
|
+
// a file inside it cannot relocate or rename itself in the roster (every
|
|
319
|
+
// consumer acting on `home` — retire, inspect --home, the Desktop's file
|
|
320
|
+
// roots — would inherit the claim). A disagreeing claim survives only as
|
|
321
|
+
// a diagnostic.
|
|
322
|
+
const claims = {
|
|
323
|
+
...(meta.home !== undefined && meta.home !== home ? { recordedHome: meta.home } : {}),
|
|
324
|
+
...(meta.instance !== undefined && meta.instance !== e.name ? { recordedInstance: meta.instance } : {}),
|
|
325
|
+
};
|
|
326
|
+
// Feature waiting-on-you: a producer's live claim that the instance is
|
|
327
|
+
// blocked on a human, read only for a running row (one bounded read of
|
|
328
|
+
// its home log); null otherwise, and null means unknown. Pane liveness is
|
|
329
|
+
// already observed in the batch; still require the independent receipt
|
|
330
|
+
// to agree before showing a claim, just as session inspect does.
|
|
331
|
+
let waitingOnYou = liveness.running === true ? liveWaiting(home) : null;
|
|
332
|
+
if (waitingOnYou) {
|
|
333
|
+
try { const s = instanceSessionTarget(home); if (!s.target) waitingOnYou = null; }
|
|
334
|
+
catch { waitingOnYou = null; }
|
|
335
|
+
}
|
|
336
|
+
// `retire` is only ever the value read above, and `background` and `sameWork` the home's own records
|
|
337
|
+
// (below): a record that carries any of them (hand-edited, or copied from a row) never stands in for it.
|
|
338
|
+
const { retire: _recordedRetire, background: _recordedBackground, sameWork: _recordedSameWork, ...recorded } = meta;
|
|
339
|
+
// Feature session-resume: how the last session of a launched home that does not run ended
|
|
340
|
+
// (lib/session-end.mjs): lost, stopped or exited. Absent while it runs or reads unknown, for a
|
|
341
|
+
// home never launched, and for one being set up, retired or quarantined.
|
|
342
|
+
const sessionEnd = record.state === "record" && liveness.running === false && meta.launched === true && !rollbackIncomplete && !spawnInProgress && !retirePending ? sessionEndOf(home, meta) : null;
|
|
343
|
+
// Feature instance-color: the home's own colour record (lib/instance-color.mjs), a palette name or
|
|
344
|
+
// null, after the record so that nothing in instance.json stands in for it.
|
|
345
|
+
// Feature instance-same-work: `sameWork: true` only while the home's flag is bound to the parent
|
|
346
|
+
// its readable record names (lib/instance-same-work.mjs sameWorkOf); absent otherwise, never false.
|
|
347
|
+
const sameWork = record.state === "record" && sameWorkOf(home, meta.parentInstance);
|
|
348
|
+
return { ...recorded, ...claims, home, instance: e.name, ...facts, color: readInstanceColor(home), ...(readInstanceBackground(home) ? { background: true } : {}), ...(sameWork ? { sameWork: true } : {}), ...(identity ? { identity } : {}), ...(meta.launch && typeof meta.launch === "object" ? { launch: redactLaunchRecipe(meta.launch) } : {}), ...(typeof meta.command === "string" ? { command: redactLaunchCommand(meta.command) } : {}), ...liveness, ...(sessionEnd ? { sessionEnd } : {}), waitingOnYou, ...(rollbackIncomplete ? { rollbackIncomplete } : {}), ...(spawnInProgress ? { spawnInProgress } : {}), ...(retirePending ? { retirePending } : {}), ...(retire ? { retire } : {}) };
|
|
349
|
+
|
|
350
|
+
});
|
|
351
|
+
};
|
|
352
|
+
// Failed deferred self-retirements leave their outcome beside the home; a
|
|
353
|
+
// successful one is evidence only and is not a problem to surface.
|
|
354
|
+
const readRetireFailuresOf = (agentDir) => {
|
|
355
|
+
const instancesDir = join(agentDir, "instances");
|
|
356
|
+
if (!existsSync(instancesDir)) return [];
|
|
357
|
+
const out = [];
|
|
358
|
+
for (const e of readdirSync(instancesDir, { withFileTypes: true })) {
|
|
359
|
+
const m = e.isFile() && /^\.oats-retired-(.+)\.json$/.exec(e.name);
|
|
360
|
+
if (!m) continue;
|
|
361
|
+
try {
|
|
362
|
+
const r = JSON.parse(readFileSync(join(instancesDir, e.name), "utf8"));
|
|
363
|
+
if (r.ok === false) out.push({ instance: m[1], completedAt: r.completedAt, error: r.error?.message, incomplete: r.result?.rollbackIncomplete, retry: r.retry, resultPath: join(instancesDir, e.name) });
|
|
364
|
+
} catch { out.push({ instance: m[1], error: "unreadable result file", resultPath: join(instancesDir, e.name) }); }
|
|
365
|
+
}
|
|
366
|
+
return out;
|
|
367
|
+
};
|
|
368
|
+
const withFailures = (entry, agentDir) => {
|
|
369
|
+
const retireFailures = readRetireFailuresOf(agentDir);
|
|
370
|
+
return retireFailures.length ? { ...entry, retireFailures } : entry;
|
|
371
|
+
};
|
|
372
|
+
const out = listAgents(root).map((a) => {
|
|
373
|
+
const { _dir, ...soul } = a;
|
|
374
|
+
return withFailures({ ...soul, dir: _dir, instances: readInstancesOf(a._dir) }, a._dir);
|
|
375
|
+
});
|
|
376
|
+
// Capability-defined agents home under <root>/<name>/ WITHOUT a soul there (it
|
|
377
|
+
// lives read-only in the module) — surface their instances too. A soul-less dir
|
|
378
|
+
// none of whose homes is a capability agent's is not one.
|
|
379
|
+
const seen = new Set(out.map((a) => a.name));
|
|
380
|
+
for (const { name, dir } of capabilityAgentDirs(root)) {
|
|
381
|
+
if (seen.has(name)) continue;
|
|
382
|
+
const instances = readInstancesOf(dir);
|
|
383
|
+
const retireFailures = readRetireFailuresOf(dir);
|
|
384
|
+
if (!instances.some((i) => i.kind === "capability") && !retireFailures.length) continue;
|
|
385
|
+
const cap = instances.find((i) => i.capability)?.capability;
|
|
386
|
+
out.push({ name, kind: "capability", capability: cap, description: cap ? `capability agent (${cap})` : "capability agent", dir, instances, ...(retireFailures.length ? { retireFailures } : {}) });
|
|
387
|
+
seen.add(name);
|
|
388
|
+
}
|
|
389
|
+
// Feature session-resume: what this local listing saw of each home's session, for the sweep
|
|
390
|
+
// (lib/session-seen.mjs). It never changes the listing, and never throws or prints.
|
|
391
|
+
recordSeen(root, out.flatMap((a) => a.instances || []));
|
|
392
|
+
return out;
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
// A substituted/missing home cannot hold its own receipt. This sibling fallback
|
|
396
|
+
// is independent of both home bytes and the recovery storage that may have failed.
|
|
397
|
+
function directoryRollbackPath(home) {
|
|
398
|
+
return join(dirname(home), `.oats-directory-rollback-${basename(home)}.json`);
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
/** How a failed tmux call reads the server it addressed (#624). "gone": no server listens on the
|
|
402
|
+
* socket (`no server running on`, or a refused connection), which is definitive. "missing-socket":
|
|
403
|
+
* the socket file is not there (`No such file or directory`). After a reboot the server is gone,
|
|
404
|
+
* but a tmux server outlives its removed socket file, so that alone establishes nothing: a caller
|
|
405
|
+
* concludes stopped from it only when no process works in the home (missingSocketUnestablished).
|
|
406
|
+
* null: anything else. */
|
|
407
|
+
function tmuxServerAbsence(e) {
|
|
408
|
+
const text = String(e?.stderr ?? e?.message ?? "");
|
|
409
|
+
if (/no server running on |(?:error connecting to|failed to connect to) .*Connection refused/i.test(text)) return "gone";
|
|
410
|
+
if (/(?:error connecting to|failed to connect to) .*No such file or directory/i.test(text)) return "missing-socket";
|
|
411
|
+
return null;
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
/** tmux's own way back for a server that lost its socket file (tmux(1), `-S`). Named, never performed. */
|
|
415
|
+
const TMUX_SOCKET_REMEDY = "tmux recreates a removed socket file when its server process receives SIGUSR1";
|
|
416
|
+
/** Processes as a refusal names them: pid and program, at most five, then how many more. */
|
|
417
|
+
function namedProcesses(processes) {
|
|
418
|
+
return `${processes.slice(0, 5).map((p) => `pid ${p.pid} ${p.command}`).join(", ")}${processes.length > 5 ? `, and ${processes.length - 5} more` : ""}`;
|
|
419
|
+
}
|
|
420
|
+
/** A missing socket file (`detail`, tmux's words) checked against `scan`, processesInHome's answer
|
|
421
|
+
* for the home (#624): null when it ran and found no process there, so the server is taken as gone,
|
|
422
|
+
* as after a reboot; otherwise why the state is not established. Any process working in the home
|
|
423
|
+
* counts, a person's shell included: the words name it, so the person can act on it. */
|
|
424
|
+
function missingSocketUnestablished(detail, scan) {
|
|
425
|
+
if (!scan.ok) return `${detail}; whether a process still works in this home could not be established (${scan.error})`;
|
|
426
|
+
if (scan.processes.length) return `${detail}; a process still works in this home (${namedProcesses(scan.processes)}), so its tmux server may still be running without its socket file: ${TMUX_SOCKET_REMEDY}`;
|
|
427
|
+
return null;
|
|
428
|
+
}
|
|
429
|
+
/** Whether this host's /proc can be read: Linux, and this process's own `cwd` link resolves. */
|
|
430
|
+
function procReadable() {
|
|
431
|
+
if (process.platform !== "linux") return { ok: false, error: "this host has no /proc to read (it is not Linux)" };
|
|
432
|
+
try { readlinkSync("/proc/self/cwd"); return { ok: true }; }
|
|
433
|
+
catch (e) { return { ok: false, error: `/proc/self/cwd cannot be read (${e.code || e.message})` }; }
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
/**
|
|
437
|
+
* Every live process on the host (other than this one and its direct children) with its working
|
|
438
|
+
* directory, from one scan: /proc on Linux (`io.procRoot` names another root), else one `lsof -a -d
|
|
439
|
+
* cwd` listing; an injected `io.exec` stands in for the host's commands, so it is lsof's. Each cwd
|
|
440
|
+
* is kept in its on-disk spelling (canonicalHomePath); one the kernel reports deleted (`<path>
|
|
441
|
+
* (deleted)`) is kept as both spellings. A process this user may not inspect (another user's, or a
|
|
442
|
+
* non-dumpable one) is not seen by either mechanism.
|
|
443
|
+
* → { ok: true, processes: [{pid, command, cwds}] } | { ok: false, error }
|
|
444
|
+
*/
|
|
445
|
+
function hostProcesses(io) {
|
|
446
|
+
const rows = typeof io?.procRoot === "string" ? procRows(io.procRoot)
|
|
447
|
+
: !io?.exec && procReadable().ok ? procRows("/proc")
|
|
448
|
+
: lsofRows(io);
|
|
449
|
+
if (!rows.ok) return rows;
|
|
450
|
+
const processes = [];
|
|
451
|
+
for (const { pid, ppid, command, cwd } of rows.rows) {
|
|
452
|
+
if (!pid || pid === process.pid || ppid === process.pid || typeof cwd !== "string") continue;
|
|
453
|
+
const spellings = cwd.endsWith(" (deleted)") ? [cwd, cwd.slice(0, -" (deleted)".length)] : [cwd];
|
|
454
|
+
processes.push({ pid, command: command ?? "?", cwds: spellings.map((p) => canonicalHomePath(p)) });
|
|
455
|
+
}
|
|
456
|
+
return { ok: true, processes };
|
|
457
|
+
}
|
|
458
|
+
/** The processes of a hostProcesses listing that work in `home`, compared in its on-disk spelling. */
|
|
459
|
+
function processesWorkingIn(processes, home) {
|
|
460
|
+
const realHome = canonicalHomePath(home);
|
|
461
|
+
return processes.filter((p) => p.cwds.some((cwd) => cwd === realHome || cwd.startsWith(`${realHome}/`))).map(({ pid, command }) => ({ pid, command }));
|
|
462
|
+
}
|
|
463
|
+
/** /proc read as a scan: each numeric entry's `cwd` link, `comm` and `stat` (its ppid is the second
|
|
464
|
+
* field after the last `)`, which ends the command). A pid that cannot be read (it ended meanwhile,
|
|
465
|
+
* this user may not inspect it, or any other failure on that one pid) is not seen. A root that
|
|
466
|
+
* cannot be listed, or one that lists no readable process, is a failed scan, never an empty one. */
|
|
467
|
+
function procRows(root) {
|
|
468
|
+
let names;
|
|
469
|
+
try { names = readdirSync(root); }
|
|
470
|
+
catch (e) { return { ok: false, error: `${root} cannot be read (${e.code || e.message})` }; }
|
|
471
|
+
const rows = [];
|
|
472
|
+
for (const name of names) {
|
|
473
|
+
if (!/^\d+$/.test(name)) continue;
|
|
474
|
+
try {
|
|
475
|
+
const cwd = readlinkSync(join(root, name, "cwd"));
|
|
476
|
+
const command = readFileSync(join(root, name, "comm"), "utf8").replace(/\n$/, "");
|
|
477
|
+
const stat = readFileSync(join(root, name, "stat"), "utf8");
|
|
478
|
+
rows.push({ pid: Number(name), ppid: Number(stat.slice(stat.lastIndexOf(")") + 1).trim().split(/\s+/)[1]), command, cwd });
|
|
479
|
+
} catch { /* not seen */ }
|
|
480
|
+
}
|
|
481
|
+
// A real /proc always lists at least this process.
|
|
482
|
+
if (!rows.length) return { ok: false, error: `${root} listed no process` };
|
|
483
|
+
return { ok: true, rows };
|
|
484
|
+
}
|
|
485
|
+
function lsofRows(io) {
|
|
486
|
+
let out;
|
|
487
|
+
try { out = (io?.exec || execFileSync)("lsof", ["-a", "-d", "cwd", "-F", "pRcn", "-w"], { encoding: "utf8", timeout: 20000, maxBuffer: 16 * 1024 * 1024, stdio: ["ignore", "pipe", "pipe"] }); }
|
|
488
|
+
catch (e) {
|
|
489
|
+
// lsof exits 1 with a full listing when some process could not be read. That is the one failure
|
|
490
|
+
// whose output is a scan: lsof ended by itself with status 1 (no signal, and no error code, which
|
|
491
|
+
// Node sets when the capture itself failed: a timeout, too much output). A scan that was cut off
|
|
492
|
+
// is a failed scan whatever it printed first. The error says what happened, never a line of the
|
|
493
|
+
// listing.
|
|
494
|
+
const completed = e?.status === 1 && e.signal == null && e.code === undefined;
|
|
495
|
+
if (completed && typeof e.stdout === "string") out = e.stdout;
|
|
496
|
+
else return { ok: false, error: e?.code === "ENOENT" ? "lsof is not on PATH; install lsof"
|
|
497
|
+
: e?.code === "ETIMEDOUT" ? "lsof timed out"
|
|
498
|
+
: e?.code === "ENOBUFS" ? "lsof printed more output than the scan reads"
|
|
499
|
+
: e?.signal ? `lsof was ended by ${e.signal}`
|
|
500
|
+
: String(e?.stderr || e?.message || "lsof failed").trim().split("\n")[0] };
|
|
501
|
+
}
|
|
502
|
+
// A listing holds at least one process (lsof and its caller are always in it), whichever exit it came with.
|
|
503
|
+
if (!/^p\d+$/m.test(String(out))) return { ok: false, error: "lsof listed no process" };
|
|
504
|
+
const rows = [];
|
|
505
|
+
let cur = {};
|
|
506
|
+
for (const line of String(out).split("\n")) {
|
|
507
|
+
const tag = line[0], value = line.slice(1);
|
|
508
|
+
if (tag === "p") { cur = { pid: Number(value) }; rows.push(cur); }
|
|
509
|
+
else if (tag === "R") cur.ppid = Number(value);
|
|
510
|
+
else if (tag === "c") cur.command = value;
|
|
511
|
+
else if (tag === "n") cur.cwd = value;
|
|
512
|
+
}
|
|
513
|
+
return { ok: true, rows };
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
/** The prompt token of a recorded claude or codex command that hands the harness the task's own
|
|
517
|
+
* text in argv, where any local user can read it: `"$(cat TASK.md)"`. It is parsed, and replaced
|
|
518
|
+
* when the home starts (withSafeTaskPrompt). */
|
|
519
|
+
const LAUNCH_PROMPT_TOKEN = '"$(cat TASK.md)"';
|
|
520
|
+
|
|
521
|
+
/** Tokenize a persisted OATS launch command. The grammar is exactly what
|
|
522
|
+
* spawn renders: space-separated tokens that are env assignments NAME='v',
|
|
523
|
+
* single-quoted words ('...' with '\'' escapes, i.e. shq output), bare words
|
|
524
|
+
* with no shell metacharacters (flags and capability launch args), the bare
|
|
525
|
+
* `--` separator, or the exact prompt token "$(cat TASK.md)". Anything else
|
|
526
|
+
* is refused with its position: the command was not one OATS
|
|
527
|
+
* generated, and rewriting it would be guessing. Re-rendering joins the
|
|
528
|
+
* tokens' original text, so untouched tokens are byte-identical. */
|
|
529
|
+
export function parseLaunchCommand(command) {
|
|
530
|
+
if (typeof command !== "string" || !command.trim() || command.includes("\0")) throw oatsError("E_LAUNCH_COMMAND_UNSUPPORTED", "instance has no valid persisted launch command to start from");
|
|
531
|
+
const bad = (at, why) => { throw oatsError("E_LAUNCH_COMMAND_UNSUPPORTED", `persisted launch command is not a shape this kernel re-renders (${why} at offset ${at}); inspect the saved command in instance.json before starting this home manually`); };
|
|
532
|
+
const tokens = [];
|
|
533
|
+
const n = command.length;
|
|
534
|
+
let i = 0;
|
|
535
|
+
while (i < n) {
|
|
536
|
+
if (command[i] === " ") { i++; continue; }
|
|
537
|
+
const start = i;
|
|
538
|
+
if (command.startsWith(LAUNCH_PROMPT_TOKEN, i)) {
|
|
539
|
+
i += LAUNCH_PROMPT_TOKEN.length;
|
|
540
|
+
if (i < n && command[i] !== " ") bad(start, "text glued to the prompt token");
|
|
541
|
+
tokens.push({ kind: "prompt", text: LAUNCH_PROMPT_TOKEN });
|
|
542
|
+
continue;
|
|
543
|
+
}
|
|
544
|
+
// NAME="$SOURCE": an environment reference, resolved on the execution
|
|
545
|
+
// host when the command runs; the persisted command carries no value.
|
|
546
|
+
const ref = /^([A-Za-z_][A-Za-z0-9_]*)="\$([A-Za-z_][A-Za-z0-9_]*)"(?= |$)/.exec(command.slice(i));
|
|
547
|
+
if (ref) { tokens.push({ kind: "envref", name: ref[1], source: ref[2], text: ref[0] }); i += ref[0].length; continue; }
|
|
548
|
+
let envName;
|
|
549
|
+
const m = /^([A-Za-z_][A-Za-z0-9_]*)='/.exec(command.slice(i));
|
|
550
|
+
if (m) { envName = m[1]; i += envName.length + 1; }
|
|
551
|
+
if (command[i] === "'") {
|
|
552
|
+
i++;
|
|
553
|
+
let value = "";
|
|
554
|
+
for (;;) {
|
|
555
|
+
if (i >= n) bad(start, "unterminated single quote");
|
|
556
|
+
if (command[i] === "'") {
|
|
557
|
+
if (command.startsWith("'\\''", i)) { value += "'"; i += 4; continue; }
|
|
558
|
+
i++; break;
|
|
559
|
+
}
|
|
560
|
+
value += command[i++];
|
|
561
|
+
}
|
|
562
|
+
if (i < n && command[i] !== " ") bad(start, "text glued to a quoted token");
|
|
563
|
+
const text = command.slice(start, i);
|
|
564
|
+
tokens.push(envName ? { kind: "env", name: envName, value, text } : { kind: "word", value, quoted: true, text });
|
|
565
|
+
continue;
|
|
566
|
+
}
|
|
567
|
+
if (envName) bad(start, "unquoted env value");
|
|
568
|
+
while (i < n && command[i] !== " ") {
|
|
569
|
+
if (/[\s'"$`\\;|&<>(){}*?~#]/.test(command[i])) bad(start, "shell metacharacter outside quotes");
|
|
570
|
+
i++;
|
|
571
|
+
}
|
|
572
|
+
const word = command.slice(start, i);
|
|
573
|
+
tokens.push(word === "--" ? { kind: "sep", text: word } : { kind: "word", value: word, quoted: false, text: word });
|
|
574
|
+
}
|
|
575
|
+
let binary = -1;
|
|
576
|
+
for (let k = 0; k < tokens.length; k++) {
|
|
577
|
+
if (tokens[k].kind === "env" || tokens[k].kind === "envref") { if (binary >= 0) bad(0, "env assignment after the binary"); continue; }
|
|
578
|
+
if (binary < 0) { if (tokens[k].kind !== "word" || !tokens[k].quoted) bad(0, "no quoted binary after the env prefix"); binary = k; }
|
|
579
|
+
}
|
|
580
|
+
if (binary < 0) bad(0, "no binary");
|
|
581
|
+
let modelIndex = -1;
|
|
582
|
+
for (let k = binary + 1; k < tokens.length; k++) {
|
|
583
|
+
if (tokens[k].kind === "sep") break;
|
|
584
|
+
if (tokens[k].kind === "word" && !tokens[k].quoted && tokens[k].value === "--model") {
|
|
585
|
+
const v = tokens[k + 1];
|
|
586
|
+
if (!v || v.kind !== "word" || v.value.startsWith("-")) bad(0, "--model without a value");
|
|
587
|
+
if (modelIndex >= 0) bad(0, "duplicate --model options");
|
|
588
|
+
modelIndex = k + 1;
|
|
589
|
+
k++;
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
return { tokens, binary, modelIndex };
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
/** One tmux command on `socket`. With `env` (a window client: oatsWindowEnvironment, which has no
|
|
596
|
+
* PATH) the tmux is the absolute one this process's own PATH finds, so its lookup never depends on
|
|
597
|
+
* the environment it is passed; none found is reported as tmux being unavailable (ENOENT). */
|
|
598
|
+
function tmuxOn(socket, args, io, env) {
|
|
599
|
+
let tmux = "tmux";
|
|
600
|
+
if (env) {
|
|
601
|
+
tmux = process.env.PATH === undefined ? null : lookupOnPath("tmux", process.env.PATH);
|
|
602
|
+
if (!tmux) throw Object.assign(new Error("no tmux was found on this process's PATH"), { code: "ENOENT" });
|
|
603
|
+
}
|
|
604
|
+
return (io?.exec || execFileSync)(tmux, ["-u", "-S", socket, ...args], { encoding: "utf8", timeout: 10000, maxBuffer: 1024 * 1024, stdio: ["ignore", "pipe", "pipe"], ...(env ? { env } : {}) });
|
|
605
|
+
}
|
|
606
|
+
|
|
607
|
+
/** Does this instance.json describe a captured home (the 0.24–0.25 captured/portable path,
|
|
608
|
+
* removed in 0.26)? It records its incarnation instead of modules. */
|
|
609
|
+
export function isCapturedHome(meta) {
|
|
610
|
+
return !!meta && typeof meta === "object" && ["executionBinding", "incarnationId", "captured"].some((key) => Object.hasOwn(meta, key));
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
/** Marker a self-retiring instance leaves BESIDE its home: the retirement is
|
|
614
|
+
* requested and owed, and a detached completion is on its way. It is not
|
|
615
|
+
* written into the home, so the caller changes no instance bytes and the
|
|
616
|
+
* completion's work inspection sees exactly what the instance left. */
|
|
617
|
+
export function retirePendingMarkerPath(home) {
|
|
618
|
+
return join(dirname(home), `.oats-retire-pending-${basename(home)}.json`);
|
|
619
|
+
}
|
|
620
|
+
|
|
621
|
+
/** The retire-pending marker of `home` as a status row reads it → `{ retirePending, marker }`: both
|
|
622
|
+
* undefined when there is none; `retirePending` what it parsed as (a placeholder when it did not
|
|
623
|
+
* parse), `marker` what retireStateOf takes. */
|
|
624
|
+
function readRetirePending(home) {
|
|
625
|
+
const pending = retirePendingMarkerPath(home);
|
|
626
|
+
if (!existsSync(pending)) return {};
|
|
627
|
+
try { const read = JSON.parse(readFileSync(pending, "utf8")); return { retirePending: read, marker: { read } }; }
|
|
628
|
+
catch { return { retirePending: { reason: "retire pending" }, marker: { read: undefined } }; }
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
/** A status row's `retire` (feature status-retire-state, lib/retire-state.mjs): whether a retire of
|
|
632
|
+
* `home` runs, could not be told, failed or was interrupted, read from what is beside the home
|
|
633
|
+
* (`marker`: `{ read }` when its retire marker is there, `read` what its file parsed as, undefined
|
|
634
|
+
* when it did not parse; the row's own read, so `retirePending` and this agree). Only read: no
|
|
635
|
+
* claim is taken, no file removed, no process signalled. → the value, or undefined when no retire
|
|
636
|
+
* runs, is scheduled or is owed.
|
|
637
|
+
* - The marker of a self-retire comes first, whatever the claim says (its completion holds the
|
|
638
|
+
* claim for its own retire), and gives `self: true`. A completion's result that says `ok:
|
|
639
|
+
* false` is `failed`, with its time, code and message. Otherwise, a result that says anything
|
|
640
|
+
* else included, the marker's completion decides: `running` while it lives (pid and recorded
|
|
641
|
+
* start), `interrupted` once it is gone, and `unknown` when that cannot be read or the marker
|
|
642
|
+
* names no completion. A marker that does not parse is `unknown`.
|
|
643
|
+
* - Without a marker, the home's claim held for a retire is `running` while its holder lives and
|
|
644
|
+
* `unknown` when that cannot be read, with `self: false`. A holder that is gone, a stop's claim
|
|
645
|
+
* or no claim gives no value.
|
|
646
|
+
* `since` is required (a reader drops a value without one): the recorded time when it is an
|
|
647
|
+
* instant as `toISOString()` gives it (the result's `completedAt`, then the marker's
|
|
648
|
+
* `requestedAt`; the claim's `at`), else the marker's or the claim file's mtime. When none can be
|
|
649
|
+
* read there is no value at all. */
|
|
650
|
+
function retireStateOf(home, marker) {
|
|
651
|
+
const mtimeOf = (path) => { try { return statSync(path).mtime.toISOString(); } catch { return undefined; } };
|
|
652
|
+
// A file beside the home as JSON, only when it is a regular file: opened without blocking and
|
|
653
|
+
// checked on the open descriptor, so a pipe (whose open or read would not return) or a device put
|
|
654
|
+
// there is no value, never a status that hangs. Anything that does not read is undefined.
|
|
655
|
+
const regularJson = (path) => {
|
|
656
|
+
let fd;
|
|
657
|
+
try {
|
|
658
|
+
fd = openSync(path, fsConstants.O_RDONLY | (fsConstants.O_NONBLOCK ?? 0));
|
|
659
|
+
return fstatSync(fd).isFile() ? JSON.parse(readFileSync(fd, "utf8")) : undefined;
|
|
660
|
+
} catch { return undefined; } finally { if (fd !== undefined) closeSync(fd); }
|
|
661
|
+
};
|
|
662
|
+
const instantOr = (...times) => times.find((t) => isInstantString(t));
|
|
663
|
+
if (marker) {
|
|
664
|
+
const pending = marker.read, markerTime = () => mtimeOf(retirePendingMarkerPath(home));
|
|
665
|
+
if (!isPlainObject(pending)) return readRetireState({ state: "unknown", self: true, since: markerTime() });
|
|
666
|
+
const result = regularJson(deferredRetireResultPath(home));
|
|
667
|
+
if (isPlainObject(result) && result.ok === false) {
|
|
668
|
+
return readRetireState({ state: "failed", self: true, since: instantOr(result.completedAt, pending.requestedAt) ?? markerTime(), code: result.error?.code, message: result.error?.message });
|
|
669
|
+
}
|
|
670
|
+
const pid = pending.completionPid;
|
|
671
|
+
const state = !Number.isSafeInteger(pid) || pid <= 0 ? "unknown"
|
|
672
|
+
: { alive: "running", gone: "interrupted" }[processLiveness({ pid, processStart: pending.completionStart }).state] ?? "unknown";
|
|
673
|
+
return readRetireState({ state, self: true, since: instantOr(pending.requestedAt) ?? markerTime() });
|
|
674
|
+
}
|
|
675
|
+
// Most rows have no claim: asked without the throw of a read that finds none, which is most of
|
|
676
|
+
// what reading it costs. A path that is not there (a dangling link too) reads as no claim either way.
|
|
677
|
+
// The claim is read as homeClaimHolder reads it (claimAction, processLiveness), through regularJson.
|
|
678
|
+
const lock = retireClaimPath(home);
|
|
679
|
+
if (!existsSync(lock)) return undefined;
|
|
680
|
+
const holder = regularJson(lock);
|
|
681
|
+
if (!isPlainObject(holder) || claimAction(holder) !== "retire") return undefined;
|
|
682
|
+
const { state } = processLiveness(holder);
|
|
683
|
+
if (state !== "alive" && state !== "unknown") return undefined;
|
|
684
|
+
return readRetireState({ state: state === "alive" ? "running" : "unknown", self: false, since: shownHolder(holder).since ?? mtimeOf(lock) });
|
|
685
|
+
}
|
|
686
|
+
|
|
687
|
+
/** Where a deferred self-retirement writes its explicit outcome: a FILE beside
|
|
688
|
+
* the (former) home, so it survives the home's removal and never reads as an
|
|
689
|
+
* instance directory. */
|
|
690
|
+
export function deferredRetireResultPath(home) {
|
|
691
|
+
return join(dirname(home), `.oats-retired-${basename(home)}.json`);
|
|
692
|
+
}
|
|
693
|
+
|
|
694
|
+
/** The lifecycle claim file of `home`: `<instances>/.oats-retirement/claims/<name>.lock`. Beside
|
|
695
|
+
* the homes, never inside one: a home's bytes are what its retire observes, copies and removes.
|
|
696
|
+
* One file for every verb that holds a home (a retire, a stop, an upgrade, a resume): its record
|
|
697
|
+
* names the holder's verb (`action`) from the instant it exists (lib/claim.mjs `facts`). One file
|
|
698
|
+
* for every spelling of the home: `<instances>` is the instances directory's own spelling on disk
|
|
699
|
+
* (canonicalHomePath), and `<name>` the home's name once `.` and `..` are resolved, so that
|
|
700
|
+
* `H/.`, or `H` through a link to its deployment, names H's claim. */
|
|
701
|
+
export function retireClaimPath(home) {
|
|
702
|
+
const at = resolve(home);
|
|
703
|
+
return join(instancesRetirementRoot(canonicalHomePath(dirname(at))), "claims", `${basename(at)}.lock`);
|
|
704
|
+
}
|
|
705
|
+
|
|
706
|
+
/** The verbs that take a home's lifecycle claim: what claimHomeFor accepts, and so every `action`
|
|
707
|
+
* a claim of the kernel's names. `resume` is a `session start --resume`. */
|
|
708
|
+
const CLAIM_VERBS = Object.freeze(["retire", "stop", "upgrade", "resume"]);
|
|
709
|
+
/** The verb the holder of a home's claim recorded (`action`): one of CLAIM_VERBS, never the
|
|
710
|
+
* record's text. A claim is read back as whatever is in its file, which other instances of the
|
|
711
|
+
* deployment can write, and this goes into messages, remedies and `details` (lib/claim.mjs
|
|
712
|
+
* shownHolder, the same rule for the holder's own fields). Anything else is a retire's, as a
|
|
713
|
+
* record without one is: a kernel before feature `lifecycle-claim-stop` wrote none, and only its
|
|
714
|
+
* retire took the claim. */
|
|
715
|
+
const claimAction = (holder) => CLAIM_VERBS.includes(holder?.action) ? holder.action : "retire";
|
|
716
|
+
|
|
717
|
+
/** The kernel a home's last launch pointed its `oats` at (instance.json launch.kernelBin), or null. */
|
|
718
|
+
export function recordedKernelBin(home) {
|
|
719
|
+
try { const bin = JSON.parse(readFileSync(join(home, "instance.json"), "utf8"))?.launch?.kernelBin; return typeof bin === "string" ? bin : null; }
|
|
720
|
+
catch { return null; }
|
|
721
|
+
}
|
|
722
|
+
|
|
723
|
+
/** One line for a roster/inspect: `acts as <address> via grant, expires <t>` or `alias <alias> on <team>`. */
|
|
724
|
+
export function servedIdentityLine(identity) {
|
|
725
|
+
if (!identity) return null;
|
|
726
|
+
if (identity.mode === "global" && identity.grant) return `acts as ${identity.address || identity.alias || identity.resident || "?"} via grant${identity.grant.expiresAt ? `, expires ${identity.grant.expiresAt}` : ""}`;
|
|
727
|
+
return `alias ${identity.alias || "?"} on ${identity.team || "?"}`;
|
|
728
|
+
}
|
|
729
|
+
|
|
730
|
+
export { CLAIM_VERBS, claimAction, defaultTmuxWindows, directoryRollbackPath, hostProcesses, lookupOnPath, missingSocketUnestablished, namedProcesses, procReadable, processesWorkingIn, readRetirePending, retireStateOf, subdirs, tmuxFailure, tmuxOn, tmuxServerAbsence, unreadableRecordSaid };
|