@awebai/oats 0.51.0 → 0.53.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (166) hide show
  1. package/README.md +3 -1
  2. package/bin/oats.mjs +407 -123
  3. package/docs/capabilities.md +75 -6
  4. package/docs/configuration.md +200 -91
  5. package/docs/desktop-cli-api.md +1563 -113
  6. package/docs/desktop-instance-start.md +69 -0
  7. package/docs/desktop.md +10 -7
  8. package/docs/execution-targets.md +145 -58
  9. package/docs/first-team.md +3 -1
  10. package/docs/harness-trust.md +50 -2
  11. package/docs/implementation.md +238 -17
  12. package/docs/integrations.md +13 -9
  13. package/docs/knowledge-reference/acceptance.md +1 -0
  14. package/docs/knowledge-reference/harvester.md +5 -3
  15. package/docs/knowledge-reference/model.md +5 -3
  16. package/docs/knowledge-theory.md +1 -1
  17. package/docs/knowledge.md +25 -2
  18. package/docs/launch-prompt-completion.md +50 -48
  19. package/docs/macos-test-runs.md +246 -0
  20. package/docs/oats-local.schema.json +4 -3
  21. package/docs/official-catalog.md +5 -5
  22. package/docs/packages.md +14 -14
  23. package/docs/release-lane.md +225 -11
  24. package/docs/release-notes/v0.44.0.md +1 -1
  25. package/docs/release-notes/v0.52.0.md +933 -0
  26. package/docs/release-notes/v0.53.0.md +1274 -0
  27. package/docs/schedules.md +97 -4
  28. package/docs/souls-and-instances.md +332 -40
  29. package/docs/tui.md +584 -0
  30. package/docs/upgrading.md +298 -0
  31. package/docs/workspaces.md +3 -3
  32. package/lib/automations.mjs +22 -22
  33. package/lib/claim.mjs +278 -49
  34. package/lib/config-data.mjs +4 -1
  35. package/lib/core.mjs +1282 -289
  36. package/lib/errors.mjs +170 -0
  37. package/lib/harness-trust-write.mjs +68 -27
  38. package/lib/harness-trust.mjs +34 -16
  39. package/lib/instance-events.mjs +19 -1
  40. package/lib/instance-git.mjs +39 -3
  41. package/lib/instance-inspect.mjs +45 -17
  42. package/lib/instance-lifecycle.mjs +306 -57
  43. package/lib/instance-resolution.mjs +59 -6
  44. package/lib/launch-preference.mjs +236 -9
  45. package/lib/launch-prompt-completion.mjs +7 -43
  46. package/lib/launch-prompt-evidence.mjs +14 -7
  47. package/lib/launch-prompt-fixtures/README.md +86 -152
  48. package/lib/launch-prompt-fixtures/dev-channel-confirmation.json +50 -0
  49. package/lib/launch-prompt-fixtures.mjs +122 -109
  50. package/lib/launch-prompt-transport.mjs +2 -56
  51. package/lib/launch-prompts.mjs +102 -100
  52. package/lib/local-edit.mjs +118 -0
  53. package/lib/packages.mjs +13 -4
  54. package/lib/pi-bridge.mjs +308 -0
  55. package/lib/refused-text.mjs +11 -0
  56. package/lib/remote.mjs +190 -25
  57. package/lib/resolve.mjs +2 -1
  58. package/lib/retained-after-retire.mjs +2 -2
  59. package/lib/retire-output.mjs +12 -1
  60. package/lib/schedule-host.mjs +125 -22
  61. package/lib/schedule.mjs +73 -24
  62. package/lib/shell-word.mjs +13 -0
  63. package/lib/soul-launch-verbs.mjs +153 -0
  64. package/lib/stable-node.mjs +62 -0
  65. package/lib/system-tools.mjs +39 -0
  66. package/lib/teams-verbs.mjs +18 -46
  67. package/lib/tmux-server-scope.mjs +62 -0
  68. package/lib/triggers.mjs +4 -4
  69. package/lib/workspace.mjs +54 -30
  70. package/lib/worktree-hooks.mjs +98 -20
  71. package/lib/worktree.mjs +83 -24
  72. package/package-catalog.json +4 -4
  73. package/package.json +8 -2
  74. package/packages/client/attach-exit.mjs +25 -0
  75. package/packages/client/capability-show-contract.mjs +230 -0
  76. package/packages/client/capability-warnings-contract.mjs +57 -0
  77. package/packages/client/cli-adapter.mjs +561 -0
  78. package/packages/client/cli-environment.mjs +53 -0
  79. package/packages/client/cli-locator.mjs +253 -0
  80. package/packages/client/cli-probe-contract.mjs +47 -0
  81. package/packages/client/client-terms.mjs +60 -0
  82. package/packages/client/deployment-contract.mjs +72 -0
  83. package/packages/client/deployment-data.mjs +483 -0
  84. package/packages/client/deployment-facts.mjs +95 -0
  85. package/packages/client/deployment-label.mjs +76 -0
  86. package/packages/client/deployment-observer.mjs +89 -0
  87. package/packages/client/deployment-panel.mjs +180 -0
  88. package/packages/client/deployment-read-cli.mjs +57 -0
  89. package/packages/client/display-text.mjs +50 -0
  90. package/packages/client/harness-names.mjs +30 -0
  91. package/packages/client/inspect-contract.mjs +62 -0
  92. package/packages/client/instance-acts.mjs +90 -0
  93. package/packages/client/instance-admission.mjs +45 -0
  94. package/packages/client/instance-events-contract.mjs +76 -0
  95. package/packages/client/instance-git-contract.mjs +80 -0
  96. package/packages/client/instance-presentation.mjs +86 -0
  97. package/packages/client/instance-tree.mjs +462 -0
  98. package/packages/client/kernel-environment.mjs +11 -0
  99. package/packages/client/kernel-lines.mjs +31 -0
  100. package/packages/client/kernel-made.mjs +23 -0
  101. package/packages/client/launch-contract.mjs +51 -0
  102. package/packages/client/launch-prompt-outcome.mjs +200 -0
  103. package/packages/client/lifecycle-cli.mjs +61 -0
  104. package/packages/client/lifecycle-contract.mjs +413 -0
  105. package/packages/client/liveness-main.mjs +10 -0
  106. package/packages/client/liveness.mjs +48 -0
  107. package/packages/client/machine-contract.mjs +123 -0
  108. package/packages/client/own-codes.mjs +31 -0
  109. package/packages/client/own-environment.mjs +22 -0
  110. package/packages/client/panel-views.mjs +293 -0
  111. package/packages/client/readiness-contract.mjs +174 -0
  112. package/packages/client/refresh-loop.mjs +52 -0
  113. package/packages/client/remote-address.mjs +151 -0
  114. package/packages/client/remote-identity-memory.mjs +94 -0
  115. package/packages/client/remote-roster.mjs +153 -0
  116. package/packages/client/roster-sections.mjs +80 -0
  117. package/packages/client/session-attach.mjs +175 -0
  118. package/packages/client/spawn-apply-cli.mjs +104 -0
  119. package/packages/client/spawn-apply-contract.mjs +195 -0
  120. package/packages/client/spawn-decision.mjs +46 -0
  121. package/packages/client/spawn-messages.mjs +142 -0
  122. package/packages/client/spawn-preview-cli.mjs +38 -0
  123. package/packages/client/spawn-preview-contract.mjs +318 -0
  124. package/packages/client/team-members.mjs +41 -0
  125. package/packages/client/team-rows.mjs +45 -0
  126. package/packages/client/terminal-contract.mjs +57 -0
  127. package/packages/client/terminal-exec.mjs +21 -0
  128. package/packages/client/tmux-status.mjs +66 -0
  129. package/packages/client/waiting-on-you.mjs +88 -0
  130. package/packages/client/workspace-admission.mjs +45 -0
  131. package/packages/client/workspace-choices.mjs +95 -0
  132. package/packages/client/workspace-cli.mjs +142 -0
  133. package/packages/client/workspace-views.mjs +183 -0
  134. package/packages/record/README.md +21 -0
  135. package/packages/record/bin/setup.mjs +108 -15
  136. package/packages/tui/README.md +64 -0
  137. package/packages/tui/bin/tui.mjs +7 -0
  138. package/packages/tui/lib/actions.mjs +44 -0
  139. package/packages/tui/lib/client.mjs +35 -0
  140. package/packages/tui/lib/config.mjs +151 -0
  141. package/packages/tui/lib/main.mjs +176 -0
  142. package/packages/tui/lib/model.mjs +392 -0
  143. package/packages/tui/lib/read.mjs +473 -0
  144. package/packages/tui/lib/store.mjs +364 -0
  145. package/packages/tui/lib/term/keys.mjs +367 -0
  146. package/packages/tui/lib/term/screen.mjs +134 -0
  147. package/packages/tui/lib/term/style.mjs +43 -0
  148. package/packages/tui/lib/term/text.mjs +109 -0
  149. package/packages/tui/lib/term/tty.mjs +178 -0
  150. package/packages/tui/lib/term/width.mjs +124 -0
  151. package/packages/tui/lib/views/detail.mjs +46 -0
  152. package/packages/tui/lib/views/frame.mjs +256 -0
  153. package/packages/tui/lib/views/help.mjs +140 -0
  154. package/packages/tui/lib/views/instances.mjs +137 -0
  155. package/packages/tui/lib/views/scroll.mjs +19 -0
  156. package/packages/tui/lib/views/switcher.mjs +97 -0
  157. package/packages/tui/package.json +8 -0
  158. package/skills/oats-getting-started/SKILL.md +30 -23
  159. package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/frame-05-channel-seeded.txt +0 -35
  160. package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/frame-06-first-after-channel.txt +0 -35
  161. package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/frame-07-after-channel-200ms.txt +0 -35
  162. package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/frame-08-installed-after-channel-200ms.txt +0 -35
  163. package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/manifest.json +0 -77
  164. package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/max-bypass-source.json +0 -88
  165. package/lib/launch-prompt-fixtures/structural-completion.json +0 -205
  166. package/lib/launch-prompt-policy.mjs +0 -87
