@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.
Files changed (64) hide show
  1. package/bin/oats.mjs +18 -10
  2. package/docs/configuration.md +17 -27
  3. package/docs/desktop-cli-api.md +59 -3
  4. package/docs/desktop.md +25 -4
  5. package/docs/execution-targets.md +6 -1
  6. package/docs/implementation.md +106 -5
  7. package/docs/integrations.md +8 -4
  8. package/docs/knowledge.md +93 -38
  9. package/docs/official-catalog.md +3 -3
  10. package/docs/packages.md +12 -12
  11. package/docs/release-notes/v0.57.0.md +283 -0
  12. package/docs/release-notes/v0.57.1.md +275 -0
  13. package/docs/schedules.md +8 -3
  14. package/docs/servers.md +18 -0
  15. package/docs/souls-and-instances.md +126 -15
  16. package/docs/tui.md +333 -95
  17. package/docs/workspaces.md +2 -2
  18. package/lib/core.mjs +439 -126
  19. package/lib/instance-lifecycle.mjs +45 -9
  20. package/lib/session-viewer.mjs +29 -4
  21. package/lib/worktree.mjs +23 -2
  22. package/package-catalog.json +2 -2
  23. package/package.json +1 -1
  24. package/packages/client/cli-adapter.mjs +9 -7
  25. package/packages/client/cli-locator.mjs +2 -2
  26. package/packages/client/composed-gate.mjs +34 -0
  27. package/packages/client/inspect-boundary.mjs +157 -0
  28. package/packages/client/inspect-cache.mjs +86 -0
  29. package/packages/client/instance-lifecycle.mjs +10 -3
  30. package/packages/client/keyed-catalog.mjs +132 -0
  31. package/packages/client/launch-prompt-outcome.mjs +1 -1
  32. package/packages/client/launch-view.mjs +46 -0
  33. package/packages/client/session-attach.mjs +7 -5
  34. package/packages/client/soul-catalog.mjs +77 -0
  35. package/packages/client/soul-colors.mjs +31 -0
  36. package/packages/client/soul-facts.mjs +85 -0
  37. package/packages/client/soul-rows.mjs +48 -0
  38. package/packages/client/spawn-apply-cli.mjs +11 -6
  39. package/packages/client/spawn-apply.mjs +212 -0
  40. package/packages/client/spawn-messages.mjs +131 -85
  41. package/packages/client/spawn-preview-contract.mjs +3 -0
  42. package/packages/client/spawn-preview-facts.mjs +119 -0
  43. package/packages/client/spawn-preview.mjs +152 -0
  44. package/packages/client/spawn-transaction.mjs +136 -0
  45. package/packages/tui/README.md +43 -13
  46. package/packages/tui/lib/actions.mjs +18 -2
  47. package/packages/tui/lib/client.mjs +4 -0
  48. package/packages/tui/lib/config.mjs +9 -14
  49. package/packages/tui/lib/main.mjs +241 -55
  50. package/packages/tui/lib/model.mjs +230 -29
  51. package/packages/tui/lib/panel.mjs +955 -0
  52. package/packages/tui/lib/read.mjs +134 -24
  53. package/packages/tui/lib/store.mjs +184 -31
  54. package/packages/tui/lib/term/capture.mjs +260 -0
  55. package/packages/tui/lib/term/screen.mjs +44 -8
  56. package/packages/tui/lib/term/style.mjs +78 -6
  57. package/packages/tui/lib/term/text.mjs +24 -4
  58. package/packages/tui/lib/term/through.mjs +213 -0
  59. package/packages/tui/lib/term/tty.mjs +7 -60
  60. package/packages/tui/lib/views/act.mjs +85 -0
  61. package/packages/tui/lib/views/frame.mjs +153 -37
  62. package/packages/tui/lib/views/help.mjs +22 -14
  63. package/skills/oats-getting-started/SKILL.md +4 -3
  64. package/packages/tui/lib/open.mjs +0 -45
@@ -70,6 +70,11 @@ export const APPLY_WAIT_MS = 600_000;
70
70
  * clock the wall clock (ms since the epoch), for when a running apply started (`running.since`)
71
71
  * after `after(ms, fn)` runs fn once after ms and answers a cancel; mint the reference and key maker
72
72
  * terms the client's own (client-terms.mjs): every reason is worded with them; required
73
+ * exec optional: the client's own execFile, passed to `invoke` as `invoke(bin, args, { exec })` for the plan
74
+ * read and for the apply alike; without it `invoke` is given no third argument and cliLifecycle's own
75
+ * defaults run. A given exec runs every call cliLifecycle hands it; one with `detached: true` is an apply,
76
+ * which it runs in a session of its own (as execFileInSession does) and never ends, neither at a deadline
77
+ * nor by a signal to its group.
73
78
  * An apply's answer is awaited APPLY_WAIT_MS. When that passes the boundary answers `unknown` and the apply stays
74
79
  * in flight here: its reference, its key, its place as the one apply. Its answer, whenever it comes, is read and
75
80
  * kept 30 minutes like any other; the same reference meanwhile is answered at once (`unknown` while it runs, the
@@ -84,8 +89,10 @@ export const APPLY_WAIT_MS = 600_000;
84
89
  * the workspace's roster group (its `probe` says which features a routed command's host answers with,
85
90
  * lifecycle-contract.mjs `answeringFeatures`); `instances` are that deployment's own rows. */
