@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
@@ -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,11 +36,22 @@ 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');
44
- if (!record(options) || Object.keys(options).some(k => !['target', 'choices', 'task', 'wake', 'decision', 'key', 'deadlineMs'].includes(k))) return failure('E_BAD_ARGS');
48
+ if (!record(options) || Object.keys(options).some(k => !['target', 'choices', 'task', 'wake', 'decision', 'key', 'deadlineMs', 'maxAge'].includes(k))) return failure('E_BAD_ARGS');
49
+ // Feature spawn-apply-max-age (#1246 K1): the kernel may reuse deployment observations up to maxAge seconds old.
50
+ // Only beside --expect-decision, which fences a drifted decision, and only where the CLI lists it (an older
51
+ // kernel refuses the flag).
52
+ const maxAge = options.maxAge;
53
+ if (maxAge !== undefined && (!Number.isInteger(maxAge) || maxAge < 1 || maxAge > 3600)) return failure('E_BAD_ARGS');
54
+ const reuse = maxAge !== undefined && Array.isArray(cli.features) && cli.features.includes('spawn-apply-max-age') ? ['--max-age', String(maxAge)] : [];
45
55
  // The broker derives the deadline from the confirmed preview (spawnApplyDeadlineMs); 60 s without one.
46
56
  const timeout = options.deadlineMs ?? SPAWN_APPLY_MS;
47
57
  if (!spawnApplyDeadline(timeout)) return failure('E_BAD_ARGS');
