@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
@@ -1,43 +1,28 @@
1
- import fs from 'node:fs';
2
1
  import {WATCH_LIMITS as L} from './model.mjs';
3
2
 
4
3
  export function parseWatchArgs(argv) {
5
- const options = {mode:'default',dir:null,session:null,platforms:['codex','claude'],tail:L.defaultTail,verbose:false,json:false,width:null,help:false};
6
- const seen = new Set(), values = ['cwd','session','platform','tail','width'];
4
+ const options = {tail:L.defaultTail,verbose:false,json:false,width:null,help:false};
5
+ const seen = new Set(), values = ['tail','width'];
7
6
  const fail = message => ({ok:false,message});
8
7
  for (let i = 0; i < argv.length; i++) {
9
8
  const match = /^--([a-z]+)(?:=(.*))?$/.exec(argv[i]);
10
- if (!match) return fail(`Unsupported argument: ${argv[i]}`);
9
+ if (!match) return fail('Unsupported argument: '+argv[i]);
11
10
  const [, name, inline] = match;
12
- if (![...values,'all','verbose','json','help'].includes(name)) return fail(`Unknown option: --${name}`);
13
- if (seen.has(name)) return fail(`Duplicate option: --${name}`);
11
+ if (!Object.hasOwn(options,name)) return fail('Unknown option: --'+name);
12
+ if (seen.has(name)) return fail('Duplicate option: --'+name);
14
13
  seen.add(name);
15
14
  if (!values.includes(name)) {
16
- if (inline !== undefined) return fail(`--${name} does not take a value`);
17
- if (name !== 'all') options[name] = true;
15
+ if (inline !== undefined) return fail('--'+name+' does not take a value');
16
+ options[name] = true;
18
17
  continue;
19
18
  }
20
19
  const value = inline ?? argv[++i];
21
- if (value === undefined || value === '' || value.startsWith('--')) return fail(`Missing value for --${name}`);
22
- if (name === 'tail' || name === 'width') {
23
- const n = Number(value), min = name === 'tail' ? 0 : L.widthMin, max = name === 'tail' ? L.maxTail : L.widthMax;
24
- if (!/^\d+$/.test(value) || !Number.isSafeInteger(n) || n < min || n > max) return fail(`--${name} must be an integer from ${min} to ${max}`);
25
- options[name] = n;
26
- } else if (name === 'platform') {
27
- if (!['codex','claude'].includes(value)) return fail('--platform must be codex or claude');
28
- options.platforms = [value];
29
- } else if (name === 'session') {
30
- if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(value)) return fail('Invalid session id');
31
- options.session = value;
32
- } else {
33
- try {
34
- if (!fs.statSync(value).isDirectory()) return fail('--cwd must name an existing directory');
35
- options.dir = fs.realpathSync(value);
36
- } catch { return fail('--cwd must name an existing directory'); }
20
+ if (value === undefined || value === '' || value.startsWith('--')) return fail('Missing value for --'+name);
21
+ const n = Number(value), min = name === 'tail' ? 0 : L.widthMin, max = name === 'tail' ? L.maxTail : L.widthMax;
22
+ if (!/^\d+$/.test(value) || !Number.isSafeInteger(n) || n < min || n > max) {
23
+ return fail('--'+name+' must be an integer from '+min+' to '+max);
37
24
  }
25
+ options[name] = n;
38
26
  }
39
- const modes = ['cwd','all','session'].filter(name => seen.has(name));
40
- if (modes.length > 1) return fail('--cwd, --all and --session are mutually exclusive');
41
- if (modes.length) options.mode = modes[0];
42
27
  return {ok:true,options};
43
28
  }
@@ -79,7 +79,7 @@ export function createDispatchIndex({storeDir} = {}) {
79
79
  }
80
80
 
