mlai-code 0.3.6 → 0.3.8

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.
package/src/tui/ansi.mjs CHANGED
@@ -10,8 +10,15 @@ export const strip=s=>String(s??'').replace(SGR,'');
10
10
  /** Zero-width code points: combining marks, variation selectors, zero-width joiners. */
11
11
  const ZERO=/[\u0300-\u036f\u0483-\u0489\u0591-\u05bd\u0610-\u061a\u064b-\u065f\u0e31\u0e34-\u0e3a\u1ab0-\u1aff\u1dc0-\u1dff\u200b-\u200f\u20d0-\u20ff\ufe00-\ufe0f\ufe20-\ufe2f]/u;
12
12
  function wide(cp){
13
- return cp>=0x1100&&(cp<=0x115f||cp===0x2329||cp===0x232a||(cp>=0x2e80&&cp<=0x303e)||(cp>=0x3041&&cp<=0x33ff)||(cp>=0x3400&&cp<=0x4dbf)||(cp>=0x4e00&&cp<=0x9fff)||(cp>=0xa000&&cp<=0xa4cf)||(cp>=0xac00&&cp<=0xd7a3)||(cp>=0xf900&&cp<=0xfaff)||(cp>=0xfe30&&cp<=0xfe4f)||(cp>=0xff00&&cp<=0xff60)||(cp>=0xffe0&&cp<=0xffe6)||(cp>=0x1f300&&cp<=0x1f64f)||(cp>=0x1f900&&cp<=0x1f9ff)||(cp>=0x20000&&cp<=0x3fffd));
13
+ return cp>=0x1100&&(cp<=0x115f||cp===0x2329||cp===0x232a||(cp>=0x2e80&&cp<=0x303e)||(cp>=0x3041&&cp<=0x33ff)||(cp>=0x3400&&cp<=0x4dbf)||(cp>=0x4e00&&cp<=0x9fff)||(cp>=0xa000&&cp<=0xa4cf)||(cp>=0xac00&&cp<=0xd7a3)||(cp>=0xf900&&cp<=0xfaff)||(cp>=0xfe30&&cp<=0xfe4f)||(cp>=0xff00&&cp<=0xff60)||(cp>=0xffe0&&cp<=0xffe6)||(cp>=0x1f300&&cp<=0x1f64f)||(cp>=0x1f680&&cp<=0x1f6ff)||(cp>=0x1f7e0&&cp<=0x1f7eb)||(cp>=0x1f900&&cp<=0x1f9ff)||(cp>=0x1fa70&&cp<=0x1faff)||(cp>=0x20000&&cp<=0x3fffd)||EMOJI_WIDE.has(cp));
14
14
  }
15
+ /** Symbols below U+1F300 that terminals draw two columns wide (East Asian Width W: ✅ ⭐ ⌛ ❌ ☕ ...). */
16
+ const EMOJI_WIDE=new Set([0x231a,0x231b,0x23e9,0x23ea,0x23eb,0x23ec,0x23f0,0x23f3,0x25fd,0x25fe,0x2614,0x2615,
17
+ 0x2648,0x2649,0x264a,0x264b,0x264c,0x264d,0x264e,0x264f,0x2650,0x2651,0x2652,0x2653,0x267f,0x2693,0x26a1,0x26aa,0x26ab,
18
+ 0x26bd,0x26be,0x26c4,0x26c5,0x26ce,0x26d4,0x26ea,0x26f2,0x26f3,0x26f5,0x26fa,0x26fd,0x2705,0x270a,0x270b,0x2728,0x274c,
19
+ 0x274e,0x2753,0x2754,0x2755,0x2757,0x2795,0x2796,0x2797,0x27b0,0x27bf,0x2b1b,0x2b1c,0x2b50,0x2b55,0x1f004,0x1f0cf,0x1f18e,
20
+ 0x1f191,0x1f192,0x1f193,0x1f194,0x1f195,0x1f196,0x1f197,0x1f198,0x1f199,0x1f19a,0x1f201,0x1f21a,0x1f22f,0x1f232,0x1f233,
21
+ 0x1f234,0x1f235,0x1f236,0x1f238,0x1f239,0x1f23a,0x1f250,0x1f251]);
15
22
  /** Columns one character takes. */
