@awebai/oats 0.55.1 → 0.57.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/oats.mjs +96 -72
- package/docs/capabilities.md +67 -3
- package/docs/design/2026-09-23-workspace-module-contracts.md +27 -3
- package/docs/desktop-cli-api.md +375 -37
- package/docs/desktop-instance-start.md +105 -12
- package/docs/desktop.md +65 -11
- package/docs/execution-targets.md +184 -9
- package/docs/harness-trust.md +128 -11
- package/docs/implementation.md +153 -11
- package/docs/integrations.md +5 -3
- package/docs/knowledge.md +117 -43
- package/docs/official-catalog.md +3 -3
- package/docs/packages.md +12 -12
- package/docs/release-lane.md +26 -1
- package/docs/release-notes/v0.56.0.md +699 -0
- package/docs/release-notes/v0.57.0.md +283 -0
- package/docs/schedules.md +8 -3
- package/docs/servers.md +21 -5
- package/docs/souls-and-instances.md +134 -19
- package/docs/tui.md +215 -31
- package/docs/upgrading.md +4 -1
- package/docs/workspaces.md +26 -6
- package/lib/automations.mjs +3 -4
- package/lib/bounded-read.mjs +18 -0
- package/lib/capability-show.mjs +13 -2
- package/lib/claim.mjs +3 -4
- package/lib/core.mjs +919 -278
- package/lib/errors.mjs +39 -0
- package/lib/harness-trust-write.mjs +119 -40
- package/lib/harness-trust.mjs +31 -18
- package/lib/instance-inspect.mjs +160 -11
- package/lib/instance-lifecycle.mjs +90 -37
- package/lib/packages.mjs +8 -5
- package/lib/pi-bridge.mjs +18 -19
- package/lib/remote.mjs +88 -51
- package/lib/retire-output.mjs +9 -4
- package/lib/schedule.mjs +3 -4
- package/lib/servers.mjs +39 -6
- package/lib/session-viewer.mjs +25 -1
- package/lib/triggers.mjs +3 -4
- package/lib/workspace.mjs +6 -6
- package/lib/worktree.mjs +33 -8
- package/lib/write-through-private-file.mjs +26 -0
- package/package-catalog.json +2 -2
- package/package.json +1 -1
- package/packages/client/cli-adapter.mjs +108 -13
- package/packages/client/cli-locator.mjs +16 -14
- package/packages/client/deployment-panel.mjs +4 -3
- package/packages/client/display-text.mjs +2 -1
- package/packages/client/instance-events-contract.mjs +4 -3
- package/packages/client/instance-lifecycle.mjs +235 -0
- package/packages/client/instance-presentation.mjs +9 -0
- package/packages/client/instance-tree.mjs +10 -8
- package/packages/client/kernel-lines.mjs +3 -3
- package/packages/client/launch-contract.mjs +11 -0
- package/packages/client/launch-prompt-outcome.mjs +1 -1
- package/packages/client/lifecycle-cli.mjs +12 -6
- package/packages/client/lifecycle-confirmation.mjs +407 -0
- package/packages/client/lifecycle-contract.mjs +6 -2
- package/packages/client/own-codes.mjs +1 -0
- package/packages/client/panel-views.mjs +39 -2
- package/packages/client/readiness-contract.mjs +2 -2
- package/packages/client/remote-roster.mjs +50 -5
- package/packages/client/roster-sections.mjs +3 -3
- package/packages/client/session-start.mjs +98 -0
- package/packages/client/start-gate.mjs +46 -0
- package/packages/client/start-messages.mjs +17 -0
- package/packages/client/workspace-views.mjs +2 -2
- package/packages/tui/README.md +21 -8
- package/packages/tui/lib/actions.mjs +11 -2
- package/packages/tui/lib/client.mjs +9 -2
- package/packages/tui/lib/config.mjs +39 -9
- package/packages/tui/lib/main.mjs +168 -20
- package/packages/tui/lib/model.mjs +315 -13
- package/packages/tui/lib/open.mjs +45 -0
- package/packages/tui/lib/read.mjs +171 -16
- package/packages/tui/lib/store.mjs +171 -10
- package/packages/tui/lib/term/tty.mjs +71 -12
- package/packages/tui/lib/views/act.mjs +85 -0
- package/packages/tui/lib/views/frame.mjs +145 -33
- package/packages/tui/lib/views/help.mjs +46 -11
- package/skills/oats-getting-started/SKILL.md +6 -3
package/lib/retire-output.mjs
CHANGED
|
@@ -3,7 +3,12 @@
|
|
|
3
3
|
* receipt's `workRecovery` (lib/core.mjs, retireInstance); another renders
|
|
4
4
|
* its `extraWorktrees`. A receipt from an
|
|
5
5
|
* older kernel, or a stored one, may carry `workRecoveries[]` instead: one
|
|
6
|
-
* block is printed per entry. A third renders its `warnings`.
|
|
6
|
+
* block is printed per entry. A third renders its `warnings`. Their lines hold
|
|
7
|
+
* text the kernel did not write (paths as the system or Git names them, a
|
|
8
|
+
* hook's words, the names a capability declares), so each line goes to the
|
|
9
|
+
* terminal through terminalText (lib/refused-text.mjs): a name cannot clear the
|
|
10
|
+
* screen or write a line of its own. The receipt's JSON is never passed
|
|
11
|
+
* through it. Dependency-free. */
|
|
7
12
|
import { terminalText } from "./refused-text.mjs";
|
|
8
13
|
|
|
9
14
|
export const formatBytes = (n) => n < 1024 ? `${n} B` : n < 1024 ** 2 ? `${(n / 1024).toFixed(1)} KiB` : n < 1024 ** 3 ? `${(n / 1024 ** 2).toFixed(1)} MiB` : `${(n / 1024 ** 3).toFixed(1)} GiB`;
|
|
@@ -53,7 +58,7 @@ export function workRecoveryLines(receipt, { host } = {}) {
|
|
|
53
58
|
if (again.length) lines.push(` after the retire hooks: ${again.join(" and ")} copied again under after-hooks/`);
|
|
54
59
|
}
|
|
55
60
|
if (lines.length) lines.push(RECOVERY_POINTER);
|
|
56
|
-
return lines;
|
|
61
|
+
return lines.map((line) => terminalText(line));
|
|
57
62
|
}
|
|
58
63
|
|
|
59
64
|
/** The lines `oats retire` prints for the home's extra trees it handled
|
|
@@ -62,9 +67,9 @@ export function extraWorktreeLines(receipt, { host } = {}) {
|
|
|
62
67
|
const rows = Array.isArray(receipt?.extraWorktrees) ? receipt.extraWorktrees : [];
|
|
63
68
|
return rows.map((t) => {
|
|
64
69
|
const at = t.branch ? `branch ${t.branch}` : t.detachedAt ? `detached at ${t.detachedAt}` : "a HEAD that could not be read";
|
|
65
|
-
return t.outcome === "removed"
|
|
70
|
+
return terminalText(t.outcome === "removed"
|
|
66
71
|
? `Extra worktree ${t.path} removed (${at}); its branch and commits stay in ${t.repo}${host ? ` on ${host}` : ""}`
|
|
67
|
-
: `Extra worktree ${t.path} re-homed${host ? ` on ${host}` : ""} to ${t.movedTo} (${at}): ${t.reason}
|
|
72
|
+
: `Extra worktree ${t.path} re-homed${host ? ` on ${host}` : ""} to ${t.movedTo} (${at}): ${t.reason}`);
|
|
68
73
|
});
|
|
69
74
|
}
|
|
70
75
|
|
package/lib/schedule.mjs
CHANGED
|
@@ -22,7 +22,7 @@
|
|
|
22
22
|
* `unknown`, its job blocked until `reconcile` proves what happened; it keeps
|
|
23
23
|
* its host slot too, unless it is a command whose process exit was observed. */
|
|
24
24
|
import { runScheduleCommand } from "./schedule-command.mjs";
|
|
25
|
-
import { closeSync, constants as fsConstants, existsSync, fstatSync, lstatSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, realpathSync,
|
|
25
|
+
import { closeSync, constants as fsConstants, existsSync, fstatSync, lstatSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, realpathSync, rmSync, writeFileSync } from "node:fs";
|
|
26
26
|
import { createHash } from "node:crypto";
|
|
27
27
|
import { homedir } from "node:os";
|
|
28
28
|
import { basename, dirname, isAbsolute, join, resolve, sep } from "node:path";
|
|
@@ -36,6 +36,7 @@ import { pollSourced, tickTriggers } from "./triggers.mjs";
|
|
|
36
36
|
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
|
+
import { writeThroughPrivateFile } from "./write-through-private-file.mjs";
|
|
39
40
|
|
|
40
41
|
export const SCHEDULE_FILE = "oats-schedules.json";
|
|
41
42
|
export const SCHEDULE_API = 2;
|
|
@@ -142,9 +143,7 @@ function readJsonBounded(path, fallback, label, { atomicReplace = false } = {})
|
|
|
142
143
|
function readJson(path, fallback) { return readJsonBounded(path, fallback, basename(path)).value; }
|
|
143
144
|
function writeJson(path, value) {
|
|
144
145
|
mkdirSync(dirname(path), { recursive: true });
|
|
145
|
-
|
|
146
|
-
writeFileSync(tmp, JSON.stringify(value, null, 2) + "\n");
|
|
147
|
-
renameSync(tmp, path);
|
|
146
|
+
writeThroughPrivateFile(path, `${path}.tmp-${process.pid}`, JSON.stringify(value, null, 2) + "\n");
|
|
148
147
|
}
|
|
149
148
|
export function readDefinitions(ws) {
|
|
150
149
|
const doc = readJsonBounded(definitionsPath(ws), { version: 1, jobs: {} }, "definitions").value;
|
package/lib/servers.mjs
CHANGED
|
@@ -609,7 +609,8 @@ export function listSnapshots(serverId) {
|
|
|
609
609
|
|
|
610
610
|
/** Route one lifecycle command to a server. Returns the remote envelope,
|
|
611
611
|
* having kept the local snapshot store in step with it:
|
|
612
|
-
* - spawn: compatibility checked first, a snapshot written on success;
|
|
612
|
+
* - spawn: compatibility checked first, a snapshot written on success; a
|
|
613
|
+
* --preview runs the same checks, needs spawn-preview-2 and writes nothing;
|
|
613
614
|
* - retire: the target comes from the instance's snapshot when one exists
|
|
614
615
|
* (the registry may have changed since), the snapshot is removed only
|
|
615
616
|
* when the remote kernel reports the home gone;
|
|
@@ -654,8 +655,24 @@ export function routeCommand(serverId, cmd, oatsArgs, io = {}) {
|
|
|
654
655
|
const status = runRemote(target, json(withScope(["status"])), io).envelope;
|
|
655
656
|
if (!status.ok) return { envelope: status, stderr: "" };
|
|
656
657
|
checkRemoteSupport(remote, target, oatsArgs, status.result);
|
|
658
|
+
// A preview answers what the apply would, refusals included (every check
|
|
659
|
+
// above), and writes nothing here (#610). Only a host that advertises
|
|
660
|
+
// spawn-preview-2 is proven to answer --preview without spawning.
|
|
661
|
+
const preview = oatsArgs.includes("--preview");
|
|
662
|
+
if (preview) requireRemoteFeature(remote, target, "spawn-preview-2");
|
|
657
663
|
const { envelope, stderr } = runRemote(target, json(withScope(["spawn", ...hostHarnessArgs(remote, oatsArgs)])), io);
|
|
658
|
-
if (envelope.ok && envelope.result?.
|
|
664
|
+
if (preview && envelope.ok && envelope.result?.preview === true && envelope.result.spawnPreviewApi === 2) {
|
|
665
|
+
// The host's preview with the two fields a routed spawn adds; never a
|
|
666
|
+
// `snapshot` key, which on the apply path says what was (or was not) saved.
|
|
667
|
+
const prior = envelope.result.instance ? readSnapshot(serverId, envelope.result.instance) : undefined;
|
|
668
|
+
const sameAsPrior = prior && prior.home && envelope.result.home && resolve(prior.home) === resolve(envelope.result.home);
|
|
669
|
+
const warnings = prior && !sameAsPrior
|
|
670
|
+
? { warnings: [...(envelope.result.warnings || []), `a spawn would save no route: ${envelope.result.instance} already names ${prior.home} through ${serverId}; that instance (${envelope.result.home}) would not be managed from here, and would be retired on the host with oats retire ${envelope.result.instance} --home ${envelope.result.home}`] }
|
|
671
|
+
: {};
|
|
672
|
+
return { envelope: { ...envelope, result: { ...envelope.result, server: serverId, target, ...warnings } }, stderr };
|
|
673
|
+
}
|
|
674
|
+
// An answer that says it is a preview created nothing: it is never recorded as a route.
|
|
675
|
+
if (envelope.ok && envelope.result?.instance && envelope.result.preview !== true) {
|
|
659
676
|
// A generated name can still collide with a saved route of another
|
|
660
677
|
// soul on the same host (dev --purpose foo-1 vs dev-foo --purpose 1).
|
|
661
678
|
// The existing route is never overwritten: the new instance is
|
|
@@ -765,6 +782,8 @@ export function routeCommand(serverId, cmd, oatsArgs, io = {}) {
|
|
|
765
782
|
// `inspect --instructions` (feature soul-composed-instructions): an older host would ignore the
|
|
766
783
|
// flag and answer without the field — refused here instead, nothing sent.
|
|
767
784
|
if (cmd === "inspect" && args.includes("--instructions")) requireRemoteFeature(remote, target, "soul-composed-instructions");
|
|
785
|
+
// `inspect --skills` (feature soul-skills): the same, for the soul's own skills.
|
|
786
|
+
if (cmd === "inspect" && args.includes("--skills")) requireRemoteFeature(remote, target, "soul-skills");
|
|
768
787
|
const scoped = args.includes("--dir") || args.includes("--home") ? args : [...args, "--dir", target.workspace];
|
|
769
788
|
const { envelope, stderr } = runRemote(target, json([cmd, ...scoped]), io);
|
|
770
789
|
return { envelope: envelope.result && typeof envelope.result === "object" ? { ...envelope, result: { ...envelope.result, server: serverId, ...(route ? { route: { home: route.home, instance: route.snapshot?.instance || null, frozen: !!route.snapshot } } : {}) } } : envelope, stderr };
|
|
@@ -873,27 +892,41 @@ export function hostFeatures(result) {
|
|
|
873
892
|
return [...list];
|
|
874
893
|
}
|
|
875
894
|
|
|
876
|
-
|
|
895
|
+
/** `workspaceKeys` (feature roster-workspace-key): when given, only the groups that can belong to
|
|
896
|
+
* one of those workspaces are probed and returned. A group is judged by its registration: kept
|
|
897
|
+
* when the registration's `workspaceKey` is one of the keys or is not known, dropped when it names
|
|
898
|
+
* another workspace (its saved routes under that target with it). A group with no registration
|
|
899
|
+
* (saved routes only) is always kept: its workspace is unknown, and it is the row an operator may
|
|
900
|
+
* need to forget. Keys compare by exact string equality, never parsed as a repo reference. */
|
|
901
|
+
export async function rosterGroups({ server, workspaceKeys, io = {} } = {}) {
|
|
877
902
|
const started = Date.now();
|
|
878
903
|
if (server && !ID_RE.test(server)) throw serverError("E_BAD_ARGS", `server id ${JSON.stringify(server)} is not a valid id`);
|
|
904
|
+
if (workspaceKeys !== undefined) {
|
|
905
|
+
if (!Array.isArray(workspaceKeys)) throw serverError("E_BAD_ARGS", "workspaceKeys must be a list of workspace keys");
|
|
906
|
+
for (const k of workspaceKeys) if (typeof k !== "string" || !WORKSPACE_KEY_RE.test(k)) throw serverError("E_BAD_ARGS", `--workspace-key ${JSON.stringify(k)} is not a canonical workspace key (as a host's oats status --json reports it: no whitespace or control characters)`);
|
|
907
|
+
}
|
|
879
908
|
if (server && !readServers()[server] && !existsSync(join(REMOTE_SNAPSHOT_DIR(), server))) throw serverError("E_SERVER_UNKNOWN", `no server registered as ${JSON.stringify(server)} and no saved routes for it (oats server list)`);
|
|
880
909
|
const perTargetTimeoutMs = io.perTargetTimeoutMs || ROSTER_PER_TARGET_TIMEOUT_MS;
|
|
881
910
|
const budgetMs = io.budgetMs || ROSTER_BUDGET_MS;
|
|
882
911
|
const timeoutMs = Math.min(perTargetTimeoutMs, budgetMs);
|
|
883
912
|
const servers = readServers();
|
|
884
913
|
const groups = new Map();
|
|
885
|
-
const add = (serverId, target, registrationPresent, label) => {
|
|
914
|
+
const add = (serverId, target, registrationPresent, label, workspaceKey) => {
|
|
886
915
|
const key = `${serverId}:${targetKey(target)}`;
|
|
887
916
|
if (!groups.has(key)) groups.set(key, { id: key, server: serverId, label: label || serverId, registrationPresent, target, probe: null, agentsRoot: undefined, workspace: null, souls: [], instances: [], retireFailures: [], _snapshots: [] });
|
|
888
917
|
const g = groups.get(key);
|
|
889
|
-
if (registrationPresent) g.registrationPresent = true;
|
|
918
|
+
if (registrationPresent) { g.registrationPresent = true; g._workspaceKey = workspaceKey ?? null; }
|
|
890
919
|
return g;
|
|
891
920
|
};
|
|
892
|
-
for (const [id, s] of Object.entries(servers)) { if (server && id !== server) continue; add(id, targetOf({ id, ...s }), true, s.label); }
|
|
921
|
+
for (const [id, s] of Object.entries(servers)) { if (server && id !== server) continue; add(id, targetOf({ id, ...s }), true, s.label, s.workspaceKey); }
|
|
893
922
|
for (const serverId of listSnapshotServers()) {
|
|
894
923
|
if (server && serverId !== server) continue;
|
|
895
924
|
for (const snap of listSnapshots(serverId)) { if (!snap.target) continue; add(serverId, snap.target, false, servers[serverId]?.label)._snapshots.push(snap); }
|
|
896
925
|
}
|
|
926
|
+
// The workspace filter applies to whole groups, before any probe: a group whose registration
|
|
927
|
+
// names another workspace is never asked.
|
|
928
|
+
if (workspaceKeys) for (const [key, g] of groups) if (g.registrationPresent && g._workspaceKey !== null && !workspaceKeys.includes(g._workspaceKey)) groups.delete(key);
|
|
929
|
+
for (const g of groups.values()) delete g._workspaceKey;
|
|
897
930
|
// Groups keep their registration order in the answer, whatever order their probes finish in.
|
|
898
931
|
await Promise.all([...groups.values()].map(async (g) => {
|
|
899
932
|
let status;
|
package/lib/session-viewer.mjs
CHANGED
|
@@ -36,6 +36,19 @@ const MOUSE_BINDINGS = [
|
|
|
36
36
|
* A constant: no caller text is ever part of a tmux command string. */
|
|
37
37
|
const DETACH_BINDING = "set-option @oats-detached 1 ; detach-client";
|
|
38
38
|
|
|
39
|
+
/** Whether a `tmux -V` answer names a release with the client's `-T <features>` flag (tmux 3.2):
|
|
40
|
+
* `tmux X.Y` with an optional letter suffix only. A development build (`tmux next-3.6`,
|
|
41
|
+
* `tmux master`), another vendor's spelling or no answer is not one. */
|
|
42
|
+
export function tmuxHasClientFeatures(versionText) {
|
|
43
|
+
const m = /^tmux (\d+)\.(\d+)[a-z]*$/.exec(String(versionText ?? "").trim());
|
|
44
|
+
if (!m) return false;
|
|
45
|
+
const [major, minor] = [Number(m[1]), Number(m[2])];
|
|
46
|
+
return major > 3 || (major === 3 && minor >= 2);
|
|
47
|
+
}
|
|
48
|
+
/** The probe's answer per `exec`: one `tmux -V` per process for the real one, and a fresh probe
|
|
49
|
+
* for each fake a test injects. */
|
|
50
|
+
const clientFeatures = new WeakMap();
|
|
51
|
+
|
|
39
52
|
export function prepareSessionViewer(target, { exec = execFileSync, detachKey } = {}) {
|
|
40
53
|
if (detachKey !== undefined) requireDetachKey(detachKey);
|
|
41
54
|
if (!inspectSessionTarget(target, { exec }).present) throw new Error("session no longer exists");
|
|
@@ -81,7 +94,18 @@ export function prepareSessionViewer(target, { exec = execFileSync, detachKey }
|
|
|
81
94
|
if (detachKey === undefined) return false;
|
|
82
95
|
try { return run(["show-options", "-t", `=${viewer}:`, "-qv", "@oats-detached"]) === "1"; } catch { return false; }
|
|
83
96
|
};
|
|
84
|
-
|
|
97
|
+
// Synchronized output (DEC 2026) for this client alone, the tmux client's own option, before the
|
|
98
|
+
// command and after the socket (every viewer call starts `-u -S <socket>`): tmux then wraps each redraw in ESC[?2026h … ESC[?2026l, and a terminal that gets
|
|
99
|
+
// one in two reads does not paint the half-drawn state (#1193). A terminal without the mode
|
|
100
|
+
// ignores it. tmux before 3.2 has no -T, and a probe that fails leaves it out: never the
|
|
101
|
+
// attach's failure.
|
|
102
|
+
if (!clientFeatures.has(exec)) {
|
|
103
|
+
let sync = false;
|
|
104
|
+
try { sync = tmuxHasClientFeatures(run(["-V"])); } catch { /* no answer: today's client */ }
|
|
105
|
+
clientFeatures.set(exec, sync);
|
|
106
|
+
}
|
|
107
|
+
const features = clientFeatures.get(exec) ? ["-T", "sync"] : [];
|
|
108
|
+
return { binary: "tmux", args: ["-u", "-S", target.socket, ...features, "attach-session", "-t", `=${viewer}`], env, cleanup, detached };
|
|
85
109
|
} catch (e) { cleanup(); throw e; }
|
|
86
110
|
}
|
|
87
111
|
|
package/lib/triggers.mjs
CHANGED
|
@@ -36,7 +36,7 @@
|
|
|
36
36
|
* State: <scope>/.agents/schedules/triggers.json (gitignored with the schedule state). */
|
|
37
37
|
import { spawnSync } from "node:child_process";
|
|
38
38
|
import { createHash } from "node:crypto";
|
|
39
|
-
import { existsSync, mkdirSync, readFileSync, readdirSync,
|
|
39
|
+
import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
|
|
40
40
|
import { dirname, join } from "node:path";
|
|
41
41
|
import { fileURLToPath } from "node:url";
|
|
42
42
|
import { readDefinitions, writeDefinitions, stateDir, withScopeLock, childEnv, parseEnvelopeText, schedulerStatus, readRegistry, definitionsPath, runWarnings } from "./schedule.mjs";
|
|
@@ -47,6 +47,7 @@ import { REFUSED_TEXT, safeText } from "./refused-text.mjs";
|
|
|
47
47
|
import { lockedPackageRef } from "./packages.mjs";
|
|
48
48
|
import { teamLabelProblem } from "./workspace.mjs";
|
|
49
49
|
import { MAX_INSTANCE_NAME, slug } from "./core.mjs";
|
|
50
|
+
import { writeThroughPrivateFile } from "./write-through-private-file.mjs";
|
|
50
51
|
|
|
51
52
|
export const TRIGGER_API = 1;
|
|
52
53
|
export const TRIGGER_SOURCES = Object.freeze(["github.pull_request"]);
|
|
@@ -377,9 +378,7 @@ const sameTrigger = (recorded, id) => recorded === id || (typeof recorded === "s
|
|
|
377
378
|
function writeTriggerState(ws, st) {
|
|
378
379
|
const file = statePath(ws);
|
|
379
380
|
mkdirSync(dirname(file), { recursive: true });
|
|
380
|
-
|
|
381
|
-
writeFileSync(tmp, JSON.stringify(st, null, 2) + "\n");
|
|
382
|
-
renameSync(tmp, file);
|
|
381
|
+
writeThroughPrivateFile(file, `${file}.tmp-${process.pid}`, JSON.stringify(st, null, 2) + "\n");
|
|
383
382
|
}
|
|
384
383
|
/** What only a source's own polls write. A state written for another source has none of it, so a
|
|
385
384
|
* trigger's row never shows one source's lists, counts or words (`skipped[].why`, a refusal's
|
package/lib/workspace.mjs
CHANGED
|
@@ -202,7 +202,7 @@ function* refFields(value) {
|
|
|
202
202
|
function referenceProblems(problems, refs) {
|
|
203
203
|
const sources = new Map(refs);
|
|
204
204
|
return problems.map((problem) => sources.has(problem.path)
|
|
205
|
-
? { ...problem, message: defaultRemote.
|
|
205
|
+
? { ...problem, message: defaultRemote.displayDiagnosticText(problem.message, sources.get(problem.path)) }
|
|
206
206
|
: problem);
|
|
207
207
|
}
|
|
208
208
|
|
|
@@ -509,13 +509,13 @@ export async function confirmMembership(workspaceObs, memberRef, { remote: injec
|
|
|
509
509
|
let key;
|
|
510
510
|
try { key = refKey(remote, memberRef); }
|
|
511
511
|
catch (e) {
|
|
512
|
-
if (e?.code === "E_REPO_REF") return unconfirmed(defaultRemote.
|
|
512
|
+
if (e?.code === "E_REPO_REF") return unconfirmed(defaultRemote.displayRepoRef(typeof memberRef === "string" ? memberRef : String(memberRef)), "not-listed", `${show(defaultRemote.displayRepoRef(memberRef))} is not a repo ref: ${e.message}`);
|
|
513
513
|
throw e;
|
|
514
514
|
}
|
|
515
515
|
if (!checked.keys.has(key)) return unconfirmed(key, "not-listed", `${key} is not in members of workspace ${workspaceObs.key}`);
|
|
516
516
|
const cannotRead = (e) => {
|
|
517
|
-
const url = defaultRemote.
|
|
518
|
-
return unconfirmed(key, "cannot-read", `cannot read ${url ?? defaultRemote.
|
|
517
|
+
const url = defaultRemote.displayRepoRef(e.details?.url ?? e.provenance?.url ?? null);
|
|
518
|
+
return unconfirmed(key, "cannot-read", `cannot read ${url ?? defaultRemote.displayRepoRef(memberRef)}${e.details?.reason ? ` (${e.details.reason})` : ""}`, { url });
|
|
519
519
|
};
|
|
520
520
|
let obs;
|
|
521
521
|
try { obs = await remote.observeRemote(memberRef); }
|
|
@@ -538,7 +538,7 @@ export async function confirmMembership(workspaceObs, memberRef, { remote: injec
|
|
|
538
538
|
let backlinkKey;
|
|
539
539
|
try { backlinkKey = refKey(remote, read.value.workspace); }
|
|
540
540
|
catch (e) {
|
|
541
|
-
if (e?.code === "E_REPO_REF") return unconfirmed(key, "no-backlink", `${key}@${obs.commit.slice(0, 12)} oats-membership.yaml names an unparseable workspace ${show(defaultRemote.
|
|
541
|
+
if (e?.code === "E_REPO_REF") return unconfirmed(key, "no-backlink", `${key}@${obs.commit.slice(0, 12)} oats-membership.yaml names an unparseable workspace ${show(defaultRemote.displayRepoRef(read.value.workspace))}`, { commit: obs.commit });
|
|
542
542
|
throw e;
|
|
543
543
|
}
|
|
544
544
|
if (backlinkKey !== workspaceObs.key) {
|
|
@@ -811,7 +811,7 @@ export async function discoverWorkspace(ref, { at, local, lock = null, remote: i
|
|
|
811
811
|
const sourceRef = entry.source.slice(0, pin);
|
|
812
812
|
const commit = entry.source.slice(pin + 1);
|
|
813
813
|
const file = `${entry.soul.replace(/\/+$/, "")}/soul.yaml`;
|
|
814
|
-
const pushProblem = (code, path, message) => { problems.push({ code, repoKey: null, path: `external/${index}:${path}`, message, source: defaultRemote.
|
|
814
|
+
const pushProblem = (code, path, message) => { problems.push({ code, repoKey: null, path: `external/${index}:${path}`, message, source: defaultRemote.displayRepoRef(entry.source, { pinned: { ref: sourceRef, commit } }) }); if (!soulsUnread.external.includes(entry.source)) soulsUnread.external.push(entry.source); };
|
|
815
815
|
let key;
|
|
816
816
|
try { key = refKey(remote, sourceRef); }
|
|
817
817
|
catch (e) { if (e?.code === "E_REPO_REF") { pushProblem("E_REPO_REF", "source", e.message); continue; } throw e; }
|
package/lib/worktree.mjs
CHANGED
|
@@ -19,16 +19,18 @@
|
|
|
19
19
|
* is passed after `--end-of-options` where the git subcommand honours it. The
|
|
20
20
|
* remote URL is recorded, printed and handed to hooks without userinfo (A2). */
|
|
21
21
|
import { execFileSync, spawn as spawnChild, spawnSync } from "node:child_process";
|
|
22
|
-
import { existsSync, linkSync, lstatSync, mkdirSync, readFileSync, realpathSync,
|
|
22
|
+
import { existsSync, linkSync, lstatSync, mkdirSync, readFileSync, realpathSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";
|
|
23
23
|
import { basename, dirname, isAbsolute, join, resolve } from "node:path";
|
|
24
24
|
import { checkHolderByHand, ifItDoesNotEnd, lifecycleBusy, nothingAfter, oatsError, OWN_START_REMEDY } from "./errors.mjs";
|
|
25
25
|
import { appendEvent } from "./instance-events.mjs";
|
|
26
|
+
import { attachedToTree } from "./instance-lifecycle.mjs";
|
|
26
27
|
import { recordedTeams } from "./teams.mjs";
|
|
27
28
|
import { canonicalCloneKey, memberCloneOf } from "./instance-resolution.mjs";
|
|
28
29
|
import { loadLocal } from "./workspace.mjs";
|
|
29
30
|
import { GIT_FETCH_TIMEOUT_MS } from "./remote.mjs";
|
|
30
31
|
import { terminateGroup, watchGroup } from "./process-group.mjs";
|
|
31
32
|
import { CLAIM_WAIT_MS, acquireClaim, claimUnavailable, recordInClaim, releaseClaim, shownHolder } from "./claim.mjs";
|
|
33
|
+
import { writeThroughPrivateFile } from "./write-through-private-file.mjs";
|
|
32
34
|
import {
|
|
33
35
|
cloneOfMember, instanceSoulDir, isCapturedHome, isWorkspaceHome, capturedHomeRefusal, preWorkspaceHome, lifecycleHookEnv,
|
|
34
36
|
refuseBesideRetire, retirePendingMarkerPath, stableSoulId, workspaceOf,
|
|
@@ -227,16 +229,19 @@ function readRecord(path) {
|
|
|
227
229
|
return { state: "unreadable" };
|
|
228
230
|
}
|
|
229
231
|
function writeRecord(path, rec) {
|
|
230
|
-
|
|
231
|
-
writeFileSync(tmp, JSON.stringify(rec, null, 2) + "\n", { mode: 0o600 });
|
|
232
|
-
renameSync(tmp, path);
|
|
232
|
+
writeThroughPrivateFile(path, `${path}.tmp-${process.pid}`, JSON.stringify(rec, null, 2) + "\n", 0o600);
|
|
233
233
|
}
|
|
234
234
|
/** Create the record only if none exists (two concurrent adds: one wins, the other sees it). */
|
|
235
235
|
function createRecord(path, rec) {
|
|
236
236
|
mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
|
|
237
237
|
const tmp = `${path}.tmp-${process.pid}`;
|
|
238
|
-
|
|
239
|
-
|
|
238
|
+
// Its own code, not the one writer (#1076): it puts the record in place with an exclusive link,
|
|
239
|
+
// which no rename does. The write is in the block whose finally removes the private file, so a
|
|
240
|
+
// write that fails once the file is made leaves nothing behind either.
|
|
241
|
+
try {
|
|
242
|
+
writeFileSync(tmp, JSON.stringify(rec, null, 2) + "\n", { mode: 0o600 });
|
|
243
|
+
linkSync(tmp, path);
|
|
244
|
+
}
|
|
240
245
|
// Reached only when a record appeared after this add, which holds the purpose's claim, read that
|
|
241
246
|
// there was none: whoever wrote it did not hold the claim, and whether it still runs was not read.
|
|
242
247
|
catch (e) { if (e.code === "EEXIST") throw lifecycleBusy("unknown", `another oats worktree add of purpose ${rec.purpose} wrote ${path} at the same moment; nothing was done`, `check whether the process that record names still runs (its \`pid\`), then run the command again`, { purpose: rec.purpose, record: path }); throw e; }
|
|
@@ -604,7 +609,14 @@ export async function worktreeAdd(homeArg, o = {}) {
|
|
|
604
609
|
|
|
605
610
|
/** `oats worktree remove --purpose <p>`: `git worktree remove` (which refuses a dirty tree),
|
|
606
611
|
* the branch kept, no hook, the record dropped. A `creating` record whose adder is gone is
|
|
607
|
-
* rolled back instead. Only recorded trees: a hand-made one is git's to remove.
|
|
612
|
+
* rolled back instead. Only recorded trees: a hand-made one is git's to remove.
|
|
613
|
+
*
|
|
614
|
+
* An instance can be attached to the tree: its `work` is a link to it (#958). The tree is not
|
|
615
|
+
* removed under a session that runs there, or that cannot be read (#964): E_CHILDREN_RUNNING,
|
|
616
|
+
* under the purpose's claim and before Git is asked anything, the record kept. This command stops
|
|
617
|
+
* nobody, and no flag removes anyway. An attached instance whose session is stopped does not
|
|
618
|
+
* refuse: the tree is removed, and the answer's `warnings` name it, since its link then points at
|
|
619
|
+
* a path that is gone. A tree that is already gone is removed under nobody: no one is looked at. */
|
|
608
620
|
export async function worktreeRemove(homeArg, o = {}) {
|
|
609
621
|
validateTreeArgs(o, { forRemove: true });
|
|
610
622
|
const home = homeArg;
|
|
@@ -626,6 +638,17 @@ export async function worktreeRemove(homeArg, o = {}) {
|
|
|
626
638
|
return { purpose, path: tree, removed: true, rolledBack: true, branch: rec.branch, branchKept: rb.branchKept, ...(rb.branchKeptReason ? { branchKeptReason: rb.branchKeptReason } : {}), ...(warned.length ? { warnings: warned } : {}) };
|
|
627
639
|
}
|
|
628
640
|
const clone = rec.clone;
|
|
641
|
+
// Who is attached, asked while the tree is there (a link through an alias resolves only then).
|
|
642
|
+
// The owner's lineage is read under the home's real path: the command may have been given a
|
|
643
|
+
// link to the home, whose name and parents are not the instance's.
|
|
644
|
+
const realHome = realpathOr(home);
|
|
645
|
+
const attached = existsSync(tree) ? attachedToTree(dirname(dirname(dirname(realHome))), basename(realHome), tree) : [];
|
|
646
|
+
const inUse = attached.filter((c) => c.session !== "stopped");
|
|
647
|
+
if (inUse.length) {
|
|
648
|
+
const seen = inUse.map((c) => `${c.instance} (${c.session === "running" ? "its session is running" : "whether its session is running could not be read"})`).join(", ");
|
|
649
|
+
const step = inUse.length === 1 ? `stop it (\`oats instance stop ${inUse[0].instance}\`) or retire it` : "stop each one (`oats instance stop <instance>`) or retire it";
|
|
650
|
+
throw Object.assign(oatsError("E_CHILDREN_RUNNING", `${tree} is the work of ${inUse.length === 1 ? "an attached instance" : "attached instances"}: ${seen}; nothing was removed (the record is kept). To remove the tree, ${step}, then remove again`), { details: { purpose, path: tree, children: inUse } });
|
|
651
|
+
}
|
|
629
652
|
if (existsSync(tree)) {
|
|
630
653
|
const status = git(["-C", tree, "status", "--porcelain", "--ignore-submodules=none"]);
|
|
631
654
|
const r = await trackedGit(["-C", clone, "worktree", "remove", "--end-of-options", tree], { track });
|
|
@@ -637,6 +660,8 @@ export async function worktreeRemove(homeArg, o = {}) {
|
|
|
637
660
|
await trackedGit(["-C", clone, "worktree", "prune"], { track });
|
|
638
661
|
if (existsSync(tree)) throw Object.assign(oatsError("E_WORK_PRESERVATION_FAILED", `${tree} is still there after git worktree remove; the record is kept`), { details: { purpose, path: tree } });
|
|
639
662
|
rmSync(recPath, { force: true });
|
|
640
|
-
|
|
663
|
+
// What the removal left each attached instance with (their sessions were stopped).
|
|
664
|
+
const warned = [...claimWarnings, ...attached.map((c) => `${c.instance}: its work was ${tree}, which was removed; its work link ${join(c.home, "work")} now points at a path that is gone`)];
|
|
665
|
+
return { purpose, path: tree, removed: true, rolledBack: false, branch: rec.branch, branchKept: true, ...(warned.length ? { warnings: warned } : {}) };
|
|
641
666
|
});
|
|
642
667
|
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/** The one writer of a file the kernel writes through a private file beside it (awebai/oats#1076).
|
|
2
|
+
* The rule, decided on awebai/oats#963: a private file is removed when its write or its rename
|
|
3
|
+
* fails, and the error answered is that failure's. A file system with no space makes the file and
|
|
4
|
+
* has no block for its bytes; nothing else would remove it, and each later attempt would leave one
|
|
5
|
+
* more. Dependency-free and synchronous, as every caller is.
|
|
6
|
+
*
|
|
7
|
+
* What differs between callers stays theirs to give: the private file's name (`<path>.tmp-<pid>`
|
|
8
|
+
* for most, a nonce or a leading dot for some: two processes writing one path never share it),
|
|
9
|
+
* the bytes (each makes its own JSON), and the mode the private file is created with. No caller
|
|
10
|
+
* syncs today, and this adds none. A caller that needs more than this (an exclusive create through
|
|
11
|
+
* a link, an exact mode, a failed removal reported) keeps its own code. */
|
|
12
|
+
import { renameSync, rmSync, writeFileSync } from "node:fs";
|
|
13
|
+
|
|
14
|
+
/** Write `bytes` to `privatePath`, created with `mode` when one is given (as writeFileSync applies
|
|
15
|
+
* it: on creation, less the umask), and rename it over `path`. When the write or the rename fails,
|
|
16
|
+
* the private file is removed and that failure's error is thrown; a failure of the removal itself
|
|
17
|
+
* is not answered. */
|
|
18
|
+
export function writeThroughPrivateFile(path, privatePath, bytes, mode) {
|
|
19
|
+
try {
|
|
20
|
+
writeFileSync(privatePath, bytes, mode !== undefined ? { mode } : undefined);
|
|
21
|
+
renameSync(privatePath, path);
|
|
22
|
+
} catch (e) {
|
|
23
|
+
try { rmSync(privatePath, { force: true }); } catch { /* the first error is the one answered */ }
|
|
24
|
+
throw e;
|
|
25
|
+
}
|
|
26
|
+
}
|
package/package-catalog.json
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
"packages": {
|
|
4
4
|
"oats.okf": {
|
|
5
5
|
"url": "https://github.com/awebai/oats-okf.git",
|
|
6
|
-
"ref": "v5.0
|
|
6
|
+
"ref": "v5.2.0",
|
|
7
7
|
"path": "oats-package"
|
|
8
8
|
},
|
|
9
9
|
"oats.aweb": {
|
|
@@ -43,7 +43,7 @@
|
|
|
43
43
|
},
|
|
44
44
|
"oats.framework": {
|
|
45
45
|
"url": "https://github.com/awebai/oats.git",
|
|
46
|
-
"ref": "oats-framework/v1.10.
|
|
46
|
+
"ref": "oats-framework/v1.10.2",
|
|
47
47
|
"path": "oats-package"
|
|
48
48
|
}
|
|
49
49
|
},
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@awebai/oats",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.57.0",
|
|
4
4
|
"description": "OATS (Open Agent Team Specification) — durable souls, disposable instances, targetable capability packages, and the runtime-neutral oats CLI/kernel.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"agents",
|
|
@@ -23,7 +23,7 @@
|
|
|
23
23
|
// * A provider operation names its instance by --home: the home of
|
|
24
24
|
// exactly one row the server reports (packages/desktop/server/capabilities.mjs), never
|
|
25
25
|
// a caller path.
|
|
26
|
-
import { execFile } from "node:child_process";
|
|
26
|
+
import { execFile, spawn } from "node:child_process";
|
|
27
27
|
import { mkdtempSync, openSync, writeSync, closeSync, rmSync } from "node:fs";
|
|
28
28
|
import { tmpdir } from "node:os";
|
|
29
29
|
import { isAbsolute, join } from "node:path";
|
|
@@ -62,6 +62,7 @@ const SPAWN_ARG_RULES = {
|
|
|
62
62
|
backend: { flag: "--backend", re: /^tmux$/ },
|
|
63
63
|
// The flag is the kernel's (harness-names.mjs harnessFlag): the caller names it, never guessed.
|
|
64
64
|
harness: { flag: null, re: /^(pi|claude|codex)$/ },
|
|
65
|
+
// A configuration's name, or the word that selects none (launch-contract.mjs LAUNCH_CONFIG_NONE), which this rule admits.
|
|
65
66
|
launchConfig: { flag: "--launch-config", re: /^[a-z0-9][a-z0-9._-]*$/i },
|
|
66
67
|
server: { flag: "--server", re: /^[a-z0-9][a-z0-9-]{0,63}$/ }, // registered server id (remote route)
|
|
67
68
|
model: { flag: "--model", re: /^[^-][^\0]*$/ }, // model pattern — not option-shaped
|
|
@@ -142,11 +143,19 @@ export function writeTaskFile(taskText, io = {}) {
|
|
|
142
143
|
* owns through it). It passes the options through as given (cwd, env, timeout, maxBuffer, no shell)
|
|
143
144
|
* and calls back with `execFile`'s own error: every caller tells a timeout by `error.killed` and an
|
|
144
145
|
* overflow by `error.code === 'ERR_CHILD_PROCESS_STDIO_MAXBUFFER'`, so an `exec` that wraps or
|
|
145
|
-
* replaces that error turns both into a plain failure.
|
|
146
|
-
|
|
146
|
+
* replaces that error turns both into a plain failure.
|
|
147
|
+
* `detached: true` is given for a stop or retire apply and for a start: the child must run in a session of
|
|
148
|
+
* its own, so a signal to the client's process group (a Ctrl-C, a hang-up) never reaches it (a killed stop
|
|
149
|
+
* strands its home on a kernel before 0.52.0; a killed start can leave its lock, #889). An `exec` must start
|
|
150
|
+
* such a child that way and never drop the option: `execFile` itself does not honour it (it passes spawn a
|
|
151
|
+
* fixed list of options), so this home's own default for it is `execFileInSession`. Such a child is given no
|
|
152
|
+
* deadline (`timeout: 0`, the default of an apply): execFileInSession arms its kill only for a positive one,
|
|
153
|
+
* and the caller's own wait ends instead (cliStart's START_WAIT_MS; instance-lifecycle.mjs APPLY_WAIT_MS). */
|
|
154
|
+
function runJson(bin, argv, { cwd, exec, timeout = ENVELOPE_TIMEOUT_MS, parse = parseEnvelope, strictExit = false, detached = false } = {}) {
|
|
155
|
+
const run = exec ?? (detached ? execFileInSession : execFile);
|
|
147
156
|
return new Promise((resolveP, rejectP) => {
|
|
148
157
|
try {
|
|
149
|
-
|
|
158
|
+
run(bin, argv, { cwd, encoding: "utf8", timeout, maxBuffer: 4 * 1024 * 1024, shell: false, ...(detached ? { detached: true } : {}) },
|
|
150
159
|
(err, stdout) => {
|
|
151
160
|
// New reads require a clean exit for success. Keep the historical
|
|
152
161
|
// envelope-wins policy for existing mutations unless opted in.
|
|
@@ -300,6 +309,14 @@ export function cliServerRemove(bin, id, io = {}) {
|
|
|
300
309
|
if (typeof id !== "string" || !MACHINE_ID.test(id)) return Promise.resolve(badMachineArgs());
|
|
301
310
|
return runJson(bin, ["server", "remove", id, "--json"], { cwd: io.cwd || process.cwd(), exec: io.exec, timeout: io.timeout });
|
|
302
311
|
}
|
|
312
|
+
/** `oats server forget <server> --instance <instance> --json` (#1131): drop this computer's saved route to a
|
|
313
|
+
* remote instance its host no longer lists. Both values are one roster row's identity, each one argv entry,
|
|
314
|
+
* never option-shaped. A clean exit is required for success (`strictExit`): an answer the CLI did not finish
|
|
315
|
+
* printing is the adapter's own error, never the kernel's. */
|
|
316
|
+
export function cliServerForget(bin, { server, instance } = {}, io = {}) {
|
|
317
|
+
if (!argText(server, 256) || !argText(instance, 256)) return Promise.resolve({ schemaVersion: 1, ok: false, error: { code: "E_BAD_ARGS", message: "Invalid forget arguments" } });
|
|
318
|
+
return runJson(bin, ["server", "forget", server, "--instance", instance, "--json"], { cwd: io.cwd || process.cwd(), exec: io.exec, timeout: io.timeout || 15_000, strictExit: true });
|
|
319
|
+
}
|
|
303
320
|
/** `oats server connect <id> --ssh <host> --dir <folder on the host> [--install-oats] --json`, in the deployment's scope. */
|
|
304
321
|
export function cliServerConnect(bin, { id, host, folder, installOats, workspaceDir }, io = {}) {
|
|
305
322
|
if (machineFieldProblem({ id, host, folder }) || !absoluteReadPath(workspaceDir)) return Promise.resolve(badMachineArgs());
|
|
@@ -417,9 +434,24 @@ function parseRosterEnvelope(stdout) {
|
|
|
417
434
|
return doc;
|
|
418
435
|
}
|
|
419
436
|
|
|
420
|
-
/**
|
|
437
|
+
/** A value the kernel takes for `server roster --workspace-key` (feature roster-workspace-key): a
|
|
438
|
+
* registration's key grammar (not empty, no whitespace or control character), and not an option
|
|
439
|
+
* (the kernel refuses a value that starts with `--`). */
|
|
440
|
+
export const ROSTER_WORKSPACE_KEY = /^(?!--)[^\s\x00-\x1f\x7f]{1,2048}$/;
|
|
441
|
+
/** At most this many keys in one read: one per open window. */
|
|
442
|
+
export const ROSTER_WORKSPACE_KEYS_MAX = 64;
|
|
443
|
+
|
|
444
|
+
/** One bounded aggregate read; the CLI owns registry and saved-route resolution. `io.workspaceKeys`, only
|
|
445
|
+
* for a CLI that lists `roster-workspace-key`: the read probes those workspaces' registrations (and those
|
|
446
|
+
* of unknown workspace, and saved routes) and no other; each is one `--workspace-key=<key>` argv element.
|
|
447
|
+
* None, or an empty list, is the unfiltered read. A key the kernel would refuse is refused here. */
|
|
421
448
|
export function cliRemoteRoster(bin, io = {}) {
|
|
422
|
-
|
|
449
|
+
const keys = io.workspaceKeys ?? [];
|
|
450
|
+
if (!Array.isArray(keys) || keys.length > ROSTER_WORKSPACE_KEYS_MAX || !keys.every((k) => typeof k === "string" && ROSTER_WORKSPACE_KEY.test(k))) {
|
|
451
|
+
throw Object.assign(new Error("Invalid workspace keys for the roster read"), { code: "E_BAD_ARGS" });
|
|
452
|
+
}
|
|
453
|
+
const argv = ["server", "roster", ...[...new Set(keys)].map((k) => `--workspace-key=${k}`), "--json"];
|
|
454
|
+
return runJson(bin, argv, { cwd: io.cwd || process.cwd(), exec: io.exec, timeout: io.timeout || 60_000, parse: parseRosterEnvelope });
|
|
423
455
|
}
|
|
424
456
|
|
|
425
457
|
/** Local retire predates the envelope; preserve its incomplete-cleanup result. */
|
|
@@ -448,7 +480,9 @@ function flagFor(harnessFlag) {
|
|
|
448
480
|
throw Object.assign(new Error("The kernel's harness flag was not named"), { code: "E_BAD_ARGS" });
|
|
449
481
|
}
|
|
450
482
|
|
|
451
|
-
/** Shared explicit launch choices; every value remains one argv entry.
|
|
483
|
+
/** Shared explicit launch choices; every value remains one argv entry. `launchConfig` is a configuration's
|
|
484
|
+
* name or the word that selects none (launch-contract.mjs LAUNCH_CONFIG_NONE): `--launch-config none`
|
|
485
|
+
* asks for the bare harness, alone or beside a harness. */
|
|
452
486
|
export function launchChoiceArgv({ launchConfig, harness, model, yolo, harnessFlag } = {}) {
|
|
453
487
|
const argv = [];
|
|
454
488
|
for (const [key, v] of Object.entries({ launchConfig, harness, model })) {
|
|
@@ -464,7 +498,56 @@ export function launchChoiceArgv({ launchConfig, harness, model, yolo, harnessFl
|
|
|
464
498
|
return argv;
|
|
465
499
|
}
|
|
466
500
|
|
|
467
|
-
/**
|
|
501
|
+
/** `execFile`'s shape, return and errors, for a child in a session of its own (`detached`: a new session and
|
|
502
|
+
* process group). `execFile` drops `detached`, so this is the `exec` a kernel caller of this home uses for a
|
|
503
|
+
* stop or retire apply and a start. Like `execFile` it collects stdout and stderr (`encoding`, default utf8),
|
|
504
|
+
* ends the child with `killSignal` (SIGTERM) when `timeout` (0: none) passes or an output passes `maxBuffer`,
|
|
505
|
+
* and calls back once the child's streams close: `(null, stdout, stderr)` on a clean exit; else an Error with
|
|
506
|
+
* `code` (the exit status, or a system code), `killed` and `signal`, or the overflow's own error, whose `code`
|
|
507
|
+
* is ERR_CHILD_PROCESS_STDIO_MAXBUFFER. stdin is a pipe, as `execFile`'s, that nobody writes. */
|
|
508
|
+
export function execFileInSession(bin, argv, options = {}, callback = () => {}) {
|
|
509
|
+
const { cwd, env, encoding = "utf8", timeout = 0, maxBuffer = 1024 * 1024, killSignal = "SIGTERM" } = options;
|
|
510
|
+
const child = spawn(bin, argv, { cwd, env, shell: false, detached: true, windowsHide: true });
|
|
511
|
+
const chunks = { stdout: [], stderr: [] }, sizes = { stdout: 0, stderr: 0 };
|
|
512
|
+
let ex = null, killed = false, timer = null, exited = false;
|
|
513
|
+
const text = name => { const all = Buffer.concat(chunks[name]); return encoding && encoding !== "buffer" ? all.toString(encoding) : all; };
|
|
514
|
+
function kill() { killed = true; try { child.kill(killSignal); } catch (error) { ex ??= error; exit(); } }
|
|
515
|
+
function exit(code = null, signal = null) {
|
|
516
|
+
if (exited) return; exited = true; clearTimeout(timer);
|
|
517
|
+
const stdout = text("stdout"), stderr = text("stderr");
|
|
518
|
+
if (!ex && code === 0 && signal === null) { callback(null, stdout, stderr); return; }
|
|
519
|
+
const cmd = [bin, ...argv].join(" ");
|
|
520
|
+
if (!ex) ex = Object.assign(new Error(`Command failed: ${cmd}\n${stderr}`), { code, killed: child.killed || killed, signal });
|
|
521
|
+
ex.cmd = cmd; callback(ex, stdout, stderr);
|
|
522
|
+
}
|
|
523
|
+
for (const name of ["stdout", "stderr"]) child[name].on("data", chunk => {
|
|
524
|
+
if (ex) return;
|
|
525
|
+
const room = maxBuffer - sizes[name];
|
|
526
|
+
if (chunk.length > room) {
|
|
527
|
+
chunks[name].push(chunk.subarray(0, Math.max(room, 0))); sizes[name] = maxBuffer;
|
|
528
|
+
ex = Object.assign(new RangeError(`${name} maxBuffer length exceeded`), { code: "ERR_CHILD_PROCESS_STDIO_MAXBUFFER" }); kill(); return;
|
|
529
|
+
}
|
|
530
|
+
chunks[name].push(chunk); sizes[name] += chunk.length;
|
|
531
|
+
});
|
|
532
|
+
child.on("close", exit);
|
|
533
|
+
child.on("error", error => { ex = error; child.stdout?.destroy(); child.stderr?.destroy(); exit(); });
|
|
534
|
+
if (timeout > 0) { timer = setTimeout(kill, timeout); }
|
|
535
|
+
return child;
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
/** How long a client waits for a start's answer. The wait ends; the start does not. */
|
|
539
|
+
export const START_WAIT_MS = ENVELOPE_TIMEOUT_MS;
|
|
540
|
+
|
|
541
|
+
/** Start/restart is owned by the kernel, never a GUI stop-then-spawn pair. A start runs in a session of its own
|
|
542
|
+
* (`detached`, execFileInSession) with no deadline of its own (`timeout: 0`, no kill timer), so neither a signal
|
|
543
|
+
* to the client's group nor a deadline ends it (#889: a start killed mid-way can leave its lock). The client
|
|
544
|
+
* waits for its answer `io.wait` (START_WAIT_MS, 60 s); `io.after(ms, fn)` runs fn once after ms and answers a
|
|
545
|
+
* cancel. When the wait ends first, the start answers the code `E_START_UNCONFIRMED`, with no message: nothing is
|
|
546
|
+
* known of the start, and each client words that in its own words, under no speaker (it is not the kernel's).
|
|
547
|
+
* The child goes on: what it prints
|
|
548
|
+
* is still read, so it neither blocks on a full pipe nor writes to a closed one, and its answer, when it comes
|
|
549
|
+
* after the wait, is not kept. A start has no entry to keep it on, and its answer says nothing the roster
|
|
550
|
+
* does not: after a failed start the row is read again. */
|
|
468
551
|
export function cliStart(bin, { home, workspaceDir, server, restart = false, ...choices }, io = {}) {
|
|
469
552
|
if (typeof home !== "string" || !home.startsWith("/") || home.includes("\0")
|
|
470
553
|
|| (server !== undefined && (typeof server !== "string" || !/^[a-z0-9][a-z0-9-]{0,63}$/.test(server)))
|
|
@@ -474,11 +557,19 @@ export function cliStart(bin, { home, workspaceDir, server, restart = false, ...
|
|
|
474
557
|
let options;
|
|
475
558
|
try { options = launchChoiceArgv(choices); }
|
|
476
559
|
catch (e) { return Promise.resolve({ schemaVersion: 1, ok: false, error: { code: e.code, message: e.message } }); }
|
|
477
|
-
|
|
560
|
+
const { wait = START_WAIT_MS, after = waitTimer } = io;
|
|
561
|
+
let cancel = () => {};
|
|
562
|
+
const answered = runJson(bin, ["session", restart ? "restart" : "start", "--home", home,
|
|
478
563
|
...(server ? ["--server", server] : []), ...options, "--json"], {
|
|
479
|
-
cwd: workspaceDir, exec: io.exec, timeout:
|
|
564
|
+
cwd: workspaceDir, exec: io.exec, timeout: 0, detached: true,
|
|
565
|
+
}).finally(() => cancel());
|
|
566
|
+
const waited = new Promise((resolve) => {
|
|
567
|
+
cancel = after(wait, () => resolve({ schemaVersion: 1, ok: false, error: { code: "E_START_UNCONFIRMED" } }));
|
|
480
568
|
});
|
|
569
|
+
return Promise.race([answered, waited]);
|
|
481
570
|
}
|
|
571
|
+
/** A wait's timer that keeps no process alive: `after(ms, fn)` -> cancel. */
|
|
572
|
+
const waitTimer = (ms, fn) => { const timer = setTimeout(fn, ms); timer.unref?.(); return () => clearTimeout(timer); };
|
|
482
573
|
|
|
483
574
|
/** Named configuration data travels in private JSON files, not shell text. */
|
|
484
575
|
export async function cliLaunchConfig(bin, { action, name, definition, keepEnv, context, server, home, soul, agentsRoot, choices, localCwd }, io = {}) {
|
|
@@ -524,8 +615,8 @@ export function operationArgs(args) {
|
|
|
524
615
|
return entries.flatMap(([k, v]) => ['--arg', `${k}=${v}`]);
|
|
525
616
|
}
|
|
526
617
|
/** `maxAge` (feature observe-max-age) is inspect's alone; `features` is the probe's list and
|
|
527
|
-
* gates the
|
|
528
|
-
export async function cliCapability(bin, { action, context, server, soul, agentsRoot, home, operation, args, localCwd, maxAge, instructions = false, features }, io = {}) {
|
|
618
|
+
* gates the flags (also `instructions` and `skills`), so an undeclared kernel gets the flagless argv even when a value is given. */
|
|
619
|
+
export async function cliCapability(bin, { action, context, server, soul, agentsRoot, home, operation, args, localCwd, maxAge, instructions = false, skills = false, features }, io = {}) {
|
|
529
620
|
const bad = message => { throw Object.assign(new Error(message), { code: 'E_BAD_ARGS' }); };
|
|
530
621
|
const value = (v, label) => {
|
|
531
622
|
if (typeof v !== 'string' || !v || v.startsWith('-') || v.includes('\0')) bad(`Invalid ${label}`);
|
|
@@ -555,7 +646,11 @@ export async function cliCapability(bin, { action, context, server, soul, agents
|
|
|
555
646
|
// row names the feature (packages/desktop: server/capabilities.mjs, renderer/composed-gate.mjs): a host without it refuses the flag.
|
|
556
647
|
if (instructions && (action !== 'inspect' || !soul || home)) bad('Composed instructions belong to a soul inspection');
|
|
557
648
|
const composed = instructions && Array.isArray(features) && features.includes('soul-composed-instructions') ? ['--instructions'] : [];
|
|
558
|
-
|
|
649
|
+
// --skills (feature soul-skills) adds the soul's own skills (souls[0].skills): inspect --soul only, gated the same
|
|
650
|
+
// way; routed, the caller asks only for a host whose roster row names soul-skills (composed-gate.mjs hostReportsSkills).
|
|
651
|
+
if (skills && (action !== 'inspect' || !soul || home)) bad('Skills belong to a soul inspection');
|
|
652
|
+
const skillsArgv = skills && Array.isArray(features) && features.includes('soul-skills') ? ['--skills'] : [];
|
|
653
|
+
return await runJson(bin, [...argv, ...target, ...composed, ...skillsArgv, ...maxAgeArgv(features, maxAge), '--json'], {
|
|
559
654
|
cwd: localCwd, exec: io.exec, timeout: io.timeout ?? (action === 'run' ? 300_000 : ENVELOPE_TIMEOUT_MS),
|
|
560
655
|
});
|
|
561
656
|
}
|