@awebai/oats 0.51.0 → 0.52.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 (128) hide show
  1. package/README.md +1 -0
  2. package/bin/oats.mjs +109 -37
  3. package/docs/capabilities.md +9 -2
  4. package/docs/configuration.md +134 -88
  5. package/docs/desktop-cli-api.md +927 -92
  6. package/docs/desktop-instance-start.md +56 -0
  7. package/docs/desktop.md +10 -7
  8. package/docs/execution-targets.md +144 -58
  9. package/docs/first-team.md +3 -1
  10. package/docs/harness-trust.md +50 -2
  11. package/docs/implementation.md +66 -9
  12. package/docs/integrations.md +9 -8
  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/oats-local.schema.json +4 -3
  20. package/docs/official-catalog.md +4 -4
  21. package/docs/packages.md +14 -14
  22. package/docs/release-lane.md +15 -5
  23. package/docs/release-notes/v0.44.0.md +1 -1
  24. package/docs/release-notes/v0.52.0.md +933 -0
  25. package/docs/schedules.md +91 -4
  26. package/docs/souls-and-instances.md +95 -25
  27. package/docs/tui.md +152 -0
  28. package/docs/workspaces.md +2 -2
  29. package/lib/claim.mjs +186 -46
  30. package/lib/core.mjs +730 -185
  31. package/lib/errors.mjs +170 -0
  32. package/lib/harness-trust-write.mjs +68 -27
  33. package/lib/harness-trust.mjs +34 -16
  34. package/lib/instance-inspect.mjs +40 -11
  35. package/lib/instance-lifecycle.mjs +169 -47
  36. package/lib/launch-preference.mjs +16 -0
  37. package/lib/launch-prompt-completion.mjs +7 -43
  38. package/lib/launch-prompt-evidence.mjs +14 -7
  39. package/lib/launch-prompt-fixtures/README.md +86 -152
  40. package/lib/launch-prompt-fixtures/dev-channel-confirmation.json +50 -0
  41. package/lib/launch-prompt-fixtures.mjs +122 -109
  42. package/lib/launch-prompt-transport.mjs +2 -56
  43. package/lib/launch-prompts.mjs +102 -100
  44. package/lib/schedule-host.mjs +154 -22
  45. package/lib/schedule.mjs +73 -24
  46. package/lib/system-tools.mjs +39 -0
  47. package/lib/tmux-server-scope.mjs +62 -0
  48. package/lib/triggers.mjs +4 -4
  49. package/lib/workspace.mjs +5 -11
  50. package/lib/worktree-hooks.mjs +98 -20
  51. package/lib/worktree.mjs +83 -24
  52. package/package-catalog.json +3 -3
  53. package/package.json +7 -2
  54. package/packages/client/capability-show-contract.mjs +230 -0
  55. package/packages/client/capability-warnings-contract.mjs +57 -0
  56. package/packages/client/cli-adapter.mjs +548 -0
  57. package/packages/client/cli-environment.mjs +53 -0
  58. package/packages/client/cli-locator.mjs +253 -0
  59. package/packages/client/cli-probe-contract.mjs +47 -0
  60. package/packages/client/client-terms.mjs +60 -0
  61. package/packages/client/deployment-contract.mjs +68 -0
  62. package/packages/client/deployment-data.mjs +483 -0
  63. package/packages/client/deployment-facts.mjs +34 -0
  64. package/packages/client/deployment-label.mjs +76 -0
  65. package/packages/client/deployment-observer.mjs +89 -0
  66. package/packages/client/deployment-panel.mjs +142 -0
  67. package/packages/client/deployment-read-cli.mjs +53 -0
  68. package/packages/client/display-text.mjs +44 -0
  69. package/packages/client/harness-names.mjs +30 -0
  70. package/packages/client/inspect-contract.mjs +62 -0
  71. package/packages/client/instance-acts.mjs +54 -0
  72. package/packages/client/instance-admission.mjs +45 -0
  73. package/packages/client/instance-events-contract.mjs +74 -0
  74. package/packages/client/instance-git-contract.mjs +80 -0
  75. package/packages/client/instance-presentation.mjs +22 -0
  76. package/packages/client/instance-tree.mjs +453 -0
  77. package/packages/client/kernel-environment.mjs +11 -0
  78. package/packages/client/launch-contract.mjs +51 -0
  79. package/packages/client/launch-prompt-outcome.mjs +165 -0
  80. package/packages/client/lifecycle-cli.mjs +61 -0
  81. package/packages/client/lifecycle-contract.mjs +372 -0
  82. package/packages/client/liveness-main.mjs +10 -0
  83. package/packages/client/liveness.mjs +35 -0
  84. package/packages/client/machine-contract.mjs +123 -0
  85. package/packages/client/own-environment.mjs +22 -0
  86. package/packages/client/panel-views.mjs +286 -0
  87. package/packages/client/readiness-contract.mjs +172 -0
  88. package/packages/client/refresh-loop.mjs +52 -0
  89. package/packages/client/remote-address.mjs +126 -0
  90. package/packages/client/remote-roster.mjs +67 -0
  91. package/packages/client/roster-sections.mjs +80 -0
  92. package/packages/client/spawn-apply-cli.mjs +104 -0
  93. package/packages/client/spawn-apply-contract.mjs +183 -0
  94. package/packages/client/spawn-decision.mjs +46 -0
  95. package/packages/client/spawn-messages.mjs +119 -0
  96. package/packages/client/spawn-preview-cli.mjs +32 -0
  97. package/packages/client/spawn-preview-contract.mjs +314 -0
  98. package/packages/client/team-members.mjs +41 -0
  99. package/packages/client/team-rows.mjs +45 -0
  100. package/packages/client/terminal-contract.mjs +57 -0
  101. package/packages/client/tmux-status.mjs +66 -0
  102. package/packages/client/waiting-on-you.mjs +88 -0
  103. package/packages/client/workspace-admission.mjs +45 -0
  104. package/packages/client/workspace-cli.mjs +142 -0
  105. package/packages/client/workspace-views.mjs +147 -0
  106. package/packages/tui/README.md +46 -0
  107. package/packages/tui/bin/tui.mjs +7 -0
  108. package/packages/tui/lib/actions.mjs +29 -0
  109. package/packages/tui/lib/client.mjs +4 -0
  110. package/packages/tui/lib/main.mjs +105 -0
  111. package/packages/tui/lib/term/keys.mjs +323 -0
  112. package/packages/tui/lib/term/screen.mjs +122 -0
  113. package/packages/tui/lib/term/style.mjs +43 -0
  114. package/packages/tui/lib/term/text.mjs +49 -0
  115. package/packages/tui/lib/term/tty.mjs +168 -0
  116. package/packages/tui/lib/term/width.mjs +124 -0
  117. package/packages/tui/lib/views/frame.mjs +62 -0
  118. package/packages/tui/lib/views/help.mjs +28 -0
  119. package/packages/tui/package.json +8 -0
  120. package/skills/oats-getting-started/SKILL.md +29 -22
  121. package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/frame-05-channel-seeded.txt +0 -35
  122. package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/frame-06-first-after-channel.txt +0 -35
  123. package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/frame-07-after-channel-200ms.txt +0 -35
  124. package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/frame-08-installed-after-channel-200ms.txt +0 -35
  125. package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/manifest.json +0 -77
  126. package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/max-bypass-source.json +0 -88
  127. package/lib/launch-prompt-fixtures/structural-completion.json +0 -205
  128. package/lib/launch-prompt-policy.mjs +0 -87