16
23
  export function charWidth(ch){
17
24
  const cp=ch.codePointAt(0);
@@ -20,7 +27,13 @@ export function charWidth(ch){
20
27
  return wide(cp)?2:1;
21
28
  }
22
29
  /** Columns a string takes on screen (escape codes ignored). */
23
- export function width(s){let w=0;for(const ch of strip(s))w+=charWidth(ch);return w}
30
+ export function width(s){
31
+ // The emoji after a zero-width joiner (👨‍👩‍👧, 🏳️‍🌈) is drawn inside the same two cells, and a skin tone modifier joins
32
+ // the emoji before it.
33
+ let w=0,joined=false;
34
+ for(const ch of strip(s)){const cp=ch.codePointAt(0);if(joined||(cp>=0x1f3fb&&cp<=0x1f3ff&&w>0)){joined=false;continue}if(cp===0x200d){joined=true;continue}w+=charWidth(ch)}
35
+ return w;
36
+ }
24
37
 
25
38
  /**
26
39
  * Splits a styled string into chunks of at most `cols` columns, keeping escape codes with their text and
package/src/tui/app.mjs CHANGED
@@ -13,7 +13,8 @@ import {spawn} from 'node:child_process';
13
13
  import path from 'node:path';
14
14
  import {theme as makeTheme,resolveTheme,colorAllowed,colorDepth,boxChars,width,truncate,wrap,charWidth,strip} from './ansi.mjs';
15
15
  import {keyReader} from './keys.mjs';
16
- import {Editor,loadHistory,saveHistory} from './editor.mjs';
16
+ import {Editor,loadHistory,saveHistory,layoutInput} from './editor.mjs';
17
+ export {layoutInput};
17
18
  import {Screen} from './screen.mjs';
18
19
  import {Transcript,previewLines} from './transcript.mjs';
19
20
  import {approvalLines,ruleFor,ruleMatches,parseApproval} from './approval.mjs';
@@ -39,34 +40,27 @@ const SPIN=['⠋','⠙','⠹','⠸','⠼','⠴','⠦','⠧','⠇','⠏'],SPIN_AS
39
40
  const PLACEHOLDER='Type a task. / for commands, @ for files, ! for a shell command';
40
41
  const elapsed=ms=>{const s=Math.floor(ms/1000);return s<60?s+'s':Math.floor(s/60)+'m '+String(s%60).padStart(2,'0')+'s'};
41
42
 
42
- /** Visual rows of the input: word-wrapped at `cols` (long words are cut), with where the cursor lands. */
43
- export function layoutInput(text,cursor,cols){
44
- text=String(text);const rows=[];let cur={row:0,col:0};let base=0;
45
- for(const line of text.split('\n')){
46
- // Break the line into [start,end) ranges of code units.
47
- const ranges=[];let start=0,w=0,lastSpace=-1;
48
- for(let i=0;i<line.length;){
49
- const cp=line.codePointAt(i),n=cp>0xffff?2:1,cw=charWidth(String.fromCodePoint(cp));
50
- if(w+cw>cols&&i>start){
51
- if(line[i]===' '){ranges.push([start,i+1]);start=i+1;w=0;lastSpace=-1;i+=n;continue}
52
- if(lastSpace>start){ranges.push([start,lastSpace+1]);start=lastSpace+1;w=width(line.slice(start,i));lastSpace=-1;continue}
53
- ranges.push([start,i]);start=i;w=0;lastSpace=-1;continue;
54
- }
55
- if(line[i]===' ')lastSpace=i;
56
- w+=cw;i+=n;
57
- }
58
- ranges.push([start,line.length]);
59
- const c=cursor-base;
60
- ranges.forEach(([a,b],ri)=>{
61
- const last=ri===ranges.length-1;
62
- if(c>=a&&(c<b||(last&&c===b)))cur={row:rows.length,col:width(line.slice(a,c))};
63
- rows.push(line.slice(a,b));
64
- });
65
- // A cursor at the very end of a full row goes to the start of the next visual row.
66
- if(c===line.length&&cur.row===rows.length-1&&cur.col>=cols){rows.push('');cur={row:rows.length-1,col:0}}
67
- base+=line.length+1;
68
- }
69
- return {rows,cursor:cur};
43
+ /** First visible row of a box `max` rows tall over `total` rows: keeps `top` unless the cursor row is outside it. */
44
+ export function scrollWindow(top,row,max,total){
45
+ let start=Number.isInteger(top)?top:row-max+1;
46
+ if(row<start)start=row;else if(row>=start+max)start=row-max+1;
47
+ return Math.max(0,Math.min(start,total-max));
48
+ }
49
+ /**
50
+ * Command output (/help, /status, /mcp ...) as rows that fit the terminal: a long row breaks at a space, and its
51
+ * continuation lines line up under the value column ("name value") or two spaces in, instead of the terminal
52
+ * cutting words at the edge.
53
+ */
54
+ export function fitLines(lines,cols){
55
+ const max=Math.max(20,cols-1),out=[];
56
+ for(const line of lines){
57
+ if(width(line)<=max){out.push(line);continue}
58
+ const plain=strip(line),lead=plain.match(/^ */)[0].length,key=plain.match(/^ *\S(?:.*?\S)? {2,}(?=\S)/);
59
+ let k=key&&key[0].length<=max/2?key[0].length:lead+2;if(k>max/2)k=2;
60
+ const rows=wrap(line,max);
61
+ out.push(rows[0],...(rows.length>1?wrap(rows.slice(1).join(' '),max-k).map(r=>' '.repeat(k)+r):[]));
62
+ }
63
+ return out;
70
64
  }
71
65
 
72
66
  export async function runTui({session,settings={},cloud=null,flags={},first=null,images=[],send,makeCtx,onSessionChange,chat=null,
@@ -93,7 +87,8 @@ export async function runTui({session,settings={},cloud=null,flags={},first=null
93
87
  // ---------- output helpers ----------
94
88
  // One blank line between blocks: a block that opens with a blank line right after one that ended with one keeps one.
95
89
  const print=lines=>{tr.cols=screen.cols;let l=Array.isArray(lines)?lines:String(lines).split('\n');if(st.blankEnd&&l[0]==='')l=l.slice(1);if(!l.length){draw();return}screen.print(l);st.lastLine=strip(l.at(-1)??'').trim();st.blankEnd=l.at(-1)==='';draw()};
96
- const flash=(text,ms=2500)=>{st.hint=text;st.hintUntil=Date.now()+ms;draw()};
90
+ // The hint goes away on its own: nothing else may redraw the footer while the session is idle.
91
+ const flash=(text,ms=2500)=>{st.hint=text;st.hintUntil=Date.now()+ms;draw();setTimeout(()=>{if(Date.now()>=st.hintUntil)draw()},ms+30).unref?.()};
97
92
  const title=s=>{if(stdout.isTTY)stdout.write('\x1b]0;'+s.replace(/[\x00-\x1f]/g,'')+'\x07')};
98
93
  const titleMode=()=>{const v=liveSettings?.()?.terminalTitle??settings.terminalTitle;return typeof v==='string'&&v?v:'auto'};
99
94
  const setTitle=()=>{
@@ -106,8 +101,8 @@ export async function runTui({session,settings={},cloud=null,flags={},first=null
106
101
  // ---------- ui + ctx (the shared command contract) ----------
107
102
  const ui={
108
103
  get theme(){return themeName},
109
- print:text=>print(String(text).split('\n')),
110
- error:text=>print(String(text).split('\n').map(l=>t.warn(l))),
104
+ print:text=>print(fitLines(String(text).split('\n'),screen.cols)),
105
+ error:text=>print(fitLines(String(text).split('\n').map(l=>t.warn(l)),screen.cols)),
111
106
  confirm:(question,{default:d=false}={})=>new Promise(resolve=>{st.modal={type:'confirm',question,default:d,resolve};draw()}),
112
107
  pick:(items,{title:ttl='Choose',filter=''}={})=>new Promise(resolve=>{
113
108
  const rows=items.map(i=>typeof i==='string'?{label:i,value:i}:i);
@@ -173,9 +168,15 @@ export async function runTui({session,settings={},cloud=null,flags={},first=null
173
168
  if(e.type==='approval')return onApproval(e);
174
169
  if(e.type==='inference'){const used=(Number(e.prompt_tokens)||0)+(Number(e.completion_tokens)||0);if(used)st.context={used,window:st.window||null};return}
175
170
  if(e.type==='assistant'||e.type==='answer'){st.preview='';if(e.type==='answer'||e.content)st.lastAnswer=String(e.content||'')}
176
- if(e.type==='tool'&&e.name!=='todo')st.activity=tr.tool(e.name,e.target)[0].replace(/^\S+ /,'');
177
- if(e.type==='command')st.activity='Running '+truncate(String(e.command||'').split('\n')[0],60);
178
- tr.cols=screen.cols;const lines=tr.lines(e);if(lines.length)print(lines);else draw();
171
+ // The activity line follows the engine's stages ("Loading project context") until a tool or the reply takes over.
172
+ if(e.type==='stage'&&e.content&&st.running){st.activity=strip(String(e.content)).slice(0,80);st.stageActivity=true}
173
+ if(e.type==='tool'&&e.name!=='todo'){st.activity=strip(tr.tool(e.name,e.target)[0]).replace(/^\S+ /,'');st.stageActivity=false}
174
+ if(e.type==='command'){st.activity='Running '+truncate(String(e.command||'').split('\n')[0],60);st.stageActivity=false}
175
+ tr.cols=screen.cols;let lines=tr.lines(e);
176
+ // An approved edit's card already printed its "● Edit file" row; the tool row that follows is not repeated.
177
+ if(e.type==='tool'&&st.cardHead&&lines.length===1&&strip(lines[0]).trim()===st.cardHead){st.cardHead=null;draw();return}
178
+ if(lines.length)st.cardHead=null;
179
+ if(lines.length)print(lines);else draw();
179
180
  }
180
181
 
181
182
  // ---------- approvals ----------
@@ -192,6 +193,7 @@ export async function runTui({session,settings={},cloud=null,flags={},first=null
192
193
  // The tool row just above usually names the same edit; do not repeat it as the card header.
193
194
  const same=strip(view.lines[0]||'').trim()===st.lastLine;
194
195
  print(same?view.lines.slice(1):['',...view.lines]);
196
+ st.cardHead=strip(view.lines[0]||'').trim();
195
197
  st.modal={type:'approval',a,rule,view};setTitle();draw();
196
198
  if(stdout.isTTY)stdout.write('\x07');
197
199
  }
@@ -200,6 +202,9 @@ export async function runTui({session,settings={},cloud=null,flags={},first=null
200
202
  const a=m.a;st.modal=null;
201
203
  const install=verdict!=='reject'&&a.kind==='browser'&&a.install;
202
204
  if(install)print(tr.elbow()+t.dim('Installing the test browser (one-time download)...'));
205
+ // A rejection note is queued first: the engine passes it back with the rejection, so the agent acts on it instead of
206
+ // stopping to ask how to proceed.
207
+ if(verdict==='reject'&&feedback)await session.steer(feedback).catch(()=>{});
203
208
  try{await session.decide(a.id,verdict,install?{onProgress:msg=>{st.activity=String(msg).slice(0,80);draw()}}:undefined)}catch(e){print(t.bad('Could not answer: '+e.message))}
204
209
  const plan=parseApproval(a).kind==='plan';
205
210
  if(verdict==='approve'){
@@ -207,7 +212,6 @@ export async function runTui({session,settings={},cloud=null,flags={},first=null
207
212
  else print(tr.elbow()+t.ok(plan?'Building it':'Approved'));
208
213
  }else{
209
214
  print(tr.elbow()+t.warn(plan?'Plan sent back':'Rejected')+(feedback?t.dim(' · '+truncate(feedback,screen.cols-20)):''));
210
- if(feedback)await session.steer(feedback).catch(()=>{});
211
215
  }
212
216
  nextApproval();
213
217
  }
@@ -228,7 +232,7 @@ export async function runTui({session,settings={},cloud=null,flags={},first=null
228
232
  print(tr.user(text,{images:files.length}));
229
233
  let names=[];
230
234
  try{for(const f of files)names.push(await session.addImage(await readFile(f)))}catch(e){print(t.bad('Image not attached: '+e.message))}
231
- st.running=true;st.cancelled=false;st.errorShown=false;st.started=Date.now();st.activity='Starting';st.preview='';startTicker();setTitle();draw();
235
+ st.running=true;st.cancelled=false;st.errorShown=false;st.started=Date.now();st.activity='Starting';st.stageActivity=true;st.preview='';startTicker();setTitle();draw();
232
236
  let result=null;
233
237
  try{
234
238
  try{const req=JSON.parse(await readFile(path.join(session.dir,'request.json'),'utf8'));st.window=req.contextWindow||st.window}catch{}
@@ -239,6 +243,11 @@ export async function runTui({session,settings={},cloud=null,flags={},first=null
239
243
  if(st.modal?.type==='approval'||st.modal?.type==='feedback')st.modal=null;st.approvals=[];
240
244
  clearEntries();refreshBranch();setTitle();
241
245
  }
246
+ // A message sent to steer the agent after it had stopped reading (it was writing its last reply) never reached it.
247
+ // It is not dropped (or left for the next turn's first tool call to pick up): it runs next, or goes back to the input
248
+ // when the turn was stopped.
249
+ const late=await session.takeSteering?.().catch(()=>[])||[];
250
+ if(late.length){st.queue.unshift(...late);print(tr.elbow()+t.dim('The agent finished before it read your message; '+(st.cancelled?'it is back in the input':'sending it now')))}
242
251
  if(result&&!result.intake){
243
252
  if(result.state!=='completed'&&result.error&&!st.errorShown)print(t.warn(' '+result.error));
244
253
  print(['',' '+summaryLine(result,{dim:t.dim,green:s=>t.ok(t.bold(s)),yellow:s=>t.important(t.bold(s)),red:s=>t.bad(t.bold(s)),bold:t.bold})+t.dim(' · '+elapsed(Date.now()-st.started))]);
@@ -331,9 +340,13 @@ export async function runTui({session,settings={},cloud=null,flags={},first=null
331
340
  // ---------- rendering ----------
332
341
  function boxLines(ed,{label='',placeholder='',glyph=box.arrow,border=t.border,right=''}){
333
342
  const cols=screen.cols,inner=Math.max(10,cols-6);
343
+ // Up/Down then move through the wrapped rows as drawn (the width follows resizes).
344
+ if(ed instanceof Editor)ed.wrapCols=inner;
334
345
  const {rows,cursor}=layoutInput(ed.text,ed.cursor,inner);
335
346
  const maxRows=Math.max(3,Math.min(12,Math.floor(screen.rows/3)));
336
- let start=0;if(rows.length>maxRows)start=Math.min(Math.max(0,cursor.row-maxRows+1),rows.length-maxRows);
347
+ // The visible window only scrolls when the cursor leaves it, so Up/Down move the cursor instead of the text.
348
+ let start=0;if(rows.length>maxRows)start=scrollWindow(ed instanceof Editor?ed.viewTop:undefined,cursor.row,maxRows,rows.length);
349
+ if(ed instanceof Editor)ed.viewTop=start;
337
350
  const shown=rows.slice(start,start+maxRows);
338
351
  const top=label?border(box.tl+box.h+' ')+label+' '+border(box.h.repeat(Math.max(0,cols-6-width(label)))+box.tr):border(box.tl+box.h.repeat(cols-3)+box.tr);
339
352
  const body=shown.map((r,i)=>{
@@ -488,7 +501,7 @@ export async function runTui({session,settings={},cloud=null,flags={},first=null
488
501
  ticker=setInterval(async()=>{
489
502
  st.frame++;
490
503
  if(st.running&&session?.dir){
491
- try{const p=JSON.parse(await readFile(path.join(session.dir,'inference-progress.json'),'utf8'));const next=p.state==='running'&&p.content?String(p.content):'';if(next!==st.preview)st.preview=next}catch{}
504
+ try{const p=JSON.parse(await readFile(path.join(session.dir,'inference-progress.json'),'utf8'));const next=p.state==='running'&&p.content?String(p.content):'';if(next!==st.preview)st.preview=next;if(next&&st.stageActivity&&st.activity!=='Writing the reply')st.activity='Writing the reply'}catch{}
492
505
  }
493
506
  draw();
494
507
  },120);
@@ -505,7 +518,8 @@ export async function runTui({session,settings={},cloud=null,flags={},first=null
505
518
  // ---------- keys ----------
506
519
  async function quit(code=0){
507
520
  if(st.exiting)return;st.exiting=true;
508
- if(st.running)await session.cancel().catch(()=>{});
521
+ // Round 5: wait until the run is closed on the server (bounded); exiting right after the cancel left it open there.
522
+ if(st.running)await (session.stopNow?session.stopNow(8000,{code:null}):session.cancel()).catch(()=>{});
509
523
  const n=terminals.running().length;if(n){st.exiting=false;print(t.dim(' Stopping '+n+' background terminal'+(n===1?'':'s')+'...'));st.exiting=true;await terminals.stopAll()}
510
524
  exitResolve(code);
511
525
  }
@@ -702,7 +716,8 @@ export async function runTui({session,settings={},cloud=null,flags={},first=null
702
716
  process.kill(process.pid,'SIGTSTP');
703
717
  }
704
718
  // BUG-0516: on a closed terminal (SIGHUP) or SIGTERM the engine is stopped for sure before exiting.
705
- const onSignal=()=>{session.stopNow?.().catch(()=>{});quit(130)};
719
+ // Round 5: quit only after the engine stopped and the run is closed on the server (stopNow waits, bounded).
720
+ const onSignal=sig=>{if(st.exiting)return;Promise.resolve(session.stopNow?.(2500,{code:sig==='SIGHUP'?'terminal_closed':'terminated'})).catch(()=>{}).finally(()=>quit(130))};
706
721
  stdin.on('data',onData);stdout.on('resize',onResize);
707
722
  process.on('SIGTERM',onSignal);process.on('SIGHUP',onSignal);
708
723
  setup();
package/src/tui/bg.mjs CHANGED
@@ -113,7 +113,11 @@ export function attachSession(session,{write,approvalView,renderEvent,c,verbose=
113
113
  let pending=null,shown=new Set(),finished=false,resolveDone;
114
114
  const done=new Promise(r=>resolveDone=r);
115
115
  const lines=[];
116
- const onEvent=e=>{if(e.type==='approval')return;const r=renderEvent(e,{c,verbose});if(r)(replaying?lines.push(r):write(r))};
116
+ // CLI r5: the engine sends the final text twice (assistant, then answer); attach printed both.
117
+ let said='';
118
+ const onEvent=e=>{if(e.type==='approval')return;const r=renderEvent(e,{c,verbose});if(!r)return;
119
+ if(e.type==='answer'&&String(r).trim()===said)return;if(e.type==='assistant')said=String(r).trim();
120
+ (replaying?lines.push(r):write(r))};
117
121
  let replaying=true;session.offset=0;session.on('event',onEvent);
118
122
  const end=(state,detached=false)=>{if(finished)return;finished=true;clearInterval(timer);session.off('event',onEvent);resolveDone({state,detached})};
119
123
  const tick=async()=>{
package/src/tui/chat.mjs CHANGED
@@ -149,7 +149,9 @@ export class Chat extends EventEmitter{
149
149
  const idx=s.meta.turns.length;await snapshot(s,idx);
150
150
  const after=()=>s.meta.turns.length>idx?snapshotAfter(s,idx):null;// BUG-0525: what the agent changed this turn, for /rewind
151
151
  const next=()=>{const to=queue.shift();if(!to)return null;const from=this.model;this.model=to;this.emit('fallback',{from:from||this.defaultModel||'pixis',to});this.emit('change');return to};
152
- try{r=await s.send(task,{cloud:this.cloud,steps:this.steps,effort:this.effort,onProgress,allowUnsandboxed:this.allowUnsandboxed,images,run:this.runBody(),
152
+ // MINI_ONE_SHOT: nothing in a terminal session starts the engine's automatic continue, so it must not promise one
153
+ // (round 5: "the work continues automatically in a minute" after the 30-minute limit, and then nothing happened).
154
+ try{r=await s.send(task,{cloud:this.cloud,steps:this.steps,effort:this.effort,onProgress,allowUnsandboxed:this.allowUnsandboxed,images,run:this.runBody(),extraEnv:{MINI_ONE_SHOT:'1'},
153
155
  ...(this.addDirs.length?{extraRead:this.addDirs}:{}),...(this.extensions?{extensions:this.extensions}:{})})}
154
156
  catch(e){await after();if(modelBusy(e)&&next())continue;throw e}
155
157
  await after();
@@ -8,6 +8,69 @@
8
8
  */
9
9
  import {readFile,writeFile,mkdir} from 'node:fs/promises';
10
10
  import path from 'node:path';
11
+ import {width} from './ansi.mjs';
12
+
13
+ /** Grapheme clusters (an emoji with skin tone or ZWJ family, a letter with accents) move and delete as one. */
14
+ const SEG=typeof Intl?.Segmenter==='function'?new Intl.Segmenter(undefined,{granularity:'grapheme'}):null;
15
+ function graphemes(s){
16
+ if(SEG)return Array.from(SEG.segment(s),g=>g.segment);
17
+ return Array.from(s);
18
+ }
19
+ /** Start of the grapheme that ends at i (looks back a bounded window, so long text stays fast). */
20
+ export function prevBoundary(text,i){
21
+ if(i<=0)return 0;
22
+ const from=Math.max(0,i-64),g=graphemes(text.slice(from,i));
23
+ return i-(g.at(-1)?.length||1);
24
+ }
25
+ /** End of the grapheme that starts at i. */
26
+ export function nextBoundary(text,i){
27
+ if(i>=text.length)return text.length;
28
+ const g=graphemes(text.slice(i,i+64));
29
+ return i+(g[0]?.length||1);
30
+ }
31
+
32
+ /**
33
+ * Visual rows of the input: word-wrapped at `cols` (long words are cut, a grapheme is never split), with where the
34
+ * cursor lands. Every row is at most `cols` wide: a space that falls exactly at the wrap point is kept out of the
35
+ * row (a cursor on it shows at the start of the next row). spans[r]=[start,end,next] are absolute offsets of row r.
36
+ */
37
+ export function layoutInput(text,cursor,cols){
38
+ text=String(text);cols=Math.max(1,cols|0);
39
+ const rows=[],spans=[];let cur={row:0,col:0};let base=0;
40
+ for(const line of text.split('\n')){
41
+ // [start,end,next) ranges of code units; end<next when a wrapping space is dropped from the row.
42
+ const ranges=[];let start=0,w=0,lastSpace=-1,i=0;
43
+ const gs=graphemes(line);let gi=0;
44
+ while(gi<gs.length){
45
+ const g=gs[gi],cw=width(g);
46
+ if(w+cw>cols&&i>start){
47
+ if(g===' '){ranges.push([start,i,i+1]);i+=1;gi++;start=i;w=0;lastSpace=-1;continue}
48
+ if(lastSpace>start){ranges.push([start,lastSpace+1,lastSpace+1]);start=lastSpace+1;w=width(line.slice(start,i));lastSpace=-1;continue}
49
+ ranges.push([start,i,i]);start=i;w=0;lastSpace=-1;continue;
50
+ }
51
+ if(g===' ')lastSpace=i;
52
+ w+=cw;i+=g.length;gi++;
53
+ }
54
+ ranges.push([start,line.length,line.length]);
55
+ const c=cursor-base;
56
+ ranges.forEach(([a,b,n],ri)=>{
57
+ const last=ri===ranges.length-1;
58
+ if(c>=a&&(c<b||(last&&c===b)))cur={row:rows.length,col:width(line.slice(a,c))};
59
+ else if(c>=b&&c<n)cur={row:rows.length+1,col:0};
60
+ rows.push(line.slice(a,b));spans.push([base+a,base+b,base+n]);
61
+ });
62
+ // A cursor at the very end of a full row goes to the start of the next visual row.
63
+ if(c===line.length&&cur.row===rows.length-1&&cur.col>=cols){rows.push('');spans.push([base+line.length,base+line.length,base+line.length]);cur={row:rows.length-1,col:0}}
64
+ base+=line.length+1;
65
+ }
66
+ return {rows,cursor:cur,spans};
67
+ }
68
+ /** The offset in visual row `row` closest to display column `col` (for Up/Down through wrapped text). */
69
+ function offsetAtColumn(text,span,col){
70
+ const [a,b]=span;let w=0,i=a;
71
+ for(const g of graphemes(text.slice(a,b))){const cw=width(g);if(w+cw>col)break;w+=cw;i+=g.length}
72
+ return i;
73
+ }
11
74
 
12
75
  const isWord=ch=>/[\p{L}\p{N}_]/u.test(ch||'');
13
76
  export class Editor{
@@ -24,12 +87,26 @@ export class Editor{
24
87
  lineStart(i=this.cursor){return this.text.lastIndexOf('\n',i-1)+1}
25
88
  lineEnd(i=this.cursor){const e=this.text.indexOf('\n',i);return e<0?this.text.length:e}
26
89
  move(to){this.cursor=Math.max(0,Math.min(this.text.length,to));return 'changed'}
27
- left(){if(this.cursor>0){const cp=this.text.codePointAt(this.cursor-2);this.cursor-=cp>0xffff?2:1}return 'changed'}
28
- right(){if(this.cursor<this.text.length){const cp=this.text.codePointAt(this.cursor);this.cursor+=cp>0xffff?2:1}return 'changed'}
90
+ left(){this.cursor=prevBoundary(this.text,this.cursor);return 'changed'}
91
+ right(){this.cursor=nextBoundary(this.text,this.cursor);return 'changed'}
29
92
  wordLeft(){let i=this.cursor;while(i>0&&!isWord(this.text[i-1]))i--;while(i>0&&isWord(this.text[i-1]))i--;return this.move(i)}
30
93
  wordRight(){let i=this.cursor;while(i<this.text.length&&!isWord(this.text[i]))i++;while(i<this.text.length&&isWord(this.text[i]))i++;return this.move(i)}
31
- /** Up/Down move between lines; at the first or last line they walk the history instead. */
94
+ /**
95
+ * Up/Down move between lines; at the first or last line they walk the history instead. When the app sets
96
+ * `wrapCols` (the input box's text width) they move between the wrapped rows the person sees, keeping the column.
97
+ */
32
98
  vertical(d){
99
+ if(this.wrapCols>0){
100
+ const {spans,cursor}=layoutInput(this.text,this.cursor,this.wrapCols);
101
+ const target=cursor.row+d;
102
+ if(target<0||target>=spans.length)return this.historyStep(d);
103
+ // Remember the column across a run of Up/Down so a short row in between does not pull the cursor left.
104
+ const col=this.goalCol!=null&&this.goalAt===this.cursor?this.goalCol:cursor.col;
105
+ let to=offsetAtColumn(this.text,spans[target],col);
106
+ // The end of a wrapped row is the start of the next one; stop on the row's last character instead.
107
+ const next=spans[target+1];if(next&&next[0]===spans[target][2]&&to>=spans[target][1])to=Math.max(spans[target][0],prevBoundary(this.text,spans[target][1]));
108
+ this.move(to);this.goalCol=col;this.goalAt=this.cursor;return 'changed';
109
+ }
33
110
  const {row,col}=this.pos(),lines=this.lines();
34
111
  if((d<0&&row===0)||(d>0&&row===lines.length-1))return this.historyStep(d);
35
112
  const target=row+d;let i=0;for(let r=0;r<target;r++)i+=lines[r].length+1;
@@ -45,10 +122,10 @@ export class Editor{
45
122
  }
46
123
  backspace(){
47
124
  if(this.cursor===0)return 'changed';
48
- const cp=this.text.codePointAt(this.cursor-2),n=cp>0xffff?2:1;
49
- this.text=this.text.slice(0,this.cursor-n)+this.text.slice(this.cursor);this.cursor-=n;return 'changed';
125
+ const a=prevBoundary(this.text,this.cursor);
126
+ this.text=this.text.slice(0,a)+this.text.slice(this.cursor);this.cursor=a;return 'changed';
50
127
  }
51
- del(){if(this.cursor<this.text.length){const cp=this.text.codePointAt(this.cursor),n=cp>0xffff?2:1;this.text=this.text.slice(0,this.cursor)+this.text.slice(this.cursor+n)}return 'changed'}
128
+ del(){if(this.cursor<this.text.length){const b=nextBoundary(this.text,this.cursor);this.text=this.text.slice(0,this.cursor)+this.text.slice(b)}return 'changed'}
52
129
  kill(from,to){const a=Math.min(from,to),b=Math.max(from,to);this.yank=this.text.slice(a,b);this.text=this.text.slice(0,a)+this.text.slice(b);this.cursor=a;return 'changed'}
53
130
  /** Adds a submitted entry to history (no duplicates in a row, no blanks). */
54
131
  remember(entry){
package/src/tui/plain.mjs CHANGED
@@ -30,3 +30,39 @@ export function plainUi({write=t=>process.stdout.write(t),writeErr=t=>process.st
30
30
  };
31
31
  return ui;
32
32
  }
33
+
34
+ /**
35
+ * Long input lines in the plain (--no-tui) prompt. Node's readline writes a chunk of typed or pasted text straight to
36
+ * the terminal without updating how many wrapped rows sit above the cursor (prevRows). The next edit in the middle
37
+ * of the line then redraws from the wrong row: the start of the prompt is printed again below the old one and the
38
+ * text looks garbled. After each key, when the counts disagree, set the row the terminal cursor is really on and redraw.
39
+ * Only plain cursor moves and erase-below are used, which every terminal (and the Windows console) supports.
40
+ */
41
+ export function trackWrappedInput(rl,input=process.stdin){
42
+ let queued=false;
43
+ const fix=()=>{
44
+ queued=false;
45
+ if(rl.closed||typeof rl.getCursorPos!=='function'||typeof rl._refreshLine!=='function')return;
46
+ if(rl.cursor!==rl.line.length)return;// mid-line edits already redraw through readline itself
47
+ const pos=rl.getCursorPos();
48
+ // Text that ends exactly at the right edge leaves the terminal cursor on that row (pending wrap).
49
+ const real=pos.cols===0&&pos.rows>0?pos.rows-1:pos.rows;
50
+ if((rl.prevRows||0)===pos.rows)return;
51
+ rl.prevRows=real;rl._refreshLine();
52
+ };
53
+ const onKey=()=>{if(!queued){queued=true;setImmediate(fix)}};
54
+ input.on('keypress',onKey);
55
+ return ()=>input.off('keypress',onKey);
56
+ }
57
+ /**
58
+ * Prints a line above a prompt whose typed text may wrap over several rows: clears every row of the input (not only
59
+ * the cursor's), writes the text, then draws the prompt and the typed text again below it.
60
+ */
61
+ export function printAbove(rl,stream,text,{clearLine,cursorTo,moveCursor,clearScreenDown}){
62
+ const up=rl&&!rl.closed?rl.prevRows||0:0;
63
+ if(up)moveCursor(stream,0,-up);
64
+ cursorTo(stream,0);
65
+ if(up)clearScreenDown(stream);else clearLine(stream,0);
66
+ stream.write(text+'\n');
67
+ if(rl&&!rl.closed){rl.prevRows=0;if(rl.line&&typeof rl._refreshLine==='function')rl._refreshLine()}
68
+ }
@@ -49,7 +49,7 @@ export function itemsOf(settings){const v=settings?.statusLine?.items;return Arr
49
49
  function piece(name,d,t){
50
50
  switch(name){
51
51
  case 'mode':return modeStyle(t,d.mode)(t.bold(d.modeLabel))+t.dim(' (shift+tab)');
52
- case 'model':return d.model?t.text(d.model)+(d.credits?t.dim(' '+d.credits):''):'';
52
+ case 'model':return d.model?t.text(d.model)+(d.credits?t.dim(' · '+d.credits):''):'';
53
53
  case 'effort':return d.effort&&d.effort!=='medium'?t.dim(d.effort+' effort'):'';
54
54
  case 'vim':return d.vim?t.dim(d.vimMode==='normal'?'NORMAL':'INSERT'):'';
55
55
  case 'queue':return d.queued?t.accent(d.queued+' queued'):'';
@@ -57,8 +57,8 @@ function piece(name,d,t){
57
57
  case 'branch':return d.branch?t.dim(d.branch):'';
58
58
  case 'cwd':return d.folder?t.dim(d.folder):'';
59
59
  case 'session':return d.sessionName||d.session?t.dim(String(d.sessionName||d.session).slice(0,24)):'';
60
- case 'context':{if(!d.context)return '';const p=d.context.percent,style=p>=85?t.bad:p>=65?t.warn:t.dim;return style(p+'% context')}
61
- case 'credits':return d.tokensLeft!=null?t.dim(credits(d.tokensLeft)+' left'):d.usage?.tokens?t.dim(credits(d.usage.tokens)):'';
60
+ case 'context':{if(!d.context)return '';const p=d.context.percent,style=p>=85?t.bad:p>=65?t.warn:t.dim;return style((p===0&&d.context.used>0?'<1':p)+'% context')}
61
+ case 'credits':return d.tokensLeft!=null?t.dim(credits(d.tokensLeft)+' left'):d.usage?.tokens?t.dim(credits(d.usage.tokens)+' used'):'';
62
62
  case 'time':{const n=d.now?new Date(d.now):new Date();return t.dim(String(n.getHours()).padStart(2,'0')+':'+String(n.getMinutes()).padStart(2,'0'))}
63
63
  }
64
64
  return '';
@@ -46,8 +46,12 @@ export class Transcript{
46
46
  return ['',...lines.map((l,i)=>(i?' ':mark+' ')+style(l)),...(images?[t.dim(' + '+images+' image'+(images===1?'':'s'))]:[]),''];
47
47
  }
48
48
  assistant(content){
49
- const p=prose(finishless(content));if(!p||p===this.lastAssistant)return [];
50
- this.lastAssistant=p;this.shown=[...(this.shown||[]),p].slice(-8);
49
+ const full=prose(finishless(content));if(!full||full===this.lastAssistant)return [];
50
+ // The agent often restates its last reply with a line added (after a steering message "add END"): only the new
51
+ // part is printed, not the whole reply again.
52
+ const p=answerRest(this.shown,full);
53
+ this.lastAssistant=full;this.shown=[...(this.shown||[]),full].slice(-8);
54
+ if(!p)return [];
51
55
  // Raw scrollback: the reply exactly as written (markdown source, no wrapping or color), for copying.
52
56
  if(this.raw)return ['',...p.split('\n')];
53
57
  const md=markdown(p,{t:this.t,cols:this.cols-2,box:this.box});
@@ -58,12 +62,7 @@ export class Transcript{
58
62
  added to it (a verification note, a source list) is. */
59
63
  answer(content){
60
64
  const p=prose(finishless(content));if(!p)return [];
61
- const norm=x=>x.replace(/\s+/g,' ').trim();
62
- for(const seen of this.shown||[]){
63
- if(norm(seen)===norm(p))return [];
64
- if(seen.length>40&&p.includes(seen)){const rest=p.replace(seen,'').trim();return rest?this.assistant(rest):[]}
65
- }
66
- return this.assistant(p);
65
+ return answerRest(this.shown,p)?this.assistant(p):[];
67
66
  }
68
67
  tool(name,target){
69
68
  const t=this.t,v=verb(name);
@@ -77,6 +76,9 @@ export class Transcript{
77
76
  }
78
77
  output(e){
79
78
  const t=this.t,text=String(e.output||'').replace(/\s+$/,'');const rows=text?text.split('\n'):[];const ok=e.returncode===0;
79
+ // A call the user rejected on its card: the card already says Rejected; the engine's instructions to the agent
80
+ // ("Do not make the same change another way ...") are not for the person.
81
+ if(e.blocked&&/^The user rejected (this action|a related action)/.test(text))return [];
80
82
  if(!rows.length)return [this.elbow()+(ok?t.dim('done'):t.bad('exit '+e.returncode))];
81
83
  // One-line results read best inline; bookkeeping results (task list saved) stay quiet.
82
84
  if(ok&&/^todo: Task list updated\.?$/.test(text))return [];
@@ -114,7 +116,7 @@ export class Transcript{
114
116
  case 'edit_guard':return [this.dot(t.warn)+t.warn('Blocked edit ')+truncate(String(e.path||''),60)+t.dim(': '+truncate(String(e.content||''),this.cols-30))];
115
117
  case 'steering':return [this.elbow()+t.accent('Steering received')];
116
118
  case 'mode':return e.content?[this.elbow()+t.dim(String(e.content))]:[];
117
- case 'note':return e.content?[this.elbow()+t.dim(truncate(String(e.content),this.cols-6))]:[];
119
+ case 'note':return e.content?wrap(String(e.content),this.cols-6).map((l,i)=>(i?' ':this.elbow())+t.dim(l)):[];
118
120
  case 'error':return ['',...wrap(String(e.content||e.error||'Error'),this.cols-2).map((l,i)=>(i?' ':this.dot(t.bad))+t.bad(l))];
119
121
  case 'completion':{const l=renderEvent(e,{c:legacy(t)});return l?['',this.elbow()+l]:[]}
120
122
  case 'inference':case 'inference_progress':case 'intent':case 'budget':case 'run_metrics':case 'prompt_profile':case 'model':case 'approval':return [];
@@ -124,9 +126,21 @@ export class Transcript{
124
126
  }
125
127
  }
126
128
 
129
+ /** What a final answer adds to the replies already shown (the plain interface shares this): '' when it repeats one of
130
+ them, the extra part when it extends one, else the whole answer. */
131
+ export function answerRest(shown,p){
132
+ p=String(p||'').trim();if(!p)return '';
133
+ const norm=x=>String(x).replace(/\s+/g,' ').trim(),list=(shown||[]).filter(Boolean);
134
+ if(list.some(seen=>norm(seen)===norm(p)))return '';
135
+ // The longest earlier reply it contains, so "A" then "A + END" then answer "A + END" adds nothing the third time.
136
+ const inside=list.filter(seen=>seen.length>40&&p.includes(seen)).sort((a,b)=>b.length-a.length)[0];
137
+ return inside?p.replace(inside,'').trim():p;
138
+ }
139
+
127
140
  /** The live preview of a reply that is still streaming: the last few rendered lines of its prose. */
128
141
  export function previewLines(content,{t,cols,box,max=8}){
129
142
  const p=prose(finishless(content));if(!p)return [];
130
- const md=markdown(p,{t,cols:cols-2,box});
143
+ // The footer keeps one column free (screen.mjs cuts rows at cols-1), so the indented preview is rendered one narrower.
144
+ const md=markdown(p,{t,cols:cols-3,box});
131
145
  return md.slice(-max).map(l=>' '+l);
132
146
  }
package/src/two-words.mjs CHANGED
@@ -34,6 +34,8 @@ export function twoWordTitle(text,fallback='New Chat',second,max=TITLE_WORDS){
34
34
  if(next.toLowerCase()===first.toLowerCase())next='Task';
35
35
  return first+' '+next;
36
36
  }
37
+ /** How many meaningful words a text has (filler dropped): a follow-up such as "yes" or "continue" has fewer than two. */
38
+ export const titleWords=(text)=>tokens(text).length;
37
39
  /** The same rule under its current name. */
38
40
  export const chatTitle=twoWordTitle;
39
41
  /** The first meaningful word plus a fixed second one: "Login Fork", "Web Team". */
@@ -8,7 +8,7 @@ import os
8
8
  from urllib.parse import urlparse
9
9
 
10
10
  LOOPBACK = ('127.0.0.1', 'localhost')
11
- INSTALL_NOTE = 'Install the test browser on this Mac (one-time download of about 150 MB into ~/.mlai/runtime). It opens only your local preview.'
11
+ INSTALL_NOTE = 'Install the test browser on this computer (one-time download of about 150 MB into ~/.mlai/runtime). It opens only your local preview.'
12
12
 
13
13
 
14
14
  def laptop():
@@ -45,5 +45,5 @@ def ask_install(root, args, emit, stopped=lambda: None, timeout=600):
45
45
  time.sleep(0.4)
46
46
  verdict = decision.read_text().strip(); decision.unlink(missing_ok=True); (root / 'pending.json').unlink(missing_ok=True)
47
47
  if verdict not in ('approve', 'approve_all'): raise ValueError('The person declined the browser download. Continue without browser checks and say so; do not ask again in this task.')
48
- if not (root / 'browser-ready').exists(): raise ValueError('The test browser could not be installed on this Mac. Continue without browser checks and say so.')
48
+ if not (root / 'browser-ready').exists(): raise ValueError('The test browser could not be installed on this computer. Continue without browser checks and say so.')
49
49
  return True
@@ -70,10 +70,23 @@ def actual(page,checked,local):
70
70
  except Exception:url=''
71
71
  return url if local and url and url!='about:blank' else checked
72
72
 
73
+ class BrowserUnavailable(ValueError):
74
+ """The check cannot run on this computer at all (not a page problem), with an instruction the agent can act on."""
75
+
76
+ UNAVAILABLE=('The browser check cannot run on this computer ({reason}). Do not retry it and do not build a replacement browser harness '
77
+ '(Puppeteer, a Playwright script, or the system Chrome or Edge); verify with the project\'s own tests and build instead, '
78
+ 'and say in your summary that the browser check was not available.')
79
+
80
+ def unavailable(exc):
81
+ return BrowserUnavailable(UNAVAILABLE.format(reason=(type(exc).__name__+': '+str(exc))[:300]))
82
+
73
83
  def scenario(args,output):
74
84
  local=on_laptop()
75
85
  if not (local and os.getenv('PLAYWRIGHT_BROWSERS_PATH')):os.environ['PLAYWRIGHT_BROWSERS_PATH']=str(output.parent.parent/'pw-browsers')
76
- from playwright.sync_api import sync_playwright
86
+ # Windows bug list (round 6): a missing module surfaced as a bare "No module named 'fcntl'" and the agent spent many
87
+ # calls building its own Puppeteer harness. A runtime that cannot start now says so and what to do instead.
88
+ try:from playwright.sync_api import sync_playwright
89
+ except ImportError as exc:raise unavailable(exc) from exc
77
90
  url=args.get('url','http://127.0.0.1:3000')
78
91
  if not local_url(url):raise ValueError('Browser is restricted to the local app on this computer' if local else 'Browser is restricted to the local app on port 3000')
79
92
  url=as_preview(url)
@@ -83,7 +96,8 @@ def scenario(args,output):
83
96
  if type(width)!=int or type(height)!=int or not 320<=width<=1920 or not 400<=height<=1200:raise ValueError('Unsupported viewport')
84
97
  errors=[];console=[];noise=[];timeline=[];network=[];page=None
85
98
  with sync_playwright() as p:
86
- browser=p.chromium.launch(headless=True,args=browser_local.launch_args() if local else ['--no-sandbox','--host-resolver-rules=MAP '+PREVIEW_HOST+' 127.0.0.1','--unsafely-treat-insecure-origin-as-secure=http://'+PREVIEW_HOST+':3000'])
99
+ try:browser=p.chromium.launch(headless=True,args=browser_local.launch_args() if local else ['--no-sandbox','--host-resolver-rules=MAP '+PREVIEW_HOST+' 127.0.0.1','--unsafely-treat-insecure-origin-as-secure=http://'+PREVIEW_HOST+':3000'])
100
+ except Exception as exc:raise unavailable(exc) from exc
87
101
  checked=url if local else 'http://'+PREVIEW_HOST+':3000 (the local app under the public preview host)'
88
102
  try:
89
103
  context=browser.new_context(viewport={'width':width,'height':height},service_workers='block',accept_downloads=False)
@@ -38,6 +38,19 @@ WRITE_PROGRAMS = frozenset(('mkdir', 'touch', 'cp', 'mv', 'ln', 'rmdir', 'tar',
38
38
  'dos2unix', 'unix2dos', 'sqlite3', 'convert', 'ffmpeg', 'pandoc', 'magick', 'gzip', 'gunzip', 'xz', 'bzip2', 'wget_out', 'prettier', 'black', 'isort', 'gofmt', 'rustfmt', 'eslint_fix'))
39
39
  GIT_READ = frozenset(('status', 'diff', 'log', 'show', 'branch', 'ls-files', 'ls-tree', 'rev-parse', 'remote', 'blame', 'describe', 'shortlog', 'grep', 'config', 'cat-file', 'rev-list', 'tag', 'stash_list',
40
40
  'reflog', 'count-objects', 'help', 'version', 'var', 'check-ignore', 'name-rev', 'merge-base', 'whatchanged', 'for-each-ref', 'show-ref', 'symbolic-ref'))
41
+ # git's own options before the subcommand (git -C dir push -f, git -c k=v reset --hard): skipped, so the subcommand is
42
+ # classified as itself and not as an unknown program run.
43
+ GIT_GLOBAL_WITH_VALUE = frozenset(('-c', '-C', '--git-dir', '--work-tree', '--namespace', '--super-prefix', '--config-env'))
44
+
45
+
46
+ def git_args(args):
47
+ """The arguments from the git subcommand on: `git -C . -c a=b --no-pager push -f` -> ['push', '-f']."""
48
+ i = 0
49
+ while i < len(args) and args[i].startswith('-') and args[i] != '--':
50
+ i += 2 if args[i] in GIT_GLOBAL_WITH_VALUE else 1
51
+ return list(args[i:])
52
+
53
+
41
54
  GIT_WRITE = frozenset(('add', 'commit', 'checkout', 'switch', 'restore', 'merge', 'rebase', 'stash', 'cherry-pick', 'revert', 'mv', 'rm', 'init', 'apply', 'am', 'worktree', 'submodule', 'notes', 'bisect', 'update-index', 'reset'))
42
55
  GIT_NETWORK = frozenset(('push', 'fetch', 'pull', 'clone', 'ls-remote', 'remote_update', 'lfs'))
43
56
  NETWORK_PROGRAMS = frozenset(('curl', 'wget', 'ssh', 'scp', 'sftp', 'rsync_remote', 'nc', 'ncat', 'netcat', 'telnet', 'ftp', 'gh', 'glab', 'hub', 'aws', 'gcloud', 'az', 'vercel', 'netlify', 'wrangler',
@@ -363,6 +376,7 @@ def evaluate(words, redirects, flags, repo, cwd, home, body_programs=None):
363
376
  base = 'destructive' if recursive and targets else 'write'
364
377
  e, r = path_effect(targets, base); return e, r or (prog + ' -R' if recursive else ''), targets
365
378
  if prog == 'git':
379
+ args = git_args(args)
366
380
  sub = next((a for a in args if not a.startswith('-')), '')
367
381
  rest = args[args.index(sub) + 1:] if sub in args else []
368
382
  # BUG-0453: a token written into a git address (https://user:TOKEN@github.com/...) bypasses the GitHub tools'