@yunhozz/arc 0.4.5 → 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 (79) hide show
  1. package/MANIFEST.sha256 +78 -73
  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 +4 -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 +4 -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 +5 -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 +4 -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/grok-sandbox.mjs +74 -0
  53. package/lib/runtime/role-bridge.mjs +10 -1
  54. package/lib/runtime/role-dispatch-policy.mjs +7 -1
  55. package/lib/runtime/role-observe.mjs +401 -13
  56. package/lib/runtime/role-routing.mjs +6 -0
  57. package/lib/runtime/role-supervisor.mjs +285 -33
  58. package/lib/tui/app.mjs +3 -39
  59. package/lib/tui/interface.mjs +40 -0
  60. package/lib/tui/setup.mjs +27 -16
  61. package/lib/watch/args.mjs +12 -27
  62. package/lib/watch/dispatch.mjs +2 -2
  63. package/lib/watch/index.mjs +38 -26
  64. package/lib/watch/markdown.mjs +232 -0
  65. package/lib/watch/menu.mjs +43 -0
  66. package/lib/watch/model.mjs +7 -3
  67. package/lib/watch/render.mjs +28 -67
  68. package/lib/watch/scope.mjs +1 -5
  69. package/lib/watch/status-line.mjs +2 -4
  70. package/lib/watch/text-width.mjs +43 -0
  71. package/lib/watch/watcher.mjs +17 -36
  72. package/package.json +1 -1
  73. package/shared/skill/runtime/grok-sandbox.mjs +74 -0
  74. package/shared/skill/runtime/role-bridge.mjs +10 -1
  75. package/shared/skill/runtime/role-dispatch-policy.mjs +7 -1
  76. package/shared/skill/runtime/role-observe.mjs +401 -13
  77. package/shared/skill/runtime/role-policy.json +1 -1
  78. package/shared/skill/runtime/role-routing.mjs +6 -0
  79. package/shared/skill/runtime/role-supervisor.mjs +285 -33
@@ -4,23 +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
- import {GROK_SANDBOX_RELATIVE, grokSandboxProfileName, renderGrokSandboxProfile, grokProfileCovered, inspectGrokProfileSlot, checkGrokHome, createGrokSandboxProfile, verifyGrokSandboxProfile, removeGrokSandboxProfile, grokEventsBaseline, readGrokProfileApplied} from './grok-sandbox.mjs';
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
- import {observeCooperativeTarget} from './scope.mjs';
16
16
  import {resolveLocalCli, localCliEnvironment} from './local-cli.mjs';
17
17
  import {parseCompositeProfile, buildBridgeArgs, argsDigest, ROLE_BRIDGE_PERMISSIONS} from './role-bridge-args.mjs';
18
- import {createLineParser, normalizeClaudeStreamEvent, normalizeCodexStreamEvent, eventRecord, evaluateClaudeInit, evaluateCodexContext, readClaudeTranscriptEffort, readCodexTurnContext, classifyFailure, snapshotWorktree, detectViolations} 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';
19
19
  import {getPlatform, routingProfileFile} from './platform-registry.mjs';
20
20
 
21
21
  const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
22
22
  const sha256 = bytes => 'sha256:' + crypto.createHash('sha256').update(bytes).digest('hex');
23
23
  const STDERR_LIMIT = 65536;
24
+ const execFileAsync = promisify(execFile);
24
25
 
25
26
  export const SUPERVISOR_IMPLEMENTATIONS = new Map([
26
27
  ['claude', {
@@ -78,25 +79,195 @@ export const SUPERVISOR_IMPLEMENTATIONS = new Map([
78
79
  ]);
79
80
  export const SUPERVISOR_PLATFORM_IDS = Object.freeze([...SUPERVISOR_IMPLEMENTATIONS.keys()]);
80
81
 
82
+ const normalizePsWhitespace = value => value.trim().replace(/\s+/g, ' ');
83
+
81
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. */
82
85
  export function processStartTime(pid) {
83
86
  if (!Number.isInteger(pid) || pid <= 0) return null;
84
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});
85
88
  if (result.error || result.status !== 0) return null;
86
- return result.stdout.trim().replace(/\s+/g, ' ') || null;
89
+ return normalizePsWhitespace(result.stdout) || null;
87
90
  }
88
91
  export function processAlive({pid, startTime} = {}) {
89
92
  const current = processStartTime(pid);
90
93
  return current !== null && current === startTime;
91
94
  }
92
95
 
93
- /** Worktree root and git common dir for a cwd that may be a subdirectory of the worktree. */
94
- export async function resolveWorktree(cwd) {
95
- const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => !key.toUpperCase().startsWith('GIT_')));
96
- const result = spawnSync('git', ['--no-pager', 'rev-parse', '--show-toplevel'], {cwd, env: {...env, GIT_CONFIG_NOSYSTEM: '1', GIT_OPTIONAL_LOCKS: '0'}, encoding: 'utf8', timeout: 10000});
97
- if (result.error || result.status !== 0 || !result.stdout.endsWith('\n')) throw Error('Worktree root unavailable');
98
- return observeCooperativeTarget(result.stdout.slice(0, -1));
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(() => {}); }
99
268
  }
