@yunhozz/arc 0.4.6 → 0.4.7

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 (75) hide show
  1. package/MANIFEST.sha256 +74 -69
  2. package/README.md +35 -51
  3. package/claude/agents/arc-implementer.md +2 -2
  4. package/claude/agents/arc-planner.md +1 -1
  5. package/claude/agents/arc-qa.md +1 -1
  6. package/claude/agents/arc-reviewer.md +1 -1
  7. package/claude/agents/arc-scouter.md +1 -1
  8. package/claude/skill/references/coordination.md +2 -2
  9. package/claude/skill/references/handoff-prep.md +5 -0
  10. package/claude/skill/references/handoff.md +2 -2
  11. package/claude/skill/references/planning.md +2 -2
  12. package/claude/skill/references/verification.md +16 -3
  13. package/claude/skill/references/worktree-creation.md +2 -2
  14. package/codex/agents/arc-implementer.toml +1 -1
  15. package/codex/agents/arc-planner.toml +1 -1
  16. package/codex/agents/arc-qa.toml +1 -1
  17. package/codex/agents/arc-reviewer.toml +1 -1
  18. package/codex/agents/arc-scouter.toml +1 -1
  19. package/codex/skill/references/coordination.md +2 -2
  20. package/codex/skill/references/handoff-prep.md +5 -0
  21. package/codex/skill/references/handoff.md +2 -2
  22. package/codex/skill/references/planning.md +2 -2
  23. package/codex/skill/references/verification.md +15 -2
  24. package/gemini/agents/arc-implementer.md +2 -2
  25. package/gemini/agents/arc-planner.md +1 -1
  26. package/gemini/agents/arc-qa.md +1 -1
  27. package/gemini/agents/arc-reviewer.md +1 -1
  28. package/gemini/agents/arc-scouter.md +1 -1
  29. package/gemini/skill/references/coordination.md +3 -3
  30. package/gemini/skill/references/handoff-prep.md +5 -0
  31. package/gemini/skill/references/handoff.md +2 -2
  32. package/gemini/skill/references/planning.md +2 -2
  33. package/gemini/skill/references/verification.md +16 -3
  34. package/gemini/skill/references/worktree-creation.md +2 -2
  35. package/grok/agents/arc-implementer.md +2 -2
  36. package/grok/agents/arc-planner.md +1 -1
  37. package/grok/agents/arc-qa.md +1 -1
  38. package/grok/agents/arc-reviewer.md +1 -1
  39. package/grok/agents/arc-scouter.md +1 -1
  40. package/grok/skill/references/coordination.md +2 -2
  41. package/grok/skill/references/handoff-prep.md +5 -0
  42. package/grok/skill/references/handoff.md +2 -2
  43. package/grok/skill/references/planning.md +2 -2
  44. package/grok/skill/references/verification.md +16 -3
  45. package/grok/skill/references/worktree-creation.md +2 -2
  46. package/lib/cli/root.mjs +1 -1
  47. package/lib/management/reapply.mjs +117 -0
  48. package/lib/management/update.mjs +59 -5
  49. package/lib/npm/upgrade.mjs +6 -2
  50. package/lib/policy/role-policy.json +1 -1
  51. package/lib/prompts/agent-fragments.json +5 -5
  52. package/lib/runtime/role-bridge.mjs +10 -1
  53. package/lib/runtime/role-dispatch-policy.mjs +4 -0
  54. package/lib/runtime/role-observe.mjs +192 -14
  55. package/lib/runtime/role-supervisor.mjs +268 -23
  56. package/lib/tui/app.mjs +3 -39
  57. package/lib/tui/interface.mjs +40 -0
  58. package/lib/tui/setup.mjs +27 -16
  59. package/lib/watch/args.mjs +12 -27
  60. package/lib/watch/dispatch.mjs +2 -2
  61. package/lib/watch/index.mjs +38 -26
  62. package/lib/watch/markdown.mjs +232 -0
  63. package/lib/watch/menu.mjs +43 -0
  64. package/lib/watch/model.mjs +7 -3
  65. package/lib/watch/render.mjs +28 -67
  66. package/lib/watch/scope.mjs +1 -5
  67. package/lib/watch/status-line.mjs +2 -4
  68. package/lib/watch/text-width.mjs +43 -0
  69. package/lib/watch/watcher.mjs +17 -36
  70. package/package.json +1 -1
  71. package/shared/skill/runtime/role-bridge.mjs +10 -1
  72. package/shared/skill/runtime/role-dispatch-policy.mjs +4 -0
  73. package/shared/skill/runtime/role-observe.mjs +192 -14
  74. package/shared/skill/runtime/role-policy.json +1 -1
  75. package/shared/skill/runtime/role-supervisor.mjs +268 -23
@@ -4,22 +4,24 @@ import fs from 'node:fs';
4
4
  import fsp from 'node:fs/promises';
5
5
  import path from 'node:path';
6
6
  import crypto from 'node:crypto';
7
- import {spawn, spawnSync} from 'node:child_process';
7
+ import {execFile, spawn, spawnSync} from 'node:child_process';
8
8
  import {fileURLToPath} from 'node:url';
9
+ import {promisify} from 'node:util';
9
10
  import {GROK_CONTRACT, normalizeGrokStreamEvent, evaluateGrokObservation} from './grok-stream.mjs';
10
11
  import {GROK_SANDBOX_RELATIVE, grokSandboxProfileName, renderGrokSandboxProfile, grokProfileCovered, inspectGrokProfileSlot, checkGrokHome, createGrokSandboxProfile, verifyGrokSandboxProfile, removeGrokSandboxProfile, grokEventsBaseline, readGrokProfileApplied, grokConfigSecurityProjection} from './grok-sandbox.mjs';
11
12
  import {GEMINI_CONTRACT, normalizeGeminiStreamEvent, evaluateGeminiObservation} from './gemini-stream.mjs';
12
- import {DEFAULT_POLICY, reason, bridgeGateReasons} from './role-dispatch-policy.mjs';
13
+ import {DEFAULT_POLICY, DESCENDANT_LIMIT, DESCENDANT_SAMPLE_MS, reason, bridgeGateReasons} from './role-dispatch-policy.mjs';
13
14
  import {readLease, writeLease, writeHeartbeat, cancelRequested, TERMINAL_STATES} from './role-dispatch-store.mjs';
14
15
  import {withRoutingLock, readActivation, resolveRuntimeHomes} from './role-routing.mjs';
15
16
  import {resolveLocalCli, localCliEnvironment} from './local-cli.mjs';
16
17
  import {parseCompositeProfile, buildBridgeArgs, argsDigest, ROLE_BRIDGE_PERMISSIONS} from './role-bridge-args.mjs';
17
- import {createLineParser, normalizeClaudeStreamEvent, normalizeCodexStreamEvent, eventRecord, evaluateClaudeInit, evaluateCodexContext, readClaudeTranscriptEffort, readCodexTurnContext, classifyFailure, snapshotWorktree, snapshotControlFiles, detectViolations, allowedPathsCoverControl, claudeProjectSettingsWidenScope, resolveWorktree} from './role-observe.mjs';
18
+ import {createLineParser, normalizeClaudeStreamEvent, normalizeCodexStreamEvent, eventRecord, evaluateClaudeInit, evaluateCodexContext, readClaudeTranscriptEffort, readCodexTurnContext, classifyFailure, snapshotWorktree, snapshotControlFiles, observeHeadAdvance, detectViolations, toleratedRecord, allowedPathsCoverControl, claudeProjectSettingsWidenScope, resolveWorktree} from './role-observe.mjs';
18
19
  import {getPlatform, routingProfileFile} from './platform-registry.mjs';
