@awebai/oats 0.57.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 (50) hide show
  1. package/docs/configuration.md +17 -27
  2. package/docs/desktop.md +14 -0
  3. package/docs/execution-targets.md +6 -1
  4. package/docs/implementation.md +7 -1
  5. package/docs/integrations.md +3 -1
  6. package/docs/official-catalog.md +1 -1
  7. package/docs/packages.md +5 -5
  8. package/docs/release-notes/v0.57.1.md +275 -0
  9. package/docs/servers.md +18 -0
  10. package/docs/tui.md +214 -87
  11. package/docs/workspaces.md +1 -1
  12. package/lib/session-viewer.mjs +29 -4
  13. package/package-catalog.json +1 -1
  14. package/package.json +1 -1
  15. package/packages/client/cli-adapter.mjs +9 -7
  16. package/packages/client/composed-gate.mjs +34 -0
  17. package/packages/client/inspect-boundary.mjs +157 -0
  18. package/packages/client/inspect-cache.mjs +86 -0
  19. package/packages/client/keyed-catalog.mjs +132 -0
  20. package/packages/client/launch-view.mjs +46 -0
  21. package/packages/client/session-attach.mjs +7 -5
  22. package/packages/client/soul-catalog.mjs +77 -0
  23. package/packages/client/soul-colors.mjs +31 -0
  24. package/packages/client/soul-facts.mjs +85 -0
  25. package/packages/client/soul-rows.mjs +48 -0
  26. package/packages/client/spawn-apply-cli.mjs +11 -6
  27. package/packages/client/spawn-apply.mjs +212 -0
  28. package/packages/client/spawn-messages.mjs +131 -85
  29. package/packages/client/spawn-preview-contract.mjs +3 -0
  30. package/packages/client/spawn-preview-facts.mjs +119 -0
  31. package/packages/client/spawn-preview.mjs +152 -0
  32. package/packages/client/spawn-transaction.mjs +136 -0
  33. package/packages/tui/README.md +32 -11
  34. package/packages/tui/lib/actions.mjs +10 -1
  35. package/packages/tui/lib/config.mjs +9 -14
  36. package/packages/tui/lib/main.mjs +165 -57
  37. package/packages/tui/lib/model.mjs +28 -24
  38. package/packages/tui/lib/panel.mjs +955 -0
  39. package/packages/tui/lib/read.mjs +5 -14
  40. package/packages/tui/lib/store.mjs +77 -30
  41. package/packages/tui/lib/term/capture.mjs +260 -0
  42. package/packages/tui/lib/term/screen.mjs +44 -8
  43. package/packages/tui/lib/term/style.mjs +78 -6
  44. package/packages/tui/lib/term/text.mjs +24 -4
  45. package/packages/tui/lib/term/through.mjs +213 -0
  46. package/packages/tui/lib/term/tty.mjs +7 -60
  47. package/packages/tui/lib/views/frame.mjs +126 -40
  48. package/packages/tui/lib/views/help.mjs +12 -10
  49. package/skills/oats-getting-started/SKILL.md +3 -2
  50. package/packages/tui/lib/open.mjs +0 -45