269
+
270
+ export {resolveWorktree};
100
271
  export const artifactDirectory = (target, workflowId, dispatchId) => path.join(target.gitCommonDir, 'arc', 'workflows', workflowId, 'dispatches', dispatchId);
101
272
  /** Segment 0 (the first run) keeps its files in the dispatch directory; resumed segments use segments/<n>/. */
102
273
  export const segmentDirectory = (target, workflowId, dispatchId, segment) => segment > 0 ? path.join(artifactDirectory(target, workflowId, dispatchId), 'segments', String(segment)) : artifactDirectory(target, workflowId, dispatchId);
@@ -119,6 +290,11 @@ export async function buildBridgeInvocation({lease, config, homes, worktree, res
119
290
  if ((platform === 'gemini' || platform === 'grok') && lease.segment > 0 && !['on', 'verified'].includes(implementation?.resume)) throw fail('resume_unverified', platform === 'grok' ? 'Grok resume is not verified' : 'Gemini resume is not verified');
120
291
  if (!implementation) throw fail('permission_scope_unverified', 'Invalid composite profile: unknown platform');
121
292
  const permissions = ROLE_BRIDGE_PERMISSIONS[platform][lease.role];
293
+ if (Array.isArray(lease.allowedPaths) && allowedPathsCoverControl(lease.allowedPaths)) throw fail('permission_scope_unverified', 'allowedPaths cover a control file');
294
+ if (platform === 'claude' && permissions.sandbox) {
295
+ const scopeReason = await claudeProjectSettingsWidenScope(worktree);
296
+ if (scopeReason) throw fail('permission_scope_unverified', scopeReason);
297
+ }
122
298
  let grokSandbox;
123
299
  if (platform === 'grok' && permissions.sandbox === 'custom') {
124
300
  const name = grokSandboxProfileName(lease.dispatchId);
@@ -155,6 +331,10 @@ export async function startSupervisor({codexHome, dispatchId, cwd, userHome, env
155
331
  export async function runSupervisor(options) {
156
332
  const {codexHome, dispatchId, cwd, userHome, env = process.env, policy = DEFAULT_POLICY} = options;
157
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;
158
338
  const eventsMax = options.eventsMaxBytes ?? policy.eventsMaxBytes, codexWaitMs = options.codexWaitMs ?? 10000;
159
339
  const lockRetryMs = options.lockRetryMs ?? policy.lockRetryMs, lockDeadlineMs = options.lockDeadlineMs ?? 30000;
160
340
  const startedAt = new Date().toISOString();
@@ -227,13 +407,55 @@ export async function runSupervisor(options) {
227
407
  await writeRecord({state: 'failed', reasons: codes, spawned: spawned !== null, ...(spawned !== null ? {childPid: spawned} : {}), ...extra}).catch(() => {});
228
408
  await commit('failed', codes, claims);
229
409
  };
230
- const failWithProfileCleanup = (code, spawned = null) => {
410
+ const failWithProfileCleanup = (code, spawned = null, extra = {}) => {
231
411
  cleanGrokProfile();
232
- return earlyFailure(code, spawned, grokProfileRecord());
412
+ return earlyFailure(code, spawned, {...grokProfileRecord(), ...extra});
233
413
  };
234
414
 
235
415
  let child = null, eventsFd = null, killTimers = [], terminating = null, termAt = 0;
236
- 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 */ } } };
237
459
  const groupAlive = () => { try { process.kill(-child.pid, 0); return true; } catch (error) { return error.code === 'EPERM'; } };
238
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.
239
461
  const reapGroup = async () => {
@@ -273,8 +495,16 @@ export async function runSupervisor(options) {
273
495
  const {path, sha256, dirCreated} = createdGrokProfile;
274
496
  grokSandboxProfile = {name: invocation.grokSandbox.name, path, sha256, dirCreated, created: true, removed: null, dirRemoved: false, eventsBaseline: null, applied: null};
275
497
  }
498
+ const extra = invocation.grokSandbox ? [
499
+ {label: 'grok-home:config.toml', path: path.join(homes.grok, 'config.toml'), project: grokConfigSecurityProjection},
500
+ {label: 'grok-home:sandbox.toml', path: path.join(homes.grok, 'sandbox.toml')},
501
+ ] : [];
502
+ const snapshot = async () => ({
503
+ ...await snapshotWorktree(target.realpath),
504
+ control: await snapshotControlFiles({gitCommonDir: target.gitCommonDir, gitDir: target.gitDir, worktree: target.realpath, extra}),
505
+ });
276
506
  let before;
277
- try { before = await snapshotWorktree(target.realpath); } catch { return await failWithProfileCleanup('execution_failed'); }
507
+ try { before = await snapshot(); } catch { return await failWithProfileCleanup('execution_failed'); }
278
508
 
279
509
  if (invocation.promptFile) {
280
510
  let promptFd;
@@ -297,10 +527,16 @@ export async function runSupervisor(options) {
297
527
  }
298
528
  // The child is a process-group leader so one signal reaches its descendants. The prompt uses the platform-specific input channel.
299
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});
300
531
  let exitResolve, exited = false;
301
532
  const exitPromise = new Promise(resolve => { exitResolve = resolve; });
302
- child.on('exit', (code, signal) => { exited = true; exitResolve({code, signal}); });
303
- 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}));
304
540
  child.stdin.on('error', () => {});
305
541
  if (options.afterSpawn) await options.afterSpawn(child); // test injection point for post-spawn failures
306
542
  if (platform === 'grok') child.stdin.end();
@@ -311,15 +547,18 @@ export async function runSupervisor(options) {
311
547
  let eventsBytes = 0, eventsTruncated = false, stderrLength = 0, contextTask = null;
312
548
  const stderrParts = [];
313
549
  const terminate = why => {
314
- if (terminating) return;
550
+ if (terminating || originalGroupGone !== undefined) return;
315
551
  terminating = why; termAt = Date.now(); killGroup('SIGTERM');
316
552
  killTimers.push(setTimeout(() => {
317
553
  killGroup('SIGKILL');
318
554
  killTimers.push(setTimeout(() => exitResolve({code: null, signal: null, unobserved: true}), graceMs));
319
555
  }, graceMs));
320
556
  };
557
+ onStop = () => terminate('supervisor_signal');
558
+ if (stopSignal?.aborted) onStop();
559
+ else stopSignal?.addEventListener('abort', onStop, {once: true});
321
560
  const deadline = options.timeoutMs ?? lease.timeoutMinutes * 60000;
322
- timers.add(setTimeout(() => terminate('timeout'), deadline));
561
+ if (!exited) executionTimer = setTimeout(() => terminate('timeout'), deadline);
323
562
  let cancelBusy = false;
324
563
  timers.add(setInterval(async () => {
325
564
  if (cancelBusy || terminating || exited) return;
@@ -414,9 +653,11 @@ export async function runSupervisor(options) {
414
653
  if (!mine(current)) throw Error('Lease changed before the child was recorded');
415
654
  await writeLease(codexHome, {...current, state: 'running', child: {pid: child.pid, startTime}}, {runtimePlatforms});
416
655
  });
656
+ queueDescendantSample();
657
+ descendantTimer = setInterval(queueDescendantSample, descendantSampleMs);
658
+ timers.add(descendantTimer);
417
659
  } catch { state.internal = 'execution_failed'; terminate('internal'); }
418
660
 
419
-
420
661
  let exit = await exitPromise;
421
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.
422
663
  if (!terminating && !exit.unobserved && (exit.signal || !state.terminal) && await cancelRequested(codexHome, dispatchId)) { terminating = 'cancel'; termAt = Date.now(); }
@@ -424,18 +665,19 @@ export async function runSupervisor(options) {
424
665
  let orphanGroupReaped = false;
425
666
  if (!termAt && !exit.unobserved && child?.pid && groupAlive()) { orphanGroupReaped = true; termAt = Date.now(); killGroup('SIGTERM'); }
426
667
  if (termAt && !exit.unobserved && !await reapGroup()) exit = {code: null, signal: null, unobserved: true};
668
+ stopGroupSignals(!exit.unobserved);
669
+ const escapes = await finishDescendants();
427
670
  await Promise.race([stdoutClosed, sleep(1000)]);
428
671
  parser.end();
429
672
  if (contextTask) await contextTask;
430
673
  for (const timer of timers) { clearInterval(timer); clearTimeout(timer); }
431
- for (const timer of killTimers) clearTimeout(timer);
432
- timers.clear(); killTimers = [];
674
+ timers.clear();
433
675
  fs.closeSync(eventsFd); eventsFd = null;
434
676
 
435
677
  if (exit.unobserved) {
436
678
  // The child was signalled but its exit was never observed: the slot stays occupied.
437
679
  const claims = {...lease.claims, terminal: {level: 'unverified', source: 'none'}};
438
- 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(() => {});
439
681
  await locked(async () => {
440
682
  const current = await readLease(codexHome, dispatchId, {runtimePlatforms});
441
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});
@@ -444,8 +686,9 @@ export async function runSupervisor(options) {
444
686
  }
445
687
 
446
688
  let after = null;
447
- try { after = await snapshotWorktree(target.realpath); } catch { after = null; }
448
- const violations = after ? detectViolations({role: lease.role, allowedPaths: lease.allowedPaths, before, after}) : {reason: null, changedPaths: [], headChanged: false, refsChanged: false};
689
+ try { after = await snapshot(); } catch { after = null; }
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: []};
449
692
  const codes = [];
450
693
  if (state.mismatch) codes.push(state.mismatch);
451
694
  if (state.internal) codes.push(state.internal);
@@ -495,25 +738,32 @@ export async function runSupervisor(options) {
495
738
  }
496
739
  if (exit.spawnError && !codes.length) { codes.push('execution_failed'); finalState = 'failed'; }
497
740
  if ((finalState === 'completed' || finalState === 'cancelled') && codes.includes('permission_scope_mismatch')) finalState = 'failed';
498
- 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}, ...(orphanGroupReaped ? {orphanGroupReaped: true} : {}), argsDigest: invocation.argsDigest, resultPath, ...grokProfileRecord(), ...(platform === 'gemini' ? {unverifiedContracts: {delegation: GEMINI_CONTRACT.delegation}} : platform === 'grok' ? {unverifiedContracts: {delegation: GROK_CONTRACT.delegation}} : {})});
741
+ const controlFiles = violations.controlChanged.length ? {controlFiles: {changed: violations.controlChanged}} : {};
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});
499
744
  await commit(finalState, codes, claims, {sessionId, resultPath});