@@ -0,0 +1,142 @@
1
+ /** Plain-language wording for the Spawn dialog's problems.
2
+ *
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. */
8
+ import { displayLine } from './display-text.mjs';
9
+ import { ROLLED_BACK_CODES } from './spawn-apply-contract.mjs';
10
+
11
+ const UNMATCHED = 'E_LAUNCH_PREFERENCE_UNMATCHED';
12
+
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
+ };
56
+
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.',
62
+ };
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.',
83
+ };
84
+
85
+ /** { text, code, detail } for a { code, message } reason. `stage` is 'preview'
86
+ * (reading defaults) or 'spawn' (after the operator pressed Spawn).
87
+ *
88
+ * For an unmatched launch preference whose reason carries the kernel's `fix`, the answer also has
89
+ * `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
91
+ * code alone, so that no reader of `detail` shows a kernel text without its speaker. A `fix` decides it
92
+ * because `previewFailure` keeps one only beside the kernel's own message, never beside a table's sentence:
93
+ * 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. */
95
+ export function spawnProblem(reason, stage = 'preview') {
96
+ const code = typeof reason?.code === 'string' ? reason.code : 'E_CLI_FAILED';
97
+ const own = stage === 'spawn' ? SPAWN : PREVIEW;
98
+ const message = typeof reason?.message === 'string' ? reason.message.trim() : '';
99
+ // A missing harness is said as the kernel words it, with its fix (launch preferences, 0.30).
100
+ const fix = typeof reason?.fix === 'string' ? reason.fix.trim() : '';
101
+ if (code === UNMATCHED) {
102
+ 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 };
106
+ }
107
+ // The kernel's message usually already ends with its fix: said once.
108
+ 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 };
111
+ }
112
+
113
+ /** The spawn catalog's state, for the soul chooser. */
114
+ export function catalogProblem(catalog) {
115
+ if (!catalog) return '';
116
+ const parts = [];
117
+ if (catalog.reason) parts.push('OATS couldn’t load this workspace’s souls, so the list may be out of date. Sync the workspace and try again.');
118
+ if (catalog.ambiguous?.length) parts.push(`Not offered because two repositories declare the same name: ${catalog.ambiguous.join(', ')}.`);
119
+ return parts.join(' ');
120
+ }
121
+
122
+ /** Feature worktree-event (#802): the kernel rolled the spawn back (E_INTERRUPTED,
123
+ * E_REQUIRED_HOOK_FAILED, E_HOOK_ENVIRONMENT_CONTRACT without `unconfirmed`), so nothing
124
+ * was created; or its cleanup is owed (the same codes with it). The kernel's message names
125
+ * the capability and its log: it goes under Details, through displayLine. */
126
+ export function rolledBackProblem(reason, instance) {
127
+ const code = reason?.code;
128
+ if (!ROLLED_BACK_CODES.includes(code)) return null;
129
+ const text = code === 'E_INTERRUPTED'
130
+ ? `The spawn of ${instance} was interrupted while its worktree was being set up, and was rolled back. Nothing was created.`
131
+ : `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) };
133
+ }
134
+ export function cleanupOwedProblem(reason, instance) {
135
+ 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.`,
137
+ code: reason.code, detail: kernelDetail(reason.code, reason.message) };
138
+ }
139
+ function kernelDetail(code, message) {
140
+ const line = displayLine(message);
141
+ return line ? `${code} · ${line}` : code;
142
+ }
@@ -0,0 +1,38 @@
1
+ /** Fixed read-only API2 argv. Never dispatch API1 or fall back to spawn. */
2
+ import { execFile } from 'node:child_process';
3
+ import { parseEnvelope } from './cli-adapter.mjs';
4
+ import { previewChoices, previewTarget, previewSupported, previewFailure, choiceArgv } from './spawn-preview-contract.mjs';
5
+ /** A refusal, in the kernel's own shape (`{ code, message, details: { fix } }`). `previewFailure` decides what of the
6
+ * kernel's travels: its message when that is printable and within the bound, and its `fix` only beside that message.
7
+ * No other key of `details` travels. */
8
+ function failure(code, message, kernelFix) {
9
+ const { fix, ...error } = previewFailure(code, null, message, kernelFix).reason;
10
+ return { schemaVersion: 1, ok: false, error: fix === undefined ? error : { ...error, details: { fix } } };
11
+ }
12
+ /** `io.exec` is a client's own `execFile` (the rule is at cli-adapter.mjs `runJson`). */
13
+ export function cliSpawnPreview(cli, options = {}, io = {}) {
14
+ // Defense at the actual exec owner as well as at HTTP admission.
15
+ if (!previewSupported(cli)) return Promise.resolve(failure('E_PREVIEW_UNAVAILABLE'));
16
+ const target = previewTarget(options.target), choices = previewChoices(options.choices);
17
+ if (!target || !choices || Object.keys(options).some(k => !['target', 'choices', 'maxAge'].includes(k))) return Promise.resolve(failure('E_BAD_ARGS'));
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 and apply never pass it.
20
+ const maxAge = options.maxAge;
21
+ if (maxAge !== undefined && (!Number.isInteger(maxAge) || maxAge < 1 || maxAge > 3600)) return Promise.resolve(failure('E_BAD_ARGS'));
22
+ const reuse = maxAge !== undefined && Array.isArray(cli.features) && cli.features.includes('spawn-preview-max-age') ? ['--max-age', String(maxAge)] : [];
23
+ const argv = ['spawn', target.selector.soul, '--dir', target.context, '--agents-root', target.selector.agentsRoot, '--preview', ...choiceArgv(choices, cli), ...reuse, '--json'];
24
+ const env = { ...(io.env ?? process.env) };
25
+ for (const k of ['PI_AGENTS_ROOT', 'OATS_DEPLOYMENT', 'OATS_RESOLUTION', 'OATS_PREVIEW_PREFLIGHT_BUDGET_MS']) delete env[k];
26
+ return new Promise(resolve => {
27
+ try {
28
+ (io.exec ?? execFile)(cli.bin, argv, { cwd: target.context, env, shell: false, encoding: 'utf8', timeout: 30000, maxBuffer: 4 * 1024 * 1024 }, (err, stdout) => {
29
+ if (err?.code === 'ERR_CHILD_PROCESS_STDIO_MAXBUFFER') return resolve(failure('E_CLI_OUTPUT_LIMIT'));
30
+ if (err?.killed) return resolve(failure('E_CLI_TIMEOUT'));
31
+ const doc = parseEnvelope(stdout);
32
+ if (doc?.ok === false) return resolve(failure(doc.error?.code, doc.error?.message, doc.error?.details?.fix));
33
+ if (err) return resolve(failure('E_CLI_FAILED'));
34
+ resolve(doc?.ok === true ? doc : failure('E_CLI_PROTOCOL'));
35
+ });
36
+ } catch { resolve(failure('E_CLI_FAILED')); }
37
+ });
38
+ }
@@ -0,0 +1,318 @@
1
+ /** Spawn preview (API 2) on workspace model v2: the choices a spawn may carry,
2
+ * their fixed argv, and the bounded projection of the kernel's preview. */
3
+ import { absolute, record } from './readiness-contract.mjs';
4
+ import { spawnDecision } from './spawn-decision.mjs';
5
+ import { teamRow, defaultTeamOf } from './team-rows.mjs';
6
+ import { harnessOf, harnessFlag, HARNESSES } from './harness-names.mjs';
7
+ import { launchOf, PREVIEW_FROM } from './launch-contract.mjs';
8
+ import { previewWarningsOf } from './capability-warnings-contract.mjs';
9
+ export { absolute, record };
10
+ const exact = (v, keys) => record(v) && Object.keys(v).every(k => keys.includes(k));
11
+ const name = v => typeof v === 'string' && /^[A-Za-z0-9][A-Za-z0-9._-]{0,255}$/.test(v);
12
+ /** The kernel caps instance names, explicit and derived, at 64 characters
13
+ * (#159, E_INSTANCE_NAME_INVALID). A longer --name or --purpose can never
14
+ * name an instance, so it is refused before any CLI call. */
15
+ export const INSTANCE_NAME_MAX = 64;
16
+ const INSTANCE_TOKEN = new RegExp(`^[a-z0-9][a-z0-9-]{0,${INSTANCE_NAME_MAX - 1}}$`, 'i');
17
+ const arg = (v, max = 1024) => typeof v === 'string' && !!v && v.length <= max && !v.startsWith('-') && !/[\x00-\x1f\x7f]/.test(v);
18
+ const safe = (v, max = 4096) => typeof v === 'string' && v.length <= max && !/[\x00-\x1f\x7f]|https?:\/\/[^/\s]*@|(?:gh[pousr]_|github_pat_)[A-Za-z0-9_]{16,}/.test(v);
19
+ const nullable = v => v === null || safe(v);
20
+ const names = v => Array.isArray(v) && v.length <= 512 && v.every(x => safe(x, 512));
21
+ const CAPABILITY = /^[a-z0-9][a-z0-9._-]{0,127}$/;
22
+ const RESIDENT = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
23
+ /** A team label (teams contract; the kernel's label grammar). */
24
+ const TEAM_LABEL = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
25
+ const JOIN_MAX = 16;
26
+ const joinText = v => typeof v === 'string' && v.split(',').every(l => TEAM_LABEL.test(l)) && new Set(v.split(',')).size === v.split(',').length && v.split(',').length <= JOIN_MAX;
27
+ /** The soul's teams as the preview reports them (kernel `teams`, primary
28
+ * first), without the payloads: [{label, team, mapped}]; null when not
29
+ * reported, undefined when unreadable. Idempotent over the server projection. */
30
+ function teamsOf(v) {
31
+ if (v.teams === undefined || v.teams === null) return null;
32
+ if (!Array.isArray(v.teams) || v.teams.length > 64) return undefined;
33
+ const out = [];
34
+ for (const t of v.teams) {
35
+ // 0.29 {label, team, mapped} or team model v2 {label, team, default, from} (team-rows.mjs).
36
+ const row = teamRow(t);
37
+ if (!row || (row.team !== null && !safe(row.team, 256))) return undefined;
38
+ out.push(row);
39
+ }
40
+ return new Set(out.map(t => t.label)).size === out.length ? out : undefined;
41
+ }
42
+ /** Whether the messaging provider declares the spawn setting `join` (teams
43
+ * contract). The ONE gate for the spawn Teams choice: a provider that does not
44
+ * declare it would ignore a bound join=, so without the declared fact the row
45
+ * is not offered. The kernel's fact (teams contract bdd7e55e, kernel #181):
46
+ * each preview modules[] row carries `declares` — its sorted setting key names —
47
+ * under feature settings-declared (the dialog checks the feature). */
48
+ const joinDeclared = row => Array.isArray(row?.declares) && row.declares.includes('join');
49
+ /** The soul's messaging provider, the identity its bound payload carries, and
50
+ * where that identity's mode came from: the one module on layer messaging,
51
+ * decision.effective.providers[cap].identity (what the apply binds; the
52
+ * preview's settings must agree), and settingsOrigins[cap]['/identity/mode']
53
+ * ({kind, at}; feature settings-origins). No identity or no origin means the
54
+ * kernel reported none — the Desktop never supplies one. */
55
+ function originOf(o) {
56
+ if (o === undefined || o === null) return null;
57
+ if (!exact(o, ['kind', 'at']) || !safe(o.kind, 64) || !o.kind || !safe(o.at, 512) || !o.at) return undefined;
58
+ return { kind: o.kind, at: o.at };
59
+ }
60
+ function messagingOf(v) {
61
+ // Idempotent: the renderer re-validates the server's projection, which carries
62
+ // `messaging` itself (the kernel's preview never does) instead of the kernel's settings.
63
+ if (Object.hasOwn(v, 'messaging')) {
64
+ const m = v.messaging;
65
+ if (m === null) return null;
66
+ if (!exact(m, ['provider', 'identity', 'origin', 'join', 'joinDeclared']) || !Object.hasOwn(m, 'origin') || !CAPABILITY.test(m.provider ?? '')
67
+ || typeof m.joinDeclared !== 'boolean' || m.join !== null && !joinText(m.join)) return undefined;
68
+ const origin = originOf(m.origin);
69
+ if (origin === undefined) return undefined;
70
+ const join = { join: m.join, joinDeclared: m.joinDeclared };
71
+ if (m.identity === null) return { provider: m.provider, identity: null, origin, ...join };
72
+ const i = m.identity;
73
+ if (!exact(i, ['mode', 'resident']) || !['local', 'global'].includes(i.mode) || i.resident !== null && !RESIDENT.test(i.resident)) return undefined;
74
+ return { provider: m.provider, identity: { mode: i.mode, resident: i.resident }, origin, ...join };
75
+ }
76
+ if (!Array.isArray(v.modules)) return null;
77
+ const rows = v.modules.filter(m => record(m) && m.layer === 'messaging');
78
+ if (!rows.length) return null;
79
+ if (rows.length !== 1 || !CAPABILITY.test(rows[0].name ?? '')) return undefined;
80
+ const cap = rows[0].name, bound = v.decision?.effective?.providers?.[cap], shown = v.settings?.[cap];
81
+ if (!record(bound) || !record(shown) || JSON.stringify(bound.identity ?? null) !== JSON.stringify(shown.identity ?? null)) return undefined;
82
+ // The bound join (what the apply binds) must be the preview's settings echo.
83
+ if ((bound.join ?? null) !== (shown.join ?? null) || bound.join !== undefined && !joinText(bound.join)) return undefined;
84
+ const join = { join: bound.join ?? null, joinDeclared: joinDeclared(rows[0]) };
85
+ if (Object.hasOwn(v, 'settingsOrigins') && !record(v.settingsOrigins) || v.settingsOrigins?.[cap] !== undefined && !record(v.settingsOrigins[cap])) return undefined;
86
+ const origin = originOf(v.settingsOrigins?.[cap]?.['/identity/mode']);
87
+ if (origin === undefined) return undefined;
88
+ const i = bound.identity;
89
+ if (i === undefined) return { provider: cap, identity: null, origin, ...join };
90
+ if (!record(i) || !['local', 'global'].includes(i.mode) || i.resident !== undefined && !RESIDENT.test(i.resident)) return undefined;
91
+ return { provider: cap, identity: { mode: i.mode, resident: i.resident ?? null }, origin, ...join };
92
+ }
93
+ /** The composition this spawn will record (kernel `modules[]`, feature instance-modules), for the
94
+ * dialog's Core capabilities and Capabilities: [{name, layer, from:{kind, package?, version?,
95
+ * repoKey?}, composedFrom?}] — the same facts /api/capabilities exposes, scoped to this spawn. Only
96
+ * these strings, each on a fixed grammar; never settings, declares, skills, commands, commits or
97
+ * integrity. null when the kernel reports no modules; undefined (a protocol error) when a row is
98
+ * malformed, duplicated or over the cap. The server's projection re-validates with its keys exact.
99
+ * `composedFrom` (why the module is there; feature preview-composed-from, kernel #328) is read from
100
+ * the kernel only when `composedFrom` says the CLI reports the feature, and kept only when it is
101
+ * exactly "soul" or "workspace": any other value is dropped, never refused — the row still projects,
102
+ * without a reason. The server's projection carries it only where the server read it. */
103
+ const MODULES_MAX = 256;
104
+ const MODULE_LAYER = /^[a-z][a-z0-9-]{0,31}$/;
105
+ const MODULE_KIND = /^[a-z][a-z0-9-]{0,31}$/;
106
+ const MODULE_VERSION = /^[0-9A-Za-z][0-9A-Za-z.+-]{0,63}$/;
107
+ const repoKey = v => arg(v, 512) && safe(v, 512) && !/\s/.test(v);
108
+ const is = (re, v) => typeof v === 'string' && re.test(v); // never a coerced number
109
+ const COMPOSED_FROM = ['soul', 'workspace'];
110
+ /** The CLI reports why each preview module is there (modules[].composedFrom). */
111
+ export const previewComposedFrom = cli => Array.isArray(cli?.features) && cli.features.includes('preview-composed-from');
112
+ function modulesOf(v, projected, composedFrom) {
113
+ if (v.modules === undefined || v.modules === null) return null;
114
+ if (!Array.isArray(v.modules) || v.modules.length > MODULES_MAX) return undefined;
115
+ const out = [];
116
+ for (const m of v.modules) {
117
+ if (!record(m) || projected && !exact(m, ['name', 'layer', 'from', 'composedFrom']) || !is(CAPABILITY, m.name)) return undefined;
118
+ const layer = m.layer ?? null, f = m.from;
119
+ if (layer !== null && !is(MODULE_LAYER, layer) || !record(f) || projected && !exact(f, ['kind', 'package', 'version', 'repoKey']) || !is(MODULE_KIND, f.kind)) return undefined;
120
+ const from = { kind: f.kind };
121
+ if (f.package !== undefined) { if (!is(CAPABILITY, f.package)) return undefined; from.package = f.package; }
122
+ if (f.version !== undefined) { if (!is(MODULE_VERSION, f.version)) return undefined; from.version = f.version; }
123
+ if (f.repoKey !== undefined) { if (!repoKey(f.repoKey)) return undefined; from.repoKey = f.repoKey; }
124
+ const why = (projected || composedFrom) && COMPOSED_FROM.includes(m.composedFrom) ? { composedFrom: m.composedFrom } : {};
125
+ out.push({ name: m.name, layer, from, ...why });
126
+ }
127
+ return new Set(out.map(m => m.name)).size === out.length ? out : undefined;
128
+ }
129
+ export const previewSupported = cli => cli?.ok === true && absolute(cli.bin) && cli.spawnPreviewApi === 2
130
+ && Array.isArray(cli.features) && cli.features.includes('spawn-preview-2');
131
+ export function previewSelector(v) {
132
+ return exact(v, ['soul', 'agentsRoot']) && name(v.soul) && absolute(v.agentsRoot) ? { soul: v.soul, agentsRoot: v.agentsRoot } : null;
133
+ }
134
+ export function previewChoices(v) {
135
+ if (!exact(v, ['purpose', 'name', 'work', 'branch', 'base', 'harness', 'model', 'launchConfig', 'backend', 'yolo', 'relation', 'identity', 'join'])) return null;
136
+ // --name (exact, unprefixed; feature spawn-name) and --purpose are mutually exclusive.
137
+ if (Object.hasOwn(v, 'purpose') && Object.hasOwn(v, 'name')) return null;
138
+ const out = {};
139
+ for (const k of ['purpose', 'name', 'branch', 'base', 'harness', 'launchConfig', 'backend']) if (Object.hasOwn(v, k)) {
140
+ if (!arg(v[k]) || (k === 'purpose' || k === 'name') && !INSTANCE_TOKEN.test(v[k])
141
+ || k === 'launchConfig' && !/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/.test(v[k])
142
+ || k === 'harness' && !HARNESSES.includes(v[k]) || k === 'backend' && v[k] !== 'tmux') return null;
143
+ out[k] = v[k];
144
+ }
145
+ // The only work override the Desktop offers: a checkout soul in a worktree.
146
+ if (Object.hasOwn(v, 'work')) { if (v.work !== 'worktree') return null; out.work = 'worktree'; }
147
+ if (Object.hasOwn(v, 'yolo')) { if (typeof v.yolo !== 'boolean') return null; out.yolo = v.yolo; }
148
+ // Messaging identity (decision 27; feature spawn-provider-payload): sent to
149
+ // the soul's messaging provider as --provider <cap> identity.mode=… — there
150
+ // is no kernel flag. `provider` is the capability the preview reported on
151
+ // layer messaging; the kernel refuses any other (E_CAPABILITY_MISSING).
152
+ if (Object.hasOwn(v, 'identity')) {
153
+ const i = v.identity;
154
+ if (!record(i) || !CAPABILITY.test(i.provider ?? '')) return null;
155
+ if (exact(i, ['provider', 'mode']) && i.mode === 'local') out.identity = { provider: i.provider, mode: 'local' };
156
+ else if (exact(i, ['provider', 'mode', 'resident']) && i.mode === 'global' && RESIDENT.test(i.resident ?? '')) out.identity = { provider: i.provider, mode: 'global', resident: i.resident };
157
+ else return null;
158
+ }
159
+ // Teams to join beyond the workspace's default team (teams contract): the provider's
160
+ // spawn setting, sent as --provider <cap> join=<a,b>. Labels are the preview's
161
+ // mapped ones; the kernel/provider decides eligibility (E_TEAM_NOT_ELIGIBLE).
162
+ if (Object.hasOwn(v, 'join')) {
163
+ const j = v.join;
164
+ if (!exact(j, ['provider', 'labels']) || !CAPABILITY.test(j.provider ?? '') || !Array.isArray(j.labels) || !j.labels.length
165
+ || !j.labels.every(l => typeof l === 'string' && TEAM_LABEL.test(l)) || !joinText(j.labels.join(','))) return null;
166
+ out.join = { provider: j.provider, labels: [...j.labels] };
167
+ }
168
+ const model = v.model === undefined ? { kind: 'inherit' } : v.model;
169
+ if (exact(model, ['kind']) && ['inherit', 'native-default'].includes(model.kind)) out.model = { kind: model.kind };
170
+ else if (exact(model, ['kind', 'value']) && model.kind === 'custom' && arg(model.value) && model.value !== '@native-default') out.model = { kind: model.kind, value: model.value };
171
+ else return null;
172
+ const relation = v.relation === undefined ? { kind: 'unrelated' } : v.relation;
173
+ if (!record(relation)) return null;
174
+ if (exact(relation, ['kind']) && relation.kind === 'unrelated') out.relation = { kind: 'unrelated' };
175
+ else {
176
+ const a = relation.anchor;
177
+ if (!exact(relation, ['kind', 'anchor']) || !['child', 'sibling', 'parent'].includes(relation.kind)
178
+ || !exact(a, ['instance', 'agent', 'agentsRoot', 'server']) || !name(a.instance) || !name(a.agent) || !absolute(a.agentsRoot) || a.server != null) return null;
179
+ out.relation = { kind: relation.kind, anchor: { instance: a.instance, agent: a.agent, agentsRoot: a.agentsRoot, server: null } };
180
+ }
181
+ return out;
182
+ }
183
+ /** The spawn flags for admitted choices — shared by preview and apply. The
184
+ * harness flag is the kernel's (feature harness: --harness; a released kernel: --runtime). */
185
+ export function choiceArgv(choices, cli) {
186
+ const argv = [];
187
+ for (const [k, flag] of [['purpose', '--purpose'], ['name', '--name'], ['work', '--work'], ['branch', '--branch'], ['base', '--base'], ['harness', harnessFlag(cli)], ['launchConfig', '--launch-config'], ['backend', '--backend']]) if (choices[k] !== undefined) argv.push(flag, choices[k]);
188
+ if (choices.model.kind !== 'inherit') argv.push('--model', choices.model.kind === 'native-default' ? '@native-default' : choices.model.value);
189
+ if (choices.yolo !== undefined) argv.push(choices.yolo ? '--yolo' : '--no-yolo');
190
+ if (choices.relation.kind !== 'unrelated') argv.push('--relation', choices.relation.kind, '--relative-to', choices.relation.anchor.instance, '--relative-root', choices.relation.anchor.agentsRoot);
191
+ if (choices.identity) {
192
+ argv.push('--provider', choices.identity.provider, `identity.mode=${choices.identity.mode}`);
193
+ if (choices.identity.mode === 'global') argv.push('--provider', choices.identity.provider, `identity.resident=${choices.identity.resident}`);
194
+ }
195
+ if (choices.join) argv.push('--provider', choices.join.provider, `join=${choices.join.labels.join(',')}`);
196
+ return argv;
197
+ }
198
+ export function previewTarget(v) {
199
+ const selector = previewSelector(v?.selector);
200
+ return selector && safe(v.workspace) && !!v.workspace && absolute(v.context)
201
+ ? { workspace: v.workspace, context: v.context, selector } : null;
202
+ }
203
+ const errors = {
204
+ E_BAD_ARGS: 'Preview requires one local workspace, qualified soul and bounded choices.',
205
+ E_PREVIEW_UNAVAILABLE: 'Spawning needs an OATS CLI that advertises spawn-preview-2 (spawnPreviewApi 2). Update OATS and retry.',
206
+ E_WORKSPACE_UNKNOWN: 'Choose a known local workspace.',
207
+ E_SOUL_UNKNOWN: 'The exact selected soul is unavailable or ambiguous.',
208
+ E_TARGET_CHANGED: 'The workspace, soul, anchor or CLI changed while reading. Reading again.',
209
+ E_UNSUPPORTED_MODE: 'This soul cannot be spawned standalone from here.',
210
+ 'unsupported-remote-operation': 'Defaults are decided on the execution server; they are not read here.',
211
+ E_RELATIVE_AMBIGUOUS: 'The selected relation anchor cannot be addressed unambiguously.',
212
+ E_SESSION_UNKNOWN: 'The selected relation anchor is no longer available.', E_HOME_MISMATCH: 'The relation anchor no longer matches its home.',
213
+ E_UNSUPPORTED_OPTION: 'A chosen option is not supported for this soul or installed CLI.',
214
+ E_BRANCH_EXISTS: 'The proposed branch already exists. Choose another branch and preview again.',
215
+ E_BASE_UNKNOWN: 'The proposed base does not resolve to a commit.', E_CHILD_SPAWNS_DISABLED: 'The selected parent does not allow child spawns.',
216
+ E_LAUNCH_ENV_MISSING: 'Required launch environment references are unavailable.',
217
+ E_LAUNCH_EXECUTABLE: 'The selected launch executable is unavailable.', E_LAUNCH_PROBE_UNSUPPORTED: 'The selected launch cannot be preflighted safely.',
218
+ E_LAUNCH_CONFIG_UNKNOWN: 'The selected launch configuration is unavailable.', E_MODEL_UNKNOWN: 'The selected model could not be resolved.',
219
+ // 0.52.0: several launch configurations for the harness, no default, and the spawn names none. Listed so the
220
+ // code survives where the kernel's own message cannot travel (the apply's reason; a message over the bound).
221
+ E_LAUNCH_CONFIG_AMBIGUOUS: 'More than one launch configuration is declared for this harness and none is the default.',
222
+ // 0.53.0: `souls.launch` holds a key that names no soul, and the spawn names no launch. Listed for the same
223
+ // reason: the code survives where the kernel's own message cannot travel (the apply's reason, after the
224
+ // server's own preview before a dispatch was refused; a message the bound or the filter here does not pass).
225
+ E_LAUNCH_PREFERENCE_UNMATCHED: 'A launch preference on this machine names a soul the workspace does not offer, and this spawn names no launch.',
226
+ E_CLONE_MISSING: 'This soul works in a member repository that is not cloned on this machine.',
227
+ E_INSTANCE_NAME_INVALID: 'That name is not a valid instance name (a lowercase slug of at most 64 characters that is not a soul name).',
228
+ E_INSTANCE_NAME_TAKEN: 'An instance with that name already exists in this deployment.',
229
+ E_SOUL_AMBIGUOUS: 'More than one member declares a soul with this name.',
230
+ E_BUSY: 'Two spawn previews are already running. Retry when one finishes.',
231
+ E_CLI_TIMEOUT: 'The spawn preview timed out.', E_CLI_OUTPUT_LIMIT: 'The spawn preview exceeded its output limit.',
232
+ E_CLI_PROTOCOL: 'The CLI returned an invalid or mismatched API 2 preview.', E_CLI_FAILED: 'The installed CLI could not complete the preview.',
233
+ E_FORBIDDEN_FRAME: 'This frame cannot request a spawn preview.',
234
+ };
235
+ const KERNEL_CODE = /^E_[A-Z0-9_]{1,63}$/;
236
+ /** A kernel refusal keeps its own code and message (bounded, printable): the
237
+ * kernel's remedy — "git clone … " for E_CLONE_MISSING — is the useful part.
238
+ * Desktop-side codes use the fixed table. */
239
+ export function previewFailure(code, target = null, kernelMessage, kernelFix) {
240
+ const kernel = typeof code === 'string' && KERNEL_CODE.test(code) && typeof kernelMessage === 'string'
241
+ && kernelMessage.trim() && kernelMessage.length <= 2048 && safe(kernelMessage.replace(/\n/g, ' '), 2048);
242
+ // A launch refusal's `fix` (E_HARNESS_UNAVAILABLE, E_LAUNCH_CONFIG_UNKNOWN: the kernel's own words) travels with it.
243
+ const fix = kernel && typeof kernelFix === 'string' && kernelFix.trim() && safe(kernelFix, 1024) ? { fix: kernelFix } : {};
244
+ if (kernel) return { spawnPreviewViewApi: 1, status: 'unavailable', target: previewTarget(target), data: null, reason: { code, message: kernelMessage, ...fix } };
245
+ if (!Object.hasOwn(errors, code)) code = 'E_CLI_FAILED';
246
+ return { spawnPreviewViewApi: 1, status: 'unavailable', target: previewTarget(target), data: null, reason: { code, message: errors[code] } };
247
+ }
248
+ /** The kernel's v2 preview, projected to what the dialog shows and the apply
249
+ * binds. Top-level facts must agree with the decision the apply is bound to
250
+ * (`--expect-decision`); the revision is opaque producer data. The modules
251
+ * are projected as names, sources and (with `composedFrom`, the CLI's feature
252
+ * preview-composed-from) why each is there (modulesOf); capabilities[], skills,
253
+ * settings and the task are the kernel's business and are not projected. */
254
+ const hex24 = v => typeof v === 'string' && /^[a-f0-9]{24}$/.test(v);
255
+ /** Optional launch policy, not observed answers or readiness. Keep absence for
256
+ * older CLIs distinct from an explicit policy that answers no prompts. */
257
+ function launchPromptAnswersOf(v) {
258
+ if (!record(v) || typeof v.awebDevelopmentChannel !== 'boolean'
259
+ || !(v.consentSource === null || safe(v.consentSource) && !!v.consentSource)) return null;
260
+ return { awebDevelopmentChannel: v.awebDevelopmentChannel, consentSource: v.consentSource };
261
+ }
262
+ /** The capabilities whose `worktree` hook this spawn would run, in order (feature worktree-event,
263
+ * OATS 0.49.0): [{capability, required}]. Read tolerantly, unlike the rest of the preview: anything
264
+ * else (null, absent, malformed) is undefined, never a refused preview. The apply's CLI deadline and
265
+ * the dialog's Setup fact read it. Bounded like the preview's modules (MAX_HOOKS): a spawn runs at most one
266
+ * `worktree` hook per capability it composes. */
267
+ export const MAX_HOOKS = MODULES_MAX;
268
+ export function worktreeHooksOf(v) {
269
+ if (!Array.isArray(v) || v.length > MAX_HOOKS) return undefined;
270
+ const out = [];
271
+ for (const h of v) {
272
+ if (!record(h) || typeof h.capability !== 'string' || !h.capability || !safe(h.capability, 256) || typeof h.required !== 'boolean') return undefined;
273
+ out.push({ capability: h.capability, required: h.required });
274
+ }
275
+ return out;
276
+ }
277
+ export function previewData(v, expected, { composedFrom = false } = {}) {
278
+ const t = previewTarget(expected);
279
+ if (!t || !record(v) || v.spawnPreviewApi !== 2 || v.preview !== true || !record(v.subject)
280
+ || v.subject.soul !== t.selector.soul || v.subject.agentsRoot !== t.selector.agentsRoot || v.subject.dir !== t.context) return null;
281
+ const d = spawnDecision(v.decision, { effectiveRequired: true });
282
+ if (!d || !hex24(v.resolution) || d.resolution !== v.resolution) return null;
283
+ const e = d.effective, base = d.base;
284
+ if (v.instance !== d.instance || v.home !== d.home || v.branch !== d.branch
285
+ || (v.base === null ? base !== null : !record(v.base) || v.base.ref !== base?.ref || v.base.oid !== base?.oid)
286
+ || v.work !== e.work || v.repo !== e.repo || harnessOf(v) !== e.harness || v.model !== e.model || v.launchConfig !== e.launchConfig
287
+ || (v.yolo ?? null) !== e.yolo || v.backend !== e.backend || (v.relation ?? null) !== (e.relation?.kind ?? null)
288
+ || Object.hasOwn(v, 'policy') && v.policy?.childSpawns?.allowed !== e.childSpawns) return null;
289
+ // `team` (the primary label) is 0.29's; team model v2 (0.30) removes it: absent reads as null.
290
+ if (!safe(v.modelSource) || !v.modelSource || v.team != null && !safe(v.team, 256)
291
+ || (e.work === 'worktree' ? !absolute(v.worktree) : v.worktree !== null)
292
+ || !record(v.backendStatus) || v.backendStatus.name !== v.backend || typeof v.backendStatus.installed !== 'boolean' || v.backendStatus.started !== false
293
+ || !record(v.preflight) || !['complete', 'timeout'].includes(v.preflight.status) || !Number.isInteger(v.preflight.budgetMs) || v.preflight.budgetMs <= 0 || v.preflight.budgetMs > 20000
294
+ || !Number.isSafeInteger(v.preflight.elapsedMs) || v.preflight.elapsedMs < 0) return null;
295
+ const messaging = messagingOf(v), teams = teamsOf(v), modules = modulesOf(v, Object.hasOwn(v, 'messaging'), composedFrom);
296
+ // Team model v2: the soul's default (the kernel's DefaultTeam, or null); absent on 0.29.
297
+ const defaultTeam = Object.hasOwn(v, 'defaultTeam') ? defaultTeamOf(v.defaultTeam) : undefined;
298
+ if (messaging === undefined || teams === undefined || modules === undefined || (Object.hasOwn(v, 'defaultTeam') && defaultTeam === undefined)) return null;
299
+ // Launch preferences (0.30): the Launch with flags applied; its effective launch IS the preview's.
300
+ const launch = Object.hasOwn(v, 'launch') ? launchOf(v.launch, PREVIEW_FROM) : undefined;
301
+ const launchPromptAnswers = Object.hasOwn(v, 'launchPromptAnswers') ? launchPromptAnswersOf(v.launchPromptAnswers) : undefined;
302
+ if (launchPromptAnswers === null) return null;
303
+ const worktreeHooks = worktreeHooksOf(v.worktreeHooks);
304
+ // Only reports carry `problem`: a preview that would hit one refuses with the error instead.
305
+ if (Object.hasOwn(v, 'launch') && (launch === undefined || launch.problem !== null || launch.effective.harness !== e.harness || launch.effective.model !== e.model
306
+ || launch.effective.launchConfig !== e.launchConfig)) return null;
307
+ return { spawnPreviewApi: 2, preview: true, subject: { soul: v.subject.soul, agentsRoot: v.subject.agentsRoot, dir: v.subject.dir },
308
+ decision: d, resolution: d.resolution, instance: d.instance, home: d.home, branch: d.branch, base: base ? { ...base } : null,
309
+ repo: e.repo, work: e.work, worktree: v.worktree, ...(worktreeHooks ? { worktreeHooks } : {}), harness: e.harness, model: e.model, modelSource: v.modelSource, relation: e.relation?.kind ?? null,
310
+ launchConfig: e.launchConfig, yolo: e.yolo, backend: e.backend, team: v.team ?? null,
311
+ backendStatus: { name: v.backendStatus.name, installed: v.backendStatus.installed, started: false },
312
+ preflight: { status: v.preflight.status, budgetMs: v.preflight.budgetMs, elapsedMs: v.preflight.elapsedMs }, messaging, teams, modules,
313
+ ...(defaultTeam !== undefined ? { defaultTeam } : {}), ...(launch ? { launch } : {}),
314
+ ...(launchPromptAnswers ? { launchPromptAnswers } : {}),
315
+ // Capability warnings (0.49.0): the kernel's message strings, tolerant and idempotent (a malformed list reads as none,
316
+ // never refuses the preview); absent on an older kernel. Shown only: the apply binds nothing on them.
317
+ ...(Object.hasOwn(v, 'warnings') ? { warnings: previewWarningsOf(v.warnings) } : {}) };
318
+ }
@@ -0,0 +1,41 @@
1
+ /** Who is in each team, wherever it runs: a projection of the held observations of ONE workspace
2
+ * view's deployments (#482): its local deployments' rosters and its remote groups' panels, never
3
+ * another workspace's. It runs no command and adds no ssh: the remote roster loop's `server roster`
4
+ * read is the only source for other machines. A member is a row whose identity.team is a non-empty
5
+ * string; the renderer groups them by team, and by deployment within a team (`deployment`, labelled
6
+ * by machine). `workspace` is the member's DEPLOYMENT id: every action on a member is addressed to it. */
7
+ import { canAddressRemote, rowReason } from './remote-address.mjs';
8
+
9
+ const text = v => typeof v === 'string' && v ? v : null;
10
+ const team = row => text(row?.identity?.team);
11
+
12
+ function member(row, { deployment, server = null, serverLabel = null }) {
13
+ return {
14
+ workspace: deployment.id, deployment: { ...deployment }, server, serverLabel,
15
+ instance: row.instance, agent: row.agent, agentsRoot: row.agentsRoot, home: row.home, team: team(row),
16
+ running: row.running === true ? true : row.running === false ? false : null,
17
+ // The roster's own rule (a saved route decides when this computer's OATS reports no fact).
18
+ addressable: canAddressRemote(row), missingRemotely: row.missingRemotely === true,
19
+ // The roster's own reason for a row that can't be opened (spec 01), once, here: the sentence and its short label.
20
+ reason: rowReason(row)?.sentence ?? null, reasonLabel: rowReason(row)?.label ?? null,
21
+ createdAt: text(row.createdAt),
22
+ };
23
+ }
24
+
25
+ /** `deployments`: [{deployment, instances}], the view's local deployments and their rows;
26
+ * `groups`: [{group, deployment, panel}], the view's remote groups and their projected panels (remotePanel).
27
+ * `deployment` is `{id, machine, path}`. */
28
+ export function teamMembers({ deployments = [], groups = [] }) {
29
+ const members = deployments.flatMap(({ deployment, instances = [] }) => instances.filter(row => team(row)).map(row => member(row, { deployment })));
30
+ const servers = [], notReached = [];
31
+ for (const { group, deployment, panel } of groups) {
32
+ const label = group.label || group.server, rows = panel.instances || [];
33
+ for (const row of rows.filter(r => team(r))) members.push(member(row, { deployment, server: group.server, serverLabel: label }));
34
+ servers.push({ server: group.server, label, group: group.id, deployment: deployment.id, reached: group.probe?.ok === true,
35
+ error: group.probe?.ok === true ? null : text(group.probe?.error?.message) ?? 'Server is unreachable',
36
+ registered: group.registrationPresent === true });
37
+ // A failed group holding no rows (last-known or current) is a server we have nothing to show for.
38
+ if (group.probe?.ok !== true && !rows.length) notReached.push({ server: group.server, label, deployment: deployment.id });
39
+ }
40
+ return { members, servers, notReached };
41
+ }
@@ -0,0 +1,45 @@
1
+ /** Soul team rows, shared by the spawn-preview contract and the teams panel. No I/O.
2
+ * 0.29: {label, team, mapped}. Team model v2 (0.30): {label, team, default, from}. */
3
+ const record = v => !!v && typeof v === 'object' && !Array.isArray(v);
4
+ const LABEL = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
5
+ const text = (v, max = 256) => typeof v === 'string' && v.length > 0 && v.length <= max && !/[\x00-\x1f\x7f]/.test(v);
6
+ /** The kernel's team-id rule (provider-neutral, a safety rule): what every generic reader accepts.
7
+ * Only the Desktop's aweb team form (the teams route's argv) keeps the stricter `<name>:<namespace>`. */
8
+ export const TEAM_ID = /^[A-Za-z0-9][A-Za-z0-9._:@/+-]{0,255}$/;
9
+ const teamId = v => typeof v === 'string' && TEAM_ID.test(v);
10
+ /** One soul team row: 0.29 {label, team, mapped} or team model v2 (0.30) {label, team, default, from}.
11
+ * A v2 row keeps `default`/`from` and gains `mapped` = (team !== null), the same fact the 0.29 row
12
+ * states, so existing views read both. Idempotent: a projected v2 row re-validates. */
13
+ export function teamRow(t) {
14
+ if (!record(t) || typeof t.label !== 'string' || !LABEL.test(t.label) || !(t.team === null || teamId(t.team))) return null;
15
+ if (Object.hasOwn(t, 'default')) {
16
+ // The known keys are validated; others (a payload, as 0.29 rows carry) are ignored, never passed on.
17
+ if (typeof t.default !== 'boolean' || !text(t.from, 32) || (Object.hasOwn(t, 'mapped') && t.mapped !== (t.team !== null))) return null;
18
+ return { label: t.label, team: t.team, mapped: t.team !== null, default: t.default, from: t.from };
19
+ }
20
+ if (typeof t.mapped !== 'boolean' || (t.mapped ? t.team === null : t.team !== null)) return null;
21
+ return { label: t.label, team: t.team, mapped: t.mapped };
22
+ }
23
+
24
+ /** The kernel's DefaultTeam: `{label, team: <id>|null (unmapped), from}`, `from` being `soul` or
25
+ * `deployment` (team model v2), or `workspace` too (team model 3: the workspace's defaultTeam). Null when
26
+ * none is configured, or undefined when the value is not that shape. */
27
+ export function defaultTeamOf(v) {
28
+ if (v === null) return null;
29
+ if (!record(v) || typeof v.label !== 'string' || !LABEL.test(v.label) || !(v.team === null || teamId(v.team)) || !['deployment', 'soul', 'workspace'].includes(v.from)) return undefined;
30
+ return { label: v.label, team: v.team, from: v.from };
31
+ }
32
+ /** A list of v2 TeamRows (the default first), or undefined when any row is not one. */
33
+ export function teamRowsOf(v, { v2 = true } = {}) {
34
+ if (!Array.isArray(v) || v.length > 128) return undefined;
35
+ const rows = v.map(teamRow);
36
+ if (rows.some(r => !r || (v2 && !Object.hasOwn(r, 'default'))) || new Set(rows.map(r => r.label)).size !== rows.length) return undefined;
37
+ return rows;
38
+ }
39
+ export const TEAM_LABEL_PATTERN = LABEL;
40
+ /** The team model a CLI's features report: 3 (feature team-model-3, OATS 0.38: a soul's teams are
41
+ * committed in the workspace), 2 (team-model-2, OATS 0.30–0.37), or null (before: the 0.29 views). */
42
+ export function teamModelOf(features) {
43
+ const list = Array.isArray(features) ? features : [];
44
+ return list.includes('team-model-3') ? 3 : list.includes('team-model-2') ? 2 : null;
45
+ }