@awebai/oats 0.57.0 → 0.58.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/bin/oats.mjs +24 -11
  2. package/docs/configuration.md +19 -28
  3. package/docs/desktop-cli-api.md +38 -15
  4. package/docs/desktop.md +14 -0
  5. package/docs/execution-targets.md +10 -1
  6. package/docs/implementation.md +7 -1
  7. package/docs/integrations.md +3 -1
  8. package/docs/official-catalog.md +1 -1
  9. package/docs/packages.md +5 -5
  10. package/docs/release-notes/v0.57.1.md +275 -0
  11. package/docs/release-notes/v0.58.0.md +107 -0
  12. package/docs/servers.md +18 -0
  13. package/docs/souls-and-instances.md +9 -0
  14. package/docs/tui.md +224 -87
  15. package/docs/workspaces.md +1 -1
  16. package/lib/core.mjs +11 -4
  17. package/lib/session-viewer.mjs +29 -4
  18. package/package-catalog.json +1 -1
  19. package/package.json +1 -1
  20. package/packages/client/cli-adapter.mjs +9 -7
  21. package/packages/client/cli-locator.mjs +2 -2
  22. package/packages/client/composed-gate.mjs +34 -0
  23. package/packages/client/inspect-boundary.mjs +157 -0
  24. package/packages/client/inspect-cache.mjs +86 -0
  25. package/packages/client/keyed-catalog.mjs +132 -0
  26. package/packages/client/launch-view.mjs +46 -0
  27. package/packages/client/panel-views.mjs +1 -1
  28. package/packages/client/session-attach.mjs +7 -5
  29. package/packages/client/soul-catalog.mjs +77 -0
  30. package/packages/client/soul-colors.mjs +31 -0
  31. package/packages/client/soul-facts.mjs +85 -0
  32. package/packages/client/soul-rows.mjs +48 -0
  33. package/packages/client/spawn-apply-cli.mjs +19 -8
  34. package/packages/client/spawn-apply.mjs +216 -0
  35. package/packages/client/spawn-messages.mjs +131 -85
  36. package/packages/client/spawn-preview-cli.mjs +2 -1
  37. package/packages/client/spawn-preview-contract.mjs +3 -0
  38. package/packages/client/spawn-preview-facts.mjs +119 -0
  39. package/packages/client/spawn-preview.mjs +164 -0
  40. package/packages/client/spawn-transaction.mjs +136 -0
  41. package/packages/record/lib/directory-identity.mjs +14 -0
  42. package/packages/record/lib/native-history.mjs +6 -5
  43. package/packages/tui/README.md +32 -11
  44. package/packages/tui/lib/actions.mjs +10 -1
  45. package/packages/tui/lib/config.mjs +9 -14
  46. package/packages/tui/lib/main.mjs +165 -57
  47. package/packages/tui/lib/model.mjs +28 -24
  48. package/packages/tui/lib/panel.mjs +1019 -0
  49. package/packages/tui/lib/read.mjs +5 -14
  50. package/packages/tui/lib/store.mjs +77 -30
  51. package/packages/tui/lib/term/capture.mjs +260 -0
  52. package/packages/tui/lib/term/screen.mjs +44 -8
  53. package/packages/tui/lib/term/style.mjs +78 -6
  54. package/packages/tui/lib/term/text.mjs +24 -4
  55. package/packages/tui/lib/term/through.mjs +213 -0
  56. package/packages/tui/lib/term/tty.mjs +7 -60
  57. package/packages/tui/lib/views/frame.mjs +126 -40
  58. package/packages/tui/lib/views/help.mjs +12 -10
  59. package/skills/oats-getting-started/SKILL.md +3 -2
  60. package/packages/tui/lib/open.mjs +0 -45
@@ -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 start. Like `execFile` it collects stdout and stderr (`encoding`, default utf8),
504
- * ends the child with `killSignal` (SIGTERM) when `timeout` (0: none) passes or an output passes `maxBuffer`,
505
- * and calls back once the child's streams close: `(null, stdout, stderr)` on a clean exit; else an Error with
506
- * `code` (the exit status, or a system code), `killed` and `signal`, or the overflow's own error, whose `code`
507
- * is ERR_CHILD_PROCESS_STDIO_MAXBUFFER. stdin is a pipe, as `execFile`'s, that nobody writes. */
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 (packages/desktop: server/capabilities.mjs, renderer/composed-gate.mjs): a host without it refuses the flag.
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.58.0 (the band is
16
+ // Desktop accepts desktopApi === 1 and semver >=0.26.0 <0.59.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, 58, 0] };
55
+ export const ACCEPT_RANGE = { min: [0, 26, 0], maxExclusive: [0, 59, 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
+ }
@@ -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
+ }
@@ -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;
@@ -14,7 +14,7 @@
14
14
  * rosterAnswered, // boolean: a roster answer arrived under the current CLI
15
15
  * rosterFailure, // string | null: the roster read's failure while no answer has arrived
16
16
  * cli, // the kernel record (cli-locator.mjs)
17
- * observing, // Set<deployment id>: a read in flight
17
+ * observing, // keyed by deployment id (`has`): a read in flight
18
18
  * remoteCollecting, // boolean: the remote roster is being read
19
19
  * home, // string: the user's home directory, for the short label
20
20
  * at, // string: the ISO time of this call
@@ -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
  }