500
745
  } catch {
501
746
  // Unexpected failure after the child started: stop it, then record a failed state if the child is gone.
502
747
  const spawnedPid = child?.pid ?? null;
503
- let stopped = true;
504
- 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} : {})};
505
754
  for (const timer of timers) { clearInterval(timer); clearTimeout(timer); }
506
- for (const timer of killTimers) clearTimeout(timer);
507
- if (stopped) await failWithProfileCleanup('execution_failed', spawnedPid).catch(() => {});
755
+ if (stopped) await failWithProfileCleanup('execution_failed', spawnedPid, details).catch(() => {});
508
756
  else {
509
757
  const codes = ['execution_failed', 'terminal_state_unverified'];
510
- 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(() => {});
511
759
  await locked(async () => {
512
760
  const current = await readLease(codexHome, dispatchId, {runtimePlatforms});
513
761
  if (current && !TERMINAL_STATES.includes(current.state)) await writeLease(codexHome, {...current, state: 'unknown', reasons: codes.map(reason)}, {runtimePlatforms});
514
762
  }).catch(() => {});
515
763
  }
516
764
  } finally {
765
+ if (onStop) stopSignal?.removeEventListener('abort', onStop);
766
+ clearTimeout(executionTimer);
517
767
  for (const timer of timers) { clearInterval(timer); clearTimeout(timer); }
518
768
  if (eventsFd !== null) { try { fs.closeSync(eventsFd); } catch { /* closed */ } }
519
769
  }
@@ -522,5 +772,7 @@ export async function runSupervisor(options) {
522
772
  const isMain = () => { try { return Boolean(process.argv[1]) && fs.realpathSync(process.argv[1]) === fileURLToPath(import.meta.url); } catch { return false; } };
523
773
  if (isMain()) {
524
774
  const [, , codexHome, dispatchId, cwd, userHome] = process.argv;
525
- 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));
526
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
+ }