86
91
  export function createLifecycleBoundary({ invoke = cliLifecycle, now = () => performance.now(), clock = () => Date.now(), mint = () => randomBytes(32).toString('hex'),
87
- after = (ms, fn) => { const timer = setTimeout(fn, ms); timer.unref?.(); return () => clearTimeout(timer); }, terms } = {}) {
92
+ after = (ms, fn) => { const timer = setTimeout(fn, ms); timer.unref?.(); return () => clearTimeout(timer); }, terms, exec } = {}) {
88
93
  requireTerms(terms, 'createLifecycleBoundary');
94
+ // The CLI call, with the client's exec when it gave one: the same exec for a plan read and an apply.
95
+ const call = (bin, args) => (exec ? invoke(bin, args, { exec }) : invoke(bin, args));
89
96
  const plans = new Map(), actions = new Map(), reads = new Map(), beforeEffect = new Set(BEFORE_EFFECT_CODES);
90
97
  let reservedPlans = 0, activeApply = null;
91
98
  const sweep = () => { for (const map of [plans, actions]) for (const [key, value] of map) {
@@ -122,7 +129,7 @@ export function createLifecycleBoundary({ invoke = cliLifecycle, now = () => per
122
129
  if (!reads.has(key)) {
123
130
  const args = { operation: request.operation, phase: 'plan', instance: selected.target.instance, home: selected.target.home, context: selected.context,
124
131
  ...(selected.remote ? { server: selected.remote.server } : {}), choices };
125
- const pending = Promise.resolve().then(() => invoke(selected.bin, args)).catch(() => ({ ok: false, error: { code: 'E_CLI_FAILED' } })).finally(() => reads.delete(key));
132
+ const pending = Promise.resolve().then(() => call(selected.bin, args)).catch(() => ({ ok: false, error: { code: 'E_CLI_FAILED' } })).finally(() => reads.delete(key));
126
133
  reads.set(key, pending);
127
134
  }
128
135
  reservedPlans++;
@@ -202,7 +209,7 @@ export function createLifecycleBoundary({ invoke = cliLifecycle, now = () => per
202
209
  const args = { operation: entry.plan.action, phase: 'apply', instance: entry.target.instance, home: entry.target.home,
203
210
  context: entry.context, ...(entry.remote ? { server: entry.remote.server } : {}), choices: clone(entry.choices), revision: entry.plan.planRevision, key: entry.key };
204
211
  let cancel = () => {};
205
- const answered = Promise.resolve().then(() => invoke(entry.bin, args)).then(result => interpret(result, entry, current.features))
212
+ const answered = Promise.resolve().then(() => call(entry.bin, args)).then(result => interpret(result, entry, current.features))
206
213
  .catch(() => denied('E_OUTCOME_UNKNOWN', entry.target, { status: 'unknown', planRef: entry.id }))
207
214
  .then(result => { entry.reply = clone(result); return result; })
208
215
  .finally(() => { cancel(); entry.pending = null; entry.waited = null; entry.expires = now() + 30 * 60_000; if (activeApply === entry) activeApply = null; });
@@ -0,0 +1,132 @@
1
+ /** One kernel-read document per deployment, held under the KEY of the workspace state it was
2
+ * read under, re-read only when that key moves. The souls catalog and the capabilities table are
3
+ * two instances of this; the invariants live here once:
4
+ *
5
+ * - One flight per deployment at a time; a newer keyed flight replaces the map entry and the
6
+ * older promise still settles (its result lands under its own key).
7
+ * - A failed read keeps the last good value with the failure next to it (a stale table beats an
8
+ * empty view) and is retried only after `retryMs`.
9
+ * - `prefetch` starts a read UNBOUND (key null) before the workspace state is known, so a cold
10
+ * cycle runs it alongside the roster reads. Cold means NOTHING is held for the deployment (or
11
+ * what is held is a failure past its retry window): a value that landed unbound, good or failed,
12
+ * is held and stops further prefetches for its window, so a deployment whose roster reads keep
13
+ * failing costs one read, not one per cycle. `settle` binds the state's key to the unbound
14
+ * flight — still in the air or already landed — but ONLY when both belong to the same cycle:
15
+ * every prefetch opens a cycle, and a flight started by an older prefetch (its roster reads
16
+ * failed) is never bound to a state it was not read under; that cycle reads under its key
17
+ * instead. A value held under null answers for no key, so it is never served as current.
18
+ * - `demand` is the request path with nothing good to show: it reads now (a same-key flight is
19
+ * joined), whatever the retry window says — the window throttles background cycles, never a
20
+ * user who is looking at a failure. `refresh` is a LIVE read: it joins only a live same-key
21
+ * flight, never a background one.
22
+ * - `observedAt` is the kernel's observation stamp when it reports one, else the read's
23
+ * completion time; a failure keeps the previous stamp.
24
+ * - Every held result has an AGE BOUND: `ttlMs` (HELD_TTL_MS, the background max-age) from the
25
+ * time it was stored. Past it the entry is `stale` — and that is REQUEST-DRIVEN: the cycle's
26
+ * `settle` still answers from a stale entry (age alone never starts a kernel run in the
27
+ * background; a `souls` plus an `oats capabilities` run per deployment every minute, focused or
28
+ * blurred, is exactly the churn the app must not cause), while a request that finds it stale
29
+ * answers at once and `revalidate`s: one single-flight re-read behind the answer, joined by
30
+ * every request until it lands. The key sees what `workspace status` reports; the TTL bounds
31
+ * what it cannot (local configuration edited outside Desktop: `oats teams`, `oats soul teams`,
32
+ * `oats sync` from a terminal) to "TTL + one read of the next time someone looks", without the
33
+ * Desktop naming or touching any deployment file — that is the kernel's to know.
34
+ *
35
+ * `read(deployment, cli, { maxAge })` is the catalog's kernel read; it resolves
36
+ * `{ value, reason, observedAt }` (value null on failure) and must not throw. */
37
+ import { OBSERVE_MAX_AGE_FEATURE } from './deployment-contract.mjs';
38
+
39
+ /** How long a held result may be served (catalogs and inspections alike): the background
40
+ * max-age, so nothing held is older than what a background poll would accept from the kernel. */
41
+ export const HELD_TTL_MS = 60_000;
42
+
43
+ export function createKeyedCatalog({ read, retryMs, ttlMs = HELD_TTL_MS, now = () => Date.now() }) {
44
+ const held = new Map(), flights = new Map(), cycles = new Map(), unbound = new Map(), current = new Map();
45
+ const iso = ms => new Date(ms).toISOString();
46
+ const inWindow = entry => !entry.reason || now() - entry.at < retryMs;
47
+ const fresh = entry => now() - entry.at < ttlMs;
48
+ /** A held entry answers a CYCLE for `key` while it is good (age is a request's concern), or its failure is inside the retry window. */
49
+ const answers = (last, key) => !!last && last.key === key && inWindow(last);
50
+ /** Anything held inside its window (bound or not) makes a prefetch pointless. */
51
+ const usable = last => !!last && inWindow(last);
52
+ /** Build the flight's entry and hold it — unless the flight is keyed and the key moved on while it
53
+ * flew (a newer settle/demand/refresh under another key has its own flight): then the newer state's
54
+ * entry is not overwritten. Either way the flight resolves with the entry IT built, so a request
55
+ * awaiting it is answered for the key it asked, not with whatever happens to be held. */
56
+ function land(deployment, flight, result) {
57
+ const last = held.get(deployment), at = now(), key = flight.key; // the key is read at completion: an adopted flight lands bound
58
+ const entry = result.value
59
+ ? { key, value: result.value, reason: null, at, observedAt: result.observedAt ?? iso(at) }
60
+ : { key, value: last?.value ?? null, reason: result.reason ?? { code: 'E_CLI_FAILED', message: '' }, at, observedAt: last?.observedAt ?? null };
61
+ const superseded = key !== null && current.has(deployment) && current.get(deployment) !== key;
62
+ if (!superseded) {
63
+ held.set(deployment, entry);
64
+ if (key === null) unbound.set(deployment, flight.cycle); else unbound.delete(deployment);
65
+ }
66
+ return entry;
67
+ }
68
+ function start(deployment, cli, key, maxAge) {
69
+ // Live = the kernel observes the remotes afresh: asked for (maxAge 0), or the only thing a kernel
70
+ // without observe-max-age can do — then a refresh joins the flight instead of starting a twin.
71
+ const live = maxAge === 0 || !(Array.isArray(cli?.features) && cli.features.includes(OBSERVE_MAX_AGE_FEATURE));
72
+ const flight = { key, live, cycle: cycles.get(deployment) ?? 0, promise: null };
73
+ // Dispatched synchronously: a prefetch's kernel process starts in the same tick as the roster reads.
74
+ let dispatched;
75
+ try { dispatched = Promise.resolve(read(deployment, cli, maxAge !== undefined ? { maxAge } : {})); } catch (error) { dispatched = Promise.reject(error); }
76
+ flight.promise = dispatched
77
+ .catch(() => ({ value: null, reason: { code: 'E_CLI_FAILED', message: '' }, observedAt: null }))
78
+ .then(result => ({ ...structuredClone(land(deployment, flight, result)), stale: false }))
79
+ .finally(() => { if (flights.get(deployment) === flight) flights.delete(deployment); });
80
+ flights.set(deployment, flight);
81
+ return flight;
82
+ }
83
+ const snapshot = deployment => { const entry = held.get(deployment); return entry ? { ...structuredClone(entry), stale: !fresh(entry) } : null; };
84
+ return {
85
+ /** Open a cycle; start an unbound read when nothing usable is held and nothing is in flight. */
86
+ prefetch(deployment, cli, { maxAge } = {}) {
87
+ cycles.set(deployment, (cycles.get(deployment) ?? 0) + 1);
88
+ if (flights.has(deployment) || usable(held.get(deployment))) return null;
89
+ return start(deployment, cli, null, maxAge).promise;
90
+ },
91
+ /** Bind this cycle's key: adopt the cycle's unbound flight (in flight or landed), answer from a
92
+ * held entry for the key, or start a keyed read. Synchronous: `pending` is what is still coming. */
93
+ settle(deployment, cli, key, { maxAge } = {}) {
94
+ const cycle = cycles.get(deployment) ?? 0, last = held.get(deployment);
95
+ current.set(deployment, key);
96
+ let flight = flights.get(deployment);
97
+ if (flight && flight.key === null && flight.cycle === cycle) flight.key = key;
98
+ if (last && last.key === null && unbound.get(deployment) === cycle) { last.key = key; unbound.delete(deployment); }
99
+ if (answers(last, key)) return { entry: snapshot(deployment), pending: null };
100
+ if (!flight || flight.key !== key) flight = start(deployment, cli, key, maxAge);
101
+ return { entry: snapshot(deployment), pending: flight.promise };
102
+ },
103
+ /** Read now for `key` (the request path with nothing good held): join a same-key flight, else
104
+ * start one with `maxAge`, ignoring the retry window. */
105
+ async demand(deployment, cli, key, { maxAge } = {}) {
106
+ current.set(deployment, key);
107
+ const flight = flights.get(deployment);
108
+ return (flight?.key === key ? flight : start(deployment, cli, key, maxAge)).promise;
109
+ },
110
+ /** The request path with a STALE good entry: start one same-key re-read behind the answer, or
111
+ * join the one in flight; never awaited by the caller, whose answer is the held entry with
112
+ * `refreshing`. Resolves with the landed entry for whoever attaches it — null when another
113
+ * key's flight is in the air (a cycle moved the state on and is reading it: that read answers,
114
+ * and starting a stale-key read beside it would displace it and cost a duplicate). */
115
+ revalidate(deployment, cli, key, { maxAge } = {}) {
116
+ const flight = flights.get(deployment);
117
+ if (flight) return flight.key === key ? flight.promise : null;
118
+ return start(deployment, cli, key, maxAge).promise;
119
+ },
120
+ /** A LIVE read for `key` (maxAge 0): joins only a live same-key flight; a background flight in
121
+ * the air is not it (its heads may be up to maxAge old), so a live one starts beside it. */
122
+ async refresh(deployment, cli, key) {
123
+ current.set(deployment, key);
124
+ const flight = flights.get(deployment);
125
+ return (flight?.key === key && flight.live ? flight : start(deployment, cli, key, 0)).promise;
126
+ },
127
+ held: snapshot,
128
+ refreshing(deployment) { return flights.has(deployment); },
129
+ forget(deployment) { held.delete(deployment); flights.delete(deployment); unbound.delete(deployment); current.delete(deployment); },
130
+ forgetAll() { held.clear(); flights.clear(); unbound.clear(); current.clear(); },
131
+ };
132
+ }
@@ -126,7 +126,7 @@ export function retainedSpawnMessage(d) {
126
126
  const p = launchPromptOutcome(d.launchPrompts);
127
127
  return `${d.instance} was retained: ${p.reason}.${inputNote(p)} Inspect its existing pane, then use oats session start --home for this home. Do not spawn again.`;
128
128
  }
129
- /** A Start or Restart of an existing home that stopped at a launch prompt, in the Desktop's words: the
129
+ /** A Start or Restart of an existing home that stopped at a launch prompt, in the clients' words: the
130
130
  * kernel answers E_SPAWN_INCOMPLETE with the same retained details as a spawn. `instance` is the name the
131
131
  * dialog started; `d` the decoded details. It claims the weaker thing for both statuses: a blocked start and
132
132
  * one whose completion was not seen are both "not confirmed", never "failed" and never "started". */
@@ -0,0 +1,46 @@
1
+ /** Soul launch preferences in words (feature `launch-preference`, OATS 0.30; the decoded Launch
2
+ * from launch-contract.mjs). One vocabulary for the soul page, the soul side panel, the spawn
3
+ * grid and the spawn dialog: the EFFECTIVE harness and model, where that choice came from, where
4
+ * to change it, and the soul's own preference only when this computer runs something else. */
5
+
6
+ /** A kernel `at` in words: `[<repoKey>:]<file>#/<json pointer>` → "oats-workspace.yaml ›
7
+ * teams › engineering, in <repoKey>"; a file with no repo is this computer's; `package:<id>:` is
8
+ * that package's. Pointer segments are unescaped (`~1` is `/`, `~0` is `~`). Unrecognised: as sent. */
9
+ export function declaredIn(at) {
10
+ const m = /^(?:(.+):)?([^:#/][^:#]*)#\/(.+)$/.exec(at);
11
+ if (!m) return at;
12
+ const where = `${m[2]} › ${m[3].split('/').map(p => p.replace(/~1/g, '/').replace(/~0/g, '~')).join(' › ')}`;
13
+ const pkg = /^package:(.+)$/.exec(m[1] ?? '');
14
+ return pkg ? `${where}, in the ${pkg[1]} package` : m[1] ? `${where}, in ${m[1]}` : `${where}, on this computer`;
15
+ }
16
+
17
+ const NAMES = Object.freeze({ pi: 'Pi', claude: 'Claude Code', codex: 'Codex' });
18
+ export const launchHarnessName = value => Object.hasOwn(NAMES, value) ? NAMES[value] : value;
19
+
20
+ /** Where the effective launch came from (Launch.from), in words. */
21
+ export const LAUNCH_FROM = Object.freeze({
22
+ __proto__: null,
23
+ flag: 'chosen for this spawn',
24
+ local: 'set for this soul on this computer',
25
+ 'local-default': "this computer's default for every soul",
26
+ soul: "the soul's preference",
27
+ host: 'no preference set: the host default',
28
+ recorded: 'recorded when it was spawned',
29
+ });
30
+ export const launchFromText = from => LAUNCH_FROM[from] ?? `from: ${from}`;
31
+
32
+ /** The feature gate: every launch view reads `launch` only from a kernel that declares it. */
33
+ export const launchFeature = cli => Array.isArray(cli?.features) && cli.features.includes('launch-preference');
34
+ /** The decoded Launch to show, or null (no feature, or none reported). */
35
+ export const shownLaunch = (launch, cli) => launchFeature(cli) && launch && typeof launch === 'object' && launch.effective ? launch : null;
36
+
37
+ /** A model in words: the id as sent, or the harness's own when null. */
38
+ export const launchModelText = ({ harness, model }) => model ?? `${launchHarnessName(harness)}'s default model`;
39
+ /** "Claude Code · claude-opus-5-5" for a preference or an effective launch. */
40
+ export const preferenceText = p => `${launchHarnessName(p.harness)} · ${launchModelText(p)}`;
41
+ /** True when the soul declares a preference and this computer runs something else. */
42
+ export const declaredDiffers = l => !!l.declared && (l.declared.harness !== l.effective.harness || l.declared.model !== l.effective.model);
43
+ /** "Set in …": where the deciding value lives (Launch.at), or null (a flag, the host default). */
44
+ export const launchAtText = at => typeof at === 'string' && at ? `Set in ${declaredIn(at)}` : null;
45
+ /** The soul's own preference, said beside an effective launch that differs from it. */
46
+ export const declaredText = l => declaredDiffers(l) ? `The soul prefers ${preferenceText(l.declared)}; this computer runs ${launchHarnessName(l.effective.harness)}${l.declared.harness === l.effective.harness ? ` with ${launchModelText(l.effective)}` : ''}.` : null;
@@ -61,9 +61,11 @@ function envelopeOf(stdout) {
61
61
  return envelope?.schemaVersion === 1 && typeof envelope.ok === 'boolean' ? envelope : null;
62
62
  }
63
63
  /** What a refusal said, for each error `refusal` returns from its last line: the envelope's own
64
- * `code`, `message` and `details.fix`, each null where it gave no string. Kept beside the error and
65
- * not on it, so the error thrown has the properties it always had; read by `preflightFailure` only. */
66
- const keptRefusals = new WeakMap();
64
+ * `code`, `message` and `details.fix`, each null where it gave no string. Kept on the error under this
65
+ * module's own symbol, not enumerable and not writable, so the error thrown has the enumerable
66
+ * properties it always had, the module holds no state, and an error made by hand (or a copy of one)
67
+ * carries none; read by `preflightFailure` only. */
68
+ const KEPT_REFUSAL = Symbol('kept refusal');
67
69
  const stringOrNull = value => (typeof value === 'string' ? value : null);
68
70
  /** A refusal envelope as a coded error. The CLI reports ssh's own failure as E_SSH: a transport
69
71
  * failure, unless its details say ssh never started on this computer (nothing to retry); a 0.31
@@ -74,7 +76,7 @@ function refusal(envelope) {
74
76
  if (code === 'E_SSH') return unreachable();
75
77
  if (code === 'E_HERDR_REMOVED') return herdrRemoved(typeof message === 'string' && message ? message : HERDR_REMOVED);
76
78
  const error = coded(typeof code === 'string' && code ? code : 'E_TERM_OPEN_FAILED', message || 'remote session inspection failed');
77
- keptRefusals.set(error, { code: stringOrNull(code), message: stringOrNull(message), fix: stringOrNull(details?.fix) });
79
+ Object.defineProperty(error, KEPT_REFUSAL, { value: Object.freeze({ code: stringOrNull(code), message: stringOrNull(message), fix: stringOrNull(details?.fix) }) });
78
80
  return error;
79
81
  }
80
82
  /** What a failed preflight says. `error` is what `prepareRemoteTerm` threw; `server` is the label a
@@ -92,7 +94,7 @@ function refusal(envelope) {
92
94
  * message of a CLI that did not start holds a path and is never shown. */
93
95
  export function preflightFailure(error, server) {
94
96
  const code = terminalFailure(error?.code).code;
95
- const kept = code === 'E_TERM_OPEN_FAILED' ? keptRefusals.get(error) : undefined;
97
+ const kept = code === 'E_TERM_OPEN_FAILED' && error !== null && typeof error === 'object' && Object.hasOwn(error, KEPT_REFUSAL) ? error[KEPT_REFUSAL] : undefined;
96
98
  const said = kept && (kept.code !== null || kept.message !== null || kept.fix !== null) ? { ...kept } : null;
97
99
  return { code, sentence: terminalMessage(error?.code, server), said };
98
100
  }
@@ -0,0 +1,77 @@
1
+ /** The deployment's spawn catalog: `oats souls --json`, read only when the
2
+ * workspace it describes moved (member/external commits, the workspace
3
+ * commit) or the accepted CLI changed — never on every roster poll. One read
4
+ * per deployment at a time; a failed read is retried after RETRY_MS, and the
5
+ * last good catalog stays in place with the failure reported next to it.
6
+ *
7
+ * On a cold cycle the server starts this read alongside status/workspace status
8
+ * (`prefetch`) and binds it to the key that cycle's workspace status produces
9
+ * (`settle`); the holding rules are keyed-catalog.mjs's.
10
+ *
11
+ * A client makes its own catalog and owns it: nothing is held at module level, so two catalogs
12
+ * share no flight, no held entry and no cycle. It takes the client's terms (client-terms.mjs),
13
+ * which the default kernel read words its refusals with, and an optional `exec` that read
14
+ * runs the CLI through (cli-adapter.mjs `runJson`'s `io.exec`). */
15
+ import { cliWorkspace } from './workspace-cli.mjs';
16
+ import { requireTerms } from './client-terms.mjs';
17
+ import { soulsData, observationData } from './deployment-data.mjs';
18
+ import { createKeyedCatalog } from './keyed-catalog.mjs';
19
+
20
+ export const SOUL_CATALOG_RETRY_MS = 60_000;
21
+
22
+ /** The state a souls catalog was read under: the CLI, the workspace and member commits and the
23
+ * externals — everything `workspace status` reports that moves the list. What it cannot see
24
+ * (local configuration edited outside Desktop: teams, launch preferences) is bounded by the held
25
+ * result's TTL (keyed-catalog HELD_TTL_MS); the client names no deployment file to find out. */
26
+ export function soulCatalogKey(cli, workspaceStatus) {
27
+ const ws = workspaceStatus || {};
28
+ return JSON.stringify([cli?.bin ?? null, cli?.version ?? null, ws.workspace?.key ?? null, ws.workspace?.commit ?? null,
29
+ (ws.members || []).map(m => [m.key ?? null, m.commit ?? null, m.status ?? null]),
30
+ (ws.external || []).map(e => [e.source ?? null, e.soul ?? null])]);
31
+ }
32
+
33
+ export function createSoulCatalog({ terms, exec, invoke = (cli, options) => exec ? cliWorkspace(cli, options, terms, { exec }) : cliWorkspace(cli, options, terms), now = () => Date.now() } = {}) {
34
+ requireTerms(terms, 'createSoulCatalog');
35
+ async function read(deployment, cli, options) {
36
+ try {
37
+ // `maxAge` only reaches argv when the kernel declares observe-max-age (the adapter's call).
38
+ const result = await invoke(cli, { action: 'souls', context: deployment, ...options });
39
+ if (result?.ok !== true) return { value: null, reason: result?.reason?.code ? { code: result.reason.code, message: String(result.reason.message || '') } : { code: 'E_CLI_FAILED', message: '' } };
40
+ const souls = soulsData(result.document), { observedAt } = observationData(result.document); // a malformed stamp is no stamp; the catalog stands
41
+ return { value: { souls: souls.souls, ambiguous: souls.ambiguous, workspace: souls.workspace, problems: souls.problems }, observedAt };
42
+ } catch (error) { return { value: null, reason: { code: error?.code === 'E_CLI_PROTOCOL' ? 'E_CLI_PROTOCOL' : 'E_CLI_FAILED', message: '' } }; }
43
+ }
44
+ const catalog = createKeyedCatalog({ read, retryMs: SOUL_CATALOG_RETRY_MS, now });
45
+ /** The public entry: the catalog fields at the top, the failure next to them. */
46
+ const project = entry => entry && { key: entry.key, souls: entry.value?.souls ?? null, ambiguous: entry.value?.ambiguous ?? [],
47
+ workspace: entry.value?.workspace ?? null, problems: entry.value?.problems ?? [], reason: entry.reason, at: entry.at, observedAt: entry.observedAt, stale: entry.stale };
48
+ function settle(deployment, cli, workspaceStatus, options = {}) {
49
+ const { entry, pending } = catalog.settle(deployment, cli, soulCatalogKey(cli, workspaceStatus), options);
50
+ return { entry: project(entry), pending: pending && pending.then(project) };
51
+ }
52
+ /** The request path (/api/agents) found the held catalog for this state past its TTL: start one re-read
53
+ * behind the answer (or join the one in flight) and resolve with the landed, projected entry — null when
54
+ * nothing stale is held for this key (fresh, missing or another state's: the cycle owns those). */
55
+ function revalidate(deployment, cli, workspaceStatus, options = {}) {
56
+ const key = soulCatalogKey(cli, workspaceStatus), held = catalog.held(deployment);
57
+ if (!held || held.key !== key || held.reason || !held.stale) return null;
58
+ const pending = catalog.revalidate(deployment, cli, key, options);
59
+ return pending && pending.then(project);
60
+ }
61
+ return {
62
+ /** The catalog for this workspace state, reading it only when needed. */
63
+ async observe(deployment, cli, workspaceStatus, options = {}) {
64
+ const { entry, pending } = settle(deployment, cli, workspaceStatus, options);
65
+ return pending ? await pending : entry;
66
+ },
67
+ /** Synchronous decision for this workspace state: what is held now, and what (if anything) is still coming. */
68
+ settle,
69
+ revalidate,
70
+ /** Start an unbound read when nothing usable is held and nothing is in flight; null when nothing started. */
71
+ prefetch(deployment, cli, options = {}) { const flight = catalog.prefetch(deployment, cli, options); return flight && flight.then(project); },
72
+ refreshing: catalog.refreshing,
73
+ /** Read-only view of what is held (tests and diagnostics); the server reads catalogs through settle. */
74
+ held(deployment) { return project(catalog.held(deployment)); },
75
+ forget: catalog.forget,
76
+ };
77
+ }
@@ -0,0 +1,31 @@
1
+ /** Display-only identity colors. Zero dependencies, DOM, IO or resolver behavior.
2
+ * Palette names are the entire accepted metadata contract, never CSS or URLs.
3
+ * This helper can also be used by a future read-only backend projection. */
4
+ export const SOUL_COLORS = Object.freeze(['sand', 'sage', 'slate', 'mauve', 'clay', 'olive']);
5
+
6
+ export function normalizeSoulColor(value) {
7
+ if (typeof value !== 'string') return null;
8
+ const name = value.trim().toLowerCase();
9
+ return SOUL_COLORS.includes(name) ? name : null;
10
+ }
11
+
12
+ const text = value => typeof value === 'string' ? value : '';
13
+
14
+ /** Qualified CURRENT identity, not a basename, roster index, or worktree guess.
15
+ * Tuple encoding avoids delimiter collisions; the fixed hash/avalanche gives
16
+ * stable, muted, random-looking distribution. Six colors are NOT unique IDs. */
17
+ export function colorForIdentity({ root, name, host } = {}) {
18
+ const key = JSON.stringify([text(root), text(name), text(host)]);
19
+ let hash = 0x811c9dc5;
20
+ for (let i = 0; i < key.length; i++) hash = Math.imul(hash ^ key.charCodeAt(i), 0x01000193);
21
+ hash = Math.imul(hash ^ (hash >>> 16), 0x85ebca6b);
22
+ hash = Math.imul(hash ^ (hash >>> 13), 0xc2b2ae35);
23
+ return SOUL_COLORS[((hash ^ (hash >>> 16)) >>> 0) % SOUL_COLORS.length];
24
+ }
25
+
26
+ /** Roster/inspection soul shape. Do not infer a host or canonical source path. */
27
+ export function soulColor(soul) {
28
+ return normalizeSoulColor(soul?.color) || colorForIdentity({
29
+ root: soul?.agentsRoot, name: soul?.name, host: soul?.server,
30
+ });
31
+ }
@@ -0,0 +1,85 @@
1
+ /** What a client says about one soul, from its row (soul-rows.mjs, or a remote roster's) and its inspection
2
+ * (inspect-contract.mjs `inspectData` of an inspect-boundary.mjs answer), as plain data: no DOM, no state.
3
+ * The Desktop's soul inspector and soul grid draw from it, and so does any other client, so a soul reads the
4
+ * same wherever it is shown.
5
+ *
6
+ * soulFacts(row, inspected, cli, terms) -> {
7
+ * work where it works, in words ("works in its own worktree"), or null when the row names no mode
8
+ * refusal why a spawn of it here would be refused (spawnRefusal), or null
9
+ * refusalLine "Can't spawn here · <refusal>", or null
10
+ * launch the decoded Launch a spawn here would use (launch-view.mjs shownLaunch), or null: a kernel
11
+ * without launch-preference, or none reported
12
+ * rows the harness card, [label, value] each: with a launch Harness, Model, Launch configuration
13
+ * (when set), Chosen by, The soul prefers (when it differs); a kernel before 0.30 its Default
14
+ * harness and Default model; neither, none
15
+ * notes what is said beside the rows: with a launch, where its deciding value is set ("Set in …",
16
+ * when reported); with neither a launch nor a declared harness, that there is no default
17
+ * problem a launch problem, in its parts: { lead, lines, code }: the client's own line, the kernel's
18
+ * message and fix under its name (kernel-lines.mjs, with the client's terms), and its code
19
+ * }
20
+ *
21
+ * `inspected` may be null (a soul not inspected yet, the grid): the launch is then the row's. `terms` are the
22
+ * client's (client-terms.mjs); a call without them throws, also where no line would name the client. */
23
+ import { requireTerms } from './client-terms.mjs';
24
+ import { kernelLines } from './kernel-lines.mjs';
25
+ import { harnessOf } from './harness-names.mjs';
26
+ import { shownLaunch, launchHarnessName, launchModelText, launchFromText, launchAtText, preferenceText, declaredDiffers } from './launch-view.mjs';
27
+
28
+ /** Where a soul works, by its declared work mode. */
29
+ export const WORK_TEXT = Object.freeze({ worktree: 'works in its own worktree', checkout: 'works in the repo checkout', attached: 'attaches to an owning instance' });
30
+ /** A work mode in words, or null for none. */
31
+ export const workText = work => typeof work === 'string' && work ? WORK_TEXT[work] || `works in ${work}` : null;
32
+
33
+ /** Kernel #217's Desktop facts (`spawnable`, `problem`, `file`) are read only from a CLI that reports the feature. */
34
+ export const desktopFacts = cli => Array.isArray(cli?.features) && cli.features.includes('desktop-facts');
35
+
36
+ /** Kernel #217 (desktop-facts): the reason a spawn of this soul here would refuse, as the kernel
37
+ * reports it (`spawnable: false` + `problem`), else null. */
38
+ export function spawnRefusal(agent, cli) {
39
+ return desktopFacts(cli) && agent?.spawnable === false ? (typeof agent.problem?.message === "string" && agent.problem.message ? agent.problem.message : "A spawn of this soul would be refused here.") : null;
40
+ }
41
+ /** The line a soul a spawn here would refuse carries, beside its disabled Spawn. */
42
+ export const cantSpawnLine = refusal => `Can't spawn here · ${refusal}`;
43
+
44
+ /** What a launch problem of a soul's report means, in the client's words: the report is the launch a spawn
45
+ * that names none would get, and each problem is what the kernel reports of that spawn: why it would be
46
+ * refused, in the report's own message and fix. */
47
+ export const LAUNCH_REFUSED_HERE = 'A spawn of this soul with no launch chosen would be refused here.';
48
+ /** A launch problem's parts: the client's own line, then the kernel's message and fix, each a line of its own
49
+ * under the kernel's name and through the display filter, and the code. One rule for every problem, keyed on
50
+ * no code: the kernel computes the report for a spawn that names no launch and sets a problem only where it
51
+ * would refuse that spawn. */
52
+ export function launchProblemParts(problem, terms) {
53
+ return { lead: LAUNCH_REFUSED_HERE, lines: kernelLines(problem.message, problem.fix, terms), code: problem.code };
54
+ }
55
+
56
+ /** Said when a soul has neither a launch report nor a declared harness. */
57
+ export const NO_DEFAULT_HARNESS = 'No default harness: you choose one when you launch it.';
58
+
59
+ export function soulFacts(row, inspected, cli, terms) {
60
+ requireTerms(terms, 'soulFacts');
61
+ // 0.30 launch preferences: `inspect --soul`'s own, else the row's; null without the feature.
62
+ const launch = shownLaunch(inspected?.launch ?? row?.launch, cli);
63
+ const refusal = spawnRefusal(row, cli);
64
+ return { work: workText(row?.work), refusal, refusalLine: refusal === null ? null : cantSpawnLine(refusal), launch, ...harness(launch, inspected?.souls?.[0] ?? null, terms) };
65
+ }
66
+
67
+ /** The harness card: what a spawn here runs, where that choice came from and where to change it (0.30), else
68
+ * the harness the soul declares by default and the model within it (a kernel before 0.30), else none. */
69
+ function harness(launch, soul, terms) {
70
+ if (launch) {
71
+ const at = launchAtText(launch.at);
72
+ return {
73
+ rows: [['Harness', launchHarnessName(launch.effective.harness)], ['Model', launchModelText(launch.effective)],
74
+ ...(launch.effective.launchConfig ? [['Launch configuration', launch.effective.launchConfig]] : []), ['Chosen by', launchFromText(launch.from)],
75
+ ...(declaredDiffers(launch) ? [['The soul prefers', preferenceText(launch.declared)]] : [])],
76
+ notes: at ? [at] : [],
77
+ problem: launch.problem ? launchProblemParts(launch.problem, terms) : null,
78
+ };
79
+ }
80
+ const declared = harnessOf(soul);
81
+ if (typeof declared === 'string' && declared) {
82
+ return { rows: [['Default harness', launchHarnessName(declared)], ...(typeof soul.model === 'string' && soul.model ? [['Default model', soul.model]] : [])], notes: [], problem: null };
83
+ }
84
+ return { rows: [], notes: [NO_DEFAULT_HARNESS], problem: null };
85
+ }
@@ -0,0 +1,48 @@
1
+ /** The souls a local deployment offers, one row each: what a client lists and opens. The rows come
2
+ * from the kernel's spawn catalog (`oats souls --json`, held by soul-catalog.mjs: non-private souls
3
+ * of confirmed members, external souls and package souls, each with its declared work mode), and
4
+ * two facts the catalog does not carry: a soul's colour, from the roster's `souls` (soul-colors.mjs
5
+ * keeps only a palette name), and its member's name, from `workspace status`. Nothing is read from
6
+ * soul.yaml, and a soul outside the catalog has no row, so it is not offered for spawning.
7
+ *
8
+ * soulRows(deployment, catalog) -> rows, sorted by name
9
+ *
10
+ * deployment an observed deployment, as deployment-panel.mjs `observedEntry` makes it: `root`
11
+ * (the agents root), `souls` (the roster's) and `workspaceStatus.members`
12
+ * catalog the held catalog's `souls` list; null or absent: no rows
13
+ *
14
+ * No state: the rows are built from the two arguments on every call. */
15
+ import { dirname } from 'node:path';
16
+ import { normalizeSoulColor } from './soul-colors.mjs';
17
+
18
+ export function soulRows(deployment, catalog) {
19
+ const agents = [];
20
+ const root = deployment.root, context = dirname(root);
21
+ const memberNames = new Map((deployment.workspaceStatus?.members || []).map((m) => [m.key, m.name]));
22
+ const roster = new Map(deployment.souls.map((soul) => [soul.name, soul]));
23
+ for (const soul of catalog || []) {
24
+ const color = normalizeSoulColor(roster.get(soul.name)?.color);
25
+ agents.push({
26
+ name: soul.name, description: soul.description || "", kind: "persistent", work: soul.work,
27
+ ...(color ? { color } : {}), ...(soul.team ? { team: soul.team } : {}), ...(Array.isArray(soul.labels) ? { labels: [...soul.labels] } : {}),
28
+ // desktop-facts: whether a spawn here would refuse (problem), and the soul.yaml (path, url).
29
+ ...(typeof soul.spawnable === "boolean" ? { spawnable: soul.spawnable, problem: soul.problem ?? null } : {}),
30
+ ...(Object.hasOwn(soul, "file") ? { file: soul.file } : {}),
31
+ // Team model v2 (0.30): the soul's teams here (the default first) and its default, as the kernel resolved them.
32
+ ...(Array.isArray(soul.teams) ? { teams: soul.teams.map((t) => ({ ...t })) } : {}),
33
+ ...(Object.hasOwn(soul, "defaultTeam") ? { defaultTeam: soul.defaultTeam && { ...soul.defaultTeam } } : {}),
34
+ // Launch preferences (0.30): the soul's declared and effective harness + model, and where it came from.
35
+ ...(soul.launch ? { launch: structuredClone(soul.launch) } : {}),
36
+ // Its composed capabilities (souls-capabilities; null = it did not resolve), for Capabilities' "Used by".
37
+ ...(Object.hasOwn(soul, "capabilities") ? { capabilities: soul.capabilities && soul.capabilities.map((c) => ({ ...c })) } : {}),
38
+ // The kernel's soul key (`oats soul teams <key>`): the qualified name for a package soul, the bare name otherwise.
39
+ ...(typeof soul.key === "string" ? { key: soul.key } : {}),
40
+ ...(soul.kind === "package" ? { package: soul.package, version: soul.version, qualifiedName: soul.qualifiedName } : {}),
41
+ origin: soul.origin || "", soulKind: soul.kind, repo: soul.repoKey || null, capability: null,
42
+ soulSource: { repoKey: soul.repoKey ?? null, commit: soul.commit ?? null, path: soul.path ?? null },
43
+ agentsRoot: root, workspace: context,
44
+ repoName: memberNames.get(soul.repoKey) || (soul.kind === "external" ? "external" : soul.kind === "package" ? `package ${soul.package}` : soul.repoKey || ""),
45
+ });
46
+ }
47
+ return agents.sort((a, b) => a.name.localeCompare(b.name));
48
+ }
@@ -2,8 +2,7 @@
2
2
  * started is conservative dispatch evidence, NOT a creation/rollback receipt.
3
3
  * The broker must qualify a success receipt before exposing it or handing off. */
4
4
  import { retainedSpawnDetails } from './launch-prompt-outcome.mjs';
5
- import { execFile } from 'node:child_process';
6
- import { parseEnvelope, writeTaskFile } from './cli-adapter.mjs';
5
+ import { parseEnvelope, writeTaskFile, execFileInSession } from './cli-adapter.mjs';
7
6
  import { absolute, record, previewTarget, choiceArgv } from './spawn-preview-contract.mjs';
8
7
  import { spawnDecision } from './spawn-decision.mjs';
9
8
  import { spawnApplySupported, spawnApplyChoicesSupported, spawnPrepareInput, spawnReference, spawnApplyReason, spawnApplyDeadline,
@@ -37,7 +36,12 @@ function refusal(doc, cli) {
37
36
  return { started: true, envelope: { schemaVersion: 1, ok: false, error: { ...error, ...(details ? { details } : {}) } } };
38
37
  }
39
38
  /** `io.exec` is a client's own `execFile` (the rule is at cli-adapter.mjs `runJson`). Its return is used here:
40
- * the child of a spawn this call owns is ended through it at the deadline. */
39
+ * the child of a spawn this call owns is ended through it at the deadline.
40
+ * A spawn is a change: it runs in a session of its own (`detached: true`, whatever exec is given; this home's
41
+ * default for it is `execFileInSession`), so a hang-up or a Ctrl-C to the client's process group does not reach
42
+ * it while its worktree hooks run. Its deadline still ends it: SIGTERM (then SIGKILL) on a worktree-event kernel,
43
+ * and execFileInSession's own kill of an older kernel's (armed for a positive `timeout`), each signalling the
44
+ * child alone; the kernel rolls a spawn it was interrupted in back. */
41
45
  export async function cliSpawnApply(cli, options = {}, io = {}) {
42
46
  // Repeat the complete positive mode fence here, before even creating inputs.
43
47
  if (!spawnApplySupported(cli)) return failure('E_APPLY_UNAVAILABLE');
@@ -65,17 +69,18 @@ export async function cliSpawnApply(cli, options = {}, io = {}) {
65
69
  // too, so even a re-entrant injected dependency cannot downgrade the mode.
66
70
  if (!spawnApplySupported(cli)) return failure('E_APPLY_UNAVAILABLE');
67
71
  if (!spawnApplyChoicesSupported(cli, choices, !!input.wake)) return failure('E_UNSUPPORTED_OPTION');
68
- // worktree-event: the deadline is ours, not execFile's. execFile's own timeout destroys the child's
72
+ // worktree-event: the deadline is ours, not the exec's. execFile's own timeout destroys the child's
69
73
  // output before it signals it, which would lose the envelope a kernel prints after our SIGTERM
70
74
  // (E_INTERRUPTED, once its rollback is done). So: SIGTERM at the deadline with the output still read,
71
- // and SIGKILL only if the CLI is still running SIGTERM_GRACE_MS later. Older kernels keep execFile's.
75
+ // and SIGKILL only if the CLI is still running SIGTERM_GRACE_MS later. Older kernels keep the exec's
76
+ // own `timeout` (execFileInSession arms its kill, SIGTERM, for a positive one): E_CLI_TIMEOUT.
72
77
  const own = worktreeEvent(cli), timer = io.timer ?? ((fn, ms) => { const t = setTimeout(fn, ms); return () => clearTimeout(t); });
73
78
  const limit = io.timeoutMs ?? timeout, grace = io.graceMs ?? SIGTERM_GRACE_MS;
74
79
  return await new Promise(resolve => {
75
80
  let expired = false, settled = false, cancelDeadline = () => {}, cancelGrace = () => {};
76
81
  try {
77
82
  started = true;
78
- const child = (io.exec ?? execFile)(cli.bin, argv, { cwd: target.context, env, shell: false, encoding: 'utf8', ...(own ? {} : { timeout: limit }), maxBuffer: 4 * 1024 * 1024 }, (err, stdout) => {
83
+ const child = (io.exec ?? execFileInSession)(cli.bin, argv, { cwd: target.context, env, shell: false, encoding: 'utf8', detached: true, ...(own ? {} : { timeout: limit }), maxBuffer: 4 * 1024 * 1024 }, (err, stdout) => {
79
84
  settled = true; cancelDeadline(); cancelGrace();
80
85
  if (err?.code === 'ERR_CHILD_PROCESS_STDIO_MAXBUFFER' || typeof stdout === 'string' && Buffer.byteLength(stdout) > 4 * 1024 * 1024) return resolve(failure('E_CLI_OUTPUT_LIMIT', true));
81
86
  if (err?.killed && !own) return resolve(failure('E_CLI_TIMEOUT', true));