@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.
- package/bin/oats.mjs +24 -11
- package/docs/configuration.md +19 -28
- package/docs/desktop-cli-api.md +38 -15
- package/docs/desktop.md +14 -0
- package/docs/execution-targets.md +10 -1
- package/docs/implementation.md +7 -1
- package/docs/integrations.md +3 -1
- package/docs/official-catalog.md +1 -1
- package/docs/packages.md +5 -5
- package/docs/release-notes/v0.57.1.md +275 -0
- package/docs/release-notes/v0.58.0.md +107 -0
- package/docs/servers.md +18 -0
- package/docs/souls-and-instances.md +9 -0
- package/docs/tui.md +224 -87
- package/docs/workspaces.md +1 -1
- package/lib/core.mjs +11 -4
- package/lib/session-viewer.mjs +29 -4
- package/package-catalog.json +1 -1
- package/package.json +1 -1
- package/packages/client/cli-adapter.mjs +9 -7
- package/packages/client/cli-locator.mjs +2 -2
- package/packages/client/composed-gate.mjs +34 -0
- package/packages/client/inspect-boundary.mjs +157 -0
- package/packages/client/inspect-cache.mjs +86 -0
- package/packages/client/keyed-catalog.mjs +132 -0
- package/packages/client/launch-view.mjs +46 -0
- package/packages/client/panel-views.mjs +1 -1
- package/packages/client/session-attach.mjs +7 -5
- package/packages/client/soul-catalog.mjs +77 -0
- package/packages/client/soul-colors.mjs +31 -0
- package/packages/client/soul-facts.mjs +85 -0
- package/packages/client/soul-rows.mjs +48 -0
- package/packages/client/spawn-apply-cli.mjs +19 -8
- package/packages/client/spawn-apply.mjs +216 -0
- package/packages/client/spawn-messages.mjs +131 -85
- package/packages/client/spawn-preview-cli.mjs +2 -1
- package/packages/client/spawn-preview-contract.mjs +3 -0
- package/packages/client/spawn-preview-facts.mjs +119 -0
- package/packages/client/spawn-preview.mjs +164 -0
- package/packages/client/spawn-transaction.mjs +136 -0
- package/packages/record/lib/directory-identity.mjs +14 -0
- package/packages/record/lib/native-history.mjs +6 -5
- package/packages/tui/README.md +32 -11
- package/packages/tui/lib/actions.mjs +10 -1
- package/packages/tui/lib/config.mjs +9 -14
- package/packages/tui/lib/main.mjs +165 -57
- package/packages/tui/lib/model.mjs +28 -24
- package/packages/tui/lib/panel.mjs +1019 -0
- package/packages/tui/lib/read.mjs +5 -14
- package/packages/tui/lib/store.mjs +77 -30
- package/packages/tui/lib/term/capture.mjs +260 -0
- package/packages/tui/lib/term/screen.mjs +44 -8
- package/packages/tui/lib/term/style.mjs +78 -6
- package/packages/tui/lib/term/text.mjs +24 -4
- package/packages/tui/lib/term/through.mjs +213 -0
- package/packages/tui/lib/term/tty.mjs +7 -60
- package/packages/tui/lib/views/frame.mjs +126 -40
- package/packages/tui/lib/views/help.mjs +12 -10
- package/skills/oats-getting-started/SKILL.md +3 -2
- package/packages/tui/lib/open.mjs +0 -45
|
@@ -1,113 +1,128 @@
|
|
|
1
|
-
/** Plain-language wording for
|
|
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).
|
|
5
|
-
*
|
|
6
|
-
* the code and the technical message stay available
|
|
7
|
-
* troubleshooting.
|
|
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
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
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
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
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
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
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
|
-
/** {
|
|
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)
|
|
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
|
|
104
|
-
if (kernel) return {
|
|
105
|
-
return {
|
|
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
|
|
110
|
-
|
|
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
|
|
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 {
|
|
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 {
|
|
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;
|
|
@@ -16,7 +16,8 @@ export function cliSpawnPreview(cli, options = {}, io = {}) {
|
|
|
16
16
|
const target = previewTarget(options.target), choices = previewChoices(options.choices);
|
|
17
17
|
if (!target || !choices || Object.keys(options).some(k => !['target', 'choices', 'maxAge'].includes(k))) return Promise.resolve(failure('E_BAD_ARGS'));
|
|
18
18
|
// Feature spawn-preview-max-age: reuse member heads the kernel observed within maxAge seconds. Only
|
|
19
|
-
// where the CLI advertises it (an older kernel refuses the flag); prepare
|
|
19
|
+
// where the CLI advertises it (an older kernel refuses the flag); prepare never passes it. The apply's own
|
|
20
|
+
// --max-age is spawn-apply-max-age's (spawn-apply-cli.mjs).
|
|
20
21
|
const maxAge = options.maxAge;
|
|
21
22
|
if (maxAge !== undefined && (!Number.isInteger(maxAge) || maxAge < 1 || maxAge > 3600)) return Promise.resolve(failure('E_BAD_ARGS'));
|
|
22
23
|
const reuse = maxAge !== undefined && Array.isArray(cli.features) && cli.features.includes('spawn-preview-max-age') ? ['--max-age', String(maxAge)] : [];
|
|
@@ -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,164 @@
|
|
|
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 (keyed by the admission identity) serves the dialog's preview read for
|
|
7
|
+
* 60 s and prepare's for PREPARE_REUSE_MS (#1246: the prepared intent's own lifetime,
|
|
8
|
+
* so a press after the operator lingered over the form runs no second kernel preview):
|
|
9
|
+
* an answer is still admitted against the current context before it is returned, and a
|
|
10
|
+
* workspace's entries go when the client observes a change that can alter a preview (the
|
|
11
|
+
* Desktop's: server/oats-web.mjs). Prepare taking a held decision is safe because apply
|
|
12
|
+
* binds it with the kernel's --expect-decision: a decision the kernel no longer makes is
|
|
13
|
+
* refused there (E_DECISION_STALE, read as drifted), never applied. */
|
|
14
|
+
import { dirname } from 'node:path';
|
|
15
|
+
import { performance } from 'node:perf_hooks';
|
|
16
|
+
import { cliSpawnPreview } from './spawn-preview-cli.mjs';
|
|
17
|
+
import { admitInstance } from './instance-admission.mjs';
|
|
18
|
+
import { absolute, record, previewSelector, previewChoices, previewSupported, previewFailure, previewData, previewComposedFrom } from './spawn-preview-contract.mjs';
|
|
19
|
+
/** One preview's flights: its two-slot budget (`slots`), the flights in the air per invoker (`byInvoker`, where
|
|
20
|
+
* exact duplicates coalesce), and the monotonic clock that stamps each flight's start (`started`). The cache is
|
|
21
|
+
* given the same clock: it orders flight starts against invalidations, so a flight that started before its
|
|
22
|
+
* workspace was invalidated never fills the cache, even when a later request coalesced onto it. */
|
|
23
|
+
export function createSpawnPreviewFlights() {
|
|
24
|
+
let stamp = 0;
|
|
25
|
+
return { slots: new Set(), byInvoker: new WeakMap(), started: new WeakMap(), clock: () => ++stamp };
|
|
26
|
+
}
|
|
27
|
+
const missing = (factory, what) => new TypeError(`${factory}: ${what} is required`);
|
|
28
|
+
export const PREVIEW_CACHE_TTL_MS = 60000;
|
|
29
|
+
/** How old a held answer prepare may take (#1246): the lifetime of the intent it prepares. */
|
|
30
|
+
export const PREPARE_REUSE_MS = 300000;
|
|
31
|
+
// A name refusal answers the same name the same way until something changes.
|
|
32
|
+
const CACHED_REFUSALS = ['E_INSTANCE_NAME_TAKEN', 'E_INSTANCE_NAME_INVALID'];
|
|
33
|
+
const cacheable = result => result?.status === 'available' || result?.status === 'unavailable' && CACHED_REFUSALS.includes(result.reason?.code);
|
|
34
|
+
/** `clock` is the flights' clock (createSpawnPreviewFlights): required, never a clock of its own. An entry is kept
|
|
35
|
+
* for `keepMs` (at least `ttlMs`) from when it was read; `get(identity, maxAgeMs)` answers it only while it is
|
|
36
|
+
* younger than `maxAgeMs` (default `ttlMs`): the dialog's reads take 60 s, prepare's PREPARE_REUSE_MS. */
|
|
37
|
+
export function createSpawnPreviewCache({ ttlMs = PREVIEW_CACHE_TTL_MS, keepMs = ttlMs, limit = 64, now = () => performance.now(), clock } = {}) {
|
|
38
|
+
if (typeof clock !== 'function') throw missing('createSpawnPreviewCache', 'clock (the flights\' clock)');
|
|
39
|
+
const entries = new Map(), invalidatedAt = new Map();
|
|
40
|
+
let clearedAt = 0;
|
|
41
|
+
const kept = Math.max(ttlMs, keepMs);
|
|
42
|
+
return {
|
|
43
|
+
get(identity, maxAgeMs = ttlMs) {
|
|
44
|
+
const entry = entries.get(identity);
|
|
45
|
+
if (!entry) return null;
|
|
46
|
+
if (now() >= entry.expires) { entries.delete(identity); return null; }
|
|
47
|
+
if (now() - entry.readAt >= maxAgeMs) return null; // too old for this reader; a longer-lived one may still take it
|
|
48
|
+
return structuredClone(entry.result);
|
|
49
|
+
},
|
|
50
|
+
set(identity, workspace, result, startedAt) {
|
|
51
|
+
if (!cacheable(result) || typeof startedAt !== 'number' || startedAt <= clearedAt || startedAt <= (invalidatedAt.get(workspace) ?? 0)) return;
|
|
52
|
+
const readAt = now();
|
|
53
|
+
entries.delete(identity); entries.set(identity, { workspace, result: structuredClone(result), readAt, expires: readAt + kept });
|
|
54
|
+
for (const [key, entry] of entries) if (now() >= entry.expires) entries.delete(key);
|
|
55
|
+
while (entries.size > limit) entries.delete(entries.keys().next().value);
|
|
56
|
+
},
|
|
57
|
+
/** A workspace's answers go (no argument: every workspace's), and no flight in the air may refill them. */
|
|
58
|
+
invalidate(workspace) {
|
|
59
|
+
if (workspace === undefined) { clearedAt = clock(); entries.clear(); return; }
|
|
60
|
+
invalidatedAt.set(workspace, clock());
|
|
61
|
+
for (const [key, entry] of entries) if (entry.workspace === workspace) entries.delete(key);
|
|
62
|
+
},
|
|
63
|
+
size: () => entries.size,
|
|
64
|
+
clock,
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
export function admitSpawnSelection(selector, choices, { workspace: w, cli, agents = [], instances = [] } = {}) {
|
|
68
|
+
const fail = error => ({ error });
|
|
69
|
+
if (!w || typeof w.id !== 'string' || !w.id || !absolute(w.scope)) return fail('E_WORKSPACE_UNKNOWN');
|
|
70
|
+
if (w.remote || w.server) return fail('unsupported-remote-operation');
|
|
71
|
+
if (!previewSupported(cli)) return fail('E_PREVIEW_UNAVAILABLE');
|
|
72
|
+
const rows = agents.filter(a => a.name === selector.soul && a.agentsRoot === selector.agentsRoot);
|
|
73
|
+
if (rows.length !== 1) return fail('E_SOUL_UNKNOWN');
|
|
74
|
+
const soul = rows[0];
|
|
75
|
+
if (soul.remote || soul.server) return fail('unsupported-remote-operation');
|
|
76
|
+
if (soul.work === 'attached') return fail('E_UNSUPPORTED_MODE'); // no renderer workDir authority
|
|
77
|
+
// An exact (unprefixed) name only where the CLI advertises it.
|
|
78
|
+
if (choices.name !== undefined && !cli.features.includes('spawn-name')) return fail('E_UNSUPPORTED_OPTION');
|
|
79
|
+
if (choices.identity !== undefined && !cli.features.includes('spawn-provider-payload')) return fail('E_UNSUPPORTED_OPTION');
|
|
80
|
+
// The one work override offered: a checkout soul asked for a worktree.
|
|
81
|
+
if (choices.work !== undefined && soul.work !== 'checkout') return fail('E_UNSUPPORTED_OPTION');
|
|
82
|
+
const work = choices.work ?? soul.work;
|
|
83
|
+
if ((choices.base !== undefined || choices.branch !== undefined) && work !== 'worktree') return fail('E_UNSUPPORTED_OPTION');
|
|
84
|
+
const supports = (values, value) => Array.isArray(values) && values.includes(value);
|
|
85
|
+
if (choices.harness && !supports(cli.harnesses, choices.harness) || choices.backend && !supports(cli.sessionBackends, choices.backend)
|
|
86
|
+
|| choices.yolo !== undefined && !supports(cli.launchOptions, 'yolo') || choices.launchConfig && !cli.features.includes('launch-config')) return fail('E_UNSUPPORTED_OPTION');
|
|
87
|
+
let anchorIdentity = null;
|
|
88
|
+
if (choices.relation.kind !== 'unrelated') {
|
|
89
|
+
const a = choices.relation.anchor, admitted = admitInstance(a, { workspace: w, cli, instances });
|
|
90
|
+
if (admitted.code) return fail(admitted.code);
|
|
91
|
+
// The CLI takes name+root, not agent+name+root. Do not pretend that a more
|
|
92
|
+
// precise renderer selector can disambiguate what its public argv cannot.
|
|
93
|
+
const expressible = instances.filter(i => i.instance === a.instance && i.agentsRoot === a.agentsRoot && (i.server ?? null) === null);
|
|
94
|
+
if (expressible.length !== 1) return fail('E_RELATIVE_AMBIGUOUS');
|
|
95
|
+
anchorIdentity = [admitted.target, expressible[0].createdAt ?? null];
|
|
96
|
+
}
|
|
97
|
+
const target = { workspace: w.id, context: dirname(soul.agentsRoot), selector };
|
|
98
|
+
const identity = JSON.stringify([w.id, w.scope, target, soul.work, soul.repo, soul.capability, anchorIdentity, choices,
|
|
99
|
+
cli.bin, cli.version, cli.spawnPreviewApi, cli.spawnApplyApi, cli.features, cli.harnesses, cli.sessionBackends, cli.launchOptions]);
|
|
100
|
+
return { target, identity, cli: structuredClone(cli) };
|
|
101
|
+
}
|
|
102
|
+
/** One read of a preview. `flights` (createSpawnPreviewFlights) is required: the reads of one preview share it,
|
|
103
|
+
* and a cache given here must run on its clock. maxAge: the dialog's reads may reuse member heads the kernel
|
|
104
|
+
* observed within that many seconds (feature spawn-preview-max-age, passed only when the admitted CLI
|
|
105
|
+
* advertises it). Prepare's reads never do. heldMs: how old a held answer this read takes (default: the cache's
|
|
106
|
+
* TTL). exec: as createSpawnPreview's. */
|
|
107
|
+
export function createSpawnPreviewBoundary({ invoke = cliSpawnPreview, cache = null, maxAge = null, heldMs, flights, exec } = {}) {
|
|
108
|
+
if (!flights?.slots || !flights.byInvoker || !flights.started || typeof flights.clock !== 'function') throw missing('createSpawnPreviewBoundary', 'flights (createSpawnPreviewFlights)');
|
|
109
|
+
if (cache && cache.clock !== flights.clock) throw new TypeError('createSpawnPreviewBoundary: the cache must run on the flights\' clock');
|
|
110
|
+
const { slots, byInvoker, started } = flights, io = exec ? [{ exec }] : [];
|
|
111
|
+
return async function read(request, getContext) {
|
|
112
|
+
try {
|
|
113
|
+
if (!record(request) || request.action !== 'preview' || Object.keys(request).some(k => !['action', 'selector', 'choices'].includes(k))) return previewFailure('E_BAD_ARGS');
|
|
114
|
+
const selector = previewSelector(request.selector), choices = previewChoices(request.choices);
|
|
115
|
+
if (!selector || !choices) return previewFailure('E_BAD_ARGS');
|
|
116
|
+
const selected = admitSpawnSelection(selector, choices, getContext());
|
|
117
|
+
if (selected.error) return previewFailure(selected.error);
|
|
118
|
+
const { target, identity, cli } = selected;
|
|
119
|
+
const held = cache?.get(identity, heldMs);
|
|
120
|
+
if (held) return held; // admitted above against the current context, like a fresh answer
|
|
121
|
+
let pending = byInvoker.get(invoke); if (!pending) { pending = new Map(); byInvoker.set(invoke, pending); }
|
|
122
|
+
const reuse = maxAge !== null && cli.features.includes('spawn-preview-max-age') ? { maxAge } : {};
|
|
123
|
+
// A reusing read and a live one never coalesce: prepare must not ride on a dialog read's older heads.
|
|
124
|
+
const key = reuse.maxAge ? `${identity}\u0000max-age` : identity;
|
|
125
|
+
if (!pending.has(key)) {
|
|
126
|
+
if (slots.size >= 2) return previewFailure('E_BUSY', target);
|
|
127
|
+
const slot = {}; slots.add(slot);
|
|
128
|
+
const flight = Promise.resolve().then(() => invoke(cli, { target, choices, ...reuse }, ...io)).then(envelope => {
|
|
129
|
+
if (envelope?.schemaVersion !== 1 || envelope.ok !== true) return previewFailure(envelope?.error?.code, target, envelope?.error?.message, envelope?.error?.details?.fix);
|
|
130
|
+
const data = previewData(envelope.result, target, { composedFrom: previewComposedFrom(cli) });
|
|
131
|
+
return data ? { spawnPreviewViewApi: 1, status: 'available', target, data, reason: null } : previewFailure('E_CLI_PROTOCOL', target);
|
|
132
|
+
}).catch(() => previewFailure('E_CLI_FAILED', target)).finally(() => { slots.delete(slot); pending.delete(key); });
|
|
133
|
+
started.set(flight, flights.clock()); pending.set(key, flight);
|
|
134
|
+
}
|
|
135
|
+
const flight = pending.get(key), result = await flight, current = admitSpawnSelection(selector, choices, getContext());
|
|
136
|
+
if (current.identity !== identity) return previewFailure('E_TARGET_CHANGED', target);
|
|
137
|
+
cache?.set(identity, target.workspace, result, started.get(flight));
|
|
138
|
+
return result;
|
|
139
|
+
} catch { return previewFailure('E_CLI_FAILED'); }
|
|
140
|
+
};
|
|
141
|
+
}
|
|
142
|
+
export const PREVIEW_MAX_AGE_S = 60;
|
|
143
|
+
/** One client's spawn preview: `{ read, prepareRead, cache }`.
|
|
144
|
+
* read the dialog's read, through the cache; its kernel reads may reuse recent member heads (maxAge,
|
|
145
|
+
* where the CLI declares spawn-preview-max-age)
|
|
146
|
+
* prepareRead prepare's read (spawn-apply.mjs createSpawnApplyBoundary's `read`), through the same cache,
|
|
147
|
+
* taking a held answer up to `prepareReuseMs` old (PREPARE_REUSE_MS), never with maxAge; a reusing
|
|
148
|
+
* read and a live one never coalesce
|
|
149
|
+
* cache `invalidate(workspace?)` (no argument: every workspace's answers) and `size()`
|
|
150
|
+
* The two reads share one two-slot budget, one set of coalesced flights and one clock, the cache's too.
|
|
151
|
+
* exec optional: the client's own execFile, passed to `invoke` as `invoke(cli, options, { exec })` for both
|
|
152
|
+
* reads (cli-adapter.mjs `runJson` has the rule); without it `invoke` is given no third argument and
|
|
153
|
+
* cliSpawnPreview's own default runs. A read is a read: its options carry no `detached` and a 30 s
|
|
154
|
+
* deadline, and it ends with its caller. */
|
|
155
|
+
export function createSpawnPreview({ invoke = cliSpawnPreview, exec, now = () => performance.now(), ttlMs = PREVIEW_CACHE_TTL_MS,
|
|
156
|
+
prepareReuseMs = PREPARE_REUSE_MS, limit = 64, maxAge = PREVIEW_MAX_AGE_S } = {}) {
|
|
157
|
+
const flights = createSpawnPreviewFlights();
|
|
158
|
+
const cache = createSpawnPreviewCache({ ttlMs, keepMs: prepareReuseMs, limit, now, clock: flights.clock });
|
|
159
|
+
return {
|
|
160
|
+
read: createSpawnPreviewBoundary({ invoke, cache, maxAge, heldMs: ttlMs, flights, exec }),
|
|
161
|
+
prepareRead: createSpawnPreviewBoundary({ invoke, cache, heldMs: prepareReuseMs, flights, exec }),
|
|
162
|
+
cache: { invalidate: workspace => cache.invalidate(workspace), size: () => cache.size() },
|
|
163
|
+
};
|
|
164
|
+
}
|