@@ -56,7 +66,7 @@ export async function cliSpawnApply(cli, options = {}, io = {}) {
56
66
  if (input.wake) wakeFile = writeTaskFile(JSON.stringify(input.wake), io);
57
67
  const choices = input.choices;
58
68
  const argv = ['spawn', target.selector.soul, '--dir', target.context, '--agents-root', target.selector.agentsRoot, ...choiceArgv(choices, cli)];
59
- argv.push('--expect-decision', decision.revision, '--idempotency-key', options.key, '--task-file', taskFile.file);
69
+ argv.push('--expect-decision', decision.revision, ...reuse, '--idempotency-key', options.key, '--task-file', taskFile.file);
60
70
  if (wakeFile) argv.push('--wake-file', wakeFile.file);
61
71
  argv.push('--json');
62
72
  const env = { ...(io.env ?? process.env) };
@@ -65,17 +75,18 @@ export async function cliSpawnApply(cli, options = {}, io = {}) {
65
75
  // too, so even a re-entrant injected dependency cannot downgrade the mode.
66
76
  if (!spawnApplySupported(cli)) return failure('E_APPLY_UNAVAILABLE');
67
77
  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
78
+ // worktree-event: the deadline is ours, not the exec's. execFile's own timeout destroys the child's
69
79
  // output before it signals it, which would lose the envelope a kernel prints after our SIGTERM
70
80
  // (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.
81
+ // and SIGKILL only if the CLI is still running SIGTERM_GRACE_MS later. Older kernels keep the exec's
82
+ // own `timeout` (execFileInSession arms its kill, SIGTERM, for a positive one): E_CLI_TIMEOUT.
72
83
  const own = worktreeEvent(cli), timer = io.timer ?? ((fn, ms) => { const t = setTimeout(fn, ms); return () => clearTimeout(t); });
73
84
  const limit = io.timeoutMs ?? timeout, grace = io.graceMs ?? SIGTERM_GRACE_MS;
74
85
  return await new Promise(resolve => {
75
86
  let expired = false, settled = false, cancelDeadline = () => {}, cancelGrace = () => {};
76
87
  try {
77
88
  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) => {
89
+ 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
90
  settled = true; cancelDeadline(); cancelGrace();
80
91
  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
92
  if (err?.killed && !own) return resolve(failure('E_CLI_TIMEOUT', true));
@@ -0,0 +1,216 @@
1
+ /** One client's confirmed-spawn broker across all workspaces: a client makes its own (createSpawnApplyBoundary)
2
+ * and owns it, and two share nothing (references, keys, the active applies, byte reservations).
3
+ * RAM custody only. No kernel imports, placement logic, persistent instructions,
4
+ * implicit retry, name-based recovery, or mutation from result/prepare.
5
+ *
6
+ * Long spawns (#802): an apply runs the CLI for the deadline its confirmed preview implies
7
+ * (spawnApplyDeadlineMs: 60 s, or 60 s + n × 30 min + 60 s for n `worktree` hooks). The apply
8
+ * request answers within ANSWER_WITHIN_MS: with the outcome if the CLI settled, else `pending`;
9
+ * the CLI keeps running here and `result` reads its outcome. Up to MAX_APPLIES applies run at
10
+ * once per boundary, one per workspace and soul. */
11
+ import { retainedSpawnDetails, LAUNCH_DIAGNOSTIC_BYTES, FLAG_IGNORED_BYTES } from './launch-prompt-outcome.mjs';
12
+ import { randomBytes } from 'node:crypto';
13
+ import { performance } from 'node:perf_hooks';
14
+ import { cliSpawnApply } from './spawn-apply-cli.mjs';
15
+ import { admitSpawnSelection, PREVIEW_MAX_AGE_S } from './spawn-preview.mjs';
16
+ import { record } from './spawn-preview-contract.mjs';
17
+ import { spawnApplySupported, spawnApplyChoicesSupported, spawnPrepareInput, spawnRefInput, spawnPreparedData, spawnReference,
18
+ spawnCreationReceipt, spawnApplyFailure, spawnApplyDeadlineMs, ROLLED_BACK_CODES, WAKE_OUTCOME_UNKNOWN } from './spawn-apply-contract.mjs';
19
+ /** The apply request answers within this; the proxy's own 65 s timeout then never fires on a healthy spawn. */
20
+ export const ANSWER_WITHIN_MS = 50000;
21
+ export const MAX_APPLIES = 4;
22
+ const clone = v => structuredClone(v);
23
+ const byteSize = v => Buffer.byteLength(JSON.stringify(v));
24
+ const scopeKey = c => JSON.stringify([c?.workspace?.id, c?.workspace?.scope, c?.workspace?.remote, c?.workspace?.server,
25
+ c?.cli?.bin, c?.cli?.version, c?.cli?.spawnPreviewApi, c?.cli?.spawnApplyApi, c?.cli?.features, c?.cli?.harnesses, c?.cli?.sessionBackends, c?.cli?.launchOptions]);
26
+ /** `read` is required: the client's own preview's `prepareRead` (spawn-preview.mjs createSpawnPreview). Prepare
27
+ * reads through the dialog's cache: a fresh held answer for exactly these choices is the decision (no second
28
+ * CLI read); apply's --expect-decision is the drift guard. No held answer: a fresh read.
29
+ * exec optional: the client's own execFile, passed to `invoke` as `invoke(cli, options, { exec })` for every
30
+ * apply (cli-adapter.mjs `runJson` has the rule); without it `invoke` is given no third argument and
31
+ * cliSpawnApply's own default runs. An apply is a change: its options carry `detached: true`
32
+ * whatever exec is given, which runs it in a session of its own (as execFileInSession does). On a
33
+ * worktree-event kernel cliSpawnApply ends the child at the deadline through what exec returns
34
+ * (`child.kill`): a given exec must return the child. One that returns nothing leaves that apply
35
+ * unended at its deadline; there is no fallback here. On a kernel without worktree-event the options'
36
+ * `timeout` is the apply's only deadline: exec must honour it as execFileInSession does, killing the
37
+ * child when it passes and reporting `killed` even if the child then exits cleanly.
38
+ * maxAge seconds the kernel may reuse its deployment observations for the apply (#1246 K1: the member heads'
39
+ * ls-remote wave at the press). Passed to `invoke` only where the apply's CLI lists spawn-apply-max-age;
40
+ * null never. The fence is unchanged: apply's --expect-decision refuses a drifted decision (E_DECISION_STALE). */
41
+ export function createSpawnApplyBoundary({ read, invoke = cliSpawnApply, exec, maxAge = PREVIEW_MAX_AGE_S,
42
+ now = () => performance.now(), mint = () => randomBytes(32).toString('hex'), answerWithinMs = ANSWER_WITHIN_MS,
43
+ timer = (fn, ms) => { const t = setTimeout(fn, ms); return () => clearTimeout(t); } } = {}) {
44
+ if (typeof read !== 'function') throw new TypeError('createSpawnApplyBoundary: read (the client\'s prepareRead) is required');
45
+ const prepared = new Map(), submitted = new Map(), active = new Set(), io = exec ? [{ exec }] : [];
46
+ let preparing = 0, reservedBytes = 0;
47
+ const denied = (code, entry = null, status = 'unavailable', message) => spawnApplyFailure(code, { target: entry?.target, spawnRef: entry?.ref, status, message });
48
+ const sweep = () => { for (const map of [prepared, submitted]) for (const [ref, entry] of map) if (!entry.pending && entry.expires <= now()) map.delete(ref); };
49
+ const usedBytes = () => reservedBytes + [...prepared.values(), ...submitted.values()].reduce((sum, e) => sum + e.bytes, 0);
50
+ const freshId = () => {
51
+ const id = mint();
52
+ return spawnReference(id) && !prepared.has(id) && !submitted.has(id) && ![...submitted.values()].some(e => e.key === id) ? id : null;
53
+ };
54
+ function select(input, getContext) {
55
+ const c = getContext();
56
+ if (!spawnApplySupported(c?.cli)) return { error: 'E_APPLY_UNAVAILABLE' };
57
+ if (!spawnApplyChoicesSupported(c.cli, input.choices, !!input.wake)) return { error: 'E_UNSUPPORTED_OPTION' };
58
+ const s = admitSpawnSelection(input.selector, input.choices, c);
59
+ if (s.error) return s;
60
+ const soul = c.agents.find(a => a.name === input.selector.soul && a.agentsRoot === input.selector.agentsRoot);
61
+ const anchor = input.choices.relation.anchor;
62
+ if (soul?.captured || anchor && c.instances?.some(i => i.instance === anchor.instance && i.agentsRoot === anchor.agentsRoot && i.captured)) return { error: 'E_UNSUPPORTED_MODE' };
63
+ return { ...s, scope: scopeKey(c) };
64
+ }
65
+ const same = (a, b) => !b.error && a.identity === b.identity && a.scope === b.scope;
66
+ const ownsScope = (e, getContext) => { try { const c = getContext(); return spawnApplySupported(c?.cli) && !c.workspace?.remote && !c.workspace?.server && scopeKey(c) === e.scope; } catch { return false; } };
67
+ const display = (entry, status, receipt = null, reason = null, extra = {}) => ({ spawnApplyViewApi: 1, status, target: entry.target, spawnRef: entry.ref,
68
+ preview: entry.preview, wakeRequested: !!entry.input.wake, receipt, reason, applyWithinMs: entry.deadlineMs, ...extra });
69
+ async function prepare(input, getContext) {
70
+ const selection = select(input, getContext);
71
+ if (selection.error) return denied(selection.error);
72
+ const reservation = byteSize(input);
73
+ if (prepared.size + preparing >= 32 || usedBytes() + reservation > 8 * 1024 * 1024) return denied('E_BUSY');
74
+ preparing++; reservedBytes += reservation;
75
+ let observed;
76
+ try { observed = await read({ action: 'preview', selector: clone(input.selector), choices: clone(input.choices) }, getContext); }
77
+ catch { observed = { status: 'unavailable', reason: { code: 'E_CLI_FAILED' } }; }
78
+ finally { preparing--; reservedBytes -= reservation; }
79
+ const current = select(input, getContext);
80
+ if (!same(selection, current)) return denied('E_PLAN_CHANGED', { target: selection.target });
81
+ if (observed?.status !== 'available') return denied(observed?.reason?.code, { target: selection.target });
82
+ if (observed.data?.preflight?.status !== 'complete') return denied('E_PREFLIGHT_INCOMPLETE', { target: selection.target });
83
+ const preview = spawnPreparedData(observed.data, selection.target);
84
+ if (!preview) return denied('E_CLI_PROTOCOL', { target: selection.target });
85
+ if (!preview.backendStatus.installed) return denied('E_BACKEND_UNAVAILABLE', { target: selection.target });
86
+ const entry = { ...selection, input: clone(input), preview, ref: freshId(), key: null, expires: now() + 300000,
87
+ pending: false, reply: null, final: false, seenHome: false, seenBirth: null, bytes: 0, deadlineMs: spawnApplyDeadlineMs(selection.cli, preview) };
88
+ if (!entry.ref) return denied('E_BUSY', entry);
89
+ // Reserve bounded outcome storage before dispatch. A settled reply shares
90
+ // this immutable preview internally; public responses are always cloned.
91
+ // A reply keeps one of two bounded texts, never both: a retained launch's diagnostics, or the
92
+ // fact a receipt carries when Claude Code ignored the channel option. The larger bound covers either.
93
+ entry.bytes = byteSize(entry) + 3 * byteSize(preview.decision) + 2 * byteSize(entry.target) + 4096 + Math.max(LAUNCH_DIAGNOSTIC_BYTES, FLAG_IGNORED_BYTES);
94
+ if (usedBytes() + entry.bytes > 8 * 1024 * 1024) return denied('E_BUSY', entry);
95
+ prepared.set(entry.ref, entry);
96
+ return display(entry, 'prepared');
97
+ }
98
+ function observedGone(entry, getContext) {
99
+ // A prior positive observation can block retry after disappearance/replacement.
100
+ // Absence alone is NOT success/retirement proof and does not close a concurrent
101
+ // retire race. The kernel key's documented lifetime is only its surviving home.
102
+ const rows = getContext().instances || [];
103
+ const matches = rows.filter(i => i.instance === entry.preview.decision.instance && i.home === entry.preview.decision.home
104
+ && i.agent === entry.input.selector.soul && i.agentsRoot === entry.input.selector.agentsRoot && !i.server && !i.remote);
105
+ const own = matches.length === 1 && matches[0].spawnIdempotencyKey === entry.key ? matches[0] : null;
106
+ if (own) {
107
+ const birth = typeof own.createdAt === 'string' && own.createdAt.length <= 128 ? own.createdAt : null;
108
+ if (entry.seenBirth !== null && entry.seenBirth !== birth) return true;
109
+ entry.seenHome = true; entry.seenBirth = birth; return false;
110
+ }
111
+ return entry.seenHome || matches.some(i => typeof i.spawnIdempotencyKey === 'string' && i.spawnIdempotencyKey !== entry.key);
112
+ }
113
+ function interpret(result, entry, cli) {
114
+ const envelope = result?.envelope;
115
+ if (typeof result?.started !== 'boolean' || envelope?.schemaVersion !== 1 || typeof envelope.ok !== 'boolean') return denied('E_OUTCOME_UNKNOWN', entry, 'unknown');
116
+ if (envelope.ok) {
117
+ if (!result.started) return denied('E_OUTCOME_UNKNOWN', entry, 'unknown');
118
+ const receipt = spawnCreationReceipt(envelope.result, { target: entry.target, preview: entry.preview, wakeRequested: !!entry.input.wake });
119
+ if (!receipt) return denied('E_OUTCOME_UNKNOWN', entry, 'unknown');
120
+ const partial = !!entry.input.wake && receipt.wake.saved !== true;
121
+ const reason = !partial ? null : receipt.wake.error ?? { code: 'E_WAKE_OUTCOME_UNKNOWN', message: WAKE_OUTCOME_UNKNOWN };
122
+ return display(entry, partial ? 'partial' : 'complete', receipt, reason);
123
+ }
124
+ const code = envelope.error?.code;
125
+ if (!result.started) return denied(code, entry, 'refused');
126
+ if (code === 'E_SPAWN_INCOMPLETE') {
127
+ const d = retainedSpawnDetails(envelope.error.details);
128
+ if (!d || d.instance !== entry.preview.decision.instance || d.home !== entry.preview.decision.home) return denied('E_OUTCOME_UNKNOWN', entry, 'unknown');
129
+ return { ...denied(code, entry, 'incomplete'), incomplete: d };
130
+ }
131
+ // worktree-event: the kernel rolled these back. Without the unconfirmed marker its compensation
132
+ // was confirmed: refused, nothing created. With it, cleanup is owed: unknown, and final (a
133
+ // re-apply of the same key would not finish it; retiring the quarantined home does).
134
+ if (ROLLED_BACK_CODES.includes(code) && cli?.features?.includes('worktree-event')) {
135
+ const message = envelope.error.message;
136
+ if (envelope.error.details?.unconfirmed === true) { entry.final = true; return denied(code, entry, 'unknown', message); }
137
+ return denied(code, entry, 'refused', message);
138
+ }
139
+ // A taken explicit name (spawn-name) refuses before any home is kept: the
140
+ // confirmation is consumed and a fresh preview reports the taken name.
141
+ if (['E_DECISION_STALE', 'E_IDEMPOTENCY_CONFLICT', 'E_PLACEMENT_TAKEN', 'E_INSTANCE_NAME_TAKEN'].includes(code)) return denied(code, entry, 'stale');
142
+ // Do not infer rollback from arbitrary kernel/hook failures. Only the
143
+ // explicit binding/reservation/incomplete contracts above establish scope.
144
+ return denied('E_OUTCOME_UNKNOWN', entry, 'unknown');
145
+ }
146
+ function get(ref, getContext) {
147
+ const e = submitted.get(ref) || prepared.get(ref);
148
+ if (!e) return { failure: denied('E_INTENT_EXPIRED') };
149
+ if (!ownsScope(e, getContext)) return { failure: denied('E_PLAN_CHANGED', e) };
150
+ return { entry: e };
151
+ }
152
+ const sameSoul = (a, b) => a.target.workspace === b.target.workspace && a.input.selector.soul === b.input.selector.soul
153
+ && a.input.selector.agentsRoot === b.input.selector.agentsRoot;
154
+ async function apply(entry, getContext, settled) {
155
+ if (entry.pending) return display(entry, 'pending');
156
+ if (entry.reply && (entry.reply.status !== 'unknown' || entry.final)) return { ...entry.reply, repeated: true };
157
+ if (active.size >= MAX_APPLIES || [...active].some(e => sameSoul(e, entry)) || !submitted.has(entry.ref) && submitted.size >= 32) return denied('E_BUSY', entry);
158
+ const current = select(entry.input, getContext);
159
+ if (!same(entry, current)) return denied('E_PLAN_CHANGED', entry);
160
+ if (entry.key && observedGone(entry, getContext)) {
161
+ entry.reply = denied('E_INSTANCE_GONE', entry, 'refused'); return entry.reply;
162
+ }
163
+ const key = entry.key || freshId();
164
+ if (!key) return denied('E_BUSY', entry);
165
+ // Reserve key, slot and submitted record BEFORE any await. Key persists on
166
+ // this intent through unknown results; neither result nor retry can mint one.
167
+ entry.key = key; entry.pending = true; entry.expires = Infinity; active.add(entry);
168
+ prepared.delete(entry.ref); submitted.set(entry.ref, entry);
169
+ const run = (async () => {
170
+ let reply;
171
+ try {
172
+ const latest = select(entry.input, getContext);
173
+ if (!same(entry, latest)) reply = denied('E_PLAN_CHANGED', entry, 'refused');
174
+ else {
175
+ const result = await invoke(latest.cli, { target: clone(entry.target), choices: clone(entry.input.choices), task: entry.input.task,
176
+ ...(entry.input.wake ? { wake: clone(entry.input.wake) } : {}), decision: clone(entry.preview.decision), key: entry.key, deadlineMs: entry.deadlineMs,
177
+ ...(maxAge !== null && latest.cli?.features?.includes('spawn-apply-max-age') ? { maxAge } : {}) }, ...io);
178
+ reply = interpret(result, entry, latest.cli);
179
+ }
180
+ } catch { reply = denied('E_OUTCOME_UNKNOWN', entry, 'unknown'); }
181
+ // This result belongs to its original entry even if a view/workspace changed.
182
+ // The caller's current context is checked separately on both settlement paths.
183
+ entry.reply = reply; // internal preview sharing; every outward response is cloned
184
+ entry.pending = false; entry.expires = now() + 30 * 60000; active.delete(entry);
185
+ return reply;
186
+ })();
187
+ // Answer within answerWithinMs: the outcome, or `pending` while the CLI keeps running here.
188
+ let cancel = () => {};
189
+ const late = new Promise(resolve => { cancel = timer(() => resolve(null), answerWithinMs); });
190
+ const reply = await Promise.race([run, late]);
191
+ cancel();
192
+ if (!reply) {
193
+ void run.then(() => { try { settled?.(); } catch { /* a refresh must not lose an outcome */ } });
194
+ return display(entry, 'pending');
195
+ }
196
+ return ownsScope(entry, getContext) ? reply : denied('E_OUTCOME_UNKNOWN', entry, 'unknown');
197
+ }
198
+ /** `settled()` is called when an apply answered `pending` settles later (the route refreshes then). */
199
+ return async function spawnApplyRequest(request, getContext, { settled } = {}) {
200
+ try {
201
+ sweep();
202
+ if (!record(request)) return denied('E_BAD_ARGS');
203
+ if (request.action === 'prepare') {
204
+ const input = spawnPrepareInput(request);
205
+ return clone(input ? await prepare(input, getContext) : denied('E_BAD_ARGS'));
206
+ }
207
+ const r = spawnRefInput(request);
208
+ if (!r) return denied('E_BAD_ARGS');
209
+ const found = get(r.spawnRef, getContext);
210
+ if (found.failure) return clone(found.failure);
211
+ const e = found.entry;
212
+ if (r.action === 'result') return clone(e.pending ? display(e, 'pending') : e.reply || display(e, 'prepared'));
213
+ return clone(await apply(e, getContext, settled));
214
+ } catch { return denied('E_CLI_FAILED'); }
215
+ };
216
+ }