@yunhozz/arc 0.3.0 → 0.3.2

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.
@@ -4,8 +4,8 @@ export function escapeTerminalText(value=''){
4
4
  const code=character.codePointAt(0);return code<=255?'\\x'+code.toString(16).padStart(2,'0'):'\\u{'+code.toString(16)+'}';
5
5
  });
6
6
  }
7
- function width(character){return /[\p{Mark}]/u.test(character)?0:/[\u2190-\u2193\u2500-\u257f\u2588]/u.test(character)?1:character.codePointAt(0)>=0x1100?2:1;}
8
- function fit(text,columns){let used=0,result='';for(const character of text){const size=width(character);if(used+size>columns)return{text:result,complete:false};result+=character;used+=size;}return{text:result,complete:true};}
7
+ export function cellWidth(character){return /[\p{Mark}]/u.test(character)?0:/[←-↓─-▟✦✧⠀-⣿]/u.test(character)?1:character.codePointAt(0)>=0x1100?2:1;}
8
+ function fit(text,columns){let used=0,result='';for(const character of text){const size=cellWidth(character);if(used+size>columns)return{text:result,complete:false};result+=character;used+=size;}return{text:result,complete:true};}
9
9
  export function navigationHint(mode='menu',{backLabel='back'}={}){
10
10
  if(mode==='text')return'↑/↓: Select · Type/Paste Input · Backspace Delete · Enter Continue · Esc Home';
11
11
  if(mode==='busy')return'Ctrl+C Interrupt';
@@ -14,30 +14,67 @@ export function navigationHint(mode='menu',{backLabel='back'}={}){
14
14
  }
15
15
  export function wrapDetailRows(rows,columns){
16
16
  const available=Math.max(2,Math.floor(Number(columns)||80)-3),result=[];
17
- for(const row of rows){const escaped=escapeTerminalText(row);let line='',used=0;for(const character of escaped){const size=width(character);if(used+size>available){result.push(line);line='';used=0;}line+=character;used+=size;}result.push(line);}
17
+ for(const row of rows){const escaped=escapeTerminalText(row);let line='',used=0;for(const character of escaped){const size=cellWidth(character);if(used+size>available){result.push(line);line='';used=0;}line+=character;used+=size;}result.push(line);}
18
18
  return result;
19
19
  }
20
- const wordmark=[' █████ ███████ ███████ ','██ ██ ██ ██ ██ ','█████████ ███████ ██ ','██ ██ ██ ██ ██ ','██ ██ ██ ██ ███████ '];
21
- const logoStart=Math.min(...wordmark.map(row=>row.indexOf('█'))),logoEnd=Math.max(...wordmark.map(row=>row.lastIndexOf('█')));
22
- const logoStops=[[183,228,199],[116,198,157],[64,145,108]];
23
- function logoColor(column){const position=(column-logoStart)/(logoEnd-logoStart)*2,segment=Math.min(1,Math.floor(position)),fraction=position-segment;return logoStops[segment].map((value,index)=>Math.round(value+(logoStops[segment+1][index]-value)*fraction));}
20
+ const wordmark=[' █████╗ ██████╗ ██████╗','██╔══██╗██╔══██╗██╔════╝','███████║██████╔╝██║ ','██╔══██║██╔══██╗██║ ','██║ ██║██║ ██║╚██████╗','╚═╝ ╚═╝╚═╝ ╚═╝ ╚═════╝'];
21
+ const STATUS_TONES=Object.freeze({'Available':'ok','Not Available':'muted','Unauthorized':'error','Incomplete':'warn'});
22
+ export function statusSpans(row){
23
+ const spans=[];let start=0;for(const segment of escapeTerminalText(row).split(' / ')){const match=/^(.+?): (.+)$/.exec(segment);if(match)spans.push({from:start+[...match[1]].length+2,to:start+[...segment].length,role:Object.hasOwn(STATUS_TONES,match[2])?STATUS_TONES[match[2]]:'warn'});start+=[...segment].length+3;}return spans;
24
+ }
25
+ const TONE_FG={ok:[52,211,153],muted:[128,128,128],error:[248,113,113],warn:[251,191,36]};
26
+ const PANEL=38,STOPS=[[178,245,214],[110,231,183],[52,211,153],[16,185,129]];
27
+ const mix=(from,to,t)=>from.map((value,index)=>Math.round(value+(to[index]-value)*t));
28
+ export function gradientAt(t){const position=Math.max(0,Math.min(1,Number(t)||0))*3,segment=Math.min(2,Math.floor(position));return mix(STOPS[segment],STOPS[segment+1],position-segment);}
29
+ export function shimmerIntensity(column,row,frame){const f=frame%36;if(f>=18)return 0;const c=-4+f*33.5/17,p=column+0.5*row;return Math.max(0,1-Math.abs(p-c)/3)**2;}
30
+ export function wordmarkRows({columns=80,rows=24}={}){return columns-1>=24&&rows>=18?8:2;}
24
31
 
25
32
  export function renderScreen(screen={}, {columns=80,rows=24}={}){
26
33
  // Leave the last column unused to avoid terminal autowrap at the right edge.
27
34
  columns=Math.max(1,Math.floor(Number(columns)||80)-1);rows=Math.max(1,Math.floor(Number(rows)||24));
28
- const entries=screen.rows??[],hint=screen.hint??navigationHint('menu');
29
- const logo=[...wordmark];let divider='─'.repeat(Math.min(columns,34));if(screen.wordmark&&screen.version){const version='ver '+escapeTerminalText(screen.version),inline=logo[logo.length-1]+' '+version;if(fit(inline,columns).complete)logo[logo.length-1]=inline;else divider=version;}
30
- const heading=screen.wordmark?[...logo,divider]:[escapeTerminalText(screen.title)],position=screen.position?[escapeTerminalText(screen.position)]:[];
35
+ const entries=screen.rows??[],hint=screen.hint??navigationHint('menu'),full=wordmarkRows({columns:columns+1,rows})===8;
36
+ const version=screen.version?'ver '+escapeTerminalText(screen.version):'',tagline=' ✦ agent role coordination';
37
+ const fullTag=tagline+(version?' '+version:''),tag=version&&!fit(fullTag,columns).complete?' ✦ '+version:fullTag;
38
+ const frame=screen.frame??0,f=frame%36,sparkleFrame=f>=18?0:f,spinner='⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏'[frame%10];
39
+ const heading=screen.wordmark?[...(full?[...wordmark,tag]:['ARC ✦'+(version?' '+version:'')]),'─'.repeat(Math.min(columns,PANEL))]:[(screen.mode==='busy'?spinner+' ':'')+escapeTerminalText(screen.title)],position=screen.position?[escapeTerminalText(screen.position)]:[];
31
40
  const footer=screen.compactFooter?[]:screen.mode==='busy'||screen.hint==='Session ended'?[escapeTerminalText(hint)]:[...(screen.mode==='text'||screen.mode==='page'?[]:['']),'─'.repeat(columns),escapeTerminalText(hint)];
32
- const showSelection=screen.showSelection!==false;
33
- const lines=[...heading,...entries.map((row,index)=>(index===screen.selected&&showSelection?'> ':' ')+escapeTerminalText(row)),...position,...footer];
34
- const fitted=lines.map(line=>fit(line,columns));
35
- const bodySize=Math.max(0,rows-footer.length),visible=[...fitted.slice(0,Math.min(lines.length-footer.length,bodySize)),...(footer.length?fitted.slice(-Math.min(rows,footer.length)):[])].map(line=>line.text);
36
- const styles=[];
37
- if(screen.wordmark){for(let index=0;index<Math.min(wordmark.length,visible.length);index++){if(visible[index]===fitted[index].text)styles.push({line:index,color:'logo',cells:[...visible[index]].flatMap((character,column)=>character==='█'?[{column,rgb:logoColor(column)}]:[])});}if(visible.length>wordmark.length&&visible[wordmark.length]===fitted[wordmark.length].text)styles.push({line:wordmark.length,color:'green'});}
41
+ const showSelection=screen.showSelection!==false,lines=[...heading,...entries.map((row,index)=>(index===screen.selected&&showSelection?'> ':' ')+escapeTerminalText(row)),...position,...footer];
42
+ const fitted=lines.map(line=>fit(line,columns)),bodySize=Math.max(0,rows-footer.length),bodyEnd=Math.min(lines.length-footer.length,bodySize);
43
+ const indices=[...Array.from({length:bodyEnd},(_,index)=>index),...(footer.length?Array.from({length:Math.min(rows,footer.length)},(_,index)=>lines.length-Math.min(rows,footer.length)+index):[])],visible=indices.map(index=>fitted[index].text),styles=[];
38
44
  const selectedLine=heading.length+screen.selected;
39
- if(showSelection&&Number.isInteger(screen.selected)&&screen.selected>=0&&screen.selected<entries.length&&selectedLine<Math.min(bodySize,lines.length-footer.length)){const used=[...visible[selectedLine]].reduce((sum,character)=>sum+width(character),0);visible[selectedLine]+=' '.repeat(Math.max(0,Math.min(columns,34)-used));styles.push({line:selectedLine,color:'selected'});}
40
-
45
+ for(let line=0;line<visible.length;line++){
46
+ const source=indices[line],runs=[];
47
+ function add(from,to,role,fg,bg,bold){
48
+ to=Math.min(to,[...visible[line]].length);if(from>=to)return;
49
+ const run={from,to,role,...(fg?{fg}:{}),...(bg?{bg}:{}),...(bold?{bold}: {})},last=runs.at(-1);
50
+ if(last&&last.to===from&&last.role===role&&JSON.stringify(last.fg)===JSON.stringify(fg)&&JSON.stringify(last.bg)===JSON.stringify(bg)&&last.bold===run.bold)last.to=to;else runs.push(run);
51
+ }
52
+ const length=[...visible[line]].length;
53
+ if(screen.wordmark&&full&&source<6){for(const [col,character] of [...visible[line]].entries()){if(character===' ')continue;const color=gradientAt((col+0.75*source)/26.75);const intensity=shimmerIntensity(col,source,frame);add(col,col+1,character==='█'?'logo':'shadow',character==='█'?mix(color,[240,255,248],0.7*intensity):mix(color.map(value=>Math.round(value*0.55)),[150,230,200],0.5*intensity));}}
54
+ else if(screen.wordmark&&source===(full?6:0)){
55
+ if(!full)for(let col=0;col<3;col++)add(col,col+1,'logo',mix(gradientAt(col/2),[240,255,248],0.7*shimmerIntensity(col,0,frame)));
56
+ const text=lines[source],sparkle=[...text].indexOf('✦'),versionAt=text.indexOf('ver '),tagAt=text.indexOf('agent role coordination');
57
+ if(sparkle>=0)add(sparkle,sparkle+1,'sparkle',mix([110,231,183],[240,255,248],0.25*(1+Math.sin(2*Math.PI*sparkleFrame/36))));
58
+ if(tagAt>=0)add(tagAt,tagAt+'agent role coordination'.length,'tagline',[134,176,158]);
59
+ if(versionAt>=0)add(versionAt,length,'version',[52,211,153]);
60
+ }
61
+ else if(screen.wordmark&&source===heading.length-1){for(let i=0;i<length;i++){let color=gradientAt(i/(length-1||1));if(i>=0.75*length)color=mix(color,[24,52,42],(i-0.75*length)/(0.25*length));add(i,i+1,'rule',color);}}
62
+ else if(!screen.wordmark&&source===0){if(screen.mode==='busy')add(0,1,'spinner',[52,211,153]);add(screen.mode==='busy'?2:0,length,'title',[110,231,183],undefined,true);}
63
+ else if(source===selectedLine&&showSelection&&Number.isInteger(screen.selected)&&screen.selected>=0&&screen.selected<entries.length&&source<bodyEnd){
64
+ const used=[...visible[line]].reduce((sum,character)=>sum+cellWidth(character),0),padding=Math.max(0,Math.min(columns,PANEL)-used);visible[line]+=' '.repeat(padding);
65
+ add(0,length,'selected',[236,253,245],[6,95,70],true);add(length,length+padding,'selectedPad',undefined,[9,70,53]);
66
+ }
67
+ else if(source>=heading.length&&source<heading.length+entries.length&&screen.rowTones?.[source-heading.length]){
68
+ const tone=screen.rowTones[source-heading.length],text=visible[line].slice(2);
69
+ if(tone==='status')for(const {from,to,role} of screen.rowStatusSpans?.[source-heading.length]??statusSpans(entries[source-heading.length]))add(from+2,to+2,role,TONE_FG[role]);
70
+ else if(tone==='diagnostic'){const separator=text.indexOf(': ');if(separator>=0)add(2+[...text.slice(0,separator+2)].length,length,'warn',TONE_FG.warn);}
71
+ else if(tone==='diagnostic-cont')add(2,length,'warn',TONE_FG.warn);
72
+ }
73
+ else if(position.length&&source===heading.length+entries.length)add(0,length,'position',[110,130,120]);
74
+ else if(footer.length&&source===lines.length-1){let start=0;for(const segment of visible[line].split(/( · )/)){const end=start+[...segment].length;add(start,end,segment===' · '?'hintSep':'hint',segment===' · '?[70,95,85]:[150,170,160]);start=end;}}
75
+ else if(footer.length>1&&source===lines.length-2)add(0,length,'rule',[36,140,106]);
76
+ if(runs.length)styles.push({line,runs});
77
+ }
41
78
  const selectionEnabled=Number.isInteger(screen.selected)&&screen.selected>=0&&screen.selected<entries.length&&selectedLine<rows-footer.length-position.length&&fitted[selectedLine].complete;
42
79
  return{text:visible.join('\n'),selectionEnabled,styles};
43
80
  }
package/lib/tui/setup.mjs CHANGED
@@ -2,7 +2,7 @@ import {parsePositiveLimit} from '../limits.mjs';
2
2
  import {readFileSync} from 'node:fs';
3
3
  import path from 'node:path';
4
4
  import {loadModelConfig,resolveModelSettings,ModelValidationError} from '../models/index.mjs';
5
- import {escapeTerminalText} from './render.mjs';
5
+ import {escapeTerminalText,cellWidth} from './render.mjs';
6
6
  import {editPlatformRoles,editCompositeRoles} from './custom-preset.mjs';
7
7
  import {assertCatalogRoles} from '../models/catalog.mjs';
8
8
  import {ROLES,effortField,validateRoles} from '../models/config.mjs';
@@ -19,7 +19,7 @@ export function loadRoleDefaults({context,statuses,target,readText=filename=>rea
19
19
  }
20
20
  export function presetPreviewRows(roleRows,{columns=80,rows=24,selectedRole,blink=true,compact=false}={}){
21
21
  const values=roleRows.map(({role,model,effort,platform})=>({role:escapeTerminalText(role),model:escapeTerminalText(model),effort:escapeTerminalText(effort),platform:{codex:'Codex',claude:'Claude'}[platform]}));
22
- const cells=value=>[...value].reduce((total,character)=>total+(/[\p{Mark}]/u.test(character)?0:/[\u2190-\u2193\u2500-\u257f\u2588]/u.test(character)?1:character.codePointAt(0)>=0x1100?2:1),0);
22
+ const cells=value=>[...value].reduce((total,character)=>total+cellWidth(character),0);
23
23
  const width=Math.max(20,...values.flatMap(value=>[cells(value.role)+2,cells(value.model),cells('effort: '+value.effort)])),boxWidth=width+4,total=boxWidth*3+4,requiredRows=24;
24
24
  if(columns<total+3||rows<requiredRows){
25
25
  if(compact){
@@ -49,7 +49,7 @@ export function setupOptions(draft,target,verifiedCatalog,kind) {
49
49
  async function editSettings(ui,target,settings) {
50
50
  let selected=0;
51
51
  while(true){
52
- const choice=await ui.menu('Settings — '+label(target),['Language: '+languageLabel(settings.language),'Total subagents: '+settings.maxTotalSubagents,'Concurrent subagents: '+settings.maxConcurrentSubagents,'Global config: '+(settings.skipGlobal?'Off':'On'),'Back'],{selected,separatorBefore:4});
52
+ const choice=await ui.menu('Settings — '+label(target),['Language: '+languageLabel(settings.language),'Total subagents: '+settings.maxTotalSubagents,'Concurrent subagents: '+settings.maxConcurrentSubagents,'Global config: '+(settings.skipGlobal?'Off':'On'),'Back'],{selected});
53
53
  if(choice===null||choice===4)return;selected=choice;
54
54
  if(choice===0){const value=await ui.menu('Language',['EN','KR'],{backRow:true,selected:settings.language==='ko'?1:0});if(value!==null)settings.language=['en','ko'][value];}
55
55
  else if(choice===1||choice===2){
@@ -1,6 +1,23 @@
1
1
  import {StringDecoder} from 'node:string_decoder';
2
2
  import {renderScreen} from './render.mjs';
3
3
 
4
+ const BASIC={logo:'92',shadow:'32',sparkle:'92',tagline:'32',version:'32',rule:'32',title:'1;92',spinner:'32',selected:'42;30',selectedPad:'42',hint:'2',hintSep:'2',position:'2',ok:'32',muted:'2',error:'31',warn:'33'};
5
+ const rgb=color=>[0,1,2].map(index=>Math.max(0,Math.min(255,Math.round(Number(color[index])||0))));
6
+ export function toAnsi256(color){const [r,g,b]=rgb(color);return 16+36*Math.round(r/51)+6*Math.round(g/51)+Math.round(b/51);}
7
+ export function formatLine(line,style,depth){
8
+ if(depth==='none'||!style?.runs?.length)return line;
9
+ const characters=[...line];let result='',end=0,painted=false;
10
+ for(const run of style.runs){
11
+ if(!Object.hasOwn(BASIC,run.role))continue;
12
+ const from=Math.max(end,Math.min(characters.length,run.from)),to=Math.min(characters.length,run.to);if(from>=to)continue;
13
+ if(from>end){if(painted){result+='\x1b[0m';painted=false;}result+=characters.slice(end,from).join('');}
14
+ let params=BASIC[run.role];if(depth!=='16'){const values=run.bold?['1']:[];for(const [key,code] of [['fg',38],['bg',48]])if(run[key])values.push(depth==='truecolor'?code+';2;'+rgb(run[key]).join(';'):code+';5;'+toAnsi256(run[key]));params=values.join(';');}
15
+ if(params){if(painted!==params)result+='\x1b[0;'+params+'m';painted=params;}else if(painted){result+='\x1b[0m';painted=false;}
16
+ result+=characters.slice(from,to).join('');end=to;
17
+ }
18
+ if(painted)result+='\x1b[0m';return result+characters.slice(end).join('');
19
+ }
20
+
4
21
  /** Events are {name, sequence, ...detail}. Names: up/down/left/right, enter,
5
22
  * escape, backspace, text/paste (text), resize (columns,rows), blocked, eof, interrupt
6
23
  * (signal), error (error). Every data chunk gets a sequence; paste is one event.
@@ -15,7 +32,8 @@ export function createTerminalSession({input=process.stdin,output=process.stdout
15
32
  const wasRaw=Boolean(input.isRaw),wasFlowing=input.readableFlowing;
16
33
  const colorEnabled=env.NO_COLOR===undefined&&env.TERM!=='dumb';
17
34
  const truecolor=colorEnabled&&(/^(truecolor|24bit)$/i.test(env.COLORTERM??'')||/^(ghostty|cmux)$/i.test(env.TERM_PROGRAM??'')||/-direct$/.test(env.TERM??'')||(output.getColorDepth?.()??0)>=24);
18
- let disposed=false,busy=false,parsing=false,pending='',paste=null,sequence=0,escapeTimer,waiter,queue=[],screen,lastLines=0,enterEnabled=true;
35
+ const colorDepth=!colorEnabled?'none':truecolor?'truecolor':/256color/i.test(env.TERM??'')||(output.getColorDepth?.()??0)>=8?'256':'16';
36
+ let disposed=false,busy=false,parsing=false,pending='',paste=null,sequence=0,escapeTimer,waiter,queue=[],screen,lastLines=0,lastFrame,enterEnabled=true;
19
37
  let decoder=new StringDecoder('utf8'),lastWasCR=false;
20
38
  const clearTimer=()=>{clearTimeout(escapeTimer);escapeTimer=undefined;};
21
39
  function deliver(name,detail={}){
@@ -37,24 +55,19 @@ export function createTerminalSession({input=process.stdin,output=process.stdout
37
55
  function onError(error){if(!disposed)finish('error',{error});}
38
56
  function onSigint(){if(!disposed)finish('interrupt',{signal:'SIGINT'});}
39
57
  function onSigterm(){if(!disposed)finish('interrupt',{signal:'SIGTERM'});}
40
- function draw(){
58
+ function draw(repaint=false){
41
59
  const result=renderScreen(screen,{columns:output.columns,rows:output.rows});enterEnabled=screen?.mode==='page'||result.selectionEnabled;
42
- if(lastLines)output.write(`\x1b[${lastLines}A\r`);
43
- const lines=result.text.split('\n');
44
- for(let index=0;index<Math.max(lastLines,lines.length);index++){
45
- let line=lines[index]??'';const style=result.styles.find(style=>style.line===index);
46
- if(style&&colorEnabled){
47
- if(style.color==='logo'&&truecolor){const cells=new Map(style.cells.map(cell=>[cell.column,cell.rgb]));line=[...line].map((character,column)=>cells.has(column)?'\x1b[38;2;'+cells.get(column).join(';')+'m'+character+'\x1b[0m':character).join('');}
48
- else{const color=style.color==='logo'?'\x1b[92m':style.color==='selected'?(truecolor?'\x1b[48;2;16;55;26m\x1b[38;2;220;245;224m':'\x1b[42;30m'):'\x1b[32m';line=color+line+'\x1b[0m';}
49
- }
50
- output.write('\x1b[2K'+line+'\n');
51
- }
52
-
53
- if(lastLines>lines.length)output.write(`\x1b[${lastLines-lines.length}A\r`);
54
- lastLines=lines.length;return result;
60
+ const lines=result.text.split('\n'),frame=lines.map((line,index)=>'\x1b[2K'+formatLine(line,result.styles.find(style=>style.line===index),colorDepth)+'\n').join('');
61
+ if(repaint&&lastFrame===frame&&lastLines===lines.length)return result;
62
+ let outputFrame=lastLines?`\x1b[${lastLines}A\r`:'';
63
+ outputFrame+=frame+'\x1b[2K\n'.repeat(Math.max(0,lastLines-lines.length));
64
+ if(lastLines>lines.length)outputFrame+=`\x1b[${lastLines-lines.length}A\r`;
65
+ output.write('\x1b[?2026h'+outputFrame+'\x1b[?2026l');
66
+ lastFrame=frame;lastLines=lines.length;return result;
55
67
  }
56
68
  function render(value){if(disposed)return{selectionEnabled:false,text:''};discardInput();screen=value;try{return draw();}catch(error){dispose();throw error;}}
57
- function onResize(){if(disposed)return;discardInput();try{if(screen)draw();deliver('resize',{columns:output.columns,rows:output.rows});}catch(error){onError(error);}}
69
+ function repaint(value){if(disposed)return{selectionEnabled:false,text:''};screen=value;try{return draw(true);}catch(error){dispose();throw error;}}
70
+ function onResize(){if(disposed)return;lastFrame=undefined;discardInput();try{if(screen)draw();deliver('resize',{columns:output.columns,rows:output.rows});}catch(error){onError(error);}}
58
71
  function parse(){
59
72
  while(pending&&!disposed){
60
73
  if(paste!==null){const end=pending.indexOf('\x1b[201~');if(end<0){const tail=pending.lastIndexOf('\x1b');if(tail<0){paste+=pending;pending='';}else{paste+=pending.slice(0,tail);pending=pending.slice(tail);}return;}paste+=pending.slice(0,end);pending=pending.slice(end+6);deliver('paste',{text:paste});paste=null;continue;}
@@ -77,5 +90,5 @@ export function createTerminalSession({input=process.stdin,output=process.stdout
77
90
  function onData(chunk){if(disposed||busy)return;sequence++;clearTimer();pending+=typeof chunk==='string'?chunk:decoder.write(chunk);parsing=true;try{parse();}finally{parsing=false;if(waiter&&queue.length){const resolve=waiter;waiter=undefined;resolve(queue.shift());}}}
78
91
  input.on('data',onData);input.on('end',onEnd);input.on('close',onEnd);input.on('error',onError);output.on('resize',onResize);output.on('error',onError);signals.on('SIGINT',onSigint);signals.on('SIGTERM',onSigterm);
79
92
  try{input.setRawMode?.(true);input.resume();output.write('\x1b[?25l\x1b[?2004h');}catch(error){dispose();throw error;}
80
- return{render,discardInput,dispose,viewport(){return{columns:output.columns??80,rows:output.rows??24};},setBusy(value){busy=Boolean(value);discardInput();},nextEvent(){if(queue.length)return Promise.resolve(queue.shift());if(disposed)return Promise.resolve({name:'eof',sequence});if(waiter)return Promise.reject(Error('Only one terminal event reader is allowed.'));return new Promise(resolve=>{waiter=resolve;});}};
93
+ return{render,repaint,frameMs:env.TERM==='dumb'?0:80,discardInput,dispose,viewport(){return{columns:output.columns??80,rows:output.rows??24};},setBusy(value){busy=Boolean(value);discardInput();},nextEvent(){if(queue.length)return Promise.resolve(queue.shift());if(disposed)return Promise.resolve({name:'eof',sequence});if(waiter)return Promise.reject(Error('Only one terminal event reader is allowed.'));return new Promise(resolve=>{waiter=resolve;});}};
81
94
  }
@@ -28,11 +28,13 @@ Output:
28
28
 
29
29
  User and agent messages are shown in full; other events use one line.
30
30
  Tool and command outputs are never shown; common secret patterns are masked.
31
+ A spinner on the last line shows while a turn is in progress (TTY only).
31
32
  Codex Desktop sessions are not included.
32
33
  Bridge roles on a Codex host are currently held (host_sandbox_blocked) and appear once they run.
33
- Press Ctrl-C to stop.`;
34
+ Press Ctrl-L to clear the screen (TTY only) and Ctrl-C to stop.`;
34
35
 
35
36
  export async function runWatch(argv, io = {}) {
37
+ const input = io.input ?? process.stdin;
36
38
  const output = io.output ?? process.stdout, error = io.error ?? process.stderr;
37
39
  const cwd = io.cwd ?? process.cwd(), env = io.env ?? process.env;
38
40
  // Resolve relative --cwd without changing the process cwd shared by other callers.
@@ -56,13 +58,31 @@ export async function runWatch(argv, io = {}) {
56
58
  const now = io.now ?? Date.now, git = io.git ?? createGitRunner({env});
57
59
  const proc = io.process ?? process, schedule = io.setInterval ?? setInterval, unschedule = io.clearInterval ?? clearInterval;
58
60
  let width, watcher, timer, stopped = false, active;
61
+ const color = Boolean(output.isTTY && !options.json && !env.NO_COLOR);
62
+ const spinnerEnabled = Boolean(output.isTTY && !options.json);
63
+ const keysEnabled = Boolean(input.isTTY && output.isTTY && !options.json && typeof input.setRawMode === 'function');
64
+ const frames = ['⠋','⠙','⠹','⠸','⠼','⠴','⠦','⠧','⠇','⠏'];
65
+ let spinnerDrawn = false, frame = 0;
66
+ const eraseSpinner = () => {
67
+ if (!spinnerDrawn) return;
68
+ spinnerDrawn = false;
69
+ output.write('\r\x1b[2K');
70
+ };
59
71
  const resize = () => { width = options.width ?? (output.isTTY ? Math.max(L.ttyWidthMin, output.columns || L.ttyWidthMin) : L.nonTtyWidth); };
60
72
  resize();
61
73
  return new Promise(resolve => {
62
74
  const signals = ['SIGINT','SIGTERM','SIGHUP'];
75
+ let rawModeEnabled = false;
63
76
  const stop = (code = 0, cause) => {
64
77
  if (stopped) return;
65
78
  stopped = true;
79
+ if (rawModeEnabled) {
80
+ rawModeEnabled = false;
81
+ input.removeListener('data', onKey);
82
+ try { input.setRawMode(false); } catch {}
83
+ input.pause();
84
+ }
85
+ eraseSpinner();
66
86
  if (timer !== undefined) unschedule(timer);
67
87
  for (const signal of signals) proc.removeListener(signal, onSignal);
68
88
  io.signal?.removeEventListener('abort', onSignal);
@@ -78,11 +98,33 @@ export async function runWatch(argv, io = {}) {
78
98
  };
79
99
  const onSignal = () => stop();
80
100
  const onError = cause => stop(cause.code === 'EPIPE' ? 0 : 1, cause);
101
+ const drawSpinner = () => {
102
+ if (!stopped && spinnerEnabled && watcher?.busy?.()) {
103
+ const text = `${frames[frame]} working…`;
104
+ frame = (frame + 1) % frames.length;
105
+ spinnerDrawn = true;
106
+ output.write(color ? `\x1b[2m${text}\x1b[0m` : text);
107
+ }
108
+ };
109
+ const onKey = chunk => {
110
+ for (const byte of Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)) {
111
+ if (stopped) break;
112
+ if (byte === 0x03) stop();
113
+ else if (byte === 0x0c) {
114
+ output.write('\x1b[H\x1b[2J\x1b[3J');
115
+ spinnerDrawn = false;
116
+ drawSpinner();
117
+ }
118
+ }
119
+ };
81
120
  const write = events => {
121
+ if (stopped) return;
122
+ eraseSpinner();
82
123
  for (const event of events) {
83
124
  if (stopped) break;
84
- output.write((options.json ? renderJson(event) : renderHuman(event,{width,color:Boolean(output.isTTY && !options.json && !env.NO_COLOR),verbose:options.verbose})) + '\n');
125
+ output.write((options.json ? renderJson(event) : renderHuman(event,{width,color,verbose:options.verbose})) + '\n');
85
126
  }
127
+ drawSpinner();
86
128
  };
87
129
  for (const signal of signals) proc.on(signal, onSignal);
88
130
  output.on('error', onError);
@@ -90,6 +132,12 @@ export async function runWatch(argv, io = {}) {
90
132
  io.signal?.addEventListener('abort', onSignal, {once:true});
91
133
  let ticking = false;
92
134
  active = (async () => {
135
+ if (keysEnabled) {
136
+ rawModeEnabled = true;
137
+ input.setRawMode(true);
138
+ input.resume();
139
+ input.on('data', onKey);
140
+ }
93
141
  const scope = await resolveScope({mode:options.mode,dir:options.dir ?? cwd,session:options.session,git});
94
142
  if (stopped) return;
95
143
  watcher = createWatcher({options,homes,scope,git,now});
@@ -1,4 +1,4 @@
1
- export const WATCH_KINDS = Object.freeze(['session','settings','turn_start','turn_end','turn_failed','user','agent','reasoning','command','tool','tool_failed','file_change','spawn','approval','dispatch','error','other','notice']);
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','spawn','approval','dispatch','error','other','notice']);
2
2
  export const MESSAGE_KINDS = Object.freeze(['user','agent']);
3
3
  export const VERBOSE_KINDS = Object.freeze(['settings','turn_start','reasoning','other']);
4
4
  export const ROLE_NAMES = Object.freeze(['scouter','planner','implementer','qa','reviewer']);
@@ -11,7 +11,7 @@ export const WATCH_LIMITS = Object.freeze({
11
11
  claudeCwdWaitMs:10000, codexMetaBytes:4194304, lookbackDays:7,
12
12
  jsonTextMax:1000, agentNameMax:20, pathsMax:20, toolCacheMax:512, defaultTail:20,
13
13
  maxTail:1000, widthMin:40, widthMax:2000, ttyWidthMin:60, nonTtyWidth:200,
14
- gitTimeoutMs:10000,
14
+ gitTimeoutMs:10000, spinnerIdleMs:300000,
15
15
  });
16
16
 
17
17
  /**
@@ -31,7 +31,7 @@ export const WATCH_LIMITS = Object.freeze({
31
31
  * @property {'scouter'|'planner'|'implementer'|'qa'|'reviewer'|'orchestrator'} [role]
32
32
  * @property {string} [dispatchId]
33
33
  * @property {string} [workflowId]
34
- * @property {'session'|'settings'|'turn_start'|'turn_end'|'turn_failed'|'user'|'agent'|'reasoning'|'command'|'tool'|'tool_failed'|'file_change'|'spawn'|'approval'|'dispatch'|'error'|'other'|'notice'} kind
34
+ * @property {'session'|'settings'|'turn_start'|'turn_end'|'turn_failed'|'user'|'agent'|'reasoning'|'command'|'tool'|'tool_failed'|'file_change'|'file_create'|'spawn'|'approval'|'dispatch'|'error'|'other'|'notice'} kind
35
35
  * @property {string} [text] Sanitized, masked text; user/agent preserve newlines without a length cap. Other JSON text is capped at 1000 code points.
36
36
  * @property {boolean} [truncated]
37
37
  * @property {number} [exitCode]
@@ -4,7 +4,7 @@ const object = value => value !== null && typeof value === 'object' && !Array.is
4
4
  const string = value => typeof value === 'string';
5
5
 
6
6
  export function createClaudeState() {
7
- return {modelSeen:false, tools:new Map()};
7
+ return {modelSeen:false, tools:new Map(), writes:new Map()};
8
8
  }
9
9
 
10
10
  export function parseClaudeHead(obj) {
@@ -31,11 +31,12 @@ function userText(content) {
31
31
  return text.replace(/<(system-reminder|command-[\w-]+|local-command-[\w-]+|task-notification|bash-input|bash-stdout|bash-stderr)\b[^>]*>[\s\S]*?(?:<\/\1\s*>|$)/gi, '');
32
32
  }
33
33
 
34
- /** State contains only the first-model flag and a bounded tool-name cache. */
34
+ /** State contains the first-model flag and bounded tool-name and pending-Write caches. */
35
35
  export function normalizeClaudeLine(obj, state) {
36
36
  try {
37
37
  if (!object(obj) || !['user','assistant'].includes(obj.type) || !object(obj.message)) return [];
38
38
  if (!object(state) || !(state.tools instanceof Map)) return [];
39
+ if (!(state.writes instanceof Map)) state.writes = new Map();
39
40
  const events = [];
40
41
  const emit = (kind, fields={}) => {
41
42
  const event = {kind, ...fields};
@@ -53,14 +54,22 @@ export function normalizeClaudeLine(obj, state) {
53
54
  }
54
55
  // Results never contribute text, even when the line also has toolUseResult.
55
56
  for (const block of blocks) {
56
- if (block?.type === 'tool_result' && block.is_error === true) {
57
- const tool = state.tools.get(block.tool_use_id);
57
+ if (block?.type !== 'tool_result') continue;
58
+ const id = block.tool_use_id, pending = state.writes.has(id), path = state.writes.get(id);
59
+ state.writes.delete(id);
60
+ if (block.is_error === true) {
61
+ const tool = state.tools.get(id);
58
62
  emit('tool_failed', string(tool) ? {tool} : {});
63
+ } else if (pending) {
64
+ const result = obj.toolUseResult;
65
+ const paths = [...new Set([string(result?.filePath) ? result.filePath : path].filter(string))].slice(0,WATCH_LIMITS.pathsMax);
66
+ emit(result?.type === 'create' ? 'file_create' : 'file_change', {paths});
59
67
  }
60
68
  }
61
69
  if (!obj.isMeta && !Object.hasOwn(obj, 'toolUseResult')) {
62
70
  const text = userText(message.content);
63
- if (text.trim()) emit('user', {text});
71
+ if (/^\[Request interrupted by user(?: for tool use)?\]$/.test(text.trim())) emit('turn_end', {text:'interrupted by user'});
72
+ else if (text.trim()) emit('user', {text});
64
73
  }
65
74
  return events;
66
75
  }
@@ -81,7 +90,13 @@ export function normalizeClaudeLine(obj, state) {
81
90
  }
82
91
  const input = object(block.input) ? block.input : {};
83
92
  if (name === 'Bash') emit('command', string(input.command) ? {text:input.command} : {});
84
- else if (['Edit','MultiEdit','Write','NotebookEdit'].includes(name)) {
93
+ else if (name === 'Write') {
94
+ if (string(block.id)) {
95
+ state.writes.delete(block.id);
96
+ state.writes.set(block.id, string(input.file_path) ? input.file_path : undefined);
97
+ while (state.writes.size > WATCH_LIMITS.toolCacheMax) state.writes.delete(state.writes.keys().next().value);
98
+ }
99
+ } else if (['Edit','MultiEdit','NotebookEdit'].includes(name)) {
85
100
  emit('file_change', {paths:[...new Set([input.file_path,input.notebook_path].filter(string))].slice(0,WATCH_LIMITS.pathsMax)});
86
101
  } else if (['Agent','Task'].includes(name)) {
87
102
  const agent = string(input.subagent_type) ? input.subagent_type : '';
@@ -42,6 +42,24 @@ function changePaths(changes) {
42
42
  return [...new Set(strings(paths))].slice(0, WATCH_LIMITS.pathsMax);
43
43
  }
44
44
 
45
+ function splitChangePaths(changes) {
46
+ const added = [], changed = [];
47
+ const isAdd = change => object(change) && (change.type === 'add' || change.kind?.type === 'add' || Object.hasOwn(change,'add'));
48
+ if (Array.isArray(changes)) {
49
+ for (const change of changes) {
50
+ (isAdd(change) ? added : changed).push(change?.path, change?.file);
51
+ changed.push(change?.move_path);
52
+ }
53
+ } else if (object(changes)) {
54
+ for (const [path, change] of Object.entries(changes)) {
55
+ (isAdd(change) ? added : changed).push(path);
56
+ changed.push(change?.move_path);
57
+ }
58
+ }
59
+ const unique = paths => [...new Set(strings(paths))].slice(0,WATCH_LIMITS.pathsMax);
60
+ return {added:unique(added),changed:unique(changed)};
61
+ }
62
+
45
63
  /** Normalize one parsed rollout line; no I/O or transcript state. */
46
64
  export function normalizeCodexLine(obj) {
47
65
  try {
@@ -86,7 +104,11 @@ export function normalizeCodexLine(obj) {
86
104
  }
87
105
  case 'CommandExecution': return emit('command', {text:commandText(item.command), exitCode:Number.isFinite(item.exit_code) ? item.exit_code : undefined});
88
106
  case 'FileChange':
89
- case 'PatchApply': return emit('file_change', {paths:changePaths(item.changes)});
107
+ case 'PatchApply': {
108
+ const {added,changed} = splitChangePaths(item.changes);
109
+ if (!added.length) return emit('file_change', {paths:changePaths(item.changes)});
110
+ return [...emit('file_create', {paths:added}), ...(changed.length ? emit('file_change', {paths:changed}) : [])];
111
+ }
90
112
  case 'McpToolCall': return emit('tool', {tool:strings([item.server,item.tool]).join('.')});
91
113
  case 'Extension':
92
114
  return item.kind === 'web.search' ? emit('tool', {tool:'web.search', text:text(item.query)}) : emit('other', {text:`Extension:${text(item.kind) ?? ''}`});
@@ -1,14 +1,33 @@
1
+ import path from 'node:path';
1
2
  import {WATCH_LIMITS, MESSAGE_KINDS} from './model.mjs';
2
3
  import {sanitizeText, sanitizeMessage, clipCodePoints} from './policy.mjs';
4
+ import {realPath} from './scope.mjs';
3
5
 
4
6
  export const PLATFORM_COLORS = Object.freeze({codex:'36', claude:'38;5;208', other:'2'});
5
7
 
8
+ // Compare both the lexical root and its real path (e.g. /tmp and /private/tmp).
9
+ export function displayPath(file, root) {
10
+ if (!root || !path.isAbsolute(root) || !path.isAbsolute(file)) return file;
11
+ for (const base of [path.resolve(root), realPath(root)]) {
12
+ if (file === base || file.startsWith(base.endsWith(path.sep) ? base : base + path.sep)) {
13
+ const relative = path.relative(base,file).split(path.sep).join('/');
14
+ return path.basename(root) + (relative ? '/' + relative : '');
15
+ }
16
+ }
17
+ return file;
18
+ }
19
+
6
20
  export function tagColor(event) {
7
21
  if (event.kind === 'command') return event.exitCode == null || event.exitCode === 0 ? '38;5;242' : '31';
8
- return ({user:'1;35', agent:'32', file_change:'33', tool:'38;5;250', spawn:'38;5;141',
22
+ return ({user:'1;35', agent:'32', file_change:'33', file_create:'38;5;69', tool:'2', spawn:'38;5;141',
9
23
  dispatch:'38;5;137', approval:'1;4', turn_failed:'31', error:'31', tool_failed:'31'})[event.kind] ?? '2';
10
24
  }
11
25
 
26
+ export function bodyColor(event) {
27
+ const code = tagColor(event);
28
+ return code.startsWith('38;5;') ? code : code.split(';').filter(value => value !== '1' && value !== '4').join(';');
29
+ }
30
+
12
31
  export function kindTag(event) {
13
32
  if (event.kind === 'agent') {
14
33
  const name = event.role || (event.source === 'subagent' && event.label?.includes('/') ? event.label.split('/').at(-1) : '');
@@ -18,7 +37,7 @@ export function kindTag(event) {
18
37
  if (event.kind === 'command') return event.exitCode == null ? 'CMD' : `CMD(${event.exitCode})`;
19
38
  return ({session:'SESSION', settings:'SETTINGS', turn_start:'TURN', turn_end:'END',
20
39
  turn_failed:'FAIL', user:'USER', agent:'AGENT', reasoning:'THINK', tool:'TOOL',
21
- tool_failed:'TOOL!', file_change:'EDIT', spawn:'SPAWN', approval:'APPROVE',
40
+ tool_failed:'TOOL!', file_change:'EDIT', file_create:'CREATE', spawn:'SPAWN', approval:'APPROVE',
22
41
  dispatch:'DISPATCH', error:'ERROR', other:'ITEM', notice:'NOTICE'})[event.kind] ?? 'ITEM';
23
42
  }
24
43
 
@@ -26,8 +45,8 @@ function eventText(event, verbose) {
26
45
  if (event.kind === 'tool' || event.kind === 'tool_failed') {
27
46
  return [event.tool, event.text].map(sanitizeText).filter(Boolean).join(' ');
28
47
  }
29
- if (event.kind === 'file_change') {
30
- return [event.text, ...(event.paths ?? [])].map(sanitizeText).filter(Boolean).join(' ');
48
+ if (event.kind === 'file_change' || event.kind === 'file_create') {
49
+ return [event.text, ...(event.paths ?? []).map(file => displayPath(file,event.root))].map(sanitizeText).filter(Boolean).join(' ');
31
50
  }
32
51
  if (event.kind !== 'dispatch') return sanitizeText(event.text);
33
52
  return sanitizeText([event.state, event.route, event.workflowId,
@@ -43,18 +62,21 @@ export function renderHuman(event, {width, color, verbose}) {
43
62
  const tag = sanitizeText(kindTag(event)).padEnd(8);
44
63
  const prefix = `${time} ${platform} ${tag} `;
45
64
  const message = MESSAGE_KINDS.includes(event.kind);
65
+ const fullLine = message || event.kind === 'file_change' || event.kind === 'file_create';
46
66
  const text = message ? sanitizeMessage(event.text) : eventText(event, verbose);
47
67
  const messageBody = text.split('\n').map((line, i) => !line ? '' : (i ? ' '.repeat([...prefix].length) : '') + line).join('\n');
48
- const plain = message ? (text ? prefix + messageBody : prefix.trimEnd()) : clipCodePoints(prefix + text, width).text;
49
- if (!color || (!message && [...prefix].length > width)) return plain;
50
- const failure = ['turn_failed','tool_failed','error'].includes(event.kind) || (event.kind === 'command' && event.exitCode != null && event.exitCode !== 0);
68
+ const plain = message ? (text ? prefix + messageBody : prefix.trimEnd()) : fullLine ? prefix + text : clipCodePoints(prefix + text, width).text;
69
+ if (!color || (!fullLine && [...prefix].length > width)) return plain;
70
+ const code = bodyColor(event);
51
71
  const paint = (value, code) => `\x1b[${code}m${value}\x1b[0m`;
52
72
  const platformColor = event.source === 'watch' ? PLATFORM_COLORS.other : PLATFORM_COLORS[event.platform] ?? PLATFORM_COLORS.other;
53
73
  const paintedTag = paint(tag.trimEnd(), tagColor(event));
54
74
  const padding = tag.slice(tag.trimEnd().length);
55
75
  const clippedText = message ? messageBody : [...plain].slice([...prefix].length).join('');
56
76
  if (message && !text) return `${time} ${paint(platform, platformColor)} ${paintedTag}`;
57
- return `${time} ${paint(platform, platformColor)} ${paintedTag}${padding} ${failure && clippedText ? paint(clippedText, 31) : clippedText}`;
77
+ const body = message ? text.split('\n').map((line, i) => !line ? '' : (i ? ' '.repeat([...prefix].length) : '') + (code ? paint(line, code) : line)).join('\n')
78
+ : code && clippedText ? paint(clippedText, code) : clippedText;
79
+ return `${time} ${paint(platform, platformColor)} ${paintedTag}${padding} ${body}`;
58
80
  }
59
81
 
60
82
  export function renderJson(event) {
@@ -5,7 +5,7 @@ import {GIT_ALLOWED} from './git.mjs';
5
5
  const scopeCaches = new WeakMap();
6
6
 
7
7
  // Resolve the existing ancestor too: a transcript cwd can name a deleted child.
8
- function realPath(file) {
8
+ export function realPath(file) {
9
9
  let current = path.resolve(file);
10
10
  const suffix = [];
11
11
  for (;;) {
@@ -6,7 +6,7 @@ import {topLabel, childLabel, dispatchLabel, roleFromName} from './labels.mjs';
6
6
  import {normalizeCodexLine} from './normalize-codex.mjs';
7
7
  import {createClaudeState, normalizeClaudeLine, parseClaudeAgentMeta} from './normalize-claude.mjs';
8
8
  import {createTail, readTail, readHead} from './tail.mjs';
9
- import {refreshScope, inScope, claudeDirPrefixes} from './scope.mjs';
9
+ import {refreshScope, inScope, claudeDirPrefixes, realPath} from './scope.mjs';
10
10
  import {listCodexRollouts, readCodexMeta} from './discover-codex.mjs';
11
11
  import {createClaudeDiscovery, readClaudeHead} from './discover-claude.mjs';
12
12
  import {createDispatchIndex} from './dispatch.mjs';
@@ -24,6 +24,7 @@ export function createWatcher({options, homes, scope: initialScope, git, now, de
24
24
  const followed = new Map(), pending = new Map(), ignored = new Map(), detached = new Map();
25
25
  const seenAtStart = new Map(), heads = new Map(), metas = new Map(), agentMetas = new Map(), childLists = new Map();
26
26
  const compressed = new Set(), missingDispatch = new Set(), repos = new Map();
27
+ const rootsByCwd = new Map();
27
28
  const dispatch = dispatchIndex({codexHome:homes.codex});
28
29
  const claude = homes.claude ? claudeDiscovery({claudeHome:homes.claude}) : null;
29
30
  const stamp = () => new Date(now()).toISOString();
@@ -57,6 +58,7 @@ export function createWatcher({options, homes, scope: initialScope, git, now, de
57
58
  v:1, observedAt:stamp(), platform:row.platform,
58
59
  source:ref ? 'bridge' : parent ? 'subagent' : 'session',
59
60
  origin:row.origin, sessionId:row.id, label:label(row), cwd:row.cwd,
61
+ ...(row.root ? {root:row.root} : {}),
60
62
  ...(row.parentId ? {parentId:row.parentId,depth:row.depth ?? (parent?.depth ?? 0)+1} : {}),
61
63
  ...(ref ? {dispatchId:ref.dispatchId, ...(ref.workflowId ? {workflowId:ref.workflowId} : {}), ...(ref.role ? {role:ref.role} : {})} : {}),
62
64
  ...(!ref && roleFromName(row.agent?.agentRole ?? row.agent?.agentType) ? {role:roleFromName(row.agent.agentRole ?? row.agent.agentType)} : {}),
@@ -72,6 +74,8 @@ export function createWatcher({options, homes, scope: initialScope, git, now, de
72
74
  for (const line of lines) {
73
75
  const events = row.platform === 'codex' ? normalizeCodexLine(line) : normalizeClaudeLine(line,row.state);
74
76
  for (const e of events) {
77
+ if (['turn_end','turn_failed'].includes(e.kind)) row.active = false;
78
+ else if (['turn_start','user','agent','reasoning','command','tool','tool_failed','file_change','file_create','spawn','approval'].includes(e.kind)) row.active = true;
75
79
  if (!isVisible(e.kind,verbose) || (e.kind === 'notice' && !verbose)) continue;
76
80
  out.push(clean({...identity(row),...e,ts:e.ts ?? stamp(),...(e.kind === 'session' ? {text:sessionText(row)} : {})}));
77
81
  }
@@ -123,17 +127,32 @@ export function createWatcher({options, homes, scope: initialScope, git, now, de
123
127
  let history;
124
128
  try { history = previous ? {endOffset:previous.offset} : await readTail(row.file); }
125
129
  catch (error) { debug(out,`session file unreadable: ${row.id.slice(0,8)} (${error.code ?? 'error'})`); ignored.set(row.file,row.size); return; }
130
+ row.root = await sessionRoot(row.cwd);
126
131
  row.tail=createTail(row.file,{offset:previous?.offset ?? history.endOffset});
127
- row.state=createClaudeState(); row.held=[]; row.lastActivity=row.mtimeMs;
132
+ row.state=createClaudeState(); row.active=false; row.held=[]; row.lastActivity=row.mtimeMs;
128
133
  followed.set(row.id,row); pending.delete(row.file); detached.delete(row.file);
129
134
  if (!startup && !previous && !mapped(row) && (row.origin==='codex_exec'||row.platform==='claude') && now()-row.mtimeMs<=L.holdCreatedWithinMs) row.holdUntil=now()+L.holdMs;
130
135
  const showHistory = startup ? tailCount > 0 && now()-row.mtimeMs<=L.historyWindowMs : !previous;
136
+ const events=history.lines ? normalize(row,history.lines) : [];
131
137
  if (showHistory) {
132
- const events=normalize(row,history.lines);
133
138
  if (!events.some(e=>e.kind==='session')) events.unshift(clean({...identity(row),ts:events[0]?.ts??stamp(),kind:'session',text:sessionText(row)}));
134
139
  emit(row,events,out);
135
140
  }
136
141
  }
142
+ async function sessionRoot(cwd) {
143
+ if (!cwd) return undefined;
144
+ try {
145
+ const matches = (scope.roots ?? []).filter(root => inScope({kind:'dir',roots:[root]},cwd));
146
+ if (matches.length) return matches.sort((a,b) => Math.max(path.resolve(b).length,realPath(b).length) - Math.max(path.resolve(a).length,realPath(a).length))[0];
147
+ if (rootsByCwd.has(cwd)) return rootsByCwd.get(cwd);
148
+ let root = cwd;
149
+ try { root = (await git(cwd,GIT_ALLOWED[0]))?.trim() || cwd; }
150
+ catch { /* A missing repository still has a useful cwd root. */ }
151
+ if (rootsByCwd.size >= L.maxRepos) rootsByCwd.delete(rootsByCwd.keys().next().value);
152
+ rootsByCwd.set(cwd,root);
153
+ return root;
154
+ } catch { return cwd; }
155
+ }
137
156
  function rememberStart(item, startup) {
138
157
  if (startup) seenAtStart.set(item.file,{...item,offset:item.size});
139
158
  }
@@ -299,7 +318,7 @@ export function createWatcher({options, homes, scope: initialScope, git, now, de
299
318
  debug(out,`session file unreadable: ${row.id.slice(0,8)} (${error.code??'error'})`);continue;
300
319
  }
301
320
  if (result.gone) {followed.delete(id);debug(out,`session file removed: ${row.id.slice(0,8)}`);continue;}
302
- if (result.reset) {row.state=createClaudeState();debug(out,`session restarted from the beginning: ${row.id.slice(0,8)}`);}
321
+ if (result.reset) {row.state=createClaudeState();row.active=false;debug(out,`session restarted from the beginning: ${row.id.slice(0,8)}`);}
303
322
  if (result.overflowed && !row.overflowed) debug(out,`line over 4 MiB skipped in ${row.id.slice(0,8)}`);
304
323
  row.overflowed=result.overflowed;
305
324
  if (row.tail.offset!==row.size) row.lastActivity=now();
@@ -332,6 +351,7 @@ export function createWatcher({options, homes, scope: initialScope, git, now, de
332
351
  await poll(out);
333
352
  return markEmitted(sort(out));
334
353
  },
354
+ busy() {return [...followed.values()].some(row=>row.active && now()-row.lastActivity<=L.spinnerIdleMs);},
335
355
  async close() {closed=true;followed.clear();pending.clear();},
336
356
  };
337
357
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yunhozz/arc",
3
- "version": "0.3.0",
3
+ "version": "0.3.2",
4
4
  "publishConfig": {
5
5
  "access": "public",
6
6
  "registry": "https://registry.npmjs.org/"