81
81
  return {
82
- async scan({gitCommonDirs, includeAllLeases}) {
82
+ async scan({gitCommonDirs}) {
83
83
  const currentLeases = storeDir ? await readLeases() : new Map(), artifacts = new Map();
84
84
  for (const gcd of gitCommonDirs) {
85
85
  const workflows = path.join(gcd, 'arc', 'workflows');
@@ -113,7 +113,7 @@ export function createDispatchIndex({storeDir} = {}) {
113
113
  const updates = [];
114
114
  for (const [id, ref] of refs) {
115
115
  const artifact = artifacts.get(id), lease = currentLeases.get(id), value = lease ?? artifact?.record;
116
- ref.inScope = Boolean(artifact || (includeAllLeases && lease));
116
+ ref.inScope = Boolean(artifact);
117
117
  ref.artifactDir = artifact?.dir ?? null;
118
118
  ref.cwd = artifact?.cwd ?? null;
119
119
  if (!lease && !artifact) continue;
@@ -1,5 +1,4 @@
1
1
  import os from 'node:os';
2
- import path from 'node:path';
3
2
  import {parseWatchArgs} from './args.mjs';
4
3
  import {resolveConfigHome} from '../runtime/local-cli.mjs';
5
4
  import {DEFAULT_PLATFORM_REGISTRY} from '../runtime/platform-registry.mjs';
@@ -13,13 +12,10 @@ import {WATCH_LIMITS as L} from './model.mjs';
13
12
  export {parseWatchArgs};
14
13
  export const WATCH_HELP = `Usage: arc watch [options]
15
14
 
16
- Follow Claude Code and Codex session activity in one read-only stream.
15
+ Follow session activity of supported platforms in one read-only stream.
17
16
 
18
- Scope (default: the current Git worktree, or the current directory):
19
- --cwd <dir> Watch the worktree or directory at <dir>
20
- --all Watch sessions from every directory
21
- --session <id> Follow one session or ARC dispatch and its subagents
22
- --platform <name> codex or claude (default: both)
17
+ Scope:
18
+ Choose All or one platform in the menu. Every choice watches the current Git worktree, or the current directory outside Git. Requires an interactive terminal.
23
19
 
24
20
  Output:
25
21
  --tail <n> First show the last <n> events from recently active sessions (default 20, 0 = new only)
@@ -30,36 +26,52 @@ Output:
30
26
 
31
27
  Events are scoped by each session's working directory at that point; a session that moves into another worktree appears in that worktree's watch.
32
28
  Skills and plugin tools in use are shown as SKILL and PLUGIN lines.
33
- User and agent messages and file paths are shown in full; other events use one line.
29
+ User messages, agent messages, prompts and file paths are shown in full; other events use one line.
30
+ PROMPT is an agent-generated prompt sent to a child session (kind "prompt" in JSON).
31
+ Color TTY output renders Markdown in AGENT and PROMPT messages. NO_COLOR, piped output and --json keep the Markdown source text.
34
32
  Tool and command outputs are never shown; common secret patterns are masked.
35
33
  A status block on the last lines shows the watched path and, while a turn is in progress, a spinner (TTY only).
36
- Codex Desktop sessions are not included.
37
- Claude bridge Scouter, Planner and Reviewer on a Codex host need per-call escalation approval (otherwise host_sandbox_blocked) and appear once they run; Claude bridge Implementer and QA stay held.
38
34
  Press Ctrl-L to clear the screen (TTY only) and Ctrl-C to stop.`;
39
35
 
40
36
  export async function runWatch(argv, io = {}) {
41
37
  const input = io.input ?? process.stdin;
42
38
  const output = io.output ?? process.stdout, error = io.error ?? process.stderr;
43
- const cwd = io.cwd ?? process.cwd(), env = io.env ?? process.env;
44
- // Resolve relative --cwd without changing the process cwd shared by other callers.
45
- const args = argv.map((arg, i) => {
46
- if (arg.startsWith('--cwd=') && arg.length > 6) return '--cwd=' + path.resolve(cwd, arg.slice(6));
47
- if (i > 0 && argv[i-1] === '--cwd' && arg && !arg.startsWith('--')) return path.resolve(cwd, arg);
48
- return arg;
49
- });
50
- const parsed = parseWatchArgs(args);
51
- if (!parsed.ok) { error.write(`Error: ${parsed.message}. Run arc watch --help for usage.\n`); return 2; }
39
+ const parsed = parseWatchArgs(argv);
40
+ if (!parsed.ok) { error.write('Error: '+parsed.message+'. Run arc watch --help for usage.\n'); return 2; }
52
41
  const options = parsed.options;
53
42
  if (options.help) { output.write(WATCH_HELP + '\n'); return 0; }
54
43
  if (io.signal?.aborted) return 0;
55
- const userHome = io.userHome ?? os.homedir(), homes = {codex:null,claude:null}, disabled = [];
44
+ if (!(input.isTTY && output.isTTY)) {
45
+ error.write('Error: arc watch needs an interactive terminal to choose platforms.\n');
46
+ return 2;
47
+ }
48
+ const registry = io.registry ?? DEFAULT_PLATFORM_REGISTRY;
49
+ const choose = io.choosePlatforms ?? (await import('./menu.mjs')).chooseWatchPlatforms;
50
+ let platforms;
51
+ try {
52
+ platforms = await choose({input,output,env:io.env,signals:io.process,registry});
53
+ } catch (cause) {
54
+ if (cause.code === 'ARC_CANCELLED') return 130;
55
+ throw cause;
56
+ }
57
+ if (platforms === null) return 0;
58
+ return followWatch(options,{...io,input,output,error,registry,platforms});
59
+ }
60
+
61
+ export async function followWatch(options, io = {}) {
62
+ if (io.signal?.aborted) return 0;
63
+ const input = io.input ?? process.stdin;
64
+ const output = io.output ?? process.stdout, error = io.error ?? process.stderr;
65
+ const cwd = io.cwd ?? process.cwd(), env = io.env ?? process.env;
56
66
  const registry = io.registry ?? DEFAULT_PLATFORM_REGISTRY;
67
+ const userHome = io.userHome ?? os.homedir(), disabled = [];
68
+ const homes = Object.fromEntries(registry.byAnchorOrder().map(({id}) => [id,null]));
57
69
  for (const {id:platform} of registry.byAnchorOrder()) {
58
70
  try { homes[platform] = resolveConfigHome(platform, {userHome,env,cwd,runtimePlatforms:registry}); }
59
- catch (cause) { if (options.platforms.includes(platform)) disabled.push(`${platform} disabled: ${cause.message}`); }
71
+ catch (cause) { if (io.platforms.includes(platform)) disabled.push(`${platform} disabled: ${cause.message}`); }
60
72
  }
61
- options.platforms = options.platforms.filter(platform => homes[platform] !== null);
62
- if (!options.platforms.length) { error.write('Error: no usable watch source.\n'); return 1; }
73
+ const platforms = io.platforms.filter(platform => homes[platform] !== null);
74
+ if (!platforms.length) { error.write('Error: no usable watch source.\n'); return 1; }
63
75
  const now = io.now ?? Date.now, git = io.git ?? createGitRunner({env});
64
76
  const proc = io.process ?? process, schedule = io.setInterval ?? setInterval, unschedule = io.clearInterval ?? clearInterval;
65
77
  let width, watcher, timer, stopped = false, active;
@@ -67,7 +79,7 @@ export async function runWatch(argv, io = {}) {
67
79
  const color = Boolean(output.isTTY && !options.json && !env.NO_COLOR);
68
80
  const blockEnabled = Boolean(output.isTTY && !options.json);
69
81
  const fancy = color && env.TERM !== 'dumb';
70
- const label = watchLocationLabel({mode:options.mode,dir:options.dir ?? cwd,session:options.session,home:userHome});
82
+ const label = watchLocationLabel({dir:cwd,home:userHome});
71
83
  const keysEnabled = Boolean(input.isTTY && output.isTTY && !options.json && typeof input.setRawMode === 'function');
72
84
  const frames = ['⠋','⠙','⠹','⠸','⠼','⠴','⠦','⠧','⠇','⠏'];
73
85
  let drawnLines = 0, frame = 0, tick = 0;
@@ -149,9 +161,9 @@ export async function runWatch(argv, io = {}) {
149
161
  input.resume();
150
162
  input.on('data', onKey);
151
163
  }
152
- const scope = await resolveScope({mode:options.mode,dir:options.dir ?? cwd,session:options.session,git});
164
+ const scope = await resolveScope({dir:cwd,git});
153
165
  if (stopped) return;
154
- watcher = createWatcher({options,homes:{...homes,user:userHome},scope,git,now,registry});
166
+ watcher = createWatcher({options:{...options,platforms},homes:{...homes,user:userHome},scope,git,now,registry});
155
167
  for (const text of disabled) {
156
168
  const ts = new Date(now()).toISOString();
157
169
  write([{v:1,ts,observedAt:ts,source:'watch',kind:'notice',label:'watch',text}]);
@@ -0,0 +1,232 @@
1
+ import {displayWidth, wrapLineRanges} from './text-width.mjs';
2
+
3
+ const reset = '\x1b[0m';
4
+ const inline = /(?<!`)`(?<code>[^`]+)`(?!`)|\[(?<label>[^\[\]]+)\]\((?<url>[^\s()]+)\)|(?<delimiter>(?<!\*)\*\*|(?<![\p{L}\p{N}_*])\*)(?![\s*])(?<emphasis>[^*]*?)(?<!\s)\k<delimiter>(?!\*)/gu;
5
+ const fenceMarker = /^ *(`{3,}|~{3,})(.*)$/;
6
+ const pipeStart = /^ *\|/;
7
+
8
+ function inlineSpans(text) {
9
+ const spans = [];
10
+ let start = 0;
11
+ for (const {index, 0:token, groups:{code, label, url, delimiter, emphasis}} of text.matchAll(inline)) {
12
+ if (index > start) spans.push({text:text.slice(start, index)});
13
+ if (code !== undefined) spans.push({text:code, style:'38;5;180'});
14
+ else if (label !== undefined) spans.push({text:`${label} (${url})`});
15
+ else spans.push({text:emphasis, style:delimiter === '**' ? '1' : '3'});
16
+ start = index + token.length;
17
+ }
18
+ if (start < text.length) spans.push({text:text.slice(start)});
19
+ return spans;
20
+ }
21
+
22
+ function renderLine(spans, {width, baseCode, blockStyle, prefix = '', preserveWhitespace}) {
23
+ const blockCode = blockStyle ? `${baseCode};${blockStyle}` : baseCode;
24
+ // Very narrow widths may leave no room after a marker. Wrap it with the body in that case.
25
+ if (prefix && width - prefix.length < 2) {
26
+ spans.unshift({text:prefix});
27
+ prefix = '';
28
+ }
29
+ const text = spans.map(span => span.text).join('');
30
+ const avail = width - prefix.length;
31
+ const ranges = avail === Infinity ? [{from:0, to:text.length}]
32
+ : avail > 0 ? wrapLineRanges(text, avail, {preserveWhitespace}) : [{from:0, to:0}];
33
+ let spanIndex = 0, spanStart = 0;
34
+ return ranges.map(({from, to, overflows}, index) => {
35
+ let line = index ? ' '.repeat(prefix.length) : prefix;
36
+ let active = blockCode;
37
+ if (line) line = `\x1b[${active}m${line}`;
38
+ if (overflows) return `${line || `\x1b[${active}m`}�${reset}`;
39
+ while (from < to && spanIndex < spans.length) {
40
+ const span = spans[spanIndex];
41
+ const spanEnd = spanStart + span.text.length;
42
+ if (spanEnd > from) {
43
+ const code = span.style ? `${blockCode};${span.style}` : blockCode;
44
+ if (!line) line = `\x1b[${code}m`;
45
+ else if (active !== code) line += `\x1b[0;${code}m`;
46
+ line += span.text.slice(Math.max(from - spanStart, 0), to - spanStart);
47
+ active = code;
48
+ }
49
+ if (spanEnd >= to) break;
50
+ spanStart = spanEnd;
51
+ spanIndex++;
52
+ }
53
+ return line ? `${line}${reset}` : '';
54
+ });
55
+ }
56
+
57
+ function splitTableRow(line) {
58
+ if (!line?.includes('|')) return;
59
+ const row = line.trim();
60
+ const cells = [];
61
+ let start = 0;
62
+ const cell = end => row.slice(start, end).trim().replace(/\\\\|\\\|/g, token => token === '\\|' ? '|' : token);
63
+ for (const {0:token, index} of row.matchAll(/\\[\\|]|(?<!`)`[^`]+`(?!`)|\|/g)) {
64
+ if (token !== '|') continue;
65
+ if (index) cells.push(cell(index));
66
+ start = index + 1;
67
+ }
68
+ if (!start) return;
69
+ if (start < row.length) cells.push(cell(row.length));
70
+ return cells;
71
+ }
72
+
73
+ function readTable(source, index) {
74
+ if (!pipeStart.test(source[index])) return;
75
+ const divider = source[index + 1];
76
+ if (!divider?.includes('|') || !/^[ |:-]+$/.test(divider)) return;
77
+ const header = splitTableRow(source[index]);
78
+ const columns = splitTableRow(divider);
79
+ if (!header?.length || columns.length !== header.length || !columns.every(cell => /^:?-+:?$/.test(cell))) return;
80
+
81
+ const rows = [];
82
+ let end = index + 2;
83
+ for (; end < source.length && !fenceMarker.test(source[end]); end++) {
84
+ const cells = splitTableRow(source[end]);
85
+ if (!cells) break;
86
+ rows.push(header.map((_, col) => col === header.length - 1 ? cells.slice(col).join(' | ') : cells[col] ?? ''));
87
+ }
88
+ if (!rows.length) return;
89
+ const alignments = columns.map(cell => !cell.endsWith(':') ? 'left' : cell.startsWith(':') ? 'center' : 'right');
90
+ return {header, rows, alignments, end};
91
+ }
92
+
93
+ function fitTableWidths(natural, width) {
94
+ const available = width - (3 * natural.length + 1);
95
+ if (natural.reduce((sum, cols) => sum + cols, 0) <= available) return natural;
96
+ if (6 * natural.length > available) return;
97
+
98
+ // Cap the widest columns together, then use any remaining space among those columns.
99
+ let low = 6, high = available;
100
+ while (low < high) {
101
+ const cap = Math.ceil((low + high) / 2);
102
+ const total = natural.reduce((sum, cols) => sum + Math.min(cols, cap), 0);
103
+ if (total <= available) low = cap;
104
+ else high = cap - 1;
105
+ }
106
+ const widths = natural.map(cols => Math.min(cols, low));
107
+ let remaining = available - widths.reduce((sum, cols) => sum + cols, 0);
108
+ for (let col = widths.length - 1; col >= 0 && remaining > 0; col--) {
109
+ if (natural[col] > low) {
110
+ widths[col]++;
111
+ remaining--;
112
+ }
113
+ }
114
+ return widths;
115
+ }
116
+
117
+ function renderCards([header, ...rows], {width, baseCode}) {
118
+ const lines = [];
119
+ for (const row of rows) {
120
+ if (lines.length) lines.push('');
121
+ for (const [col, value] of row.entries()) {
122
+ const marker = col === 0 ? '▸ ' : ' ';
123
+ const label = `${header[col].map(span => span.text).join('')}:`;
124
+ const prefix = `${marker}${label} `;
125
+ const prefixWidth = displayWidth(prefix);
126
+ if (width - prefixWidth < 2) {
127
+ lines.push(...renderLine([{text:label}], {width, baseCode, prefix:marker}));
128
+ if (value.length) lines.push(...renderLine(value, {width, baseCode, prefix:' '}));
129
+ continue;
130
+ }
131
+ const wrapped = renderLine(value, {width:width - prefixWidth, baseCode});
132
+ for (const [index, piece] of wrapped.entries()) {
133
+ const lead = index ? ' '.repeat(prefixWidth) : prefix;
134
+ lines.push(piece ? `\x1b[${baseCode}m${lead}${piece}` : `\x1b[${baseCode}m${lead.trimEnd()}${reset}`);
135
+ }
136
+ }
137
+ }
138
+ return lines;
139
+ }
140
+
141
+ function renderTable({header, rows, alignments}, options) {
142
+ const {baseCode, width} = options;
143
+ const cells = [header, ...rows].map(row => row.map(inlineSpans));
144
+ const natural = header.map(() => 1);
145
+ for (const row of cells) {
146
+ for (const [col, spans] of row.entries()) {
147
+ natural[col] = Math.max(natural[col], displayWidth(spans.map(span => span.text).join('')));
148
+ }
149
+ }
150
+ const widths = fitTableWidths(natural, width);
151
+ if (!widths) return renderCards(cells, options);
152
+
153
+ const border = (left, cross, right) => `\x1b[${baseCode}m${left}${widths.map(cols => '─'.repeat(cols + 2)).join(cross)}${right}${reset}`;
154
+ const lines = [border('┌', '┬', '┐')];
155
+ for (const [index, row] of cells.entries()) {
156
+ if (index) lines.push(border('├', '┼', '┤'));
157
+ const wrapped = row.map((spans, col) => renderLine(spans, {width:widths[col], baseCode, blockStyle:index === 0 ? '1' : undefined}));
158
+ const height = wrapped.reduce((max, cell) => Math.max(max, cell.length), 0);
159
+ for (let line = 0; line < height; line++) {
160
+ let visual = `\x1b[${baseCode}m│`;
161
+ for (const [col, cell] of wrapped.entries()) {
162
+ const piece = cell[line] ?? '';
163
+ const pad = widths[col] - displayWidth(piece.replace(/\x1b\[[0-9;]*m/g, ''));
164
+ const left = alignments[col] === 'right' ? pad : alignments[col] === 'center' ? Math.floor(pad / 2) : 0;
165
+ visual += ' '.repeat(left + 1);
166
+ if (piece) visual += `${piece}\x1b[${baseCode}m`;
167
+ visual += `${' '.repeat(pad - left + 1)}│`;
168
+ }
169
+ lines.push(visual + reset);
170
+ }
171
+ }
172
+ lines.push(border('└', '┴', '┘'));
173
+ return lines;
174
+ }
175
+
176
+ export function renderMarkdown(text, {width, baseCode}) {
177
+ const lines = [];
178
+ const source = text.replace(/[\x00-\x09\x0b-\x1f\x7f-\x9f]/g, '').split('\n');
179
+ let fence;
180
+ for (let index = 0; index < source.length; index++) {
181
+ const line = source[index];
182
+ const marker = fenceMarker.exec(line);
183
+ if (fence) {
184
+ if (marker && marker[1][0] === fence[0] && marker[1].length >= fence.length && !marker[2].trim()) {
185
+ fence = undefined;
186
+ continue;
187
+ }
188
+ } else if (marker && (marker[1][0] === '~' || !marker[2].includes('`'))) {
189
+ fence = marker[1];
190
+ continue;
191
+ }
192
+ if (!line) {
193
+ lines.push('');
194
+ continue;
195
+ }
196
+ if (!fence) {
197
+ const table = readTable(source, index);
198
+ if (table) {
199
+ for (const visual of renderTable(table, {width, baseCode})) lines.push(visual);
200
+ index = table.end - 1;
201
+ continue;
202
+ }
203
+ }
204
+
205
+ let content = line, prefix, blockStyle;
206
+ const rawPipe = pipeStart.test(line);
207
+ if (fence) {
208
+ prefix = ' ';
209
+ blockStyle = '2';
210
+ } else if (!rawPipe) {
211
+ const heading = /^#{1,6} (.*)$/.exec(line);
212
+ const list = /^( *)([-*+]|\d+\.) (.*)$/.exec(line);
213
+ if (heading) {
214
+ content = heading[1];
215
+ blockStyle = '1;4';
216
+ } else if (/^ *(?:---|\*\*\*|___) *$/.test(line)) {
217
+ content = '─'.repeat(Math.max(0, Math.min(width, 40)));
218
+ } else if (list) {
219
+ const indent = ' '.repeat(list[1].length - list[1].length % 2);
220
+ prefix = `${indent}${list[2].endsWith('.') ? list[2] : '•'} `;
221
+ content = list[3];
222
+ } else if (line.startsWith('> ')) {
223
+ prefix = '│ ';
224
+ blockStyle = '2';
225
+ content = line.slice(2);
226
+ }
227
+ }
228
+ const spans = fence || rawPipe ? [{text:content}] : inlineSpans(content);
229
+ for (const visual of renderLine(spans, {width, baseCode, prefix, blockStyle, preserveWhitespace:Boolean(fence)})) lines.push(visual);
230
+ }
231
+ return lines;
232
+ }
@@ -0,0 +1,43 @@
1
+ import {createTuiInterface} from '../tui/interface.mjs';
2
+ import {createTerminalSession} from '../tui/terminal.mjs';
3
+
4
+ export function watchMenuRows(registry) {
5
+ const all = {label:'All',platforms:[]};
6
+ const rows = registry.byDisplayOrder().map(({id,label,capabilities}) => {
7
+ if (capabilities.watch.state !== 'verified') {
8
+ return {label:label+' (not supported)',platforms:null};
9
+ }
10
+ all.platforms.push(id);
11
+ return {label,platforms:[id]};
12
+ });
13
+ return [all,...rows];
14
+ }
15
+
16
+ export async function chooseWatchPlatforms({input,output,env,signals,registry,createSession=createTerminalSession}) {
17
+ const rows = watchMenuRows(registry);
18
+ const labels = rows.map(row => row.label);
19
+ const session = createSession({input,output,env,signals});
20
+ try {
21
+ const ui = createTuiInterface(session,{input});
22
+ let selected = 0, notice = [];
23
+ for (;;) {
24
+ const previous = selected;
25
+ selected = await ui.menu('Which platform to watch?',labels,{
26
+ selected,backRow:true,backLabel:'exit',
27
+ notice:({selected:current})=>{
28
+ if (current !== previous) notice = [];
29
+ return notice;
30
+ },
31
+ });
32
+ if (selected === null) return null;
33
+ const row = rows[selected];
34
+ if (row.platforms !== null) return row.platforms;
35
+ notice = [row.label.slice(0,-' (not supported)'.length)+' is not supported by arc watch.'];
36
+ }
37
+ } catch (error) {
38
+ if (error.code === 'ARC_TUI_EOF') return null;
39
+ throw error;
40
+ } finally {
41
+ session.dispose();
42
+ }
43
+ }
@@ -1,5 +1,9 @@
1
- export const WATCH_KINDS = Object.freeze(['session','settings','turn_start','turn_end','turn_failed','user','agent','reasoning','command','tool','tool_failed','file_change','file_create','file_delete','spawn','approval','dispatch','error','other','notice']);
2
- export const MESSAGE_KINDS = Object.freeze(['user','agent']);
1
+ export const WATCH_KINDS = Object.freeze(['session','settings','turn_start','turn_end','turn_failed','user','prompt','agent','reasoning','command','tool','tool_failed','file_change','file_create','file_delete','spawn','approval','dispatch','error','other','notice']);
2
+ export const MESSAGE_KINDS = Object.freeze(['user','prompt','agent']);
3
+
4
+ export function classifyMessageKind(event) {
5
+ return event.kind === 'user' && (event.parentId || event.dispatchId) ? 'prompt' : event.kind;
6
+ }
3
7
  export const VERBOSE_KINDS = Object.freeze(['settings','turn_start','reasoning','other']);
4
8
  export const ROLE_NAMES = Object.freeze(['scouter','planner','implementer','qa','reviewer']);
5
9
 
@@ -35,7 +39,7 @@ export const WATCH_LIMITS = Object.freeze({
35
39
  * @property {'scouter'|'planner'|'implementer'|'qa'|'reviewer'|'orchestrator'} [role]
36
40
  * @property {string} [dispatchId]
37
41
  * @property {string} [workflowId]
38
- * @property {'session'|'settings'|'turn_start'|'turn_end'|'turn_failed'|'user'|'agent'|'reasoning'|'command'|'tool'|'tool_failed'|'file_change'|'file_create'|'file_delete'|'spawn'|'approval'|'dispatch'|'error'|'other'|'notice'} kind
42
+ * @property {'session'|'settings'|'turn_start'|'turn_end'|'turn_failed'|'user'|'prompt'|'agent'|'reasoning'|'command'|'tool'|'tool_failed'|'file_change'|'file_create'|'file_delete'|'spawn'|'approval'|'dispatch'|'error'|'other'|'notice'} kind
39
43
  * @property {string} [text] Sanitized, masked text; user/agent preserve newlines without a length cap. Other JSON text is capped at 1000 code points.
40
44
  * @property {boolean} [truncated]
41
45
  * @property {number} [exitCode]
@@ -2,8 +2,11 @@ import path from 'node:path';
2
2
  import {WATCH_LIMITS, MESSAGE_KINDS} from './model.mjs';
3
3
  import {sanitizeText, sanitizeMessage, clipCodePoints} from './policy.mjs';
4
4
  import {realPath} from './scope.mjs';
5
+ import {renderMarkdown} from './markdown.mjs';
6
+ import {displayWidth, wrapLine} from './text-width.mjs';
7
+
8
+ export {displayWidth, wrapLine} from './text-width.mjs';
5
9
 
6
- const graphemes = new Intl.Segmenter(undefined, {granularity:'grapheme'});
7
10
  const roleLabels = new Map([
8
11
  ['scouter','SCOUTER'], ['planner','PLANNER'], ['implementer','IMPLEMENTER'],
9
12
  ['qa','QA'], ['reviewer','REVIEWER'], ['orchestrator','ORCHESTRATOR'],
@@ -13,54 +16,6 @@ const roleBadgeColors = new Map([
13
16
  ['implementer','1;38;5;16;48;5;214'], ['qa','1;38;5;16;48;5;228'],
14
17
  ['reviewer','1;38;5;231;48;5;161'], ['orchestrator','1;38;5;16;48;5;255'],
15
18
  ]);
16
- const zeroWidth = /^[\u0300-\u036f\u200b-\u200f\ufe00-\ufe0f]+$/u;
17
- const wide = /[\u1100-\u115f\u2e80-\u303e\u3041-\u33ff\u3400-\u4dbf\u4e00-\u9fff\ua000-\ua4cf\uac00-\ud7a3\uf900-\ufaff\ufe30-\ufe4f\uff00-\uff60\uffe0-\uffe6\u{1f300}-\u{1f64f}\u{1f900}-\u{1f9ff}\u{20000}-\u{3fffd}]/u;
18
- function graphemeWidth(text) {
19
- if (zeroWidth.test(text)) return 0;
20
- if (wide.test(text) || /\p{Emoji_Presentation}/u.test(text) || (/[\u200d\ufe0f]/u.test(text) && /\p{Extended_Pictographic}/u.test(text))) return 2;
21
- return 1;
22
- }
23
-
24
- export function displayWidth(text) {
25
- let width = 0;
26
- for (const {segment} of graphemes.segment(text)) width += graphemeWidth(segment);
27
- return width;
28
- }
29
-
30
- export function wrapLine(text, avail) {
31
- if (avail <= 0) return [text];
32
- const parts = [...graphemes.segment(text)].map(({segment}) => segment);
33
- const widths = parts.map(graphemeWidth);
34
- const lines = [];
35
- let start = 0;
36
- while (start < parts.length) {
37
- let end = start, cols = 0, space = -1, hasContent = false;
38
- while (end < parts.length && cols + widths[end] <= avail) {
39
- if (parts[end] === ' ') { if (hasContent) space = end; }
40
- else hasContent = true;
41
- cols += widths[end++];
42
- }
43
- if (end === parts.length) {
44
- const piece = parts.slice(start).join('');
45
- if (piece.trim()) lines.push(piece);
46
- break;
47
- }
48
- // A space immediately after a full line can be discarded as the boundary.
49
- if (parts[end] === ' ' && hasContent) space = end;
50
- let piece;
51
- if (space >= 0) {
52
- piece = parts.slice(start,space).join('');
53
- start = space + 1;
54
- } else {
55
- end = Math.max(start + 1,end);
56
- piece = parts.slice(start,end).join('');
57
- start = end;
58
- }
59
- if (piece.trim()) lines.push(piece);
60
- }
61
- return lines.length ? lines : [''];
62
- }
63
-
64
19
  export const PLATFORM_COLORS = Object.freeze({codex:'36', claude:'38;5;208', gemini:'38;5;135', other:'2'});
65
20
 
66
21
  // Compare both the lexical root and its real path (e.g. /tmp and /private/tmp).
@@ -78,7 +33,7 @@ export function displayPath(file, root) {
78
33
  export function tagColor(event) {
79
34
  if (event.kind === 'tool' && event.skill) return '38;5;110';
80
35
  if (event.kind === 'tool' && event.plugin) return '38;5;175';
81
- return ({command:'38;5;242', user:'1;35', agent:'32', file_change:'33', file_create:'38;5;69', file_delete:'31', tool:'38;5;101', spawn:'38;5;141',
36
+ return ({command:'38;5;242', user:'1;97', prompt:'1;35', agent:'32', file_change:'33', file_create:'38;5;69', file_delete:'31', tool:'38;5;101', spawn:'38;5;141',
82
37
  dispatch:'38;5;137', approval:'1;4', turn_failed:'31', error:'31', tool_failed:'31'})[event.kind] ?? '2';
83
38
  }
84
39
 
@@ -91,7 +46,7 @@ export function kindTag(event) {
91
46
  if (event.kind === 'tool' && event.skill) return 'SKILL';
92
47
  if (event.kind === 'tool' && event.plugin) return 'PLUGIN';
93
48
  return ({command:'CMD', session:'SESSION', settings:'SETTINGS', turn_start:'TURN', turn_end:'END',
94
- turn_failed:'FAIL', user:'USER', agent:'AGENT', reasoning:'THINK', tool:'TOOL',
49
+ turn_failed:'FAIL', user:'USER', prompt:'PROMPT', agent:'AGENT', reasoning:'THINK', tool:'TOOL',
95
50
  tool_failed:'TOOL!', file_change:'EDIT', file_create:'CREATE', file_delete:'DELETE', spawn:'SPAWN', approval:'APPROVE',
96
51
  dispatch:'DISPATCH', error:'ERROR', other:'ITEM', notice:'NOTICE'})[event.kind] ?? 'ITEM';
97
52
  }
@@ -119,15 +74,30 @@ export function renderHuman(event, {width, color, verbose, wrap = false}) {
119
74
  const message = MESSAGE_KINDS.includes(event.kind);
120
75
  const fullLine = message || event.kind === 'file_change' || event.kind === 'file_create' || event.kind === 'file_delete';
121
76
  const text = message ? sanitizeMessage(event.text) : eventText(event, verbose);
77
+ const roleName = event.kind === 'agent' ? roleLabels.get(event.role) : undefined;
78
+ const indent = ' '.repeat([...prefix].length);
79
+ const avail = width - Math.max([...prefix].length, displayWidth(prefix));
80
+ const canWrap = wrap && avail >= WATCH_LIMITS.wrapMinBody;
81
+ const paint = (value, code) => `\x1b[${code}m${value}\x1b[0m`;
82
+ const paintedPrefix = () => {
83
+ const platformColor = event.source === 'watch' ? PLATFORM_COLORS.other : PLATFORM_COLORS[event.platform] ?? PLATFORM_COLORS.other;
84
+ return `${time} ${paint(platform, platformColor)} ${paint(tag.trimEnd(), tagColor(event))}`;
85
+ };
86
+ const padding = tag.slice(tag.trimEnd().length);
87
+ const roleBadge = () => paint(` ${roleName} `,roleBadgeColors.get(event.role));
88
+ if (color && fullLine && (event.kind === 'agent' || event.kind === 'prompt')) {
89
+ const lines = text ? renderMarkdown(text, {width:canWrap ? avail : Infinity, baseCode:bodyColor(event)}) : [];
90
+ if (text && roleName) lines.unshift(roleBadge());
91
+ const body = lines.map((line,i) => i && line ? indent + line : line).join('\n');
92
+ return body ? `${paintedPrefix()}${padding} ${body}` : paintedPrefix();
93
+ }
94
+
122
95
  const paths = fullLine && !message ? (event.paths ?? []).map(file => sanitizeText(displayPath(file,event.root))).filter(Boolean) : [];
123
96
  const listPaths = paths.length >= 2;
124
97
  const bodyLines = message ? (text ? text.split('\n') : []) : fullLine
125
98
  ? [sanitizeText(event.text), ...paths.map(file => listPaths ? '- ' + file : file)].filter(Boolean) : [];
126
- const roleName = event.kind === 'agent' ? roleLabels.get(event.role) : undefined;
127
99
  if (roleName && bodyLines.length) bodyLines.unshift(roleName);
128
- const indent = ' '.repeat([...prefix].length);
129
- const avail = width - Math.max([...prefix].length, displayWidth(prefix));
130
- const lines = wrap && avail >= WATCH_LIMITS.wrapMinBody ? bodyLines.flatMap((line,i) =>
100
+ const lines = canWrap ? bodyLines.flatMap((line,i) =>
131
101
  listPaths && paths.length && i >= bodyLines.length - paths.length
132
102
  ? wrapLine(line.slice(2),avail-2).map((piece,j) => (j ? ' ' : '- ') + piece)
133
103
  : wrapLine(line,avail)) : bodyLines;
@@ -135,20 +105,11 @@ export function renderHuman(event, {width, color, verbose, wrap = false}) {
135
105
  const plain = fullLine ? (message && !lines.length ? prefix.trimEnd() : prefix + bodyText(line => line)) : clipCodePoints(prefix + text, width).text;
136
106
  if (!color || (!fullLine && [...prefix].length > width)) return plain;
137
107
  const code = bodyColor(event);
138
- const paint = (value, code) => `\x1b[${code}m${value}\x1b[0m`;
139
- const platformColor = event.source === 'watch' ? PLATFORM_COLORS.other : PLATFORM_COLORS[event.platform] ?? PLATFORM_COLORS.other;
140
- const paintedTag = paint(tag.trimEnd(), tagColor(event));
141
- const padding = tag.slice(tag.trimEnd().length);
142
108
  const clippedText = [...plain].slice([...prefix].length).join('');
143
- if (message && !text) return `${time} ${paint(platform, platformColor)} ${paintedTag}`;
144
- const body = fullLine ? bodyText((line,i) => {
145
- if (roleName && i === 0) {
146
- return paint(` ${line} `,roleBadgeColors.get(event.role));
147
- }
148
- return code ? paint(line,code) : line;
149
- })
109
+ if (message && !text) return paintedPrefix();
110
+ const body = fullLine ? bodyText(line => code ? paint(line,code) : line)
150
111
  : code && clippedText ? paint(clippedText, code) : clippedText;
151
- return `${time} ${paint(platform, platformColor)} ${paintedTag}${padding} ${body}`;
112
+ return `${paintedPrefix()}${padding} ${body}`;
152
113
  }
153
114
 
154
115
  export function renderJson(event) {
@@ -23,9 +23,7 @@ function worktreeRoots(output) {
23
23
  return [...new Set(output.split('\0').filter(field => field.startsWith('worktree ')).map(field => realPath(field.slice(9))))];
24
24
  }
25
25
 
26
- export async function resolveScope({mode, dir, session, git}) {
27
- if (mode === 'all') return {kind:'all', roots:[], gitCommonDir:null, description:'All sessions'};
28
- if (mode === 'session') return {kind:'session', roots:[], gitCommonDir:null, description:`Session ${session}`};
26
+ export async function resolveScope({dir, git}) {
29
27
  const root = realPath(dir), top = await git(root, GIT_ALLOWED[0]);
30
28
  if (top !== null) {
31
29
  const common = await git(root, GIT_ALLOWED[1]), trees = await git(root, GIT_ALLOWED[2]);
@@ -45,7 +43,6 @@ export async function refreshScope(scope, git) {
45
43
  }
46
44
 
47
45
  export function inScope(scope, cwd) {
48
- if (scope.kind === 'all' || scope.kind === 'session') return true;
49
46
  let cache = scopeCaches.get(scope);
50
47
  if (!cache) { cache = new Map(); scopeCaches.set(scope, cache); }
51
48
  if (cache.has(cwd)) return cache.get(cwd);
@@ -59,7 +56,6 @@ export function inScope(scope, cwd) {
59
56
  export const normalizeSlug = value => value.replace(/[^A-Za-z0-9]/g, '-');
60
57
 
61
58
  export function claudeDirPrefixes(scope) {
62
- if (scope.kind === 'all' || scope.kind === 'session') return null;
63
59
  const roots = scope.kind === 'repo' ? [...scope.roots, ...scope.excludedRoots ?? []] : scope.roots;
64
60
  return [...new Set(roots.flatMap(root => [normalizeSlug(root), normalizeSlug(realPath(root))]))];
65
61
  }