@@ -0,0 +1,314 @@
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_REQUIREMENT_INACTIVE: 'A declared soul requirement is not active.', 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
+ E_CLONE_MISSING: 'This soul works in a member repository that is not cloned on this machine.',
223
+ 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).',
224
+ E_INSTANCE_NAME_TAKEN: 'An instance with that name already exists in this deployment.',
225
+ E_SOUL_AMBIGUOUS: 'More than one member declares a soul with this name.',
226
+ E_BUSY: 'Two spawn previews are already running. Retry when one finishes.',
227
+ E_CLI_TIMEOUT: 'The spawn preview timed out.', E_CLI_OUTPUT_LIMIT: 'The spawn preview exceeded its output limit.',
228
+ E_CLI_PROTOCOL: 'The CLI returned an invalid or mismatched API 2 preview.', E_CLI_FAILED: 'The installed CLI could not complete the preview.',
229
+ E_FORBIDDEN_FRAME: 'This frame cannot request a spawn preview.',
230
+ };
231
+ const KERNEL_CODE = /^E_[A-Z0-9_]{1,63}$/;
232
+ /** A kernel refusal keeps its own code and message (bounded, printable): the
233
+ * kernel's remedy — "git clone … " for E_CLONE_MISSING — is the useful part.
234
+ * Desktop-side codes use the fixed table. */
235
+ export function previewFailure(code, target = null, kernelMessage, kernelFix) {
236
+ const kernel = typeof code === 'string' && KERNEL_CODE.test(code) && typeof kernelMessage === 'string'
237
+ && kernelMessage.trim() && kernelMessage.length <= 2048 && safe(kernelMessage.replace(/\n/g, ' '), 2048);
238
+ // A launch refusal's `fix` (E_HARNESS_UNAVAILABLE, E_LAUNCH_CONFIG_UNKNOWN: the kernel's own words) travels with it.
239
+ const fix = kernel && typeof kernelFix === 'string' && kernelFix.trim() && safe(kernelFix, 1024) ? { fix: kernelFix } : {};
240
+ if (kernel) return { spawnPreviewViewApi: 1, status: 'unavailable', target: previewTarget(target), data: null, reason: { code, message: kernelMessage, ...fix } };
241
+ if (!Object.hasOwn(errors, code)) code = 'E_CLI_FAILED';
242
+ return { spawnPreviewViewApi: 1, status: 'unavailable', target: previewTarget(target), data: null, reason: { code, message: errors[code] } };
243
+ }
244
+ /** The kernel's v2 preview, projected to what the dialog shows and the apply
245
+ * binds. Top-level facts must agree with the decision the apply is bound to
246
+ * (`--expect-decision`); the revision is opaque producer data. The modules
247
+ * are projected as names, sources and (with `composedFrom`, the CLI's feature
248
+ * preview-composed-from) why each is there (modulesOf); capabilities[], skills,
249
+ * settings and the task are the kernel's business and are not projected. */
250
+ const hex24 = v => typeof v === 'string' && /^[a-f0-9]{24}$/.test(v);
251
+ /** Optional launch policy, not observed answers or readiness. Keep absence for
252
+ * older CLIs distinct from an explicit policy that answers no prompts. */
253
+ function launchPromptAnswersOf(v) {
254
+ if (!record(v) || typeof v.awebDevelopmentChannel !== 'boolean'
255
+ || !(v.consentSource === null || safe(v.consentSource) && !!v.consentSource)) return null;
256
+ return { awebDevelopmentChannel: v.awebDevelopmentChannel, consentSource: v.consentSource };
257
+ }
258
+ /** The capabilities whose `worktree` hook this spawn would run, in order (feature worktree-event,
259
+ * OATS 0.49.0): [{capability, required}]. Read tolerantly, unlike the rest of the preview: anything
260
+ * else (null, absent, malformed) is undefined, never a refused preview. The apply's CLI deadline and
261
+ * the dialog's Setup fact read it. Bounded like the preview's modules (MAX_HOOKS): a spawn runs at most one
262
+ * `worktree` hook per capability it composes. */
263
+ export const MAX_HOOKS = MODULES_MAX;
264
+ export function worktreeHooksOf(v) {
265
+ if (!Array.isArray(v) || v.length > MAX_HOOKS) return undefined;
266
+ const out = [];
267
+ for (const h of v) {
268
+ if (!record(h) || typeof h.capability !== 'string' || !h.capability || !safe(h.capability, 256) || typeof h.required !== 'boolean') return undefined;
269
+ out.push({ capability: h.capability, required: h.required });
270
+ }
271
+ return out;
272
+ }
273
+ export function previewData(v, expected, { composedFrom = false } = {}) {
274
+ const t = previewTarget(expected);
275
+ if (!t || !record(v) || v.spawnPreviewApi !== 2 || v.preview !== true || !record(v.subject)
276
+ || v.subject.soul !== t.selector.soul || v.subject.agentsRoot !== t.selector.agentsRoot || v.subject.dir !== t.context) return null;
277
+ const d = spawnDecision(v.decision, { effectiveRequired: true });
278
+ if (!d || !hex24(v.resolution) || d.resolution !== v.resolution) return null;
279
+ const e = d.effective, base = d.base;
280
+ if (v.instance !== d.instance || v.home !== d.home || v.branch !== d.branch
281
+ || (v.base === null ? base !== null : !record(v.base) || v.base.ref !== base?.ref || v.base.oid !== base?.oid)
282
+ || v.work !== e.work || v.repo !== e.repo || harnessOf(v) !== e.harness || v.model !== e.model || v.launchConfig !== e.launchConfig
283
+ || (v.yolo ?? null) !== e.yolo || v.backend !== e.backend || (v.relation ?? null) !== (e.relation?.kind ?? null)
284
+ || Object.hasOwn(v, 'policy') && v.policy?.childSpawns?.allowed !== e.childSpawns) return null;
285
+ // `team` (the primary label) is 0.29's; team model v2 (0.30) removes it: absent reads as null.
286
+ if (!safe(v.modelSource) || !v.modelSource || v.team != null && !safe(v.team, 256)
287
+ || (e.work === 'worktree' ? !absolute(v.worktree) : v.worktree !== null)
288
+ || !record(v.backendStatus) || v.backendStatus.name !== v.backend || typeof v.backendStatus.installed !== 'boolean' || v.backendStatus.started !== false
289
+ || !record(v.preflight) || !['complete', 'timeout'].includes(v.preflight.status) || !Number.isInteger(v.preflight.budgetMs) || v.preflight.budgetMs <= 0 || v.preflight.budgetMs > 20000
290
+ || !Number.isSafeInteger(v.preflight.elapsedMs) || v.preflight.elapsedMs < 0) return null;
291
+ const messaging = messagingOf(v), teams = teamsOf(v), modules = modulesOf(v, Object.hasOwn(v, 'messaging'), composedFrom);
292
+ // Team model v2: the soul's default (the kernel's DefaultTeam, or null); absent on 0.29.
293
+ const defaultTeam = Object.hasOwn(v, 'defaultTeam') ? defaultTeamOf(v.defaultTeam) : undefined;
294
+ if (messaging === undefined || teams === undefined || modules === undefined || (Object.hasOwn(v, 'defaultTeam') && defaultTeam === undefined)) return null;
295
+ // Launch preferences (0.30): the Launch with flags applied; its effective launch IS the preview's.
296
+ const launch = Object.hasOwn(v, 'launch') ? launchOf(v.launch, PREVIEW_FROM) : undefined;
297
+ const launchPromptAnswers = Object.hasOwn(v, 'launchPromptAnswers') ? launchPromptAnswersOf(v.launchPromptAnswers) : undefined;
298
+ if (launchPromptAnswers === null) return null;
299
+ const worktreeHooks = worktreeHooksOf(v.worktreeHooks);
300
+ // Only reports carry `problem`: a preview that would hit one refuses with the error instead.
301
+ if (Object.hasOwn(v, 'launch') && (launch === undefined || launch.problem !== null || launch.effective.harness !== e.harness || launch.effective.model !== e.model
302
+ || launch.effective.launchConfig !== e.launchConfig)) return null;
303
+ return { spawnPreviewApi: 2, preview: true, subject: { soul: v.subject.soul, agentsRoot: v.subject.agentsRoot, dir: v.subject.dir },
304
+ decision: d, resolution: d.resolution, instance: d.instance, home: d.home, branch: d.branch, base: base ? { ...base } : null,
305
+ 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,
306
+ launchConfig: e.launchConfig, yolo: e.yolo, backend: e.backend, team: v.team ?? null,
307
+ backendStatus: { name: v.backendStatus.name, installed: v.backendStatus.installed, started: false },
308
+ preflight: { status: v.preflight.status, budgetMs: v.preflight.budgetMs, elapsedMs: v.preflight.elapsedMs }, messaging, teams, modules,
309
+ ...(defaultTeam !== undefined ? { defaultTeam } : {}), ...(launch ? { launch } : {}),
310
+ ...(launchPromptAnswers ? { launchPromptAnswers } : {}),
311
+ // Capability warnings (0.49.0): the kernel's message strings, tolerant and idempotent (a malformed list reads as none,
312
+ // never refuses the preview); absent on an older kernel. Shown only: the apply binds nothing on them.
313
+ ...(Object.hasOwn(v, 'warnings') ? { warnings: previewWarningsOf(v.warnings) } : {}) };
314
+ }
@@ -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
+ }
@@ -0,0 +1,57 @@
1
+ /** Private Desktop terminal wire v2. No numeric compatibility/owner inference. */
2
+ export const TERMINAL_API = 2;
3
+ export const TERM_WRITE_BYTES = 64 * 1024;
4
+ export const TERM_CALLER_BYTES = 1024 * 1024;
5
+ export const TERM_READY_BYTES = 64 * 1024;
6
+ export const TERM_READY_MS = 5000;
7
+ export const TERM_CLOSE_MS = 2000;
8
+ export const TERM_PREPARE_MS = 30000;
9
+ export const TERM_ATTACHMENTS_MAX = 4;
10
+ export function terminalHandle(v) {
11
+ return !!v && typeof v === 'object' && !Array.isArray(v) && Number.isSafeInteger(v.id) && v.id > 0
12
+ && typeof v.lease === 'string' && /^[a-f0-9]{64}$/.test(v.lease) ? Object.freeze({ id: v.id, lease: v.lease }) : null;
13
+ }
14
+ /** The E_HERDR_REMOVED stem the kernel and the Desktop share (OATS 0.31.0). */
15
+ export const HERDR_REMOVED = 'Herdr is no longer supported by OATS (removed in 0.31.0); tmux is the only session backend.';
16
+ export const terminalGeometry = (cols, rows) => Number.isInteger(cols) && cols >= 1 && cols <= 1000 && Number.isInteger(rows) && rows >= 1 && rows <= 1000;
17
+ /** Remote failures whose message names the server; the static message says "the server". */
18
+ const serverMessages = {
19
+ E_TERM_REMOTE_UNREACHABLE: server => `Couldn't reach ${server}.`,
20
+ E_TERM_REMOTE_GONE: server => `The session is no longer running on ${server}.`,
21
+ E_TERM_REMOTE_NO_ANSWER: server => `OATS on this computer gave no answer while connecting to ${server}.`,
22
+ E_TERM_REMOTE_NO_SSH: server => `ssh isn't available on this computer, so ${server} can't be reached. Install OpenSSH on this computer.`,
23
+ };
24
+ const messages = {
25
+ E_TERM_FORBIDDEN_FRAME: 'This document cannot access terminals.',
26
+ E_TERM_LEASE: 'This terminal handle is no longer owned by this document.',
27
+ E_TERM_BAD_ARGS: 'Invalid terminal request.', E_TERM_CAP: 'Terminal limit reached. Close a terminal first.',
28
+ E_TERM_CONTEXT_CHANGED: 'The terminal owner or preparation context changed.',
29
+ E_TERM_OPEN_FAILED: 'Could not attach to the requested terminal.',
30
+ E_TERM_NOT_READY: 'The terminal has not acknowledged readiness.',
31
+ E_TERM_REUSED: 'This terminal is already open.',
32
+ E_TERM_READY_TIMEOUT: 'terminal did not become ready; closed',
33
+ E_TERM_OUTPUT_LIMIT: 'Terminal readiness output exceeded its safe limit; closed.',
34
+ E_TERM_PREPARE_TIMEOUT: 'Terminal preparation timed out.',
35
+ E_TERM_CLOSING: 'closing… not yet confirmed', E_TERM_CLOSE_PENDING: 'closing… not yet confirmed',
36
+ E_TERM_BUSY: 'This terminal operation is already in progress.',
37
+ E_TERM_ATTACHMENT_FAILED: 'Could not prepare these attachments.',
38
+ E_TERM_ATTACHMENT_INTERRUPTED: 'Attachment interrupted; some file copies may already exist. No input was inserted.',
39
+ E_TERM_INPUT_LIMIT: 'Terminal input exceeds the safe write limit. Nothing was sent.',
40
+ E_TERM_TRANSPORT: 'The terminal service did not confirm the operation.',
41
+ E_HERDR_REMOVED: HERDR_REMOVED,
42
+ E_TERM_REMOTE_UNREACHABLE: serverMessages.E_TERM_REMOTE_UNREACHABLE('the server'),
43
+ E_TERM_REMOTE_GONE: serverMessages.E_TERM_REMOTE_GONE('the server'),
44
+ E_TERM_REMOTE_NO_ANSWER: serverMessages.E_TERM_REMOTE_NO_ANSWER('the server'),
45
+ E_TERM_REMOTE_NO_SSH: serverMessages.E_TERM_REMOTE_NO_SSH('the server'),
46
+ };
47
+ export function terminalFailure(code) {
48
+ if (typeof code !== 'string' || !Object.hasOwn(messages, code)) code = 'E_TERM_OPEN_FAILED';
49
+ return { terminalApi: TERMINAL_API, ok: false, code, message: messages[code] };
50
+ }
51
+ /** A failure's message for display, naming the server where the message has one. */
52
+ export function terminalMessage(code, server) {
53
+ const failure = terminalFailure(code);
54
+ return server && Object.hasOwn(serverMessages, failure.code) ? serverMessages[failure.code](server) : failure.message;
55
+ }
56
+ export const terminalSuccess = (status, extra = {}) => ({ terminalApi: TERMINAL_API, ok: true, status, ...extra });
57
+ export const terminalSameHandle = (a, b) => !!a && !!b && a.id === b.id && a.lease === b.lease;
@@ -0,0 +1,66 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { basename } from "node:path";
3
+
4
+ /** The session a home without a recorded tmux session is looked for in: the kernel's default (0.31),
5
+ * mirrored from the kernel's DEFAULT_TMUX_SESSION (its core module; the Desktop never imports it) — change both. */
6
+ export const DEFAULT_TMUX_SESSION = process.env.OATS_TMUX_SESSION || process.env.PI_AGENTS_TMUX_SESSION || "oats-agents";
7
+
8
+ const shells = new Set(["sh", "bash", "zsh", "fish", "dash", "ksh", "login"]);
9
+
10
+ /** One read per socket, and at most one process snapshot per roster collection. */
11
+ export function createTmuxStatusReader({ exec = execFileSync } = {}) {
12
+ const sockets = new Map();
13
+ let processes;
14
+ const run = (bin, args) => exec(bin, args, {
15
+ encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], timeout: 4000, maxBuffer: 4 * 1024 * 1024,
16
+ });
17
+ function readSocket(socket) {
18
+ if (!sockets.has(socket)) {
19
+ try {
20
+ const text = run("tmux", ["-u", ...(socket ? ["-S", socket] : []), "list-panes", "-a", "-F",
21
+ "#{session_name}\t#{window_name}\t#{window_id}\t#{pane_dead}\t#{pane_current_command}\t#{pane_pid}"]);
22
+ const panes = text.trim().split("\n").filter(Boolean).map((line) => {
23
+ const [session, window, id, dead, command, pid] = line.split("\t");
24
+ if (!session || !window || !/^@\d+$/.test(id) || !/^[01]$/.test(dead) || !/^\d+$/.test(pid)) throw new Error("Invalid tmux status response");
25
+ return { session, window, id, dead: dead === "1", command, pid };
26
+ });
27
+ sockets.set(socket, { panes });
28
+ } catch (e) {
29
+ const absent = /no server running|error connecting.*No such file or directory/i.test(String(e.stderr || ""));
30
+ sockets.set(socket, absent ? { panes: [] } : { error: e.message || "Cannot reach terminal server" });
31
+ }
32
+ }
33
+ return sockets.get(socket);
34
+ }
35
+ function hasHarness(pid) {
36
+ if (!processes) {
37
+ processes = run("ps", ["-axo", "pid=,ppid=,comm="]).split("\n")
38
+ .map((line) => line.trim().match(/^(\d+)\s+(\d+)\s+(.+)$/)).filter(Boolean);
39
+ }
40
+ const descendants = new Set([pid]);
41
+ for (let changed = true; changed;) {
42
+ changed = false;
43
+ for (const [, child, parent, name] of processes) {
44
+ if (!descendants.has(parent) || descendants.has(child)) continue;
45
+ descendants.add(child); changed = true;
46
+ if (!shells.has(basename(name).replace(/^-/, ""))) return true;
47
+ }
48
+ }
49
+ return false;
50
+ }
51
+ return (meta, defaultSession = DEFAULT_TMUX_SESSION) => {
52
+ const tmux = { ...meta.tmux, session: meta.tmux?.session || defaultSession, window: meta.tmux?.window || meta.instance };
53
+ const status = readSocket(tmux.socket || "");
54
+ const unknown = (error) => ({ tmux, running: null, runtimeState: "unreachable", runtimeError: error });
55
+ if (status.error) return unknown(status.error);
56
+ const panes = status.panes.filter((p) => p.session === tmux.session && p.window === tmux.window);
57
+ if (panes.length > 1) return unknown("Instance window has multiple panes; check its terminal before starting");
58
+ const pane = panes[0];
59
+ if (!pane || pane.dead) return { tmux, running: false, runtimeState: "stopped" };
60
+ tmux.id = pane.id;
61
+ try {
62
+ const running = !shells.has(pane.command.replace(/^-/, "")) || hasHarness(pane.pid);
63
+ return { tmux, running, runtimeState: running ? "running" : "shell", paneCommand: pane.command };
64
+ } catch (e) { return unknown(e.message); }
65
+ };
66
+ }
@@ -0,0 +1,88 @@
1
+ /** "Needs input" (Spec D): the kernel's `waitingOnYou` claim on an `oats status --json` row, validated
2
+ * once here and read through one liveness gate by every surface (row mark, card, description, collapsed
3
+ * roll-up: instance-tree.mjs's waitingRollup). Pure, no DOM, never throws. `null` (or absent) means
4
+ * unknown, never "not waiting". Display-only: nothing in Desktop acts on a claim.
5
+ * The claim contract only: the server imports it (deployment-data, remote-roster), so it imports
6
+ * contract modules and nothing else — no tree traversal, no loading UI. */
7
+ import { record } from './readiness-contract.mjs';
8
+ import { eventsTimestamp, eventsId, eventsUnsafe, EVENTS_WITHHELD } from './instance-events-contract.mjs';
9
+ import { NOT_NOTE_TEXT } from './display-text.mjs';
10
+
11
+ /** A claim's note: a non-empty string of at most 200 code points (not UTF-16 units: 101 emoji is a valid
12
+ * note), with none of NOT_NOTE_TEXT (the set's one definition is in display-text.mjs); unsafe text is
13
+ * withheld (the activity view's house rule: it shows EVENTS_WITHHELD). Anything else → null: the claim
14
+ * itself is kept. Not null is the validity answer the kernel's validWaitingMessage gives (a withheld note
15
+ * is a valid note). Never throws (no length-throwing detail helper on this path). */
16
+ export function waitingMessage(v) {
17
+ if (typeof v !== 'string' || !v || [...v].length > 200 || NOT_NOTE_TEXT.test(v)) return null;
18
+ return eventsUnsafe.test(v) ? EVENTS_WITHHELD : v;
19
+ }
20
+
21
+ /** The sidebar's claim: `{ since, producer, reason, message }` or null. Only `since` and `producer` can
22
+ * drop a claim: a missing or malformed reason (never rendered) is null, a malformed message is null, and
23
+ * so is a withheld one (#584): the row, the card and the tab then show the reason in words (waitingLabel),
24
+ * never the withheld marker. Extra keys are ignored (forward compatible). */
25
+ export function waitingOnYouData(v) {
26
+ if (!record(v) || !eventsTimestamp(v.since) || !eventsId(v.producer)) return null;
27
+ const reason = typeof v.reason === 'string' && v.reason.length <= 64 ? v.reason : null;
28
+ const message = waitingMessage(v.message);
29
+ return { since: v.since, producer: v.producer, reason, message: message === EVENTS_WITHHELD ? null : message };
30
+ }
31
+
32
+ /** The claim a row may show, or null. The only gate: liveness says running (`running === true`, and no
33
+ * reported `runtimeState` other than `running`: a tmux `shell`, a stopped pane, an unreachable or
34
+ * unsupported session never shows it), and the row is current: a remote row whose server was not reached,
35
+ * or a row the roster holds stale (`stale`: its last re-read failed), carries a last-known claim, which is
36
+ * unknown. A null or absent `runtimeState` is "not reported", never "not running" (#582): the kernel's
37
+ * remote roster sends null on every row, so a remote row is gated on the `running` its host reported; a
38
+ * local row always carries the concrete state Desktop liveness observed. */
39
+ export function waitingClaim(row, { stale = false } = {}) {
40
+ if (stale || !record(row) || row.running !== true || row.serverUnreached === true) return null;
41
+ if (row.runtimeState != null && row.runtimeState !== 'running') return null;
42
+ return waitingOnYouData(row.waitingOnYou);
43
+ }
44
+
45
+ const LABELS = Object.freeze({ permission: 'Waiting for a tool approval', question: 'Asked you a question', attention: 'Asked for your attention' });
46
+ /** The reason in words. The raw reason is never rendered: an unknown one reads "Needs input". */
47
+ export const waitingLabel = claim => Object.hasOwn(LABELS, claim?.reason ?? '') ? LABELS[claim.reason] : 'Needs input';
48
+
49
+ /** How long it has waited (floor): "under a minute", "N min", "N h", "N d". A future `since` (clock skew)
50
+ * reads "under a minute". Computed when shown, never painted into the row. */
51
+ export function waitedText(since, now = Date.now()) {
52
+ const ms = now - Date.parse(since);
53
+ if (!Number.isFinite(ms) || ms < 60000) return 'under a minute';
54
+ const min = Math.floor(ms / 60000); if (min < 60) return `${min} min`;
55
+ const h = Math.floor(min / 60); if (h < 24) return `${h} h`;
56
+ return `${Math.floor(h / 24)} d`;
57
+ }
58
+
59
+ // The app's copy is English; a fixed table keeps the date deterministic (no locale lookup).
60
+ const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
61
+ const pad = n => String(n).padStart(2, '0');
62
+ /** The claim's start in local time, as precise as it needs to be next to `now`: "14:03" on now's local
63
+ * calendar day, "Oct 2, 14:03" on another day of the same year, "2025-10-02 14:03" in another year. */
64
+ export function waitingClock(since, now = Date.now()) {
65
+ const at = new Date(since), today = new Date(now);
66
+ if (!Number.isFinite(at.getTime())) return '';
67
+ const time = `${pad(at.getHours())}:${pad(at.getMinutes())}`;
68
+ if (at.getFullYear() !== today.getFullYear()) return `${at.getFullYear()}-${pad(at.getMonth() + 1)}-${pad(at.getDate())} ${time}`;
69
+ return at.getMonth() === today.getMonth() && at.getDate() === today.getDate() ? time : `${MONTHS[at.getMonth()]} ${at.getDate()}, ${time}`;
70
+ }
71
+
72
+ /** "dev-a, dev-b" — up to 3 names, then "and N more". */
73
+ export function waitingNames(rows) {
74
+ const names = rows.map(r => r.instance);
75
+ return names.length > 3 ? `${names.slice(0, 3).join(', ')} and ${names.length - 3} more` : names.join(', ');
76
+ }
77
+
78
+ /** The card's "Below" fact: "2 need input: dev-a, dev-b". */
79
+ export const waitingBelowText = rows => `${rows.length} ${rows.length === 1 ? 'needs' : 'need'} input: ${waitingNames(rows)}`;
80
+
81
+ /** What an unavailable row (no card) appends to its title/aria-description sentence. Absolute time only:
82
+ * the sentence is painted once; `now` is the paint time (it decides whether the start needs a date). */
83
+ export function waitingSentence(claim, below = [], now = Date.now()) {
84
+ const parts = [];
85
+ if (claim) parts.push(`Needs input: ${claim.message ?? waitingLabel(claim)} since ${waitingClock(claim.since, now)}`);
86
+ if (below.length) parts.push(`${below.length} below need input: ${waitingNames(below)}`);
87
+ return parts.map(p => ` · ${p}`).join('');
88
+ }