@@ -1,113 +1,128 @@
1
- /** Plain-language wording for the Spawn dialog's problems.
1
+ /** Plain-language wording for a spawn's problems and outcomes, shared by every client (#855, 6b-2).
2
2
  *
3
3
  * The preview/apply contracts carry a stable code and a technical message
4
- * (the kernel's own text for kernel refusals — paths, hashes, commands). The
5
- * dialog shows the operator one sentence about what happened and what to do;
6
- * the code and the technical message stay available behind "Details" for
7
- * troubleshooting. Wording only: no decision here depends on the text. */
4
+ * (the kernel's own text for kernel refusals — paths, hashes, commands). A
5
+ * client shows the operator what happened (`fact`) and, in its own words, what
6
+ * to do (`next`); the code and the technical message stay available as
7
+ * `detail` for troubleshooting. The Desktop's sentences are composed in
8
+ * packages/desktop/renderer/spawn-words.mjs. Wording only: no decision here
9
+ * depends on the text. */
8
10
  import { displayLine } from './display-text.mjs';
9
11
  import { ROLLED_BACK_CODES } from './spawn-apply-contract.mjs';
12
+ import { retainedSpawnMessage } from './launch-prompt-outcome.mjs';
10
13
 
11
14
  const UNMATCHED = 'E_LAUNCH_PREFERENCE_UNMATCHED';
12
15
 
13
- const COMMON = {
14
- E_BAD_ARGS: 'Some of these values can’t be used. Check the name and Developer settings.',
15
- E_BUSY: 'Another spawn is in progress. Try again in a moment.',
16
- E_FORBIDDEN_FRAME: 'This window can’t start a spawn.',
17
- E_PREVIEW_UNAVAILABLE: 'Spawning needs a newer OATS. Update OATS, then open this dialog again.',
18
- E_APPLY_UNAVAILABLE: 'Spawning needs a newer OATS. Update OATS, then open this dialog again.',
19
- E_WORKSPACE_UNKNOWN: 'This workspace isn’t available anymore. Choose it again from the workspace menu.',
20
- E_SOUL_UNKNOWN: 'This soul isn’t in the workspace anymore. Sync the workspace and try again.',
21
- E_SOUL_AMBIGUOUS: 'Two repositories declare a soul with this name, so it can’t be spawned until one is renamed.',
22
- E_UNSUPPORTED_MODE: 'This soul can’t be started on its own from here.',
23
- 'unsupported-remote-operation': 'The execution server decides this soul’s defaults.',
24
- E_UNSUPPORTED_OPTION: 'One of the options you chose isn’t supported here. Set it back to the default and try again.',
25
- E_RELATIVE_AMBIGUOUS: 'The instance you picked for the relationship can’t be told apart from another one. Pick it again.',
26
- E_SESSION_UNKNOWN: 'The instance you picked for the relationship isn’t available anymore. Pick another one.',
27
- E_HOME_MISMATCH: 'The instance you picked for the relationship isn’t available anymore. Pick another one.',
28
- E_CHILD_SPAWNS_DISABLED: 'The parent you picked doesn’t allow child instances. Pick another one, or choose None.',
29
- E_BRANCH_EXISTS: 'That branch already exists. Choose another branch in Developer settings.',
30
- E_BASE_UNKNOWN: 'That base isn’t a branch, tag or commit in this soul’s repository. Check it in Developer settings.',
31
- E_CLONE_MISSING: 'This soul’s repository isn’t cloned on this machine yet. Clone it, then try again — Details shows how.',
32
- E_LAUNCH_ENV_MISSING: 'The chosen launch configuration can’t start on this machine. Choose another in Developer settings.',
33
- E_LAUNCH_EXECUTABLE: 'The chosen launch configuration can’t start on this machine. Choose another in Developer settings.',
34
- E_LAUNCH_PROBE_UNSUPPORTED: 'The chosen launch configuration can’t be checked safely. Choose another in Developer settings.',
35
- E_LAUNCH_CONFIG_UNKNOWN: 'That launch configuration no longer exists. Choose another in Developer settings.',
36
- // 0.52.0: the kernel refuses a spawn that names no launch configuration where the harness has several and
37
- // none is the default. The sentence names the dialog's own control; the kernel's message, which ends with
38
- // its command-line fix, stays in Details.
39
- E_LAUNCH_CONFIG_AMBIGUOUS: 'This machine has more than one launch configuration for this soul’s harness, and none is the default. Choose one under Launch configuration in Developer settings.',
40
- // 0.30 launch preferences: shown in the kernel's own words when it sends them (spawnProblem: the
41
- // message, then the reason's flat `fix`), which name the harness and where it was chosen; this is the fallback.
42
- E_HARNESS_UNAVAILABLE: 'The harness this soul would run isn’t installed on this machine. Install it, or pick another harness above.',
43
- // 0.53.0: the kernel refuses a spawn that names no launch while `souls.launch` holds a key that names no
44
- // soul. This sentence points at the controls above it and at Details, so it is read only where both are
45
- // there: at the preview, with the kernel's message and fix quoted under Details (spawnProblem's `kernel`
46
- // parts). Everywhere else the shorter one of SPAWN is read.
47
- [UNMATCHED]: 'This machine’s launch preferences name a soul this workspace doesn’t offer, so OATS won’t choose a launch for this soul. To spawn now, pick a harness above, or a launch configuration in Developer settings. To fix it for every spawn, correct the preference (Details).',
48
- E_MODEL_UNKNOWN: 'That model isn’t available for this harness. Pick another model, or keep the default.',
49
- E_INSTANCE_NAME_INVALID: 'Use lowercase letters, numbers and dashes, at most 64 characters, and don’t reuse a soul’s name.',
50
- E_INSTANCE_NAME_TAKEN: 'An instance with this name already exists. Choose another name.',
51
- E_PACKAGE_MISSING: 'A package this soul uses isn’t installed yet. Run Sync in the Workspace view.',
52
- E_PACKAGE_INTEGRITY: 'A package this soul uses no longer matches the lock. Run Sync in the Workspace view.',
53
- E_TARGET_CHANGED: 'The workspace changed while this was loading. Reading it again…',
54
- E_PLAN_CHANGED: 'The workspace changed while this was loading. Check the values and press Spawn again.',
55
- };
16
+ /** The act that follows a problem or an outcome, where the sentence a client shows names one (#855, 6b-2): the
17
+ * client says it in its own words, naming its own controls. Closed and frozen: a new code is a SURFACE change,
18
+ * with the TUI's lead told.
19
+ * change-options change an option of this spawn
20
+ * review-again look at the values again and confirm again
21
+ * check-result read the outcome again before spawning again
22
+ * update-oats update OATS, then try again
23
+ * choose-workspace choose the workspace again
24
+ * sync-workspace sync the workspace
25
+ * details the kernel's detail says more
26
+ * retire retire the instance to finish its cleanup
27
+ * view-schedules open the schedules
28
+ * open-from-list open the instance from the instance list */
29
+ export const SPAWN_NEXT = Object.freeze(['change-options', 'review-again', 'check-result', 'update-oats', 'choose-workspace',
30
+ 'sync-workspace', 'details', 'retire', 'view-schedules', 'open-from-list']);
56
31
 
57
- const PREVIEW = {
58
- E_CLI_TIMEOUT: 'OATS took too long to work out this soul’s defaults. Try again.',
59
- E_CLI_OUTPUT_LIMIT: 'OATS couldn’t work out this soul’s defaults. Try again, or see Details.',
60
- E_CLI_PROTOCOL: 'OATS couldn’t work out this soul’s defaults. Try again, or see Details.',
61
- E_CLI_FAILED: 'OATS couldn’t work out this soul’s defaults. Try again, or see Details.',
32
+ /** The shared fact of each code, and its `next` where the sentence goes on to name an act. What every client
33
+ * says alike stays in the fact: the instance list, syncing the workspace, "Try again.", "Pick it again.". */
34
+ const said = (fact, next = null) => Object.freeze({ fact, next });
35
+ const COMMON_FACTS = {
36
+ E_BAD_ARGS: said('Some of these values can’t be used.', 'change-options'),
37
+ E_BUSY: said('Another spawn is in progress. Try again in a moment.'),
38
+ E_PREVIEW_UNAVAILABLE: said('Spawning needs a newer OATS.', 'update-oats'),
39
+ E_APPLY_UNAVAILABLE: said('Spawning needs a newer OATS.', 'update-oats'),
40
+ E_WORKSPACE_UNKNOWN: said('This workspace isn’t available anymore.', 'choose-workspace'),
41
+ E_SOUL_UNKNOWN: said('This soul isn’t in the workspace anymore. Sync the workspace and try again.'),
42
+ E_SOUL_AMBIGUOUS: said('Two repositories declare a soul with this name, so it can’t be spawned until one is renamed.'),
43
+ E_UNSUPPORTED_MODE: said('This soul can’t be started on its own from here.'),
44
+ 'unsupported-remote-operation': said('The execution server decides this soul’s defaults.'),
45
+ E_UNSUPPORTED_OPTION: said('One of the options you chose isn’t supported here. Set it back to the default and try again.'),
46
+ E_RELATIVE_AMBIGUOUS: said('The instance you picked for the relationship can’t be told apart from another one. Pick it again.'),
47
+ E_SESSION_UNKNOWN: said('The instance you picked for the relationship isn’t available anymore. Pick another one.'),
48
+ E_HOME_MISMATCH: said('The instance you picked for the relationship isn’t available anymore. Pick another one.'),
49
+ E_CHILD_SPAWNS_DISABLED: said('The parent you picked doesn’t allow child instances.', 'change-options'),
50
+ E_BRANCH_EXISTS: said('That branch already exists.', 'change-options'),
51
+ E_BASE_UNKNOWN: said('That base isn’t a branch, tag or commit in this soul’s repository.', 'change-options'),
52
+ E_CLONE_MISSING: said('This soul’s repository isn’t cloned on this machine yet. Clone it, then try again.', 'details'),
53
+ E_LAUNCH_ENV_MISSING: said('The chosen launch configuration can’t start on this machine.', 'change-options'),
54
+ E_LAUNCH_EXECUTABLE: said('The chosen launch configuration can’t start on this machine.', 'change-options'),
55
+ E_LAUNCH_PROBE_UNSUPPORTED: said('The chosen launch configuration can’t be checked safely.', 'change-options'),
56
+ E_LAUNCH_CONFIG_UNKNOWN: said('That launch configuration no longer exists.', 'change-options'),
57
+ E_LAUNCH_CONFIG_AMBIGUOUS: said('This machine has more than one launch configuration for this soul’s harness, and none is the default.', 'change-options'),
58
+ // The fallback, where the kernel sent no words of its own (spawnProblem quotes them, with no `next`).
59
+ E_HARNESS_UNAVAILABLE: said('The harness this soul would run isn’t installed on this machine.', 'change-options'),
60
+ // At the preview, with the kernel's message and fix as `kernel` parts: the client names its own controls.
61
+ [UNMATCHED]: said('This machine’s launch preferences name a soul this workspace doesn’t offer, so OATS won’t choose a launch for this soul.', 'change-options'),
62
+ E_MODEL_UNKNOWN: said('That model isn’t available for this harness. Pick another model, or keep the default.'),
63
+ E_INSTANCE_NAME_INVALID: said('Use lowercase letters, numbers and dashes, at most 64 characters, and don’t reuse a soul’s name.'),
64
+ E_INSTANCE_NAME_TAKEN: said('An instance with this name already exists. Choose another name.'),
65
+ E_PACKAGE_MISSING: said('A package this soul uses isn’t installed yet.', 'sync-workspace'),
66
+ E_PACKAGE_INTEGRITY: said('A package this soul uses no longer matches the lock.', 'sync-workspace'),
67
+ E_TARGET_CHANGED: said('The workspace changed while this was loading. Reading it again…'),
68
+ E_PLAN_CHANGED: said('The workspace changed while this was loading.', 'review-again'),
62
69
  };
63
-
64
- const SPAWN = {
65
- E_PLAN_REQUIRED: 'Check the values and press Spawn to confirm.',
66
- E_DECISION_STALE: 'Something changed before the spawn went through. Nothing was created — check the updated values and press Spawn again.',
67
- E_IDEMPOTENCY_CONFLICT: 'Something changed before the spawn went through. Nothing was created — check the updated values and press Spawn again.',
68
- E_PLACEMENT_TAKEN: 'Another spawn just took this name. Nothing was created — check the new name and press Spawn again.',
69
- E_INTENT_EXPIRED: 'This spawn request expired. Check the instance list before spawning again.',
70
- E_PREFLIGHT_INCOMPLETE: 'OATS couldn’t finish checking this spawn. Try again.',
71
- E_BACKEND_UNAVAILABLE: 'That session backend isn’t installed on this machine. Choose another in Developer settings.',
72
- E_INSTANCE_GONE: 'The instance that was created isn’t there anymore. Check the instance list.',
73
- E_OUTCOME_UNKNOWN: 'We couldn’t confirm whether the instance was created. Use Check result before spawning again.',
74
- E_SPAWN_INCOMPLETE: 'The instance was created but didn’t finish starting. Open it from the instance list instead of spawning again.',
75
- E_INPUT_PREPARATION: 'The opening instruction couldn’t be prepared, so nothing was started. Try again.',
76
- E_CLI_TIMEOUT: 'OATS took too long to answer. The instance may already exist — use Check result before spawning again.',
77
- E_CLI_OUTPUT_LIMIT: 'OATS couldn’t confirm the spawn. Use Check result before spawning again.',
78
- E_CLI_PROTOCOL: 'OATS couldn’t complete the spawn. Try again, or see Details.',
79
- E_CLI_FAILED: 'OATS couldn’t complete the spawn. Try again, or see Details.',
80
- // An unmatched launch preference where nothing is above the sentence and Details hold no kernel text: the
81
- // notice after a press has left the dialog, and a preview whose reason carries no `fix`.
82
- [UNMATCHED]: 'This machine’s launch preferences name a soul this workspace doesn’t offer, so OATS won’t choose a launch for this soul. To spawn now, pick a harness or a launch configuration for this spawn. To fix it for every spawn, correct the preference.',
70
+ const PREVIEW_FACTS = {
71
+ E_CLI_TIMEOUT: said('OATS took too long to work out this soul’s defaults. Try again.'),
72
+ E_CLI_OUTPUT_LIMIT: said('OATS couldn’t work out this soul’s defaults.', 'details'),
73
+ E_CLI_PROTOCOL: said('OATS couldn’t work out this soul’s defaults.', 'details'),
74
+ E_CLI_FAILED: said('OATS couldn’t work out this soul’s defaults.', 'details'),
75
+ };
76
+ const SPAWN_FACTS = {
77
+ E_DECISION_STALE: said('Something changed before the spawn went through. Nothing was created.', 'review-again'),
78
+ E_IDEMPOTENCY_CONFLICT: said('Something changed before the spawn went through. Nothing was created.', 'review-again'),
79
+ E_PLACEMENT_TAKEN: said('Another spawn just took this name. Nothing was created.', 'review-again'),
80
+ E_INTENT_EXPIRED: said('This spawn request expired. Check the instance list before spawning again.'),
81
+ E_PREFLIGHT_INCOMPLETE: said('OATS couldn’t finish checking this spawn. Try again.'),
82
+ E_BACKEND_UNAVAILABLE: said('That session backend isn’t installed on this machine.', 'change-options'),
83
+ E_INSTANCE_GONE: said('The instance that was created isn’t there anymore. Check the instance list.'),
84
+ E_OUTCOME_UNKNOWN: said('We couldn’t confirm whether the instance was created.', 'check-result'),
85
+ E_SPAWN_INCOMPLETE: said('The instance was created but didn’t finish starting. Open it from the instance list instead of spawning again.'),
86
+ E_INPUT_PREPARATION: said('The opening instruction couldn’t be prepared, so nothing was started. Try again.'),
87
+ E_CLI_TIMEOUT: said('OATS took too long to answer. The instance may already exist.', 'check-result'),
88
+ E_CLI_OUTPUT_LIMIT: said('OATS couldn’t confirm the spawn.', 'check-result'),
89
+ E_CLI_PROTOCOL: said('OATS couldn’t complete the spawn.', 'details'),
90
+ E_CLI_FAILED: said('OATS couldn’t complete the spawn.', 'details'),
91
+ // Wherever nothing is above the sentence and Details hold no kernel text: the whole of it is shared.
92
+ [UNMATCHED]: said('This machine’s launch preferences name a soul this workspace doesn’t offer, so OATS won’t choose a launch for this soul. To spawn now, pick a harness or a launch configuration for this spawn. To fix it for every spawn, correct the preference.'),
83
93
  };
84
94
 
85
- /** { text, code, detail } for a { code, message } reason. `stage` is 'preview'
95
+ /** { fact, next, code, detail } for a { code, message } reason. `stage` is 'preview'
86
96
  * (reading defaults) or 'spawn' (after the operator pressed Spawn).
87
97
  *
88
98
  * For an unmatched launch preference whose reason carries the kernel's `fix`, the answer also has
89
99
  * `kernel: { message, fix }`: the kernel's two texts, the strings as they came, for the client to quote
90
- * under the kernel's name (the lead is the client's, `originLead` with its terms). `detail` is then the
100
+ * under the kernel's name (the lead is the client's, `originLead` with its terms), and the fact is the
101
+ * sentence's lead, with the client's controls as `next`. `detail` is then the
91
102
  * code alone, so that no reader of `detail` shows a kernel text without its speaker. A `fix` decides it
92
103
  * because `previewFailure` keeps one only beside the kernel's own message, never beside a table's sentence:
93
104
  * a reason without one (a press, a kernel that sent none, a message that did not travel) reads
94
- * `code · message` as every other code does. */
105
+ * `code · message` as every other code does.
106
+ *
107
+ * `fact` is what happened, in words every client shows alike, and `next` the act that follows (SPAWN_NEXT),
108
+ * or null where the fact says all: the client puts its own words for `next` after the fact. A code the
109
+ * tables do not know reads the stage's E_CLI_FAILED fact, with its own code. */
95
110
  export function spawnProblem(reason, stage = 'preview') {
96
111
  const code = typeof reason?.code === 'string' ? reason.code : 'E_CLI_FAILED';
97
- const own = stage === 'spawn' ? SPAWN : PREVIEW;
98
112
  const message = typeof reason?.message === 'string' ? reason.message.trim() : '';
99
113
  // A missing harness is said as the kernel words it, with its fix (launch preferences, 0.30).
100
114
  const fix = typeof reason?.fix === 'string' ? reason.fix.trim() : '';
101
115
  if (code === UNMATCHED) {
102
116
  const kernel = fix ? { message: typeof reason.message === 'string' ? reason.message : '', fix: reason.fix } : null;
103
- // The sentence that says "above" and "(Details)" is read only where Details hold the kernel's texts.
104
- if (kernel) return { text: stage === 'preview' ? COMMON[UNMATCHED] : SPAWN[UNMATCHED], code, detail: code, kernel };
105
- return { text: SPAWN[UNMATCHED], code, detail: message ? `${code} · ${message}` : code };
117
+ // The client's controls are named only where Details hold the kernel's texts.
118
+ if (kernel) return { ...(stage === 'preview' ? COMMON_FACTS : SPAWN_FACTS)[UNMATCHED], code, detail: code, kernel };
119
+ return { ...SPAWN_FACTS[UNMATCHED], code, detail: message ? `${code} · ${message}` : code };
106
120
  }
107
121
  // The kernel's message usually already ends with its fix: said once.
108
122
  const kernelWords = code === 'E_HARNESS_UNAVAILABLE' && message ? (fix && !message.includes(fix) ? `${message.replace(/[.\s]+$/, '')}: ${fix}` : message) : null;
109
- const text = kernelWords ?? own[code] ?? COMMON[code] ?? (stage === 'spawn' ? SPAWN.E_CLI_FAILED : PREVIEW.E_CLI_FAILED);
110
- return { text, code, detail: message ? `${code} · ${message}` : code };
123
+ const facts = stage === 'spawn' ? SPAWN_FACTS : PREVIEW_FACTS;
124
+ const words = kernelWords ? said(kernelWords) : facts[code] ?? COMMON_FACTS[code] ?? facts.E_CLI_FAILED;
125
+ return { fact: words.fact, next: words.next, code, detail: message ? `${code} · ${message}` : code };
111
126
  }
112
127
 
113
128
  /** The spawn catalog's state, for the soul chooser. */
@@ -126,16 +141,47 @@ export function catalogProblem(catalog) {
126
141
  export function rolledBackProblem(reason, instance) {
127
142
  const code = reason?.code;
128
143
  if (!ROLLED_BACK_CODES.includes(code)) return null;
129
- const text = code === 'E_INTERRUPTED'
144
+ const fact = code === 'E_INTERRUPTED'
130
145
  ? `The spawn of ${instance} was interrupted while its worktree was being set up, and was rolled back. Nothing was created.`
131
146
  : `A capability couldn’t set up the worktree for ${instance}, so the spawn was rolled back. Nothing was created.`;
132
- return { text, code, detail: kernelDetail(code, reason.message) };
147
+ return { fact, next: null, code, detail: kernelDetail(code, reason.message) };
133
148
  }
149
+ /** `instance` travels with the answer: the client names it in its words for `next` (retire). */
134
150
  export function cleanupOwedProblem(reason, instance) {
135
151
  if (!ROLLED_BACK_CODES.includes(reason?.code)) return null;
136
- return { text: `The spawn of ${instance} was stopped, but its cleanup didn’t finish. Retire ${instance} from the roster to complete it.`,
152
+ return { fact: `The spawn of ${instance} was stopped, but its cleanup didn’t finish.`, next: 'retire', instance,
137
153
  code: reason.code, detail: kernelDetail(reason.code, reason.message) };
138
154
  }
155
+
156
+ /** A spawn transaction's outcome in shared words (spawn-transaction.mjs `kind`), as { fact, next } for the
157
+ * client to say with its own words for `next`; `instance` is the name the spawn was given. null for a kind whose
158
+ * words are its reason's (unknown, refused: spawnProblem(outcome.reason, 'spawn')).
159
+ * created complete: "Created <i>." (launched), "Created <i> — not launched." (open-from-list);
160
+ * partial: the reason's message (view-schedules), or, for a wake whose outcome is unknown,
161
+ * "Agent created; wake outcome unavailable." (the boundary's message names the Desktop's
162
+ * Schedules: that act is view-schedules); incomplete: the retained spawn's sentence
163
+ * not-yet-visible created, and not in the instance list as a running session in time (open-from-list)
164
+ * pending-expired still running at the deadline (check-result)
165
+ * cleanup-owed cleanupOwedProblem's (retire); rolled-back: rolledBackProblem's
166
+ * never-submitted prepared, never applied (review-again)
167
+ * drifted the values changed since they were confirmed (review-again) */
168
+ export function outcomeWords(kind, view, instance) {
169
+ if (kind === 'created') {
170
+ if (view?.status === 'incomplete') return said(retainedSpawnMessage(view.incomplete));
171
+ if (view?.status === 'partial' && view.reason?.code === 'E_WAKE_OUTCOME_UNKNOWN') return said('Agent created; wake outcome unavailable.', 'view-schedules');
172
+ if (view?.status === 'partial') return said(view.reason?.message || `Created ${instance}.`, 'view-schedules');
173
+ return view?.receipt?.launched === false ? said(`Created ${instance} — not launched.`, 'open-from-list') : said(`Created ${instance}.`);
174
+ }
175
+ if (kind === 'not-yet-visible') return said(`Created ${instance} — not yet visible as a running session.`, 'open-from-list');
176
+ if (kind === 'pending-expired') return said('The spawn is still running.', 'check-result');
177
+ if (kind === 'cleanup-owed' || kind === 'rolled-back') {
178
+ const problem = (kind === 'cleanup-owed' ? cleanupOwedProblem : rolledBackProblem)(view?.reason, instance);
179
+ return problem ? said(problem.fact, problem.next) : null;
180
+ }
181
+ if (kind === 'never-submitted') return said('That spawn was never submitted.', 'review-again');
182
+ if (kind === 'drifted') return said('These values changed since you last looked.', 'review-again');
183
+ return null;
184
+ }
139
185
  function kernelDetail(code, message) {
140
186
  const line = displayLine(message);
141
187
  return line ? `${code} · ${line}` : code;
@@ -180,6 +180,9 @@ export function previewChoices(v) {
180
180
  }
181
181
  return out;
182
182
  }
183
+ /** The choices of a spawn with no field touched (#855, 6b-2): what a client sends before the operator changes
184
+ * anything (the soul's own model, no relation). A fresh object each call, for the client to change. */
185
+ export const defaultSpawnChoices = () => previewChoices({});
183
186
  /** The spawn flags for admitted choices — shared by preview and apply. The
184
187
  * harness flag is the kernel's (feature harness: --harness; a released kernel: --runtime). */
185
188
  export function choiceArgv(choices, cli) {
@@ -0,0 +1,119 @@
1
+ /** The facts a spawn preview shows, as data (#855, 6b-2): what the Desktop's spawn dialog draws in its preview
2
+ * column (renderer/spawn-dialog.mjs `renderPreview`, `composePreviewModules`), for any client to draw in its own
3
+ * way. Words about the preview only: no DOM, and nothing that names a client's controls.
4
+ *
5
+ * `previewFacts(data, { name, runsOn, cli })` for a preview projection (spawn-preview-contract.mjs `previewData`):
6
+ * identity [{ label, text, title?, muted? }]: the Name (`name`, the client's own name field; without one the
7
+ * kernel numbers the instance, `muted`) and the Home (relative to the deployment, the full path as
8
+ * `title`)
9
+ * facts [{ label, parts: [{ text, mono?, muted?, sub? }], harness? }]: Works in, Harness (with `harness`,
10
+ * the id a client may badge), Team, Relationship, Setup, Runs on (`runsOn`, the client's own words
11
+ * for the chosen deployment), in that order, each only when the preview says it. A part is plain
12
+ * text, `mono` (a branch), `muted`, or `sub` (a value's second line, muted: where it came from,
13
+ * what else)
14
+ * prompts [{ label, text, mono? }] | null: the launch-prompt note, in the kernel contract's words
15
+ * warnings [[line, …], …]: each capability warning's lines, every one (a client bounds what it shows,
16
+ * capability-warnings-contract.mjs `warningsShown`); [] when none
17
+ * modules { core: [{ layer, label, module }], caps: [module] } | null: the core slots in their order (a
18
+ * `module` or null, an empty slot) and the other capabilities by name; each module is
19
+ * { name, source, why } (why '' when the preview does not say). null when the preview carries no
20
+ * `modules` (an older kernel: no placeholder).
21
+ * `cli` is the CLI the preview was read with: it decides which launch facts the preview's `launch` may show. */
22
+ import { displayLine } from './display-text.mjs';
23
+ import { shownLaunch, launchHarnessName, launchFromText } from './launch-view.mjs';
24
+
25
+ /** The preview's work mode in words (board 6, "Works in"); an unknown mode verbatim. */
26
+ const WORK_PHRASES = Object.freeze({ __proto__: null, worktree: 'own worktree', checkout: 'shared checkout', attached: "a parent's worktree", directory: 'own folder · free to work across repos', workspace: 'all member repos' });
27
+ export const worksInText = work => WORK_PHRASES[work] ?? work;
28
+ /** The preview's home, short enough to read: relative to the deployment (the preview's subject.dir)
29
+ * when it lies inside it, else its last three segments behind "…/". The full path is the title. */
30
+ export function homeText(home, dir) {
31
+ if (typeof home !== 'string' || !home) return null;
32
+ const base = typeof dir === 'string' && dir ? dir.replace(/\/+$/, '') : '';
33
+ if (base && home.startsWith(`${base}/`) && home.length > base.length + 1) return { text: home.slice(base.length + 1), title: home };
34
+ const parts = home.split('/').filter(Boolean);
35
+ return { text: parts.length > 3 ? `…/${parts.slice(-3).join('/')}` : home, title: home };
36
+ }
37
+ /** A worktree spawn's "Works in": the new branch (mono in the view) and the ref it starts from, when the preview says. */
38
+ export function worktreeText(data) {
39
+ return { lead: 'worktree · branch ', branch: data.branch, tail: data.base?.ref ? ` from ${data.base.ref}` : '' };
40
+ }
41
+ /** The relation the preview binds, in words with its anchor ("child of api-2"); null when independent. */
42
+ const RELATION_WORDS = Object.freeze({ __proto__: null, child: 'child of', sibling: 'sibling of', parent: 'parent of' });
43
+ export function relationText(data) {
44
+ const kind = data?.relation;
45
+ if (typeof kind !== 'string' || !kind) return null;
46
+ const anchor = data.decision?.effective?.relation?.anchor?.instance;
47
+ if (!RELATION_WORDS[kind]) return kind;
48
+ return typeof anchor === 'string' && anchor ? `${RELATION_WORDS[kind]} ${anchor}` : RELATION_WORDS[kind];
49
+ }
50
+ /** A preview module's source, as the Capabilities tag says it: the package and version, the member
51
+ * repository, or the kind verbatim. Never a reason: that is moduleWhyText's, beside it. */
52
+ export function moduleSourceText(from) {
53
+ if (from?.kind === 'package') return `package ${from.package ?? ''}${from.version ? ` ${from.version}` : ''}`.trimEnd();
54
+ if (from?.kind === 'member') return `${String(from.repoKey ?? '').split('/').pop().replace(/\.git$/, '') || 'member'} · latest`;
55
+ return typeof from?.kind === 'string' ? from.kind : '';
56
+ }
57
+ /** Why a preview module is there, as the reason tag beside its source says it: the projection's
58
+ * `composedFrom` (feature preview-composed-from) — "Soul" or "Workspace default" (a core row already
59
+ * names its slot). '' (no tag) when the preview does not say: an older CLI, or a value the projection
60
+ * dropped. Never guessed from the soul. */
61
+ export function moduleWhyText(m) {
62
+ if (m?.composedFrom === 'soul') return 'Soul';
63
+ if (m?.composedFrom === 'workspace') return 'Workspace default';
64
+ return '';
65
+ }
66
+ const CORE_SLOTS = Object.freeze([['knowledge', 'Knowledge'], ['messaging', 'Messaging'], ['tasks', 'Tasks']]);
67
+ const CORE_LAYERS = CORE_SLOTS.map(([layer]) => layer);
68
+ /** The preview's `modules` rows [{name, layer, from, composedFrom?}] as the core slots and the other
69
+ * capabilities; null when the preview carries none. A module filling a core slot is the slot's only: never
70
+ * among the others. */
71
+ function previewModules(modules) {
72
+ if (!Array.isArray(modules)) return null;
73
+ const rows = modules.filter(m => m && typeof m === 'object' && typeof m.name === 'string' && m.name);
74
+ const described = m => ({ name: m.name, source: moduleSourceText(m.from), why: moduleWhyText(m) });
75
+ const core = CORE_SLOTS.map(([layer, label]) => { const m = rows.find(x => x.layer === layer); return { layer, label, module: m ? described(m) : null }; });
76
+ const caps = rows.filter(m => !CORE_LAYERS.includes(m.layer)).sort((a, b) => a.name.localeCompare(b.name)).map(described);
77
+ return { core, caps };
78
+ }
79
+
80
+ export function previewFacts(data, { name = null, runsOn = null, cli = null } = {}) {
81
+ const preview = data && typeof data === 'object' ? data : {};
82
+ const identity = [name ? { label: 'Name', text: name } : { label: 'Name', text: 'numbered by the kernel', muted: true }];
83
+ const home = homeText(preview.home, preview.subject?.dir);
84
+ if (home) identity.push({ label: 'Home', text: home.text, title: home.title });
85
+ const facts = [], fact = (label, parts, extra = {}) => { facts.push({ label, ...extra, parts }); };
86
+ const worktree = preview.work === 'worktree' && preview.branch ? worktreeText(preview) : null;
87
+ if (worktree) fact('Works in', [{ text: worktree.lead }, { text: worktree.branch, mono: true }, ...(worktree.tail ? [{ text: worktree.tail }] : [])]);
88
+ else if (preview.work) fact('Works in', [{ text: worksInText(preview.work) }]);
89
+ if (preview.harness) {
90
+ // Where the harness came from: the Launch's `from` in words (0.30), else the kernel's modelSource verbatim.
91
+ const launch = shownLaunch(preview.launch, cli);
92
+ const from = launch ? launchFromText(launch.from) : preview.modelSource;
93
+ fact('Harness', [{ text: `${launchHarnessName(preview.harness)} · ${preview.model ?? 'default model'}` }, ...(from ? [{ text: from, sub: true }] : [])], { harness: preview.harness });
94
+ }
95
+ // Team model v2: the default the kernel resolved (or none), then the other teams it may join. A 0.29 kernel reports only `team`, the primary label.
96
+ const others = (preview.teams || []).map(t => t.label).filter(label => label !== preview.defaultTeam?.label);
97
+ const also = others.length ? [{ text: `may also join ${others.join(', ')}`, sub: true }] : [];
98
+ if (preview.defaultTeam) fact('Team', [{ text: preview.defaultTeam.label }, { text: ' · default', muted: true }, ...also]);
99
+ else if (preview.defaultTeam === null && !(preview.teams?.length)) fact('Team', [{ text: 'none', muted: true }]);
100
+ else if (preview.defaultTeam === undefined && typeof preview.team === 'string' && preview.team) fact('Team', [{ text: preview.team }]);
101
+ const relation = relationText(preview);
102
+ if (relation) fact('Relationship', [{ text: relation }]);
103
+ // The capabilities whose `worktree` hook sets up ./work, in the order they run ([] or absent: none).
104
+ const hooks = (preview.worktreeHooks ?? []).map(h => `${displayLine(h.capability) ?? ''}${h.required ? ' (required)' : ''}`);
105
+ if (hooks.length) fact('Setup', [{ text: hooks.join(', ') }, { text: 'Runs after the worktree is made. Can take several minutes.', sub: true }]);
106
+ if (runsOn) fact('Runs on', [{ text: runsOn }]);
107
+ let prompts = null;
108
+ if (preview.launchPromptAnswers) {
109
+ // The launch-prompt policy is a note, not a fact: its words stay the kernel contract's, verbatim.
110
+ const policy = preview.launchPromptAnswers;
111
+ prompts = [{ label: 'Launch prompts', text: policy.awebDevelopmentChannel
112
+ ? 'The launcher will answer the aweb development-channel confirmation for this home. This policy does not confirm readiness. A harness update can block the launch until its prompt fixtures are refreshed; no fallback key is sent.'
113
+ : 'None. The launcher will not answer prompts for this home. This policy does not confirm readiness.' }];
114
+ if (policy.consentSource) prompts.push({ label: 'Prompt consent source', text: policy.consentSource, mono: true });
115
+ }
116
+ // Capability warnings (0.49.0): the kernel's strings, each as its lines; they block nothing.
117
+ const warnings = (Array.isArray(preview.warnings) ? preview.warnings : []).map(w => String(w).split('\n'));
118
+ return { identity, facts, prompts, warnings, modules: previewModules(preview.modules) };
119
+ }
@@ -0,0 +1,152 @@
1
+ /** Exact local soul/anchor admission against the deployment's spawn catalog,
2
+ * the two-slot read-only preview budget, and the dialog's settled-answer cache.
3
+ *
4
+ * A client makes its own preview (createSpawnPreview) and owns it: nothing here is
5
+ * held at module level, so two clients' budgets, caches and flights never meet.
6
+ * The cache (60 s, keyed by the admission identity) serves the dialog's preview
7
+ * read and prepare's: an answer is still admitted against the current context
8
+ * before it is returned, and a workspace's entries go when the client observes a
9
+ * change that can alter a preview (the Desktop's: server/oats-web.mjs). Prepare taking
10
+ * a held decision is safe because apply binds it with the kernel's --expect-decision:
11
+ * a decision the kernel no longer makes is refused there (E_DECISION_STALE), never applied. */
12
+ import { dirname } from 'node:path';
13
+ import { performance } from 'node:perf_hooks';
14
+ import { cliSpawnPreview } from './spawn-preview-cli.mjs';
15
+ import { admitInstance } from './instance-admission.mjs';
16
+ import { absolute, record, previewSelector, previewChoices, previewSupported, previewFailure, previewData, previewComposedFrom } from './spawn-preview-contract.mjs';
17
+ /** One preview's flights: its two-slot budget (`slots`), the flights in the air per invoker (`byInvoker`, where
18
+ * exact duplicates coalesce), and the monotonic clock that stamps each flight's start (`started`). The cache is
19
+ * given the same clock: it orders flight starts against invalidations, so a flight that started before its
20
+ * workspace was invalidated never fills the cache, even when a later request coalesced onto it. */
21
+ export function createSpawnPreviewFlights() {
22
+ let stamp = 0;
23
+ return { slots: new Set(), byInvoker: new WeakMap(), started: new WeakMap(), clock: () => ++stamp };
24
+ }
25
+ const missing = (factory, what) => new TypeError(`${factory}: ${what} is required`);
26
+ export const PREVIEW_CACHE_TTL_MS = 60000;
27
+ // A name refusal answers the same name the same way until something changes.
28
+ const CACHED_REFUSALS = ['E_INSTANCE_NAME_TAKEN', 'E_INSTANCE_NAME_INVALID'];
29
+ const cacheable = result => result?.status === 'available' || result?.status === 'unavailable' && CACHED_REFUSALS.includes(result.reason?.code);
30
+ /** `clock` is the flights' clock (createSpawnPreviewFlights): required, never a clock of its own. */
31
+ export function createSpawnPreviewCache({ ttlMs = PREVIEW_CACHE_TTL_MS, limit = 64, now = () => performance.now(), clock } = {}) {
32
+ if (typeof clock !== 'function') throw missing('createSpawnPreviewCache', 'clock (the flights\' clock)');
33
+ const entries = new Map(), invalidatedAt = new Map();
34
+ let clearedAt = 0;
35
+ return {
36
+ get(identity) {
37
+ const entry = entries.get(identity);
38
+ if (!entry) return null;
39
+ if (now() >= entry.expires) { entries.delete(identity); return null; }
40
+ return structuredClone(entry.result);
41
+ },
42
+ set(identity, workspace, result, startedAt) {
43
+ if (!cacheable(result) || typeof startedAt !== 'number' || startedAt <= clearedAt || startedAt <= (invalidatedAt.get(workspace) ?? 0)) return;
44
+ entries.delete(identity); entries.set(identity, { workspace, result: structuredClone(result), expires: now() + ttlMs });
45
+ for (const [key, entry] of entries) if (now() >= entry.expires) entries.delete(key);
46
+ while (entries.size > limit) entries.delete(entries.keys().next().value);
47
+ },
48
+ /** A workspace's answers go (no argument: every workspace's), and no flight in the air may refill them. */
49
+ invalidate(workspace) {
50
+ if (workspace === undefined) { clearedAt = clock(); entries.clear(); return; }
51
+ invalidatedAt.set(workspace, clock());
52
+ for (const [key, entry] of entries) if (entry.workspace === workspace) entries.delete(key);
53
+ },
54
+ size: () => entries.size,
55
+ clock,
56
+ };
57
+ }
58
+ export function admitSpawnSelection(selector, choices, { workspace: w, cli, agents = [], instances = [] } = {}) {
59
+ const fail = error => ({ error });
60
+ if (!w || typeof w.id !== 'string' || !w.id || !absolute(w.scope)) return fail('E_WORKSPACE_UNKNOWN');
61
+ if (w.remote || w.server) return fail('unsupported-remote-operation');
62
+ if (!previewSupported(cli)) return fail('E_PREVIEW_UNAVAILABLE');
63
+ const rows = agents.filter(a => a.name === selector.soul && a.agentsRoot === selector.agentsRoot);
64
+ if (rows.length !== 1) return fail('E_SOUL_UNKNOWN');
65
+ const soul = rows[0];
66
+ if (soul.remote || soul.server) return fail('unsupported-remote-operation');
67
+ if (soul.work === 'attached') return fail('E_UNSUPPORTED_MODE'); // no renderer workDir authority
68
+ // An exact (unprefixed) name only where the CLI advertises it.
69
+ if (choices.name !== undefined && !cli.features.includes('spawn-name')) return fail('E_UNSUPPORTED_OPTION');
70
+ if (choices.identity !== undefined && !cli.features.includes('spawn-provider-payload')) return fail('E_UNSUPPORTED_OPTION');
71
+ // The one work override offered: a checkout soul asked for a worktree.
72
+ if (choices.work !== undefined && soul.work !== 'checkout') return fail('E_UNSUPPORTED_OPTION');
73
+ const work = choices.work ?? soul.work;
74
+ if ((choices.base !== undefined || choices.branch !== undefined) && work !== 'worktree') return fail('E_UNSUPPORTED_OPTION');
75
+ const supports = (values, value) => Array.isArray(values) && values.includes(value);
76
+ if (choices.harness && !supports(cli.harnesses, choices.harness) || choices.backend && !supports(cli.sessionBackends, choices.backend)
77
+ || choices.yolo !== undefined && !supports(cli.launchOptions, 'yolo') || choices.launchConfig && !cli.features.includes('launch-config')) return fail('E_UNSUPPORTED_OPTION');
78
+ let anchorIdentity = null;
79
+ if (choices.relation.kind !== 'unrelated') {
80
+ const a = choices.relation.anchor, admitted = admitInstance(a, { workspace: w, cli, instances });
81
+ if (admitted.code) return fail(admitted.code);
82
+ // The CLI takes name+root, not agent+name+root. Do not pretend that a more
83
+ // precise renderer selector can disambiguate what its public argv cannot.
84
+ const expressible = instances.filter(i => i.instance === a.instance && i.agentsRoot === a.agentsRoot && (i.server ?? null) === null);
85
+ if (expressible.length !== 1) return fail('E_RELATIVE_AMBIGUOUS');
86
+ anchorIdentity = [admitted.target, expressible[0].createdAt ?? null];
87
+ }
88
+ const target = { workspace: w.id, context: dirname(soul.agentsRoot), selector };
89
+ const identity = JSON.stringify([w.id, w.scope, target, soul.work, soul.repo, soul.capability, anchorIdentity, choices,
90
+ cli.bin, cli.version, cli.spawnPreviewApi, cli.spawnApplyApi, cli.features, cli.harnesses, cli.sessionBackends, cli.launchOptions]);
91
+ return { target, identity, cli: structuredClone(cli) };
92
+ }
93
+ /** One read of a preview. `flights` (createSpawnPreviewFlights) is required: the reads of one preview share it,
94
+ * and a cache given here must run on its clock. maxAge: the dialog's reads may reuse member heads the kernel
95
+ * observed within that many seconds (feature spawn-preview-max-age, passed only when the admitted CLI
96
+ * advertises it). Prepare's reads never do. exec: as createSpawnPreview's. */
97
+ export function createSpawnPreviewBoundary({ invoke = cliSpawnPreview, cache = null, maxAge = null, flights, exec } = {}) {
98
+ if (!flights?.slots || !flights.byInvoker || !flights.started || typeof flights.clock !== 'function') throw missing('createSpawnPreviewBoundary', 'flights (createSpawnPreviewFlights)');
99
+ if (cache && cache.clock !== flights.clock) throw new TypeError('createSpawnPreviewBoundary: the cache must run on the flights\' clock');
100
+ const { slots, byInvoker, started } = flights, io = exec ? [{ exec }] : [];
101
+ return async function read(request, getContext) {
102
+ try {
103
+ if (!record(request) || request.action !== 'preview' || Object.keys(request).some(k => !['action', 'selector', 'choices'].includes(k))) return previewFailure('E_BAD_ARGS');
104
+ const selector = previewSelector(request.selector), choices = previewChoices(request.choices);
105
+ if (!selector || !choices) return previewFailure('E_BAD_ARGS');
106
+ const selected = admitSpawnSelection(selector, choices, getContext());
107
+ if (selected.error) return previewFailure(selected.error);
108
+ const { target, identity, cli } = selected;
109
+ const held = cache?.get(identity);
110
+ if (held) return held; // admitted above against the current context, like a fresh answer
111
+ let pending = byInvoker.get(invoke); if (!pending) { pending = new Map(); byInvoker.set(invoke, pending); }
112
+ const reuse = maxAge !== null && cli.features.includes('spawn-preview-max-age') ? { maxAge } : {};
113
+ // A reusing read and a live one never coalesce: prepare must not ride on a dialog read's older heads.
114
+ const key = reuse.maxAge ? `${identity}\u0000max-age` : identity;
115
+ if (!pending.has(key)) {
116
+ if (slots.size >= 2) return previewFailure('E_BUSY', target);
117
+ const slot = {}; slots.add(slot);
118
+ const flight = Promise.resolve().then(() => invoke(cli, { target, choices, ...reuse }, ...io)).then(envelope => {
119
+ if (envelope?.schemaVersion !== 1 || envelope.ok !== true) return previewFailure(envelope?.error?.code, target, envelope?.error?.message, envelope?.error?.details?.fix);
120
+ const data = previewData(envelope.result, target, { composedFrom: previewComposedFrom(cli) });
121
+ return data ? { spawnPreviewViewApi: 1, status: 'available', target, data, reason: null } : previewFailure('E_CLI_PROTOCOL', target);
122
+ }).catch(() => previewFailure('E_CLI_FAILED', target)).finally(() => { slots.delete(slot); pending.delete(key); });
123
+ started.set(flight, flights.clock()); pending.set(key, flight);
124
+ }
125
+ const flight = pending.get(key), result = await flight, current = admitSpawnSelection(selector, choices, getContext());
126
+ if (current.identity !== identity) return previewFailure('E_TARGET_CHANGED', target);
127
+ cache?.set(identity, target.workspace, result, started.get(flight));
128
+ return result;
129
+ } catch { return previewFailure('E_CLI_FAILED'); }
130
+ };
131
+ }
132
+ export const PREVIEW_MAX_AGE_S = 60;
133
+ /** One client's spawn preview: `{ read, prepareRead, cache }`.
134
+ * read the dialog's read, through the cache; its kernel reads may reuse recent member heads (maxAge,
135
+ * where the CLI declares spawn-preview-max-age)
136
+ * prepareRead prepare's read (spawn-apply.mjs createSpawnApplyBoundary's `read`), through the same cache,
137
+ * never with maxAge; a reusing read and a live one never coalesce
138
+ * cache `invalidate(workspace?)` (no argument: every workspace's answers) and `size()`
139
+ * The two reads share one two-slot budget, one set of coalesced flights and one clock, the cache's too.
140
+ * exec optional: the client's own execFile, passed to `invoke` as `invoke(cli, options, { exec })` for both
141
+ * reads (cli-adapter.mjs `runJson` has the rule); without it `invoke` is given no third argument and
142
+ * cliSpawnPreview's own default runs. A read is a read: its options carry no `detached` and a 30 s
143
+ * deadline, and it ends with its caller. */
144
+ export function createSpawnPreview({ invoke = cliSpawnPreview, exec, now = () => performance.now(), ttlMs = PREVIEW_CACHE_TTL_MS, limit = 64, maxAge = PREVIEW_MAX_AGE_S } = {}) {
145
+ const flights = createSpawnPreviewFlights();
146
+ const cache = createSpawnPreviewCache({ ttlMs, limit, now, clock: flights.clock });
147
+ return {
148
+ read: createSpawnPreviewBoundary({ invoke, cache, maxAge, flights, exec }),
149
+ prepareRead: createSpawnPreviewBoundary({ invoke, cache, flights, exec }),
150
+ cache: { invalidate: workspace => cache.invalidate(workspace), size: () => cache.size() },
151
+ };
152
+ }