19
20
 
20
21
  const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
21
22
  const sha256 = bytes => 'sha256:' + crypto.createHash('sha256').update(bytes).digest('hex');
22
23
  const STDERR_LIMIT = 65536;
24
+ const execFileAsync = promisify(execFile);
23
25
 
24
26
  export const SUPERVISOR_IMPLEMENTATIONS = new Map([
25
27
  ['claude', {
@@ -77,18 +79,194 @@ export const SUPERVISOR_IMPLEMENTATIONS = new Map([
77
79
  ]);
78
80
  export const SUPERVISOR_PLATFORM_IDS = Object.freeze([...SUPERVISOR_IMPLEMENTATIONS.keys()]);
79
81
 
82
+ const normalizePsWhitespace = value => value.trim().replace(/\s+/g, ' ');
83
+
80
84
  /** `ps -o lstart=` start time; used with the pid to tell a live process from a reused pid. Null when ps is unavailable or the pid is gone. */
81
85
  export function processStartTime(pid) {
82
86
  if (!Number.isInteger(pid) || pid <= 0) return null;
83
87
  const result = spawnSync('ps', ['-o', 'lstart=', '-p', String(pid)], {encoding: 'utf8', env: {PATH: process.env.PATH ?? '/usr/bin:/bin', LC_ALL: 'C'}, timeout: 5000});
84
88
  if (result.error || result.status !== 0) return null;
85
- return result.stdout.trim().replace(/\s+/g, ' ') || null;
89
+ return normalizePsWhitespace(result.stdout) || null;
86
90
  }
87
91
  export function processAlive({pid, startTime} = {}) {
88
92
  const current = processStartTime(pid);
89
93
  return current !== null && current === startTime;
90
94
  }
91
95
 
96
+ const LSTART = /[A-Z][a-z]{2} [A-Z][a-z]{2} [1-9]\d? \d{2}:\d{2}:\d{2} \d{4}/;
97
+ const PROCESS_ROW = new RegExp(`^(\\d+) (\\d+) (\\d+) (${LSTART.source})(?: (\\d+) ([A-Za-z]\\S*))?$`);
98
+ const validPid = pid => Number.isInteger(pid) && pid > 0 && pid <= 0x7fffffff;
99
+ const sameStart = (row, entry) => row?.startTime === entry.startTime;
100
+ const processEntry = ({pid, ppid, pgid, startTime}) => ({pid, ppid, pgid, startTime});
101
+
102
+ export function parseProcessTable(stdout) {
103
+ const entries = [];
104
+ for (const line of stdout.split('\n')) {
105
+ const match = PROCESS_ROW.exec(normalizePsWhitespace(line));
106
+ if (!match) continue;
107
+ const [, pid, ppid, pgid, startTime, uid, stat] = match;
108
+ const entry = {pid: Number(pid), ppid: Number(ppid), pgid: Number(pgid), startTime};
109
+ if (!validPid(entry.pid) || (entry.ppid !== 0 && !validPid(entry.ppid)) || !validPid(entry.pgid)) continue;
110
+ if (stat?.startsWith('Z')) continue;
111
+ entries.push(uid === undefined ? entry : {...entry, uid: Number(uid)});
112
+ }
113
+ return entries;
114
+ }
115
+
116
+ export async function sampleProcessTable({timeoutMs = 5000} = {}) {
117
+ try {
118
+ const {stdout} = await execFileAsync('ps', ['-A', '-o', 'pid=,ppid=,pgid=,lstart=,uid=,stat='], {
119
+ encoding: 'utf8', env: {PATH: process.env.PATH ?? '/usr/bin:/bin', LC_ALL: 'C'}, timeout: timeoutMs,
120
+ });
121
+ return parseProcessTable(stdout);
122
+ } catch { return null; }
123
+ }
124
+
125
+ function supervisorLineage(byPid, selfPid) {
126
+ const excluded = new Set([selfPid]);
127
+ let parent = byPid.get(selfPid)?.ppid ?? (selfPid === process.pid ? process.ppid : 0);
128
+ while (validPid(parent) && !excluded.has(parent)) {
129
+ excluded.add(parent);
130
+ parent = byPid.get(parent)?.ppid;
131
+ }
132
+ return excluded;
133
+ }
134
+
135
+ export function createDescendantTracker({rootPid, rootPgid, selfPid, limit = DESCENDANT_LIMIT}) {
136
+ const tracked = new Map();
137
+ let root, truncated = false;
138
+ const entries = () => [...tracked.values()];
139
+ return {
140
+ get rootStartTime() { return root?.startTime; },
141
+ get truncated() { return truncated; },
142
+ entries,
143
+ escaped: () => entries().filter(entry => entry.pgid !== rootPgid),
144
+ update(table) {
145
+ const byPid = new Map(table.map(entry => [entry.pid, entry]));
146
+ const excluded = supervisorLineage(byPid, selfPid);
147
+ const currentRoot = byPid.get(rootPid);
148
+ const rootInPlace = currentRoot?.ppid === selfPid && currentRoot.pgid === rootPgid;
149
+ if (!root && rootInPlace) root = processEntry(currentRoot);
150
+ const children = new Map();
151
+ for (const entry of table) {
152
+ if (excluded.has(entry.pid) || entry.pid === rootPid) continue;
153
+ if (!children.has(entry.ppid)) children.set(entry.ppid, []);
154
+ children.get(entry.ppid).push(entry);
155
+ }
156
+ // Seed the walk only with identities still present in this sample.
157
+ const parents = [];
158
+ if (root && rootInPlace && sameStart(currentRoot, root)) parents.push(rootPid);
159
+ for (const entry of tracked.values()) {
160
+ const current = byPid.get(entry.pid);
161
+ if (excluded.has(entry.pid) || !sameStart(current, entry)) {
162
+ tracked.delete(entry.pid);
163
+ continue;
164
+ }
165
+ tracked.set(entry.pid, processEntry(current));
166
+ parents.push(entry.pid);
167
+ }
168
+ for (const parent of parents) {
169
+ for (const entry of children.get(parent) ?? []) {
170
+ if (tracked.has(entry.pid)) continue;
171
+ if (tracked.size >= limit) { truncated = true; continue; }
172
+ tracked.set(entry.pid, processEntry(entry));
173
+ parents.push(entry.pid);
174
+ }
175
+ }
176
+ },
177
+ };
178
+ }
179
+
180
+ export async function reapDescendants(entries, {sample = sampleProcessTable, kill = process.kill, graceMs = DEFAULT_POLICY.cancelGraceMs, timeoutMs = 500, truncated = false} = {}) {
181
+ const observed = entries.length, denied = new Set();
182
+ const uid = process.geteuid?.();
183
+ const readSample = async () => {
184
+ try {
185
+ const table = await sample();
186
+ return Array.isArray(table) ? new Map(table.map(entry => [entry.pid, entry])) : null;
187
+ } catch { return null; }
188
+ };
189
+ const signal = (targets, table, name) => {
190
+ const excluded = supervisorLineage(table, process.pid);
191
+ const eligible = [];
192
+ const send = target => {
193
+ try { kill(target, name); }
194
+ catch (error) {
195
+ // A group error does not identify which members are still alive.
196
+ if (target > 0 && error.code === 'EPERM') denied.add(target);
197
+ }
198
+ };
199
+ for (const entry of targets) {
200
+ const {pid} = entry, current = table.get(pid);
201
+ if (!sameStart(current, entry) || denied.has(pid)) continue;
202
+ if (pid <= 1 || excluded.has(pid) || (current.uid !== undefined && current.uid !== uid)) {
203
+ denied.add(pid);
204
+ continue;
205
+ }
206
+ eligible.push(entry);
207
+ send(pid);
208
+ }
209
+ const eligiblePids = new Set(eligible.map(entry => entry.pid));
210
+ const blockedGroups = new Set();
211
+ for (const member of table.values()) {
212
+ if (!eligiblePids.has(member.pid) || denied.has(member.pid)) blockedGroups.add(member.pgid);
213
+ }
214
+ for (const {pid, pgid} of eligible) {
215
+ if (pgid === pid && table.get(pid).pgid === pid && !blockedGroups.has(pid)) send(-pid);
216
+ }
217
+ };
218
+ const summary = survived => ({observed, reaped: observed - survived, survived, truncated});
219
+ if (!observed) return summary(0);
220
+ let table = await readSample();
221
+ if (!table) return summary(observed);
222
+ let remaining = entries.filter(entry => sameStart(table.get(entry.pid), entry));
223
+ signal(remaining, table, 'SIGTERM');
224
+ if (!remaining.some(entry => !denied.has(entry.pid))) return summary(denied.size);
225
+ if (graceMs > 0) await sleep(graceMs);
226
+ table = await readSample();
227
+ if (!table) return summary(remaining.length);
228
+ remaining = remaining.filter(entry => denied.has(entry.pid) || sameStart(table.get(entry.pid), entry));
229
+ signal(remaining, table, 'SIGKILL');
230
+ const deadline = Date.now() + timeoutMs;
231
+ while (remaining.some(entry => !denied.has(entry.pid))) {
232
+ table = await readSample();
233
+ if (!table) break;
234
+ remaining = remaining.filter(entry => denied.has(entry.pid) || sameStart(table.get(entry.pid), entry));
235
+ const wait = deadline - Date.now();
236
+ if (wait <= 0 || !remaining.some(entry => !denied.has(entry.pid))) break;
237
+ await sleep(Math.min(25, wait));
238
+ }
239
+ return summary(remaining.length);
240
+ }
241
+
242
+ const DESCENDANTS_FILE = 'descendants.json';
243
+ const DESCENDANT_START = new RegExp(`^${LSTART.source}$`);
244
+ export const descendantRecord = stats => stats && (stats.observed > 0 || stats.truncated) ? {escapedDescendants: stats} : {};
245
+
246
+ export async function reapRecordedDescendants(artifactDir, lease, options) {
247
+ let file;
248
+ try {
249
+ file = await fsp.open(path.join(artifactDir, DESCENDANTS_FILE), fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW | fs.constants.O_NONBLOCK);
250
+ const stat = await file.stat();
251
+ if (!stat.isFile() || stat.uid !== process.geteuid?.() || stat.size > 65536) return {};
252
+ const snapshot = JSON.parse(await file.readFile('utf8'));
253
+ const {version, dispatchId, segment, rootPid, rootPgid, rootStartTime, truncated, entries} = snapshot;
254
+ // Bind the snapshot to its lease. Tampering by a user with the same UID is outside this boundary.
255
+ if (Object.keys(snapshot).length !== 8 || version !== 1 || dispatchId !== lease.dispatchId || segment !== (lease.segment ?? 0) || !validPid(rootPid) || rootPid !== lease.child?.pid || rootPgid !== rootPid) return {};
256
+ const recordedStart = typeof rootStartTime === 'string' ? normalizePsWhitespace(rootStartTime) : '';
257
+ const leaseStart = lease.child?.startTime;
258
+ if (!DESCENDANT_START.test(recordedStart) || typeof leaseStart !== 'string' || recordedStart !== normalizePsWhitespace(leaseStart)) return {};
259
+ if (typeof truncated !== 'boolean' || !Array.isArray(entries) || entries.length > DESCENDANT_LIMIT) return {};
260
+ const seen = new Set([rootPid]);
261
+ for (const entry of entries) {
262
+ if (!entry || Object.keys(entry).length !== 4 || !validPid(entry.pid) || entry.pid <= 1 || seen.has(entry.pid) || !validPid(entry.ppid) || !validPid(entry.pgid) || typeof entry.startTime !== 'string' || !DESCENDANT_START.test(entry.startTime)) return {};
263
+ seen.add(entry.pid);
264
+ }
265
+ return descendantRecord(await reapDescendants(entries.filter(entry => entry.pgid !== rootPgid), {...options, truncated}));
266
+ } catch { return {}; }
267
+ finally { await file?.close().catch(() => {}); }
268
+ }
269
+
92
270
  export {resolveWorktree};
93
271
  export const artifactDirectory = (target, workflowId, dispatchId) => path.join(target.gitCommonDir, 'arc', 'workflows', workflowId, 'dispatches', dispatchId);
94
272
  /** Segment 0 (the first run) keeps its files in the dispatch directory; resumed segments use segments/<n>/. */
@@ -153,6 +331,10 @@ export async function startSupervisor({codexHome, dispatchId, cwd, userHome, env
153
331
  export async function runSupervisor(options) {
154
332
  const {codexHome, dispatchId, cwd, userHome, env = process.env, policy = DEFAULT_POLICY} = options;
155
333
  const heartbeatMs = options.heartbeatMs ?? policy.heartbeatMs, graceMs = options.graceMs ?? policy.cancelGraceMs;
334
+ const descendantSampleMs = options.descendantSampleMs ?? policy.descendantSampleMs ?? DESCENDANT_SAMPLE_MS;
335
+ const descendantLimit = Math.min(options.descendantLimit ?? policy.descendantLimit ?? DESCENDANT_LIMIT, DESCENDANT_LIMIT);
336
+ const sampleProcesses = options.sampleProcesses ?? sampleProcessTable;
337
+ const stopSignal = options.stopSignal;
156
338
  const eventsMax = options.eventsMaxBytes ?? policy.eventsMaxBytes, codexWaitMs = options.codexWaitMs ?? 10000;
157
339
  const lockRetryMs = options.lockRetryMs ?? policy.lockRetryMs, lockDeadlineMs = options.lockDeadlineMs ?? 30000;
158
340
  const startedAt = new Date().toISOString();
@@ -225,13 +407,55 @@ export async function runSupervisor(options) {
225
407
  await writeRecord({state: 'failed', reasons: codes, spawned: spawned !== null, ...(spawned !== null ? {childPid: spawned} : {}), ...extra}).catch(() => {});
226
408
  await commit('failed', codes, claims);
227
409
  };
228
- const failWithProfileCleanup = (code, spawned = null) => {
410
+ const failWithProfileCleanup = (code, spawned = null, extra = {}) => {
229
411
  cleanGrokProfile();
230
- return earlyFailure(code, spawned, grokProfileRecord());
412
+ return earlyFailure(code, spawned, {...grokProfileRecord(), ...extra});
231
413
  };
232
414
 
233
415
  let child = null, eventsFd = null, killTimers = [], terminating = null, termAt = 0;
234
- const killGroup = signal => { if (child?.pid) { try { (options.signalGroup ?? process.kill)(-child.pid, signal); } catch { /* group already gone */ } } };
416
+ let executionTimer, originalGroupGone;
417
+ const stopGroupSignals = gone => {
418
+ originalGroupGone = gone;
419
+ for (const timer of killTimers) clearTimeout(timer);
420
+ killTimers = [];
421
+ };
422
+ let tracker, descendantTimer, pendingSample, savedSnapshot, descendantCleanup, onStop;
423
+ const sampleDescendants = async () => {
424
+ const table = await sampleProcesses();
425
+ if (!Array.isArray(table)) return;
426
+ tracker.update(table);
427
+ const entries = tracker.entries();
428
+ if (!entries.length && !tracker.truncated && !savedSnapshot) return;
429
+ const snapshot = JSON.stringify({
430
+ version: 1, dispatchId, segment: lease.segment ?? 0, rootPid: child.pid, rootPgid: child.pid,
431
+ rootStartTime: tracker.rootStartTime, truncated: tracker.truncated, entries,
432
+ }) + '\n';
433
+ if (snapshot === savedSnapshot) return;
434
+ const file = path.join(artifactDir, DESCENDANTS_FILE);
435
+ const temporary = `${file}.${crypto.randomUUID()}.tmp`;
436
+ try {
437
+ await fsp.writeFile(temporary, snapshot, {mode: 0o600, flag: 'wx'});
438
+ await fsp.rename(temporary, file);
439
+ savedSnapshot = snapshot;
440
+ } finally { await fsp.unlink(temporary).catch(() => {}); }
441
+ };
442
+ const queueDescendantSample = () => {
443
+ if (!pendingSample) pendingSample = sampleDescendants().catch(() => {}).finally(() => { pendingSample = null; });
444
+ };
445
+ const finishDescendants = () => {
446
+ if (!tracker) return {};
447
+ if (!descendantCleanup) descendantCleanup = (async () => {
448
+ clearInterval(descendantTimer);
449
+ timers.delete(descendantTimer);
450
+ await pendingSample;
451
+ await sampleDescendants().catch(() => {});
452
+ return descendantRecord(await reapDescendants(tracker.escaped(), {
453
+ sample: sampleProcesses, kill: options.killProcess, graceMs, truncated: tracker.truncated,
454
+ }));
455
+ })().catch(() => ({}));
456
+ return descendantCleanup;
457
+ };
458
+ const killGroup = signal => { if (originalGroupGone === undefined && child?.pid) { try { (options.signalGroup ?? process.kill)(-child.pid, signal); } catch { /* group already gone */ } } };
235
459
  const groupAlive = () => { try { process.kill(-child.pid, 0); return true; } catch (error) { return error.code === 'EPERM'; } };
236
460
  // Terminal states are recorded only after the whole process group is observed gone: SIGKILL goes to the group after the grace period even when the leader already exited.
237
461
  const reapGroup = async () => {
@@ -303,10 +527,16 @@ export async function runSupervisor(options) {
303
527
  }
304
528
  // The child is a process-group leader so one signal reaches its descendants. The prompt uses the platform-specific input channel.
305
529
  child = spawn(cli.executable, invocation.args, {cwd: target.realpath, env: {...childEnv, ARC_BRIDGE_CHILD: dispatchId}, detached: true, stdio: ['pipe', 'pipe', 'pipe'], shell: false});
530
+ if (child.pid) tracker = createDescendantTracker({rootPid: child.pid, rootPgid: child.pid, selfPid: process.pid, limit: descendantLimit});
306
531
  let exitResolve, exited = false;
307
532
  const exitPromise = new Promise(resolve => { exitResolve = resolve; });
308
- child.on('exit', (code, signal) => { exited = true; exitResolve({code, signal}); });
309
- child.on('error', () => { exited = true; exitResolve({code: null, signal: null, spawnError: true}); });
533
+ const observeExit = exit => {
534
+ exited = true;
535
+ clearTimeout(executionTimer);
536
+ exitResolve(exit);
537
+ };
538
+ child.on('exit', (code, signal) => observeExit({code, signal}));
539
+ child.on('error', () => observeExit({code: null, signal: null, spawnError: true}));
310
540
  child.stdin.on('error', () => {});
311
541
  if (options.afterSpawn) await options.afterSpawn(child); // test injection point for post-spawn failures
312
542
  if (platform === 'grok') child.stdin.end();
@@ -317,15 +547,18 @@ export async function runSupervisor(options) {
317
547
  let eventsBytes = 0, eventsTruncated = false, stderrLength = 0, contextTask = null;
318
548
  const stderrParts = [];
319
549
  const terminate = why => {
320
- if (terminating) return;
550
+ if (terminating || originalGroupGone !== undefined) return;
321
551
  terminating = why; termAt = Date.now(); killGroup('SIGTERM');
322
552
  killTimers.push(setTimeout(() => {
323
553
  killGroup('SIGKILL');
324
554
  killTimers.push(setTimeout(() => exitResolve({code: null, signal: null, unobserved: true}), graceMs));
325
555
  }, graceMs));
326
556
  };
557
+ onStop = () => terminate('supervisor_signal');
558
+ if (stopSignal?.aborted) onStop();
559
+ else stopSignal?.addEventListener('abort', onStop, {once: true});
327
560
  const deadline = options.timeoutMs ?? lease.timeoutMinutes * 60000;
328
- timers.add(setTimeout(() => terminate('timeout'), deadline));
561
+ if (!exited) executionTimer = setTimeout(() => terminate('timeout'), deadline);
329
562
  let cancelBusy = false;
330
563
  timers.add(setInterval(async () => {
331
564
  if (cancelBusy || terminating || exited) return;
@@ -420,9 +653,11 @@ export async function runSupervisor(options) {
420
653
  if (!mine(current)) throw Error('Lease changed before the child was recorded');
421
654
  await writeLease(codexHome, {...current, state: 'running', child: {pid: child.pid, startTime}}, {runtimePlatforms});
422
655
  });
656
+ queueDescendantSample();
657
+ descendantTimer = setInterval(queueDescendantSample, descendantSampleMs);
658
+ timers.add(descendantTimer);
423
659
  } catch { state.internal = 'execution_failed'; terminate('internal'); }
424
660
 
425
-
426
661
  let exit = await exitPromise;
427
662
  // A cancel request whose own SIGTERM stopped the child before the marker poll ran still counts as a cancel, and the group is reaped the same way.
428
663
  if (!terminating && !exit.unobserved && (exit.signal || !state.terminal) && await cancelRequested(codexHome, dispatchId)) { terminating = 'cancel'; termAt = Date.now(); }
@@ -430,18 +665,19 @@ export async function runSupervisor(options) {
430
665
  let orphanGroupReaped = false;
431
666
  if (!termAt && !exit.unobserved && child?.pid && groupAlive()) { orphanGroupReaped = true; termAt = Date.now(); killGroup('SIGTERM'); }
432
667
  if (termAt && !exit.unobserved && !await reapGroup()) exit = {code: null, signal: null, unobserved: true};
668
+ stopGroupSignals(!exit.unobserved);
669
+ const escapes = await finishDescendants();
433
670
  await Promise.race([stdoutClosed, sleep(1000)]);
434
671
  parser.end();
435
672
  if (contextTask) await contextTask;
436
673
  for (const timer of timers) { clearInterval(timer); clearTimeout(timer); }
437
- for (const timer of killTimers) clearTimeout(timer);
438
- timers.clear(); killTimers = [];
674
+ timers.clear();
439
675
  fs.closeSync(eventsFd); eventsFd = null;
440
676
 
441
677
  if (exit.unobserved) {
442
678
  // The child was signalled but its exit was never observed: the slot stays occupied.
443
679
  const claims = {...lease.claims, terminal: {level: 'unverified', source: 'none'}};
444
- await writeRecord({state: 'unknown', reasons: [...(terminating === 'timeout' ? ['timeout'] : []), 'terminal_state_unverified'], terminatedBy: terminating, eventsTruncated, ignoredLines: parser.ignored, lineOverflow: parser.overflow, ...retainGrokProfile()}).catch(() => {});
680
+ await writeRecord({state: 'unknown', reasons: [...(terminating === 'timeout' ? ['timeout'] : []), 'terminal_state_unverified'], terminatedBy: terminating, eventsTruncated, ignoredLines: parser.ignored, lineOverflow: parser.overflow, ...retainGrokProfile(), ...escapes}).catch(() => {});
445
681
  await locked(async () => {
446
682
  const current = await readLease(codexHome, dispatchId, {runtimePlatforms});
447
683
  if (current && !TERMINAL_STATES.includes(current.state)) await writeLease(codexHome, {...current, state: 'unknown', claims, reasons: [...(terminating === 'timeout' ? ['timeout'] : []), 'terminal_state_unverified'].map(reason)}, {runtimePlatforms});
@@ -451,7 +687,8 @@ export async function runSupervisor(options) {
451
687
 
452
688
  let after = null;
453
689
  try { after = await snapshot(); } catch { after = null; }
454
- const violations = after ? detectViolations({role: lease.role, allowedPaths: lease.allowedPaths, before, after}) : {reason: null, changedPaths: [], headChanged: false, refsChanged: false, controlChanged: []};
690
+ const headAdvance = after ? await observeHeadAdvance(target.realpath, before, after, lease.role, lease.allowedPaths) : null;
691
+ const violations = after ? detectViolations({role: lease.role, allowedPaths: lease.allowedPaths, before, after, headAdvance}) : {reason: null, changedPaths: [], headChanged: false, refsChanged: false, controlChanged: [], toleratedRefs: [], toleratedControl: [], toleratedCommitPaths: []};
455
692
  const codes = [];
456
693
  if (state.mismatch) codes.push(state.mismatch);
457
694
  if (state.internal) codes.push(state.internal);
@@ -502,25 +739,31 @@ export async function runSupervisor(options) {
502
739
  if (exit.spawnError && !codes.length) { codes.push('execution_failed'); finalState = 'failed'; }
503
740
  if ((finalState === 'completed' || finalState === 'cancelled') && codes.includes('permission_scope_mismatch')) finalState = 'failed';
504
741
  const controlFiles = violations.controlChanged.length ? {controlFiles: {changed: violations.controlChanged}} : {};
505
- await writeRecord({state: finalState, reasons: [...new Set(codes)], exit: {code: exit.code, signal: exit.signal}, terminatedBy: terminating, eventsTruncated, ignoredLines: parser.ignored, lineOverflow: parser.overflow, violations: {changedPaths: violations.changedPaths, headChanged: violations.headChanged, refsChanged: violations.refsChanged}, ...controlFiles, ...(orphanGroupReaped ? {orphanGroupReaped: true} : {}), argsDigest: invocation.argsDigest, resultPath, ...grokProfileRecord(), ...(platform === 'gemini' ? {unverifiedContracts: {delegation: GEMINI_CONTRACT.delegation}} : platform === 'grok' ? {unverifiedContracts: {delegation: GROK_CONTRACT.delegation}} : {})});
742
+ const tolerated = toleratedRecord(violations);
743
+ await writeRecord({state: finalState, reasons: [...new Set(codes)], exit: {code: exit.code, signal: exit.signal}, terminatedBy: terminating, eventsTruncated, ignoredLines: parser.ignored, lineOverflow: parser.overflow, violations: {changedPaths: violations.changedPaths, headChanged: violations.headChanged, refsChanged: violations.refsChanged}, ...controlFiles, ...(tolerated ? {tolerated} : {}), ...(orphanGroupReaped ? {orphanGroupReaped: true} : {}), argsDigest: invocation.argsDigest, resultPath, ...grokProfileRecord(), ...(platform === 'gemini' ? {unverifiedContracts: {delegation: GEMINI_CONTRACT.delegation}} : platform === 'grok' ? {unverifiedContracts: {delegation: GROK_CONTRACT.delegation}} : {}), ...escapes});
506
744
  await commit(finalState, codes, claims, {sessionId, resultPath});
507
745
  } catch {
508
746
  // Unexpected failure after the child started: stop it, then record a failed state if the child is gone.
509
747
  const spawnedPid = child?.pid ?? null;
510
- let stopped = true;
511
- if (spawnedPid) { if (!termAt) { termAt = Date.now(); killGroup('SIGTERM'); } stopped = await reapGroup().catch(() => false); }
748
+ clearTimeout(executionTimer);
749
+ let stopped = originalGroupGone ?? true;
750
+ if (spawnedPid && originalGroupGone === undefined) { if (!termAt) { termAt = Date.now(); killGroup('SIGTERM'); } stopped = await reapGroup().catch(() => false); }
751
+ stopGroupSignals(stopped);
752
+ const escapes = await finishDescendants();
753
+ const details = {...escapes, ...(terminating === 'supervisor_signal' ? {terminatedBy: terminating} : {})};
512
754
  for (const timer of timers) { clearInterval(timer); clearTimeout(timer); }
513
- for (const timer of killTimers) clearTimeout(timer);
514
- if (stopped) await failWithProfileCleanup('execution_failed', spawnedPid).catch(() => {});
755
+ if (stopped) await failWithProfileCleanup('execution_failed', spawnedPid, details).catch(() => {});
515
756
  else {
516
757
  const codes = ['execution_failed', 'terminal_state_unverified'];
517
- await writeRecord({state: 'unknown', reasons: codes, spawned: true, childPid: spawnedPid, ...retainGrokProfile()}).catch(() => {});
758
+ await writeRecord({state: 'unknown', reasons: codes, spawned: true, childPid: spawnedPid, ...retainGrokProfile(), ...details}).catch(() => {});
518
759
  await locked(async () => {
519
760
  const current = await readLease(codexHome, dispatchId, {runtimePlatforms});
520
761
  if (current && !TERMINAL_STATES.includes(current.state)) await writeLease(codexHome, {...current, state: 'unknown', reasons: codes.map(reason)}, {runtimePlatforms});
521
762
  }).catch(() => {});
522
763
  }
523
764
  } finally {
765
+ if (onStop) stopSignal?.removeEventListener('abort', onStop);
766
+ clearTimeout(executionTimer);
524
767
  for (const timer of timers) { clearInterval(timer); clearTimeout(timer); }
525
768
  if (eventsFd !== null) { try { fs.closeSync(eventsFd); } catch { /* closed */ } }
526
769
  }
@@ -529,5 +772,7 @@ export async function runSupervisor(options) {
529
772
  const isMain = () => { try { return Boolean(process.argv[1]) && fs.realpathSync(process.argv[1]) === fileURLToPath(import.meta.url); } catch { return false; } };
530
773
  if (isMain()) {
531
774
  const [, , codexHome, dispatchId, cwd, userHome] = process.argv;
532
- runSupervisor({codexHome, dispatchId, cwd, userHome, env: process.env}).then(() => process.exit(0), () => process.exit(1));
775
+ const controller = new AbortController();
776
+ for (const signal of ['SIGTERM', 'SIGINT', 'SIGHUP']) process.once(signal, () => controller.abort());
777
+ runSupervisor({codexHome, dispatchId, cwd, userHome, env: process.env, stopSignal: controller.signal}).then(() => process.exit(0), () => process.exit(1));
533
778
  }
package/lib/tui/app.mjs CHANGED
@@ -1,6 +1,8 @@
1
1
  import {readFileSync} from 'node:fs';
2
2
  import {createTerminalSession} from './terminal.mjs';
3
- import {escapeTerminalText,cellWidth,navigationHint,statusSpans,platformStatusSpans,wrapDetailRow,wrapDetailRows,wordmarkRows,fitChoiceRow} from './render.mjs';
3
+ import {escapeTerminalText,cellWidth,fitChoiceRow} from './render.mjs';
4
+ import {createTuiInterface} from './interface.mjs';
5
+ export {createTuiInterface};
4
6
  import {createManagementContext,prepareOperation,executeOperation,forceFinishBlockingDispatches,readCompositeConfig,currentInstallState} from '../management/operations.mjs';
5
7
  import {collectStatus} from '../management/status.mjs';
6
8
  import {runInstallFlow,loadRoleDefaults,roleDisplayName} from './setup.mjs';
@@ -9,44 +11,6 @@ import {statusInfo,statusVersion} from './mode.mjs';
9
11
  import {installerRegistryOf,platformLabel} from '../platforms/index.mjs';
10
12
  const packageVersion=JSON.parse(readFileSync(new URL('../../package.json',import.meta.url),'utf8')).version;
11
13
  const home=[{id:'install',label:'Configure'},{id:'status',label:'Status'},{id:'uninstall',label:'Uninstall'},{id:'exit',label:'Exit'}];
12
- function goHome(){throw Object.assign(Error('Return home'),{code:'ARC_TUI_HOME'});}
13
- function interrupted(){return Object.assign(Error('Session interrupted'),{code:'ARC_CANCELLED'});}
14
- export function createTuiInterface(session,{input,controller}={}){
15
- async function event(){const e=await session.nextEvent();if(e.name==='interrupt')throw interrupted();if(e.name==='eof')throw Object.assign(Error('Session closed'),{code:'ARC_TUI_EOF'});if(e.name==='error')throw e.error;return e;}
16
- async function menu(title,rows,{selected=0,info=[],infoTones,notice=[],fitRows=false,backRow=false,actionKinds,backLabel='back',wordmark=false,version,renderBody,onHorizontal,refreshMs,hint='menu'}={}){
17
- const actions=backRow?[...rows,'Back']:rows,kinds=rows.map((_,index)=>actionKinds?.[index]);if(backRow)kinds.push('cancel');
18
- selected=actions.length?Math.max(0,Math.min(selected,actions.length-1)):0;
19
- const animate=wordmark&&session.frameMs>0,pulse=typeof onHorizontal==='function'&&session.motion===true,tickMs=animate||pulse?session.frameMs:refreshMs;
20
- let pending,settled,wake,timer,blink=true,frame=0,blinkElapsed=0,repainting=false;
21
- try{while(true){
22
- const viewport=session.viewport(),display=actions,displayIndex=selected,information=[],tones=[],spans=[];
23
- const details=typeof info==='function'?info({selected,...viewport}):info;
24
- for(const [index,row] of details.entries()){const wrapped=wrapDetailRow(row,viewport.columns),tone=infoTones?.[index],states=tone==='status'?statusSpans(row):tone==='platform-status'?platformStatusSpans(row):[];for(const [line,{text,from,to,prefix}] of wrapped.entries()){information.push(text);tones.push(line&&tone==='diagnostic'?'diagnostic-cont':tone);spans.push(states.filter(span=>span.from<to&&span.to>from).map(span=>({...span,from:Math.max(span.from,from)-from+prefix,to:Math.min(span.to,to)-from+prefix})));}}
25
- while(information.at(-1)===''){information.pop();tones.pop();}if(information.length){information.push('');tones.push(undefined);}
26
- const notices=typeof notice==='function'?notice({selected,...viewport}):notice,noticeRows=wrapDetailRows(notices,viewport.columns);while(noticeRows.at(-1)==='')noticeRows.pop();
27
- const capacity=Math.max(1,viewport.rows-(wordmark?wordmarkRows(viewport):1)-information.length-noticeRows.length-4),offset=Math.max(0,Math.min(displayIndex-capacity+1,display.length-capacity)),visible=display.slice(offset,offset+capacity).map(row=>fitRows?fitChoiceRow(row,viewport.columns):row);
28
- const screen={title,wordmark,version,frame,notices,rows:[...information,...visible],selected:actions.length?information.length+displayIndex-offset:undefined,hint:navigationHint(hint,{backLabel,horizontal:typeof onHorizontal==='function'}),...(display.length>capacity?{position:(offset+1)+'-'+Math.min(offset+capacity,display.length)+'/'+display.length}:{})};
29
- if(infoTones){screen.rowTones=[...tones,...visible.map(()=>undefined)];screen.rowStatusSpans=spans;}
30
- if(backRow||actionKinds)screen.rowKinds=[...information.map(()=>undefined),...kinds.slice(offset,offset+capacity)];
31
- const body=renderBody?.({selected,blink,frame,...viewport});if(body){delete screen.rowTones;delete screen.rowStatusSpans;delete screen.rowKinds;if(body.rowKinds)screen.rowKinds=body.rowKinds;screen.rows=body.rows;screen.selected=body.selected;screen.showSelection=body.showSelection;screen.compactFooter=body.compactFooter;if(Object.hasOwn(body,'notices'))screen.notices=body.notices;if(Object.hasOwn(body,'position'))screen.position=body.position;}
32
- const rendered=(repainting?(session.repaint??session.render):session.render).call(session,screen);pending??=event().then(e=>{settled={e};wake?.();},error=>{settled={error};wake?.();});
33
- if(tickMs>0){if(!settled)await new Promise(resolve=>{wake=resolve;timer=setTimeout(resolve,tickMs);});clearTimeout(timer);timer=undefined;wake=undefined;if(!settled){if(animate||pulse)frame++;if(refreshMs>0){blinkElapsed+=tickMs;while(blinkElapsed>=refreshMs){blink=!blink;blinkElapsed-=refreshMs;}}repainting=true;continue;}}else await pending;
34
- if(Object.hasOwn(settled,'error'))throw settled.error;const e=settled.e;pending=undefined;settled=undefined;repainting=false;
35
- if(e.name==='up'&&actions.length)selected=(selected+actions.length-1)%actions.length;else if(e.name==='down'&&actions.length)selected=(selected+1)%actions.length;else if((e.name==='left'||e.name==='right')&&onHorizontal)onHorizontal({direction:e.name,selected,...viewport});else if(e.name==='escape'){if(backLabel==='exit')return null;goHome();}else if(e.name==='enter'&&actions.length&&rendered.selectionEnabled!==false)return backRow&&selected===rows.length?null:selected;
36
- }}finally{if(timer!==undefined)clearTimeout(timer);}
37
- }
38
- async function text(title,initial=''){let value=initial,selected=2;while(true){const rendered=session.render({title,mode:'text',rows:[value,'','Save','Back',''],rowKinds:[undefined,undefined,'confirm','cancel',undefined],selected,hint:navigationHint('text')});const e=await event();if(e.name==='text'||e.name==='paste')value+=e.text;else if(e.name==='backspace')value=[...value].slice(0,-1).join('');else if(e.name==='up'||e.name==='down')selected=selected===2?3:2;else if(e.name==='escape')goHome();else if(e.name==='enter'&&rendered.selectionEnabled!==false)return selected===2?value:null;}}
39
- async function page(title,rows){
40
- let offset=0;
41
- while(true){const viewport=session.viewport(),wrapped=wrapDetailRows(rows,viewport.columns),size=Math.max(1,viewport.rows-4),last=Math.max(0,wrapped.length-size);
42
- offset=Math.min(offset,last);const slice=wrapped.slice(offset,offset+size);
43
- session.render({title,mode:'page',rows:slice,position:`Rows ${offset+1}-${Math.min(offset+size,wrapped.length)} of ${wrapped.length}`,hint:navigationHint('page')});const e=await event();
44
- if(e.name==='down')offset=Math.min(last,offset+1);else if(e.name==='up')offset=Math.max(0,offset-1);else if(e.name==='escape')goHome();else if(e.name==='enter')return true;
45
- }
46
- }
47
- async function busy(action){let frame=0,timer;const screen={title:'Working',mode:'busy',rows:[],hint:navigationHint('busy'),frame};session.render(screen);session.setBusy(true);const wasFlowing=input?.readableFlowing;const abort=()=>{if(!controller?.signal.aborted)controller?.abort();},onData=chunk=>{if(String(chunk).includes('\x03')||String(chunk).includes('\x04'))abort();};input?.on('data',onData);input?.prependListener('end',abort);input?.prependListener('close',abort);try{if(input?.readableEnded||input?.destroyed){abort();throw interrupted();}if(controller?.signal.aborted)throw interrupted();if(session.frameMs>0)timer=setInterval(()=>{try{(session.repaint??session.render).call(session,{...screen,frame:++frame});}catch{clearInterval(timer);}},session.frameMs);const result=await (session.frameMs>0?Promise.resolve().then(action):action());if(controller?.signal.aborted){if(typeof result?.code!=='number')throw interrupted();return{...result,code:130,interrupted:true};}return result;}catch(error){if(controller?.signal.aborted&&(['ARC_CANCELLED','ARC_NPM_CANCELLED','ARC_ACQUISITION_CANCELLED','ARC_INSTALL_CANCELLED','ABORT_ERR'].includes(error?.code)||error?.name==='AbortError'))throw interrupted();throw error;}finally{clearInterval(timer);input?.removeListener('data',onData);input?.removeListener('end',abort);input?.removeListener('close',abort);if(wasFlowing!==true)input?.pause?.();session.setBusy(false);session.discardInput();}}
48
- return{menu,text,page,busy};
49
- }
50
14
  export function resultRows(result,registry=installerRegistryOf(),{version}={}){
51
15
  version=result.version??version;
52
16
  const clean=text=>text.replace(/; rollback: [^\r\n]*/g,''),label=platform=>platformLabel(platform,registry),errorLine=error=>clean(error.message.split(/[\r\n]/)[0]);
@@ -0,0 +1,40 @@
1
+ import {navigationHint,statusSpans,platformStatusSpans,wrapDetailRow,wrapDetailRows,wordmarkRows,fitChoiceRow} from './render.mjs';
2
+
3
+ function goHome(){throw Object.assign(Error('Return home'),{code:'ARC_TUI_HOME'});}
4
+ function interrupted(){return Object.assign(Error('Session interrupted'),{code:'ARC_CANCELLED'});}
5
+ export function createTuiInterface(session,{input,controller}={}){
6
+ async function event(){const e=await session.nextEvent();if(e.name==='interrupt')throw interrupted();if(e.name==='eof')throw Object.assign(Error('Session closed'),{code:'ARC_TUI_EOF'});if(e.name==='error')throw e.error;return e;}
7
+ async function menu(title,rows,{selected=0,info=[],infoTones,notice=[],fitRows=false,backRow=false,actionKinds,backLabel='back',wordmark=false,version,renderBody,onHorizontal,refreshMs,hint='menu'}={}){
8
+ const actions=backRow?[...rows,'Back']:rows,kinds=rows.map((_,index)=>actionKinds?.[index]);if(backRow)kinds.push('cancel');
9
+ selected=actions.length?Math.max(0,Math.min(selected,actions.length-1)):0;
10
+ const animate=wordmark&&session.frameMs>0,pulse=typeof onHorizontal==='function'&&session.motion===true,tickMs=animate||pulse?session.frameMs:refreshMs;
11
+ let pending,settled,wake,timer,blink=true,frame=0,blinkElapsed=0,repainting=false;
12
+ try{while(true){
13
+ const viewport=session.viewport(),display=actions,displayIndex=selected,information=[],tones=[],spans=[];
14
+ const details=typeof info==='function'?info({selected,...viewport}):info;
15
+ for(const [index,row] of details.entries()){const wrapped=wrapDetailRow(row,viewport.columns),tone=infoTones?.[index],states=tone==='status'?statusSpans(row):tone==='platform-status'?platformStatusSpans(row):[];for(const [line,{text,from,to,prefix}] of wrapped.entries()){information.push(text);tones.push(line&&tone==='diagnostic'?'diagnostic-cont':tone);spans.push(states.filter(span=>span.from<to&&span.to>from).map(span=>({...span,from:Math.max(span.from,from)-from+prefix,to:Math.min(span.to,to)-from+prefix})));}}
16
+ while(information.at(-1)===''){information.pop();tones.pop();}if(information.length){information.push('');tones.push(undefined);}
17
+ const notices=typeof notice==='function'?notice({selected,...viewport}):notice,noticeRows=wrapDetailRows(notices,viewport.columns);while(noticeRows.at(-1)==='')noticeRows.pop();
18
+ const capacity=Math.max(1,viewport.rows-(wordmark?wordmarkRows(viewport):1)-information.length-noticeRows.length-4),offset=Math.max(0,Math.min(displayIndex-capacity+1,display.length-capacity)),visible=display.slice(offset,offset+capacity).map(row=>fitRows?fitChoiceRow(row,viewport.columns):row);
19
+ const screen={title,wordmark,version,frame,notices,rows:[...information,...visible],selected:actions.length?information.length+displayIndex-offset:undefined,hint:navigationHint(hint,{backLabel,horizontal:typeof onHorizontal==='function'}),...(display.length>capacity?{position:(offset+1)+'-'+Math.min(offset+capacity,display.length)+'/'+display.length}:{})};
20
+ if(infoTones){screen.rowTones=[...tones,...visible.map(()=>undefined)];screen.rowStatusSpans=spans;}
21
+ if(backRow||actionKinds)screen.rowKinds=[...information.map(()=>undefined),...kinds.slice(offset,offset+capacity)];
22
+ const body=renderBody?.({selected,blink,frame,...viewport});if(body){delete screen.rowTones;delete screen.rowStatusSpans;delete screen.rowKinds;if(body.rowKinds)screen.rowKinds=body.rowKinds;screen.rows=body.rows;screen.selected=body.selected;screen.showSelection=body.showSelection;screen.compactFooter=body.compactFooter;if(Object.hasOwn(body,'notices'))screen.notices=body.notices;if(Object.hasOwn(body,'position'))screen.position=body.position;}
23
+ const rendered=(repainting?(session.repaint??session.render):session.render).call(session,screen);pending??=event().then(e=>{settled={e};wake?.();},error=>{settled={error};wake?.();});
24
+ if(tickMs>0){if(!settled)await new Promise(resolve=>{wake=resolve;timer=setTimeout(resolve,tickMs);});clearTimeout(timer);timer=undefined;wake=undefined;if(!settled){if(animate||pulse)frame++;if(refreshMs>0){blinkElapsed+=tickMs;while(blinkElapsed>=refreshMs){blink=!blink;blinkElapsed-=refreshMs;}}repainting=true;continue;}}else await pending;
25
+ if(Object.hasOwn(settled,'error'))throw settled.error;const e=settled.e;pending=undefined;settled=undefined;repainting=false;
26
+ if(e.name==='up'&&actions.length)selected=(selected+actions.length-1)%actions.length;else if(e.name==='down'&&actions.length)selected=(selected+1)%actions.length;else if((e.name==='left'||e.name==='right')&&onHorizontal)onHorizontal({direction:e.name,selected,...viewport});else if(e.name==='escape'){if(backLabel==='exit')return null;goHome();}else if(e.name==='enter'&&actions.length&&rendered.selectionEnabled!==false)return backRow&&selected===rows.length?null:selected;
27
+ }}finally{if(timer!==undefined)clearTimeout(timer);}
28
+ }
29
+ async function text(title,initial=''){let value=initial,selected=2;while(true){const rendered=session.render({title,mode:'text',rows:[value,'','Save','Back',''],rowKinds:[undefined,undefined,'confirm','cancel',undefined],selected,hint:navigationHint('text')});const e=await event();if(e.name==='text'||e.name==='paste')value+=e.text;else if(e.name==='backspace')value=[...value].slice(0,-1).join('');else if(e.name==='up'||e.name==='down')selected=selected===2?3:2;else if(e.name==='escape')goHome();else if(e.name==='enter'&&rendered.selectionEnabled!==false)return selected===2?value:null;}}
30
+ async function page(title,rows){
31
+ let offset=0;
32
+ while(true){const viewport=session.viewport(),wrapped=wrapDetailRows(rows,viewport.columns),size=Math.max(1,viewport.rows-4),last=Math.max(0,wrapped.length-size);
33
+ offset=Math.min(offset,last);const slice=wrapped.slice(offset,offset+size);
34
+ session.render({title,mode:'page',rows:slice,position:`Rows ${offset+1}-${Math.min(offset+size,wrapped.length)} of ${wrapped.length}`,hint:navigationHint('page')});const e=await event();
35
+ if(e.name==='down')offset=Math.min(last,offset+1);else if(e.name==='up')offset=Math.max(0,offset-1);else if(e.name==='escape')goHome();else if(e.name==='enter')return true;
36
+ }
37
+ }
38
+ async function busy(action){let frame=0,timer;const screen={title:'Working',mode:'busy',rows:[],hint:navigationHint('busy'),frame};session.render(screen);session.setBusy(true);const wasFlowing=input?.readableFlowing;const abort=()=>{if(!controller?.signal.aborted)controller?.abort();},onData=chunk=>{if(String(chunk).includes('\x03')||String(chunk).includes('\x04'))abort();};input?.on('data',onData);input?.prependListener('end',abort);input?.prependListener('close',abort);try{if(input?.readableEnded||input?.destroyed){abort();throw interrupted();}if(controller?.signal.aborted)throw interrupted();if(session.frameMs>0)timer=setInterval(()=>{try{(session.repaint??session.render).call(session,{...screen,frame:++frame});}catch{clearInterval(timer);}},session.frameMs);const result=await (session.frameMs>0?Promise.resolve().then(action):action());if(controller?.signal.aborted){if(typeof result?.code!=='number')throw interrupted();return{...result,code:130,interrupted:true};}return result;}catch(error){if(controller?.signal.aborted&&(['ARC_CANCELLED','ARC_NPM_CANCELLED','ARC_ACQUISITION_CANCELLED','ARC_INSTALL_CANCELLED','ABORT_ERR'].includes(error?.code)||error?.name==='AbortError'))throw interrupted();throw error;}finally{clearInterval(timer);input?.removeListener('data',onData);input?.removeListener('end',abort);input?.removeListener('close',abort);if(wasFlowing!==true)input?.pause?.();session.setBusy(false);session.discardInput();}}
39
+ return{menu,text,page,busy};
40
+ }
package/lib/tui/setup.mjs CHANGED
@@ -54,6 +54,28 @@ export function installPrepareOptions(plan,draft,catalog){
54
54
  return {kind:'install',target:'composite',platforms:plan.platforms,config,settings};
55
55
  }
56
56
 
57
+ export async function initializeInstallDraft({draft,installState,currentConfig,loadRoleDefaults,initialTarget,registry}){
58
+ if(!draft.roles){
59
+ if(installState.mode==='composite'&&currentConfig){
60
+ draft.roles=structuredClone(currentConfig.roles);
61
+ draft.hosts??=[...installState.platforms];
62
+ }else{
63
+ const initial=initialTarget(),source=await loadRoleDefaults(initial),field=registry.getPlatform(initial).runtime.models.effortField;
64
+ draft.roles=Object.fromEntries(ROLES.map(role=>[role,{platform:initial,model:source[role].model,effort:source[role][field]}]));
65
+ draft.hosts??=[initial];
66
+ }
67
+ }
68
+ draft.hosts??=[...new Set(Object.values(draft.roles).map(role=>role.platform))];
69
+ }
70
+
71
+ export async function loadInstallCatalog(id,{loadCatalog,registry}){
72
+ try{
73
+ const result=await loadCatalog(id),catalog=result?.catalog,runtime=registry.getPlatform(id).runtime;
74
+ if(result?.status==='ready'&&catalog?.platform===id&&Array.isArray(catalog.pairs)&&catalog.pairs.length&&catalog.pairs.every(pair=>runtime.routing.validatePair(pair.model,pair.effort)))return result;
75
+ }catch{}
76
+ return {status:'catalog_error',code:'catalog_error'};
77
+ }
78
+
57
79
  export async function editHosts({ui,hosts,rolePlatforms,availabilityOf,registry=DEFAULT_INSTALLER_REGISTRY}){
58
80
  const ids=registry.byDisplayOrder().map(descriptor=>descriptor.runtime.id),locked=new Set(rolePlatforms),checked=new Set([...hosts,...rolePlatforms]);
59
81
  const labels=ids.map(id=>platformLabel(id,registry)),labelWidths=labels.map(label=>[...label].reduce((width,character)=>width+cellWidth(character),0)),suffixColumn=Math.max(0,...labelWidths)+2;
@@ -93,12 +115,7 @@ export async function runInstallFlow({ui,statuses,draft,installState,currentConf
93
115
  };
94
116
  const catalogFor=async id=>{
95
117
  if(catalogs.has(id))return catalogs.get(id);
96
- let result;
97
- try{
98
- result=await loadCatalog(id);
99
- const catalog=result?.catalog,runtime=registry.getPlatform(id).runtime;
100
- if(result?.status!=='ready'||catalog?.platform!==id||!Array.isArray(catalog.pairs)||!catalog.pairs.length||catalog.pairs.some(pair=>!runtime.routing.validatePair(pair.model,pair.effort)))result={status:'catalog_error',code:'catalog_error'};
101
- }catch{result={status:'catalog_error',code:'catalog_error'};}
118
+ const result=await loadInstallCatalog(id,{loadCatalog,registry});
102
119
  catalogs.set(id,result);
103
120
  for(const usage of ['role','host','standalone'])availabilityOf(id,usage);
104
121
  return result;
@@ -108,16 +125,10 @@ export async function runInstallFlow({ui,statuses,draft,installState,currentConf
108
125
  if(!defaultsCache.has(id))defaultsCache.set(id,await defaults(id));
109
126
  return defaultsCache.get(id);
110
127
  };
111
- if(!draft.roles){
112
- if(installState.mode==='composite'&&currentConfig){draft.roles=structuredClone(currentConfig.roles);draft.hosts??=[...installState.platforms];}
113
- else{
114
- const initial=ids.find(id=>statusOf(id)?.state==='installed')??ids.find(id=>availabilityOf(id).selectable)??ids[0];
115
- const source=await defaultsFor(initial),field=registry.getPlatform(initial).runtime.models.effortField;
116
- draft.roles=Object.fromEntries(ROLES.map(role=>[role,{platform:initial,model:source[role].model,effort:source[role][field]}]));
117
- draft.hosts??=[initial];
118
- }
119
- }
120
- draft.hosts??=[...new Set(Object.values(draft.roles).map(role=>role.platform))];
128
+ await initializeInstallDraft({
129
+ draft,installState,currentConfig,loadRoleDefaults:defaultsFor,registry,
130
+ initialTarget:()=>ids.find(id=>statusOf(id)?.state==='installed')??ids.find(id=>availabilityOf(id).selectable)??ids[0],
131
+ });
121
132
  let selected=0;
122
133
  while(true){
123
134
  const plan=deriveInstallPlan({roles:draft.roles,hosts:draft.hosts,current:installState,registry});