@awebai/oats 0.56.0 → 0.57.1
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 +18 -10
- package/docs/configuration.md +17 -27
- package/docs/desktop-cli-api.md +59 -3
- package/docs/desktop.md +25 -4
- package/docs/execution-targets.md +6 -1
- package/docs/implementation.md +106 -5
- package/docs/integrations.md +8 -4
- package/docs/knowledge.md +93 -38
- package/docs/official-catalog.md +3 -3
- package/docs/packages.md +12 -12
- package/docs/release-notes/v0.57.0.md +283 -0
- package/docs/release-notes/v0.57.1.md +275 -0
- package/docs/schedules.md +8 -3
- package/docs/servers.md +18 -0
- package/docs/souls-and-instances.md +126 -15
- package/docs/tui.md +333 -95
- package/docs/workspaces.md +2 -2
- package/lib/core.mjs +439 -126
- package/lib/instance-lifecycle.mjs +45 -9
- package/lib/session-viewer.mjs +29 -4
- package/lib/worktree.mjs +23 -2
- package/package-catalog.json +2 -2
- package/package.json +1 -1
- package/packages/client/cli-adapter.mjs +9 -7
- package/packages/client/cli-locator.mjs +2 -2
- package/packages/client/composed-gate.mjs +34 -0
- package/packages/client/inspect-boundary.mjs +157 -0
- package/packages/client/inspect-cache.mjs +86 -0
- package/packages/client/instance-lifecycle.mjs +10 -3
- package/packages/client/keyed-catalog.mjs +132 -0
- package/packages/client/launch-prompt-outcome.mjs +1 -1
- package/packages/client/launch-view.mjs +46 -0
- package/packages/client/session-attach.mjs +7 -5
- package/packages/client/soul-catalog.mjs +77 -0
- package/packages/client/soul-colors.mjs +31 -0
- package/packages/client/soul-facts.mjs +85 -0
- package/packages/client/soul-rows.mjs +48 -0
- package/packages/client/spawn-apply-cli.mjs +11 -6
- package/packages/client/spawn-apply.mjs +212 -0
- package/packages/client/spawn-messages.mjs +131 -85
- package/packages/client/spawn-preview-contract.mjs +3 -0
- package/packages/client/spawn-preview-facts.mjs +119 -0
- package/packages/client/spawn-preview.mjs +152 -0
- package/packages/client/spawn-transaction.mjs +136 -0
- package/packages/tui/README.md +43 -13
- package/packages/tui/lib/actions.mjs +18 -2
- package/packages/tui/lib/client.mjs +4 -0
- package/packages/tui/lib/config.mjs +9 -14
- package/packages/tui/lib/main.mjs +241 -55
- package/packages/tui/lib/model.mjs +230 -29
- package/packages/tui/lib/panel.mjs +955 -0
- package/packages/tui/lib/read.mjs +134 -24
- package/packages/tui/lib/store.mjs +184 -31
- package/packages/tui/lib/term/capture.mjs +260 -0
- package/packages/tui/lib/term/screen.mjs +44 -8
- package/packages/tui/lib/term/style.mjs +78 -6
- package/packages/tui/lib/term/text.mjs +24 -4
- package/packages/tui/lib/term/through.mjs +213 -0
- package/packages/tui/lib/term/tty.mjs +7 -60
- package/packages/tui/lib/views/act.mjs +85 -0
- package/packages/tui/lib/views/frame.mjs +153 -37
- package/packages/tui/lib/views/help.mjs +22 -14
- package/skills/oats-getting-started/SKILL.md +4 -3
- package/packages/tui/lib/open.mjs +0 -45
|
@@ -106,6 +106,21 @@ function sessionFacts(home) {
|
|
|
106
106
|
try { const s = inspectInstanceSession(home); return { state: s.state, present: s.present, backend: s.backend ?? null, established: true }; }
|
|
107
107
|
catch (e) { return { state: "unestablished", present: null, backend: null, established: false, reason: kernelCode(e, "E_SESSION_UNAVAILABLE") }; }
|
|
108
108
|
}
|
|
109
|
+
/** The instances attached to `tree`, a tree of the home of the instance `name` under `root` (its
|
|
110
|
+
* `work/` or an extra tree; #964) → [{ instance, home, session }]. `session` is the session as a
|
|
111
|
+
* stop plan reads it (sessionFacts), in one word: "running", "stopped", or "unknown" when it could
|
|
112
|
+
* not be established, which is never taken for stopped. Who is looked at: the recorded
|
|
113
|
+
* descendants of `name`, as a plan lists them, and the instances that record `name` as their
|
|
114
|
+
* parent under a name that is not unique (a plan's `ambiguous`). Lineage does not make an
|
|
115
|
+
* instance attached: its `work` link does (core attachedWorkLink), so these are read too. For
|
|
116
|
+
* `oats worktree remove`, which removes a tree under nobody's running session. Read-only. */
|
|
117
|
+
export function attachedToTree(root, name, tree) {
|
|
118
|
+
const kids = descendantsOf(root, name);
|
|
119
|
+
return [...kids, ...(kids.ambiguous || [])].filter((c) => attachedWorkLink(c.home, tree) !== null).map((c) => {
|
|
120
|
+
const s = sessionFacts(c.home);
|
|
121
|
+
return { instance: c.instance, home: c.home, session: running(s) ? "running" : s.established ? "stopped" : "unknown" };
|
|
122
|
+
});
|
|
123
|
+
}
|
|
109
124
|
/** Retire's view of a home without its session receipt (before 0.25.9): the
|
|
110
125
|
* retirement needs only absence, which it can observe — `{state: "absent",
|
|
111
126
|
* present: false, established: true, note}`; live or ambiguous stays
|
|
@@ -353,21 +368,31 @@ function fitParts(render, parts) {
|
|
|
353
368
|
|
|
354
369
|
/** A retire plan's note for one extra tree (core extraWorktreePlan row). Too long for the Desktop, its
|
|
355
370
|
* longest parts go to the plan JSON, longest first; the tree's path stays whole, or the note says it
|
|
356
|
-
* is too long and where it is.
|
|
357
|
-
|
|
371
|
+
* is too long and where it is. `attached`: the names of the recorded children whose work is this
|
|
372
|
+
* tree (#964). The note names them and says what the retire leaves each with: its link repointed to
|
|
373
|
+
* the tree where it is re-homed, or pointing at a path that is gone where the tree is removed. A
|
|
374
|
+
* tree the retire refuses is neither moved nor removed, and nothing is said of them. `others`: the
|
|
375
|
+
* names of the instances attached to it that the plan lists under `ambiguous`. The retire does not
|
|
376
|
+
* act on them, and the note says what that leaves them with, in a clause of its own. */
|
|
377
|
+
function extraWorktreeNote(t, attached = [], others = []) {
|
|
378
|
+
const said = t.disposition !== "refuse";
|
|
379
|
+
const kids = attached.length && said ? (p) => `; attached child instance(s) ${p.kids} use it as their work, and ${t.disposition === "remove" ? "their work link would then point at a path that is gone" : "the retire repoints their work link to it"}` : () => "";
|
|
380
|
+
const rest = others.length && said ? (p) => `; attached instance(s) ${p.others}, listed under ambiguous, use it as their work: ${t.disposition === "remove" ? "the retire does not stop them, and their work link would then point at a path that is gone" : `the retire neither stops them nor repoints their work link, which would then point at a path that is gone (the tree would be at ${p.movedTo})`}` : () => "";
|
|
358
381
|
const parts = {
|
|
382
|
+
...(attached.length ? { kids: [listWithin(attached, (shown) => shown.join(", "), PLAN_LIST_BUDGET) ?? String(attached.length), `${attached.length} of the recorded children`] } : {}),
|
|
383
|
+
...(others.length ? { others: [listWithin(others, (shown) => shown.join(", "), PLAN_LIST_BUDGET) ?? String(others.length), `(${others.length} of them)`] } : {}),
|
|
359
384
|
at: [t.branch ? `branch ${t.branch}` : t.detachedAt ? `detached at ${t.detachedAt.slice(0, 12)}` : "a HEAD that could not be read", `its HEAD: see ${SEE_EXTRA}`],
|
|
360
385
|
repo: [t.repo, `its repository (see ${SEE_EXTRA})`],
|
|
361
386
|
movedTo: [t.movedTo, `the path ${SEE_EXTRA} names`],
|
|
362
387
|
reason: [t.reason, `${SEE_EXTRA} says why`],
|
|
363
388
|
};
|
|
364
|
-
const render = (p) => t.disposition === "remove" ? `extra worktree ${t.path} (${p.at}) is clean and would be removed; its branch and commits stay in ${p.repo}`
|
|
365
|
-
: t.disposition === "retain" ? `extra worktree ${t.path} (${p.at}) would be re-homed to ${p.movedTo}: ${p.reason}`
|
|
389
|
+
const render = (p) => t.disposition === "remove" ? `extra worktree ${t.path} (${p.at}) is clean and would be removed; its branch and commits stay in ${p.repo}${kids(p)}${rest(p)}`
|
|
390
|
+
: t.disposition === "retain" ? `extra worktree ${t.path} (${p.at}) would be re-homed to ${p.movedTo}: ${p.reason}${kids(p)}${rest(p)}`
|
|
366
391
|
: `extra worktree ${t.path} (${p.at}): retire refuses, ${p.reason}`;
|
|
367
392
|
const note = fitParts(render, parts);
|
|
368
393
|
if (note !== null) return note;
|
|
369
394
|
const outcome = t.disposition === "remove" ? "would be removed" : t.disposition === "retain" ? "would be re-homed" : "makes retire refuse";
|
|
370
|
-
return `an extra worktree whose path is too long for this note ${outcome}; ${SEE_EXTRA} lists it`;
|
|
395
|
+
return `an extra worktree whose path is too long for this note ${outcome}; ${SEE_EXTRA} lists it${kids({ kids: `${attached.length} of the recorded children` })}${rest({ others: `(${others.length} of them)`, movedTo: `the path ${SEE_EXTRA} names` })}`;
|
|
371
396
|
}
|
|
372
397
|
/** The plan's note when the worktree is not on the recorded branch: both names, or, too long for the
|
|
373
398
|
* note, pointers to the plan JSON fields that hold them. */
|
|
@@ -445,13 +470,22 @@ export function planRetire(ctx, root, name, { home } = {}) {
|
|
|
445
470
|
const repoFromGit = ownTree && !meta.repo ? workIs.tree?.repo ?? null : null;
|
|
446
471
|
// Attached children whose work is this home's work/ (#718): a retire that keeps the worktree
|
|
447
472
|
// repoints them to it. One note holds whatever the dialog then picks.
|
|
448
|
-
const attached = ownTree ? kids.filter((c) => attachedWorkLink(c.home, me.home) !== null) : [];
|
|
473
|
+
const attached = ownTree ? kids.filter((c) => attachedWorkLink(c.home, join(me.home, "work")) !== null) : [];
|
|
474
|
+
// The instances attached to a tree of this home that record it as their parent under a name that
|
|
475
|
+
// is not unique (`ambiguous`): the retire does not act on them, so each tree's note says what the
|
|
476
|
+
// retire leaves them with (#964). Lineage does not make an instance attached: its link does.
|
|
477
|
+
const attachedAmbiguous = (tree) => (kids.ambiguous || []).filter((c) => attachedWorkLink(c.home, tree) !== null);
|
|
478
|
+
const ambiguousOnWork = ownTree ? attachedAmbiguous(join(me.home, "work")) : [];
|
|
479
|
+
// Each extra tree's attached instances, as its note names them: the recorded children, and those
|
|
480
|
+
// of an ambiguous name.
|
|
481
|
+
const extraAttached = extraWorktrees.map((t) => ({ kids: kids.filter((c) => attachedWorkLink(c.home, t.path) !== null), others: attachedAmbiguous(t.path) }));
|
|
449
482
|
// The session as the plan shows it, whole: its state, and the reason or the note of one that is
|
|
450
483
|
// not established, which the record's launch and endpoint fields decide (awebai/oats#1065). The
|
|
451
484
|
// children as the plan names them (a child's agent is the name its soul's file gives, which its
|
|
452
485
|
// home's path does not hold), and with them what the plan shows of other homes' records: the edges
|
|
453
486
|
// it could not follow (facts.ambiguous, whole: each edge's reason counts the homes of the name)
|
|
454
|
-
// and the
|
|
487
|
+
// and the instances attached to this work and to each extra tree, which the notes name (#964;
|
|
488
|
+
// attached instances are made by spawns, so they do not move by themselves). Where Git gives no answer for work/, the
|
|
455
489
|
// reason the plan shows for that (facts.work.reason): nothing at work/ and a file there are one
|
|
456
490
|
// answer of the reading under a record that says `worktree`, and two plans. Where Git answers,
|
|
457
491
|
// what the plan shows of the tree that does not move by itself: the commit, the branch and
|
|
@@ -468,7 +502,8 @@ export function planRetire(ctx, root, name, { home } = {}) {
|
|
|
468
502
|
// note stays short, and are part of the plan's revision (awebai/oats#1065).
|
|
469
503
|
const recovery = retirementRecoveryFacts(me.home);
|
|
470
504
|
const safety = [me.home, target.session, target.launched, tree, kids.map((c) => [c.instance, c.agent, c.home]),
|
|
471
|
-
{ ambiguous: facts.ambiguous, attached: attached.map((c) => c.home)
|
|
505
|
+
{ ambiguous: facts.ambiguous, attached: attached.map((c) => c.home), ambiguousOnWork: ambiguousOnWork.map((c) => c.home),
|
|
506
|
+
extra: extraWorktrees.map((t, i) => [t.path, extraAttached[i].kids.map((c) => c.home), extraAttached[i].others.map((c) => c.home)]) },
|
|
472
507
|
// The home's extra trees, when there are any.
|
|
473
508
|
...(extraWorktrees.length ? [extraWorktrees] : []),
|
|
474
509
|
// What the plan reports of the record about work/ (its work mode, its repository, its branch),
|
|
@@ -487,7 +522,7 @@ export function planRetire(ctx, root, name, { home } = {}) {
|
|
|
487
522
|
recovery];
|
|
488
523
|
appendEvent(me.home, { kind: "retire-planned", data: { planRevision: planRevision(safety), children: kids.length, dirty: facts.work.observed ? facts.work.changed + facts.work.untracked : null } }, { workspaceOnly: true });
|
|
489
524
|
const plan = { lifecycleApi: LIFECYCLE_API, action: "retire", instance: name, home: me.home, at: new Date().toISOString(), facts, defaults, planRevision: planRevision(safety),
|
|
490
|
-
notes: boundedNotes(extraWorktrees.map(extraWorktreeNote), [
|
|
525
|
+
notes: boundedNotes(extraWorktrees.map((t, i) => extraWorktreeNote(t, extraAttached[i].kids.map((c) => c.instance), extraAttached[i].others.map((c) => c.instance))), [
|
|
491
526
|
// The two notes about a worktree that is retained are for the instance's own tree alone (#973).
|
|
492
527
|
// Not for a directory of the home (what it holds is copied and removed), not for a directory
|
|
493
528
|
// instance whose work/ is a repository of its own (the recovery note below says what is done),
|
|
@@ -502,6 +537,7 @@ export function planRetire(ctx, root, name, { home } = {}) {
|
|
|
502
537
|
], [
|
|
503
538
|
...(kids.length ? [`${kids.length} recorded child instance(s) are stopped first (bounded SIGTERM, never escalated) and retained (their homes are not removed); a child still running after the grace refuses the retirement`] : []),
|
|
504
539
|
...(attached.length ? [`attached child instance(s) ${listWithin(attached.map((c) => c.instance), (shown) => shown.join(", "), PLAN_LIST_BUDGET) ?? attached.length} use this home's work/ as their work: a retire that keeps the worktree repoints their work link to it; with --discard-worktree the worktree is removed and their work link will dangle`] : []),
|
|
540
|
+
...(ambiguousOnWork.length ? [`attached instance(s) ${listWithin(ambiguousOnWork.map((c) => c.instance), (shown) => shown.join(", "), PLAN_LIST_BUDGET) ?? ambiguousOnWork.length}, listed under ambiguous, use this home's work/ as their work: the retire neither stops them nor repoints their work link, which will then point at a path that is gone, whether the worktree is retained (the receipt names where) or removed with --discard-worktree`] : []),
|
|
505
541
|
...((kids.ambiguous || []).length ? [`${kids.ambiguous.length} instance(s) record this name as parent but the name is not unique under this root; they are listed under ambiguous and NOT acted on`] : []),
|
|
506
542
|
...(target.session.note ? [sessionNote(target.session)] : []),
|
|
507
543
|
"pull request state is unknown to the kernel; the ADE reports it when a forge connection exists",
|
package/lib/session-viewer.mjs
CHANGED
|
@@ -54,8 +54,12 @@ export function prepareSessionViewer(target, { exec = execFileSync, detachKey }
|
|
|
54
54
|
if (!inspectSessionTarget(target, { exec }).present) throw new Error("session no longer exists");
|
|
55
55
|
// UTF-8 mode (-u) like the shared session helper: a service without a
|
|
56
56
|
// UTF-8 locale (launchd) otherwise mangles tmux output.
|
|
57
|
+
// Each call in a session and process group of its own (`detached`): a hang-up, termination or
|
|
58
|
+
// interrupt sent to the attach's group (a pty hang-up once a wrapping shell has died, a C-c)
|
|
59
|
+
// must not kill a call in flight, the cleanup's kill-session first of all (#1243). The client the
|
|
60
|
+
// attach spawns is not one of these: it stays in the terminal's foreground group.
|
|
57
61
|
const run = (args) => exec("tmux", ["-u", "-S", target.socket, ...args], {
|
|
58
|
-
encoding: "utf8", timeout: 10000, stdio: ["ignore", "pipe", "pipe"],
|
|
62
|
+
encoding: "utf8", timeout: 10000, stdio: ["ignore", "pipe", "pipe"], detached: true,
|
|
59
63
|
}).trim();
|
|
60
64
|
const viewer = `oatsview-${process.pid}-${randomUUID().slice(0, 8)}`;
|
|
61
65
|
// A keyed viewer reads a table of its own, named as its session: a binding in the locked table
|
|
@@ -80,6 +84,10 @@ export function prepareSessionViewer(target, { exec = execFileSync, detachKey }
|
|
|
80
84
|
// Session-scoped on the temporary viewer: the agents' own session and
|
|
81
85
|
// the operator's tmux settings are untouched.
|
|
82
86
|
run(["set-option", "-t", viewer, "status", "off"]);
|
|
87
|
+
// When the agent's window ends (a retire), the viewer has no window left and tmux destroys it.
|
|
88
|
+
// The viewer's client must then leave, not be moved: under an operator's `detach-on-destroy off`
|
|
89
|
+
// tmux would switch it to another session, another agent's terminal (#1237).
|
|
90
|
+
run(["set-option", "-t", viewer, "detach-on-destroy", "on"]);
|
|
83
91
|
run(["unbind-key", "-a", "-q", "-T", table]);
|
|
84
92
|
for (const binding of MOUSE_BINDINGS) run(["bind-key", "-T", table, ...binding]);
|
|
85
93
|
// The key is its own argv element, after the grammar admitted it.
|
|
@@ -126,17 +134,32 @@ function holdQuit() {
|
|
|
126
134
|
* SESSION_DETACHED_EXIT when `detachKey` was given and ended the attach. */
|
|
127
135
|
export async function attachSessionTarget(target, { detachKey } = {}) {
|
|
128
136
|
if (detachKey !== undefined) { requireDetachKey(detachKey); holdQuit(); }
|
|
129
|
-
|
|
137
|
+
// HUP, TERM and INT are held from before the viewer session exists until its cleanup has
|
|
138
|
+
// finished: one that arrives in between, early or late, finds a listener and not the default
|
|
139
|
+
// action, which would end Node with the session left on the agents' server (#1243). Node runs
|
|
140
|
+
// the listener only between synchronous runs, so it may find no viewer yet, or no client.
|
|
141
|
+
let viewer = null;
|
|
130
142
|
let child;
|
|
143
|
+
let stopped = false;
|
|
131
144
|
let quit = false;
|
|
132
|
-
const stop = () => { viewer
|
|
145
|
+
const stop = () => { stopped = true; viewer?.cleanup(); child?.kill(); };
|
|
133
146
|
const signals = ["SIGHUP", "SIGTERM", "SIGINT"];
|
|
134
147
|
for (const sig of signals) process.on(sig, stop);
|
|
148
|
+
// A preparation that fails has already removed what it made.
|
|
149
|
+
try { viewer = prepareSessionViewer(target, { detachKey }); }
|
|
150
|
+
catch (e) { for (const sig of signals) process.removeListener(sig, stop); throw e; }
|
|
135
151
|
// Until the client has exited, a QUIT stops the attach as the other signals do, with status 1.
|
|
136
152
|
// Unless the key's binding has already run: then the client is on its way out, the QUIT is the
|
|
137
153
|
// key pressed again, and the attach ends as a detach.
|
|
138
154
|
if (detachKey !== undefined) onQuit = () => { if (viewer.detached()) return; quit = true; stop(); };
|
|
139
155
|
try {
|
|
156
|
+
// A signal received during the synchronous preparation is dispatched only in a poll phase of
|
|
157
|
+
// the event loop. Two setImmediate hops run at least one, wherever this attach was called
|
|
158
|
+
// from, so such a signal stops the attach here, before a client takes the terminal: one loop
|
|
159
|
+
// turn per attach. Stopped by then, the viewer ended without the key, and with no client to
|
|
160
|
+
// set the marker a keyed viewer answers 0 too; a QUIT answers 1, as it does with a client.
|
|
161
|
+
for (let hop = 0; hop < 2; hop++) await new Promise((resolve) => setImmediate(resolve));
|
|
162
|
+
if (stopped) return quit ? 1 : 0;
|
|
140
163
|
const code = await new Promise((resolve, reject) => {
|
|
141
164
|
child = spawn(viewer.binary, viewer.args, { env: viewer.env, stdio: "inherit" });
|
|
142
165
|
child.once("error", reject);
|
|
@@ -148,7 +171,9 @@ export async function attachSessionTarget(target, { detachKey } = {}) {
|
|
|
148
171
|
// The client has exited (or never started): a QUIT from here on changes nothing. One that
|
|
149
172
|
// arrives during the calls below waits for them, so cleanup completes and the status stands.
|
|
150
173
|
onQuit = null;
|
|
151
|
-
for (const sig of signals) process.removeListener(sig, stop);
|
|
152
174
|
viewer.cleanup();
|
|
175
|
+
// Only now: a HUP, TERM or INT that arrived during the cleanup was taken by the listener, and
|
|
176
|
+
// its calls, in groups of their own, ran to the end. The status stands.
|
|
177
|
+
for (const sig of signals) process.removeListener(sig, stop);
|
|
153
178
|
}
|
|
154
179
|
}
|
package/lib/worktree.mjs
CHANGED
|
@@ -23,6 +23,7 @@ import { existsSync, linkSync, lstatSync, mkdirSync, readFileSync, realpathSync,
|
|
|
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";
|
|
@@ -608,7 +609,14 @@ export async function worktreeAdd(homeArg, o = {}) {
|
|
|
608
609
|
|
|
609
610
|
/** `oats worktree remove --purpose <p>`: `git worktree remove` (which refuses a dirty tree),
|
|
610
611
|
* the branch kept, no hook, the record dropped. A `creating` record whose adder is gone is
|
|
611
|
-
* 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. */
|
|
612
620
|
export async function worktreeRemove(homeArg, o = {}) {
|
|
613
621
|
validateTreeArgs(o, { forRemove: true });
|
|
614
622
|
const home = homeArg;
|
|
@@ -630,6 +638,17 @@ export async function worktreeRemove(homeArg, o = {}) {
|
|
|
630
638
|
return { purpose, path: tree, removed: true, rolledBack: true, branch: rec.branch, branchKept: rb.branchKept, ...(rb.branchKeptReason ? { branchKeptReason: rb.branchKeptReason } : {}), ...(warned.length ? { warnings: warned } : {}) };
|
|
631
639
|
}
|
|
632
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
|
+
}
|
|
633
652
|
if (existsSync(tree)) {
|
|
634
653
|
const status = git(["-C", tree, "status", "--porcelain", "--ignore-submodules=none"]);
|
|
635
654
|
const r = await trackedGit(["-C", clone, "worktree", "remove", "--end-of-options", tree], { track });
|
|
@@ -641,6 +660,8 @@ export async function worktreeRemove(homeArg, o = {}) {
|
|
|
641
660
|
await trackedGit(["-C", clone, "worktree", "prune"], { track });
|
|
642
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 } });
|
|
643
662
|
rmSync(recPath, { force: true });
|
|
644
|
-
|
|
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 } : {}) };
|
|
645
666
|
});
|
|
646
667
|
}
|
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.
|
|
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.
|
|
46
|
+
"ref": "oats-framework/v1.12.0",
|
|
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.1",
|
|
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",
|
|
@@ -500,11 +500,13 @@ export function launchChoiceArgv({ launchConfig, harness, model, yolo, harnessFl
|
|
|
500
500
|
|
|
501
501
|
/** `execFile`'s shape, return and errors, for a child in a session of its own (`detached`: a new session and
|
|
502
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
|
|
504
|
-
* ends the child with `killSignal` (SIGTERM) when `timeout` (0: none) passes or an output passes
|
|
505
|
-
* and calls back once the child's streams close: `(null, stdout, stderr)` on a clean exit; else an
|
|
506
|
-
* `code` (the exit status, or a system code), `killed` and `signal`, or the overflow's own error,
|
|
507
|
-
* is ERR_CHILD_PROCESS_STDIO_MAXBUFFER.
|
|
503
|
+
* stop or retire apply, a start and a spawn apply. Like `execFile` it collects stdout and stderr (`encoding`,
|
|
504
|
+
* default utf8), ends the child with `killSignal` (SIGTERM) when `timeout` (0: none) passes or an output passes
|
|
505
|
+
* `maxBuffer`, and calls back once the child's streams close: `(null, stdout, stderr)` on a clean exit; else an
|
|
506
|
+
* Error with `code` (the exit status, or a system code), `killed` and `signal`, or the overflow's own error,
|
|
507
|
+
* whose `code` is ERR_CHILD_PROCESS_STDIO_MAXBUFFER. A child its `timeout` killed is never a clean exit, even
|
|
508
|
+
* when it then exits 0: the Error has `killed: true`, and stdout and stderr are still passed (execFile's kill
|
|
509
|
+
* destroys them first). stdin is a pipe, as `execFile`'s, that nobody writes. */
|
|
508
510
|
export function execFileInSession(bin, argv, options = {}, callback = () => {}) {
|
|
509
511
|
const { cwd, env, encoding = "utf8", timeout = 0, maxBuffer = 1024 * 1024, killSignal = "SIGTERM" } = options;
|
|
510
512
|
const child = spawn(bin, argv, { cwd, env, shell: false, detached: true, windowsHide: true });
|
|
@@ -515,7 +517,7 @@ export function execFileInSession(bin, argv, options = {}, callback = () => {})
|
|
|
515
517
|
function exit(code = null, signal = null) {
|
|
516
518
|
if (exited) return; exited = true; clearTimeout(timer);
|
|
517
519
|
const stdout = text("stdout"), stderr = text("stderr");
|
|
518
|
-
if (!ex && code === 0 && signal === null) { callback(null, stdout, stderr); return; }
|
|
520
|
+
if (!ex && !killed && code === 0 && signal === null) { callback(null, stdout, stderr); return; }
|
|
519
521
|
const cmd = [bin, ...argv].join(" ");
|
|
520
522
|
if (!ex) ex = Object.assign(new Error(`Command failed: ${cmd}\n${stderr}`), { code, killed: child.killed || killed, signal });
|
|
521
523
|
ex.cmd = cmd; callback(ex, stdout, stderr);
|
|
@@ -643,7 +645,7 @@ export async function cliCapability(bin, { action, context, server, soul, agents
|
|
|
643
645
|
if (!validMaxAge(maxAge)) bad('Invalid observation age');
|
|
644
646
|
// --instructions (feature soul-composed-instructions) composes a soul's AGENTS.md: inspect --soul only; a CLI that
|
|
645
647
|
// does not advertise it gets the flagless argv. Routed with --server, the caller asks only for a host whose roster
|
|
646
|
-
// row names the feature (
|
|
648
|
+
// row names the feature (inspect-boundary.mjs, composed-gate.mjs): a host without it refuses the flag.
|
|
647
649
|
if (instructions && (action !== 'inspect' || !soul || home)) bad('Composed instructions belong to a soul inspection');
|
|
648
650
|
const composed = instructions && Array.isArray(features) && features.includes('soul-composed-instructions') ? ['--instructions'] : [];
|
|
649
651
|
// --skills (feature soul-skills) adds the soul's own skills (souls[0].skills): inspect --soul only, gated the same
|
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
// Every candidate is canonicalized to an absolute executable and accepted
|
|
14
14
|
// ONLY if executable and `<bin> version --json` returns the v1 probe:
|
|
15
15
|
// {"schemaVersion":1,"name":"@awebai/oats","version":"0.24.x","desktopApi":1}
|
|
16
|
-
// Desktop accepts desktopApi === 1 and semver >=0.26.0 <0.
|
|
16
|
+
// Desktop accepts desktopApi === 1 and semver >=0.26.0 <0.58.0 (the band is
|
|
17
17
|
// spelled ONCE, in ACCEPT_RANGE below — this line only paraphrases it).
|
|
18
18
|
// API version — not source adjacency — is authoritative.
|
|
19
19
|
//
|
|
@@ -52,7 +52,7 @@ export const DESKTOP_API = 1;
|
|
|
52
52
|
// carry a `description` for every kind and `<kind> update <id> --description`
|
|
53
53
|
// sets one (feature `automation-descriptions`, which gates the Desktop's
|
|
54
54
|
// summary writes). The Desktop v1 surface is otherwise unchanged.
|
|
55
|
-
export const ACCEPT_RANGE = { min: [0, 26, 0], maxExclusive: [0,
|
|
55
|
+
export const ACCEPT_RANGE = { min: [0, 26, 0], maxExclusive: [0, 58, 0] };
|
|
56
56
|
/** The band as humans read it — derived, never hand-spelled, so the probe
|
|
57
57
|
* rejection reason, the backend's /api status and the degradation card can
|
|
58
58
|
* never disagree with the numbers actually enforced above. */
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/** When a soul field the host composes or reports is asked for: the composed AGENTS.md (feature
|
|
2
|
+
* soul-composed-instructions, `inspect --soul --instructions`) and the soul's own skills (feature soul-skills,
|
|
3
|
+
* `inspect --soul --skills`, `souls[0].skills`). The one gate module for both, shared by the renderer (whether the
|
|
4
|
+
* soul page asks) and the server (whether the ask reaches the CLI); DOM-free so the server can import it.
|
|
5
|
+
*
|
|
6
|
+
* A local soul: this computer's CLI advertises the feature. A routed soul (`--server`): the host answers, so this
|
|
7
|
+
* computer's CLI must also relay what each host reports about itself (feature server-probe-features: the roster
|
|
8
|
+
* group's `probe.features`, the host's own `version --json` features), and the host's list must name the feature.
|
|
9
|
+
* Only an array counts: `features: null` (an older host, or a list the kernel would not relay) and a group with no
|
|
10
|
+
* `features` key (a failed roster read) are unknown, and unknown is not supported. Never decided from a refusal
|
|
11
|
+
* (`E_REMOTE_INCOMPATIBLE`) and never by probing: the roster row is the answer. */
|
|
12
|
+
export const COMPOSED_FEATURE = 'soul-composed-instructions';
|
|
13
|
+
export const SKILLS_FEATURE = 'soul-skills';
|
|
14
|
+
export const PROBE_FEATURES_FEATURE = 'server-probe-features';
|
|
15
|
+
|
|
16
|
+
const advertises = (cli, feature) => !!cli?.ok && Array.isArray(cli.features) && cli.features.includes(feature);
|
|
17
|
+
/** A roster group's host advertises `feature`: its last roster read succeeded and its own list names it. Only the
|
|
18
|
+
* host's half: each caller pairs it with this CLI's routed gate for that feature. */
|
|
19
|
+
export function hostAdvertises(group, feature) {
|
|
20
|
+
const probe = group?.probe;
|
|
21
|
+
return probe?.ok === true && Array.isArray(probe.features) && probe.features.includes(feature);
|
|
22
|
+
}
|
|
23
|
+
/** This computer's CLI composes a soul's AGENTS.md on request. */
|
|
24
|
+
export const composedSupported = cli => advertises(cli, COMPOSED_FEATURE);
|
|
25
|
+
/** This computer's CLI can route the request and relays the hosts' own feature lists in the roster. */
|
|
26
|
+
export const routedComposedSupported = cli => composedSupported(cli) && advertises(cli, PROBE_FEATURES_FEATURE);
|
|
27
|
+
/** A roster group's host composes: its last roster read succeeded and its own list names the feature. */
|
|
28
|
+
export const hostComposes = (cli, group) => routedComposedSupported(cli) && hostAdvertises(group, COMPOSED_FEATURE);
|
|
29
|
+
/** This computer's CLI reports a soul's own skills on request. */
|
|
30
|
+
export const skillsSupported = cli => advertises(cli, SKILLS_FEATURE);
|
|
31
|
+
/** This computer's CLI can route the skills request and relays the hosts' own feature lists in the roster. */
|
|
32
|
+
export const routedSkillsSupported = cli => skillsSupported(cli) && advertises(cli, PROBE_FEATURES_FEATURE);
|
|
33
|
+
/** A roster group's host reports a soul's skills: its last roster read succeeded and its own list names the feature. */
|
|
34
|
+
export const hostReportsSkills = (cli, group) => routedSkillsSupported(cli) && hostAdvertises(group, SKILLS_FEATURE);
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
/** The inspect boundary: one soul's or one instance home's inspection (`oats inspect --json`), through the
|
|
2
|
+
* kernel's resolver, never a client's copy. A client makes one and asks it:
|
|
3
|
+
*
|
|
4
|
+
* createInspectBoundary({ invoke, cache, maxAge, exec }) -> { inspect(request, context) }
|
|
5
|
+
*
|
|
6
|
+
* invoke the CLI call (cli-adapter.mjs `cliCapability`, the default)
|
|
7
|
+
* cache an inspect cache the client made (inspect-cache.mjs `createInspectCache`); null: every inspect
|
|
8
|
+
* reaches the CLI
|
|
9
|
+
* maxAge seconds the kernel may reuse remote observations on a miss (a local inspect only)
|
|
10
|
+
* exec how the CLI is run (cli-adapter.mjs `runJson`'s `io.exec`); without it, execFile
|
|
11
|
+
*
|
|
12
|
+
* request { action: 'inspect', selector: { soul, agentsRoot } | { home }, refresh?, instructions?, skills? }
|
|
13
|
+
* context { workspace, cli, agents, instances, localCwd, catalogKey }
|
|
14
|
+
*
|
|
15
|
+
* It resolves the kernel's result with `observedAt` and `refreshing`, and throws an Error with a stable `code`
|
|
16
|
+
* (and, for a host's refusal, a `reason`; for a refusal whose details name team labels, those `labels`).
|
|
17
|
+
*
|
|
18
|
+
* The boundary HOLDS NOTHING: what it keeps between calls is the cache it is given, which the client owns. A
|
|
19
|
+
* client may make one boundary and keep it (the TUI: its own exec and cache) or make one per call (the
|
|
20
|
+
* Desktop's capabilities.mjs, with the backend's cache): both are the same boundary only while that holds.
|
|
21
|
+
* Never add a field, a map or a flight here; put it in the cache, or in a factory the client owns.
|
|
22
|
+
*
|
|
23
|
+
* The admission (`capabilityAdmission`: which workspace, which CLI, which action and flags, which one soul or
|
|
24
|
+
* home) and the refusal of a failed answer (`capabilityFailure`) are this module's too, and the Desktop's
|
|
25
|
+
* provider operations (capabilities.mjs, `run`) call the same two: a request is admitted one way, whatever it asks. */
|
|
26
|
+
import { dirname } from 'node:path';
|
|
27
|
+
import { cliCapability, operationArgs } from './cli-adapter.mjs';
|
|
28
|
+
import { inspectKey } from './inspect-cache.mjs';
|
|
29
|
+
import { observationData } from './deployment-data.mjs';
|
|
30
|
+
import { OBSERVE_MAX_AGE_FEATURE } from './deployment-contract.mjs';
|
|
31
|
+
import { hostComposes, hostReportsSkills } from './composed-gate.mjs';
|
|
32
|
+
import { canAddressRemote, unaddressableSentence, hostReason, shownLabel, unroutableReason } from './remote-address.mjs';
|
|
33
|
+
|
|
34
|
+
const fail = (message, code = 'E_BAD_ARGS') => { throw Object.assign(new Error(message), { code }); };
|
|
35
|
+
|
|
36
|
+
const TEAM_LABEL = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
|
|
37
|
+
|
|
38
|
+
/** Admit a capability request in its context, or throw. `actions`: the actions the caller serves (an inspect
|
|
39
|
+
* boundary serves only 'inspect'); any other is the same refusal as an unknown one. Returns what the call needs:
|
|
40
|
+
* `{ action, server, label, refresh, instructions, skills, soul, agentsRoot, home, context, key }`, where
|
|
41
|
+
* `context` is the --dir the CLI runs in and `key` the inspect cache's key for the subject. */
|
|
42
|
+
export function capabilityAdmission(request, { workspace, cli, agents = [], instances = [], catalogKey = null }, actions = ['inspect', 'run']) {
|
|
43
|
+
if (!workspace) fail('Select a known workspace', 'E_WORKSPACE_UNKNOWN');
|
|
44
|
+
// The probe integer is the gate (operationsApi 2: inspect on the workspace model).
|
|
45
|
+
if (!cli?.ok || cli.operationsApi !== 2) {
|
|
46
|
+
fail('Update the installed OATS CLI (inspection needs operations API 2)', 'cli-no-operations');
|
|
47
|
+
}
|
|
48
|
+
const server = workspace.server || undefined;
|
|
49
|
+
// A remote workspace's refusals carry a structured reason (remote-address.mjs) naming the server.
|
|
50
|
+
const label = workspace.name || server;
|
|
51
|
+
if (workspace.remote && (!server || !workspace.registrationPresent || !cli.remote?.includes('operations'))) {
|
|
52
|
+
const error = Object.assign(new Error('This workspace needs a registered server and remote operations support'), { code: 'cli-no-operations' });
|
|
53
|
+
// This computer's OATS can't route inspection to a registered server: nothing was sent.
|
|
54
|
+
if (server && workspace.registrationPresent) error.reason = unroutableReason(label);
|
|
55
|
+
throw error;
|
|
56
|
+
}
|
|
57
|
+
const { action, selector = {} } = request;
|
|
58
|
+
// Read-only plus provider operations: a v2 soul is edited in its repository,
|
|
59
|
+
// and workspace model v2 removed `oats use` (capabilities are declared).
|
|
60
|
+
if (!actions.includes(action)) fail('Unknown capability action');
|
|
61
|
+
// Declared operation arguments only travel with a run (the kernel refuses undeclared ones).
|
|
62
|
+
if (request.args !== undefined && (action !== 'run' || !operationArgs(request.args))) fail('Invalid operation arguments');
|
|
63
|
+
// refresh (bypass the cached observation) is an inspect concern only.
|
|
64
|
+
if (request.refresh !== undefined && (action !== 'inspect' || typeof request.refresh !== 'boolean')) fail('Invalid refresh flag');
|
|
65
|
+
const refresh = request.refresh === true;
|
|
66
|
+
// instructions (feature soul-composed-instructions): a soul's composed AGENTS.md, inspect of a soul only. The
|
|
67
|
+
// adapter sends it only to a CLI whose probe advertises it. Routed, it travels only when this client's roster row
|
|
68
|
+
// for the workspace says the host composes (composed-gate.mjs: the host's own probe.features, relayed by a CLI with
|
|
69
|
+
// server-probe-features); otherwise it is dropped and the read is today's. The renderer's ask is never the proof.
|
|
70
|
+
if (request.instructions !== undefined && (action !== 'inspect' || typeof request.instructions !== 'boolean' || selector.soul === undefined)) fail('Invalid instructions flag');
|
|
71
|
+
const instructions = request.instructions === true && (!server || hostComposes(cli, workspace.group));
|
|
72
|
+
// skills (feature soul-skills): a soul's own skills (`souls[0].skills`), inspect of a soul only, gated the same way:
|
|
73
|
+
// the adapter sends it only to a CLI that advertises it, and routed only when the held roster row says the host
|
|
74
|
+
// reports them (composed-gate.mjs hostReportsSkills); otherwise it is dropped and the read is today's.
|
|
75
|
+
if (request.skills !== undefined && (action !== 'inspect' || typeof request.skills !== 'boolean' || selector.soul === undefined)) fail('Invalid skills flag');
|
|
76
|
+
const skills = request.skills === true && (!server || hostReportsSkills(cli, workspace.group));
|
|
77
|
+
let soul, agentsRoot, home, key;
|
|
78
|
+
let context = workspace.scope;
|
|
79
|
+
if (selector.home !== undefined) {
|
|
80
|
+
if (selector.soul !== undefined || selector.agentsRoot !== undefined || selector.context !== undefined) fail('Select a soul or an instance home');
|
|
81
|
+
const matches = instances.filter(i => i.home === selector.home);
|
|
82
|
+
if (matches.length !== 1) fail('Select one existing home in this workspace');
|
|
83
|
+
const instance = matches[0];
|
|
84
|
+
if (server && !canAddressRemote(instance)) fail(unaddressableSentence({ ...instance, repoName: workspace.name || server }), 'E_SNAPSHOT_UNKNOWN');
|
|
85
|
+
home = instance.home;
|
|
86
|
+
// The owning agents root and the recorded work repository may differ.
|
|
87
|
+
// --home is authoritative; the CLI derives its captured context.
|
|
88
|
+
context = undefined;
|
|
89
|
+
// Identity coordinates: a restarted or re-spawned seat under the same home is another subject.
|
|
90
|
+
key = inspectKey({ deployment: workspace.scope, server, kind: 'home', home, instance: instance.instance,
|
|
91
|
+
identity: [instance.createdAt, instance.startedAt, instance.soul, instance.modules] });
|
|
92
|
+
} else if (selector.soul !== undefined) {
|
|
93
|
+
const matches = agents.filter(a => a.name === selector.soul && a.agentsRoot === selector.agentsRoot);
|
|
94
|
+
if (matches.length !== 1) fail('Select one soul and its agents root in this workspace');
|
|
95
|
+
const agent = matches[0];
|
|
96
|
+
soul = agent.name; agentsRoot = agent.agentsRoot;
|
|
97
|
+
context = dirname(agentsRoot);
|
|
98
|
+
key = inspectKey({ deployment: workspace.scope, server, kind: 'soul', soul, agentsRoot, catalogKey, instructions, skills });
|
|
99
|
+
} else fail('Select a soul or an instance home (inspection has no scope subject)');
|
|
100
|
+
return { action, server, label, refresh, instructions, skills, soul, agentsRoot, home, context, key };
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** The CLI call's options for an admitted request (cli-adapter.mjs `cliCapability`). */
|
|
104
|
+
export function capabilityCall(request, { action, server, refresh, instructions, skills, soul, agentsRoot, home, context }, { workspace, cli, localCwd, maxAge }) {
|
|
105
|
+
return {
|
|
106
|
+
action, context, server, soul, agentsRoot, home,
|
|
107
|
+
operation: request.operation, ...(request.args !== undefined ? { args: request.args } : {}), ...(instructions ? { instructions } : {}),
|
|
108
|
+
...(skills ? { skills } : {}),
|
|
109
|
+
localCwd: server ? localCwd : context || workspace.scope,
|
|
110
|
+
// --max-age travels only on a LOCAL inspect (reuse is local only: the kernel refuses it with --server)
|
|
111
|
+
// and only when the probe declared observe-max-age (the adapter's call).
|
|
112
|
+
...(action === 'inspect' && !server && (refresh || maxAge !== undefined) ? { maxAge: refresh ? 0 : maxAge } : {}),
|
|
113
|
+
features: cli.features,
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** The Error a failed answer is thrown as, for an admitted request's `server` and `label`. */
|
|
118
|
+
export function capabilityFailure(envelope, { server, label }) {
|
|
119
|
+
const code = envelope.error?.code || 'E_OPERATION_FAILED';
|
|
120
|
+
const error = Object.assign(new Error(envelope.error?.message || 'Capability operation failed'), { code });
|
|
121
|
+
// A host's (or the remote transport's) refusal: its code verbatim, a headline naming the server and the
|
|
122
|
+
// kernel's message through the display filter (hostReason; null for a code not in the kernel's shape).
|
|
123
|
+
const reason = server ? hostReason({ code, message: envelope.error?.message }, label, `${shownLabel(label, true)} refused this request.`) : null;
|
|
124
|
+
if (reason) error.reason = reason;
|
|
125
|
+
// The team labels a refusal's details name (the teams contract's conflict, sent by kernels before 0.30) travel
|
|
126
|
+
// with it, bounded: 2 to 16, each a team label. Which codes a client reads them for is the client's own.
|
|
127
|
+
const labels = envelope.error?.details?.labels;
|
|
128
|
+
if (Array.isArray(labels) && labels.length >= 2 && labels.length <= 16
|
|
129
|
+
&& labels.every(l => typeof l === 'string' && TEAM_LABEL.test(l))) error.labels = [...labels];
|
|
130
|
+
return error;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
export function createInspectBoundary({ invoke = cliCapability, cache = null, maxAge, exec } = {}) {
|
|
134
|
+
const io = exec ? { exec } : {};
|
|
135
|
+
return {
|
|
136
|
+
async inspect(request, context) {
|
|
137
|
+
const { workspace, cli, localCwd } = context;
|
|
138
|
+
const admitted = capabilityAdmission(request, context, ['inspect']);
|
|
139
|
+
const { server, refresh, key } = admitted;
|
|
140
|
+
const call = () => invoke(cli.bin, capabilityCall(request, admitted, { workspace, cli, localCwd, maxAge }), io);
|
|
141
|
+
let envelope, observedAt, refreshing = false;
|
|
142
|
+
if (cache) {
|
|
143
|
+
// A remote workspace has no state key and no invalidation signal here: its inspections are shared
|
|
144
|
+
// between concurrent requests but never served from an earlier visit (store: false).
|
|
145
|
+
// Live (observes the remotes afresh): a refresh, a routed inspect (reuse is local only, so it never carries
|
|
146
|
+
// --max-age), or any read on a kernel without the feature. A refresh joins only a live flight.
|
|
147
|
+
const live = refresh || !!server || !(Array.isArray(cli.features) && cli.features.includes(OBSERVE_MAX_AGE_FEATURE));
|
|
148
|
+
({ envelope, observedAt, refreshing } = await cache.read(key, { deployment: workspace.scope, refresh, produce: call, store: !server, live }));
|
|
149
|
+
} else {
|
|
150
|
+
envelope = await call();
|
|
151
|
+
if (envelope.ok) observedAt = observationData(envelope).observedAt ?? new Date().toISOString();
|
|
152
|
+
}
|
|
153
|
+
if (!envelope.ok) throw capabilityFailure(envelope, admitted);
|
|
154
|
+
return { ...envelope.result, observedAt, refreshing };
|
|
155
|
+
},
|
|
156
|
+
};
|
|
157
|
+
}
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
/** A bounded, coalescing cache of `oats inspect` envelopes, keyed by the exact
|
|
2
|
+
subject (deployment, server, soul+catalog or home+instance identity). Only
|
|
3
|
+
successful envelopes are kept; a provider run invalidates its deployment
|
|
4
|
+
because it can change what `inspect --home` reports. A read may ask to
|
|
5
|
+
coalesce without holding (`store: false`): a remote workspace has no state
|
|
6
|
+
key and no invalidation signal on this machine, so its inspections are
|
|
7
|
+
never served from an earlier visit, only shared between concurrent ones.
|
|
8
|
+
The kernel's observation stamp is decoded by observationData, bounded; an
|
|
9
|
+
entry is served for at most `ttlMs` after it was stored, then re-read: it
|
|
10
|
+
bounds what no key can see (teams changed on the messaging side, the
|
|
11
|
+
launch choice this machine would make now). */
|
|
12
|
+
import { observationData } from './deployment-data.mjs';
|
|
13
|
+
import { HELD_TTL_MS } from './keyed-catalog.mjs';
|
|
14
|
+
|
|
15
|
+
export const INSPECT_CACHE_LIMIT = 256;
|
|
16
|
+
/** How long a held inspection may be served: the same bound as the catalogs (keyed-catalog HELD_TTL_MS). */
|
|
17
|
+
export const INSPECT_CACHE_TTL_MS = HELD_TTL_MS;
|
|
18
|
+
|
|
19
|
+
/** Every field travels, absent ones as null: two subjects that differ in any
|
|
20
|
+
coordinate never share an entry (same soul name under two agents roots, the
|
|
21
|
+
same home before and after a restart, a catalog that changed under a soul). */
|
|
22
|
+
export function inspectKey({ deployment, server = null, kind, soul, agentsRoot, catalogKey, home, instance, identity, instructions = false, skills = false }) {
|
|
23
|
+
if (kind !== 'soul' && kind !== 'home') throw Object.assign(new Error('Inspect cache keys name a soul or a home'), { code: 'E_BAD_ARGS' });
|
|
24
|
+
const part = value => value === undefined ? null : value;
|
|
25
|
+
return JSON.stringify([part(deployment), part(server), kind, part(soul), part(agentsRoot), part(catalogKey), part(home), part(instance),
|
|
26
|
+
Array.isArray(identity) ? identity.map(part) : part(identity), instructions === true, skills === true]);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function createInspectCache({ limit = INSPECT_CACHE_LIMIT, ttlMs = INSPECT_CACHE_TTL_MS, now = () => Date.now() } = {}) {
|
|
30
|
+
// Map iteration order is insertion order; a hit re-inserts, so the first key is the LRU.
|
|
31
|
+
const entries = new Map();
|
|
32
|
+
const flights = new Map();
|
|
33
|
+
// Per-deployment epochs: a flight stores its result only if nobody invalidated
|
|
34
|
+
// its deployment while it was in the air (the run may have changed the subject).
|
|
35
|
+
const epochs = new Map();
|
|
36
|
+
const epoch = deployment => epochs.get(deployment) || 0;
|
|
37
|
+
const stamp = ms => new Date(ms).toISOString();
|
|
38
|
+
|
|
39
|
+
function store(key, entry) {
|
|
40
|
+
entries.delete(key); entries.set(key, entry);
|
|
41
|
+
while (entries.size > limit) entries.delete(entries.keys().next().value);
|
|
42
|
+
}
|
|
43
|
+
function start(key, deployment, produce, { live, keep }) {
|
|
44
|
+
const startedAt = epoch(deployment);
|
|
45
|
+
epochs.set(deployment, startedAt); // registered, so clear() can bump a deployment that is only in flight
|
|
46
|
+
const flight = (async () => {
|
|
47
|
+
const envelope = await produce();
|
|
48
|
+
if (!envelope?.ok) return { envelope, observedAt: stamp(now()) };
|
|
49
|
+
const observedAt = observationData(envelope).observedAt ?? stamp(now()); // a malformed stamp is no stamp
|
|
50
|
+
if (keep && epoch(deployment) === startedAt) store(key, { envelope, observedAt, deployment, at: now() });
|
|
51
|
+
return { envelope, observedAt };
|
|
52
|
+
})();
|
|
53
|
+
flight.live = live; // a refresh joins only a live flight: a background one may carry heads up to maxAge old
|
|
54
|
+
flights.set(key, flight);
|
|
55
|
+
flight.finally(() => { if (flights.get(key) === flight) flights.delete(key); }).catch(() => {});
|
|
56
|
+
return flight;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
return {
|
|
60
|
+
/** `live`: the flight this read would start observes the remotes afresh (a refresh, or any read on a
|
|
61
|
+
* kernel without observe-max-age); a refresh joins only a live flight. */
|
|
62
|
+
async read(key, { deployment, refresh = false, produce, store: keep = true, live = refresh }) {
|
|
63
|
+
const settled = entries.get(key);
|
|
64
|
+
// An entry past its TTL is a miss (dropped, re-read now), not a stale hit.
|
|
65
|
+
if (settled && now() - settled.at >= ttlMs) entries.delete(key);
|
|
66
|
+
else if (settled && !refresh) {
|
|
67
|
+
store(key, settled);
|
|
68
|
+
return { envelope: structuredClone(settled.envelope), observedAt: settled.observedAt, hit: true, refreshing: flights.has(key) };
|
|
69
|
+
}
|
|
70
|
+
// Identical concurrent requests share one kernel process; a refresh shares only a live one.
|
|
71
|
+
const inFlight = flights.get(key);
|
|
72
|
+
const flight = inFlight && (!refresh || inFlight.live) ? inFlight : start(key, deployment, produce, { live: live || refresh, keep });
|
|
73
|
+
const { envelope, observedAt } = await flight;
|
|
74
|
+
return { envelope: structuredClone(envelope), observedAt, hit: false, refreshing: false };
|
|
75
|
+
},
|
|
76
|
+
invalidate(deployment) {
|
|
77
|
+
epochs.set(deployment, epoch(deployment) + 1);
|
|
78
|
+
for (const [key, entry] of entries) if (entry.deployment === deployment) entries.delete(key);
|
|
79
|
+
},
|
|
80
|
+
clear() {
|
|
81
|
+
for (const deployment of epochs.keys()) epochs.set(deployment, epoch(deployment) + 1);
|
|
82
|
+
entries.clear();
|
|
83
|
+
},
|
|
84
|
+
size: () => entries.size,
|
|
85
|
+
};
|
|
86
|
+
}
|