mlai-code 0.3.7 → 0.3.9

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/README.md CHANGED
@@ -1,4 +1,4 @@
1
- # mlai-code 0.3.7
1
+ # mlai-code 0.3.9
2
2
 
3
3
  ML AI Code in your terminal. The agent works in your project on this machine; models run in ML AI Code's cloud.
4
4
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mlai-code",
3
- "version": "0.3.7",
3
+ "version": "0.3.9",
4
4
  "description": "ML AI Code in your terminal: an agent that reads, edits and runs code in your project, on your machine.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -74,4 +74,4 @@ const runEnv=new Set();
74
74
  export function addRunEnv(fn){if(typeof fn==='function')runEnv.add(fn);return ()=>runEnv.delete(fn)}
75
75
 
76
76
  /** What the install approval card says. */
77
- export const 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.';
77
+ export const 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.';
package/src/cli.mjs CHANGED
@@ -16,7 +16,7 @@ import {MODES as CLI_MODES,modeName,nextMode,engineMode,sessionMode} from './mod
16
16
  import {loadSettings} from './settings.mjs';
17
17
  import * as registry from './tui/commands.mjs';
18
18
  import {Chat,answerOf,modelList} from './tui/chat.mjs';
19
- import {plainUi} from './tui/plain.mjs';
19
+ import {plainUi,trackWrappedInput,printAbove} from './tui/plain.mjs';
20
20
  import {projectRoot} from './project.mjs';
21
21
  import {createWorktree} from './worktree.mjs';
22
22
  import {EXT_FLAGS,EXT_COMMANDS,extFlag} from './cli-ext.mjs';
@@ -551,14 +551,17 @@ async function withRemote(chat,fn){
551
551
 
552
552
  /** The line-based session (no full-screen TUI): readline, slash commands from the registry, approvals, steering. */
553
553
  async function plainLoop(o,c,chat,first){
554
- const out=t=>{readline.clearLine(process.stdout,0);readline.cursorTo(process.stdout,0);process.stdout.write(t+'\n')};
554
+ // A long typed line wraps over several rows; output printed while it is there clears all of them (R6).
555
+ let rl=null;
556
+ const out=t=>printAbove(rl,process.stdout,t,readline);
555
557
  const kind=sandboxKind(),sandboxed=SANDBOXES.includes(kind);
556
558
  const banner=()=>out(c.bold('ML AI Code')+c.dim(` · ${chat.session.meta.folder} · ${chat.modelLabel} · ${chat.mode} mode · sandbox ${sandboxed?kind:'none'}`));
557
559
  banner();
558
560
  out(c.dim('Type a task. While it works, type to steer it. Ctrl-C stops. Type / for commands, Shift+Tab switches mode.'));
559
561
  let ctx=null;
560
- const rl=readline.createInterface({input:process.stdin,output:process.stdout,terminal:true,historySize:500,
562
+ rl=readline.createInterface({input:process.stdin,output:process.stdout,terminal:true,historySize:500,
561
563
  completer:(line,cb)=>{if(!line.startsWith('/'))return cb(null,[[],line]);registry.complete(ctx,line).then(l=>cb(null,[l,line]),()=>cb(null,[[],line]))}});
564
+ trackWrappedInput(rl);
562
565
  let pending=null,lastCtrlC=0,question=null;
563
566
  const prompt=()=>{rl.setPrompt(question?question.text:pending?c.yellow('approve? [y]es / [a]ll / [n]o › '):chat.running?c.dim('steer › '):c.cyan(chat.mode==='agent'?'› ':chat.mode+' › '));rl.prompt(true)};
564
567
  const ask=text=>new Promise(resolve=>{question={text,resolve};prompt()});
package/src/home.mjs CHANGED
@@ -3,7 +3,7 @@ import path from 'node:path';
3
3
  import {mkdirSync,chmodSync,statSync} from 'node:fs';
4
4
  import {fileURLToPath} from 'node:url';
5
5
 
6
- export const VERSION='0.3.7';
6
+ export const VERSION='0.3.9';
7
7
  // BUG-0469: the production CLI signs in and calls the production domain.
8
8
  export const DEFAULT_SERVER='https://code.ml.ai';
9
9
  /** All local state lives here; nothing is written into the user's repository except what the agent edits. */
package/src/render.mjs CHANGED
@@ -56,6 +56,7 @@ export function renderEvent(e,{c=palette(false),verbose=false}={}){
56
56
  case 'todos':return (e.items||[]).map(t=>c.gray((t.status==='done'?'[x] ':t.status==='in_progress'?'[>] ':'[ ] ')+clip(t.text,120))).join('\n')||null;
57
57
  case 'edit_guard':return c.yellow('blocked edit '+clip(e.path,120)+': '+clip(e.content,300));
58
58
  case 'steering':return c.cyan('steering received');
59
+ case 'process_stopped':return c.yellow('stopped a hung command: '+clip(e.command,160)+(e.reason?' ('+clip(e.reason,160)+')':'')+'; the agent continues'); // worker/proc_watch.py (CLI r7)
59
60
  case 'retry':return verbose?c.gray('retry: '+clip(e.content,200)):null;
60
61
  case 'error':return c.red(clip(e.content||e.error||'Error',2000));
61
62
  case 'completion':{
@@ -89,5 +90,5 @@ export function exitCode(result){
89
90
  export function summaryLine(result,c=palette(false)){
90
91
  const u=result.usage||{};
91
92
  const state=result.state==='completed'&&result.cannotComplete?c.yellow('Could not be done'):result.state==='completed'?c.green('Done'):result.state==='limited'?c.yellow('Needs attention'):result.state==='stopped'?c.yellow('Stopped'):c.red('Failed');
92
- return state+c.dim(' · '+credits(u.tokens)+' · '+fmt(u.calls)+(Number(u.calls)===1?' model call':' model calls'))+(result.code==='time_limit'&&result.error?'\n'+c.yellow(result.error):'');
93
+ return state+c.dim(' · '+credits(u.tokens)+' · '+fmt(u.calls)+(Number(u.calls)===1?' model call':' model calls'))+((result.code==='time_limit'||result.code==='step_limit')&&result.error?'\n'+c.yellow(result.error):'');
93
94
  }
package/src/session.mjs CHANGED
@@ -61,6 +61,16 @@ export function serverRequest(built,{started,task,images=[]}){
61
61
  /** A title the engine made before two-word names (the first task cut at 80) becomes two words; a rename (meta.renamed) never changes. */
62
62
  export function legacyTitle(m){const t=String(m?.title||''),first=String(m?.turns?.[0]?.task||'');return t&&!m.renamed&&!isTwoWords(t)&&first&&first.slice(0,80)===t&&twoWordTitle(first)!==t?twoWordTitle(first):null}
63
63
  /** Round 5: what the CLI says when a run reaches the time limit for one run (it used to stop with only "Needs attention"). */
64
+ export const STEP_LIMIT_NOTE='This task used all of its steps for one turn and stopped. Work done so far is kept. To keep going, send "continue" (or later: mlai -c "continue"); -p runs can raise --max-steps.';
65
+ /** Which limit stopped a run. The engine's step limit ends with exit_status LimitsExceeded and no limit field; it used to
66
+ * be reported as the 30-minute limit (a -p run with --max-steps 40 stopped after 3 minutes "at the 30-minute limit"), and so
67
+ * was a run stopped for unfinished verification. */
68
+ export function limitKind(r){
69
+ if(r?.limit)return String(r.limit);
70
+ if(r?.exit_status==='LimitsExceeded')return 'steps';
71
+ if(r?.exit_status==='VerificationIncomplete')return 'verification';
72
+ return 'time';
73
+ }
64
74
  export const TIME_LIMIT_NOTE='This task reached the 30-minute limit for one run and stopped. Work done so far is kept. To keep going, send "continue" (or later: mlai -c "continue").';
65
75
  /** The error code for a failure before the engine started: the error's own code when it is a plain word. */
66
76
  const CODE_OF=e=>typeof e?.code==='string'&&/^[a-z][a-z0-9_]{1,39}$/.test(e.code)?e.code:'start_failed';
@@ -302,7 +312,8 @@ export class Session extends EventEmitter{
302
312
  // The gateway refuses calls once the plan allowance for this run is used; say so plainly.
303
313
  if(status.state!=='completed'&&started.budget!=null&&Number(usage?.tokens)>=started.budget){result.code='billing_limit';result.error='Your plan allowance ran out during this task. Changes so far are kept. Upgrade or wait for the allowance to reset, then continue.'}
304
314
  // Round 5: the 30-minute limit for one run; the person is told the work is saved and how to go on (src/render.mjs).
305
- else if(status.state==='limited'&&(status.result?.limit||'time')==='time'){result.code='time_limit';result.error=TIME_LIMIT_NOTE}
315
+ else if(status.state==='limited'&&limitKind(status.result)==='time'){result.code='time_limit';result.error=TIME_LIMIT_NOTE}
316
+ else if(status.state==='limited'&&limitKind(status.result)==='steps'){result.code='step_limit';result.error=STEP_LIMIT_NOTE}
306
317
  this.emit('done',result);
307
318
  return result;
308
319
  }finally{if(relay)await relay.close().catch(()=>{})}
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,36 +40,12 @@ 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));
70
48
  }
71
-
72
49
  /**
73
50
  * Command output (/help, /status, /mcp ...) as rows that fit the terminal: a long row breaks at a space, and its
74
51
  * continuation lines line up under the value column ("name value") or two spaces in, instead of the terminal
@@ -195,6 +172,7 @@ export async function runTui({session,settings={},cloud=null,flags={},first=null
195
172
  if(e.type==='stage'&&e.content&&st.running){st.activity=strip(String(e.content)).slice(0,80);st.stageActivity=true}
196
173
  if(e.type==='tool'&&e.name!=='todo'){st.activity=strip(tr.tool(e.name,e.target)[0]).replace(/^\S+ /,'');st.stageActivity=false}
197
174
  if(e.type==='command'){st.activity='Running '+truncate(String(e.command||'').split('\n')[0],60);st.stageActivity=false}
175
+ if(e.type==='process_stopped'&&st.running){st.activity='Stopped a hung command; continuing';st.stageActivity=false}
198
176
  tr.cols=screen.cols;let lines=tr.lines(e);
199
177
  // An approved edit's card already printed its "● Edit file" row; the tool row that follows is not repeated.
200
178
  if(e.type==='tool'&&st.cardHead&&lines.length===1&&strip(lines[0]).trim()===st.cardHead){st.cardHead=null;draw();return}
@@ -363,9 +341,13 @@ export async function runTui({session,settings={},cloud=null,flags={},first=null
363
341
  // ---------- rendering ----------
364
342
  function boxLines(ed,{label='',placeholder='',glyph=box.arrow,border=t.border,right=''}){
365
343
  const cols=screen.cols,inner=Math.max(10,cols-6);
344
+ // Up/Down then move through the wrapped rows as drawn (the width follows resizes).
345
+ if(ed instanceof Editor)ed.wrapCols=inner;
366
346
  const {rows,cursor}=layoutInput(ed.text,ed.cursor,inner);
367
347
  const maxRows=Math.max(3,Math.min(12,Math.floor(screen.rows/3)));
368
- let start=0;if(rows.length>maxRows)start=Math.min(Math.max(0,cursor.row-maxRows+1),rows.length-maxRows);
348
+ // The visible window only scrolls when the cursor leaves it, so Up/Down move the cursor instead of the text.
349
+ let start=0;if(rows.length>maxRows)start=scrollWindow(ed instanceof Editor?ed.viewTop:undefined,cursor.row,maxRows,rows.length);
350
+ if(ed instanceof Editor)ed.viewTop=start;
369
351
  const shown=rows.slice(start,start+maxRows);
370
352
  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);
371
353
  const body=shown.map((r,i)=>{
@@ -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
+ }
@@ -100,10 +100,23 @@ export class Transcript{
100
100
  }
101
101
  todos(items){
102
102
  const t=this.t;if(!Array.isArray(items)||!items.length)return [];
103
+ // Tester report (CLI 0.3.8): the same plan was printed twice in a row. A list repeated with nothing shown since, or
104
+ // identical to the last one shown, adds nothing.
105
+ const names=JSON.stringify(items.slice(0,30).map(it=>String(it?.text??'')));
106
+ const full=JSON.stringify(items.slice(0,30).map(it=>[String(it?.text??''),it?.status||'']));
107
+ const repeat=full===this.lastTodos||(names===this.lastTodoNames&&!this.shownSinceTodos);
108
+ this.lastTodos=full;this.lastTodoNames=names;
109
+ if(repeat)return [];
110
+ this.shownSinceTodos=false;
103
111
  return [this.dot(t.tool)+t.toolHead('Plan'),...items.slice(0,30).map(it=>{const s=it.status;const mark=s==='done'?t.ok('[x]'):s==='in_progress'?t.accent('[>]'):t.dim('[ ]');return ' '+mark+' '+(s==='done'?t.faint(truncate(it.text,this.cols-10)):truncate(String(it.text),this.cols-10))})];
104
112
  }
105
113
  /** Lines for one event; [] for events that stay quiet. */
106
114
  lines(e){
115
+ const out=this.eventLines(e);
116
+ if(out.length&&e?.type!=='todos')this.shownSinceTodos=true;
117
+ return out;
118
+ }
119
+ eventLines(e){
107
120
  const t=this.t;
108
121
  switch(e?.type){
109
122
  case 'assistant':return this.assistant(e.content);
@@ -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
@@ -42,6 +42,37 @@ def as_preview(value):
42
42
  u=urlparse(value)
43
43
  return u._replace(netloc=PREVIEW_HOST+':3000').geturl() if u.hostname in ('127.0.0.1','localhost') else value
44
44
 
45
+ FOREIGN=('{who} This check opened another application, not this project, so it is not evidence for this workspace. '
46
+ '{hint}')
47
+
48
+ def workspace_server(url):
49
+ """Who serves the checked address, for this workspace (MINI_REPO / MINI_ROOT): see preview.server_owner. CLI 0.3.8: port
50
+ 3000 served another workspace's app and its checks passed as the Notes app's evidence."""
51
+ repo,state=os.getenv('MINI_REPO'),os.getenv('MINI_ROOT')
52
+ if not repo or not Path(repo).is_dir():return {}
53
+ try:
54
+ import preview
55
+ port=urlparse(url).port or 80
56
+ return preview.server_owner(port,repo,state)
57
+ except Exception:return {}
58
+
59
+ def preview_url():
60
+ """This workspace's preview address (laptop previews move off port 3000 when another app holds it)."""
61
+ try:
62
+ import preview
63
+ return preview.base_url(preview.recorded_port(os.getenv('MINI_ROOT') or '/nonexistent')) if on_laptop() else 'http://127.0.0.1:3000'
64
+ except Exception:return 'http://127.0.0.1:3000'
65
+
66
+ def foreign_result(owner,url,width,height,timeline=None):
67
+ try:
68
+ import preview
69
+ who=preview.foreign_text(owner)
70
+ except Exception:who='Port %s is served by another app.'%owner.get('port')
71
+ mine=preview_url()
72
+ hint=('Use this project\'s preview at '+mine+' (start it with preview first).') if urlparse(mine).port!=owner.get('port') else 'Start the preview of this project first (it reports the address to check).'
73
+ return {'success':False,'workspaceEvidence':False,'foreignServer':owner,'error':FOREIGN.format(who=who,hint=hint),'checkedAt':url,'url':url,'timeline':timeline or [],
74
+ 'pageErrors':[],'consoleErrors':[],'networkFailures':[],'screenshot':None,'viewport':{'width':width,'height':height}}
75
+
45
76
  HYDRATION='''() => {
46
77
  const next = !!document.querySelector('script[src*="/_next/"]');
47
78
  if (!next) return {framework: null, interactive: true};
@@ -70,11 +101,22 @@ def actual(page,checked,local):
70
101
  except Exception:url=''
71
102
  return url if local and url and url!='about:blank' else checked
72
103
 
104
+ class BrowserUnavailable(ValueError):
105
+ """The check cannot run on this computer at all (not a page problem), with an instruction the agent can act on."""
106
+
107
+ UNAVAILABLE=('The browser check cannot run on this computer ({reason}). Do not retry it and do not build a replacement browser harness '
108
+ '(Puppeteer, a Playwright script, or the system Chrome or Edge); verify with the project\'s own tests and build instead, '
109
+ 'and say in your summary that the browser check was not available.')
110
+
111
+ def unavailable(exc):
112
+ return BrowserUnavailable(UNAVAILABLE.format(reason=(type(exc).__name__+': '+str(exc))[:300]))
113
+
73
114
  def scenario(args,output):
74
115
  local=on_laptop()
75
116
  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
77
- url=args.get('url','http://127.0.0.1:3000')
117
+ # Windows bug list (round 6): a missing module surfaced as a bare "No module named 'fcntl'" and the agent spent many
118
+ # calls building its own Puppeteer harness. A runtime that cannot start now says so and what to do instead.
119
+ url=args.get('url') or preview_url()
78
120
  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
121
  url=as_preview(url)
80
122
  steps=args.get('steps',[])
@@ -82,8 +124,13 @@ def scenario(args,output):
82
124
  width=args.get('width',1280);height=args.get('height',800)
83
125
  if type(width)!=int or type(height)!=int or not 320<=width<=1920 or not 400<=height<=1200:raise ValueError('Unsupported viewport')
84
126
  errors=[];console=[];noise=[];timeline=[];network=[];page=None
127
+ owner=workspace_server(url)
128
+ if owner.get('owner')=='foreign':return foreign_result(owner,url,width,height)
129
+ try:from playwright.sync_api import sync_playwright
130
+ except ImportError as exc:raise unavailable(exc) from exc
85
131
  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'])
132
+ 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'])
133
+ except Exception as exc:raise unavailable(exc) from exc
87
134
  checked=url if local else 'http://'+PREVIEW_HOST+':3000 (the local app under the public preview host)'
88
135
  try:
89
136
  context=browser.new_context(viewport={'width':width,'height':height},service_workers='block',accept_downloads=False)
@@ -114,7 +161,12 @@ def scenario(args,output):
114
161
  interactive=hydrated(page)
115
162
  if interactive is False:errors.insert(0,NOT_INTERACTIVE)
116
163
  checked=actual(page,checked,local)
117
- return {'success':not errors,'interactive':interactive,'checkedAt':checked,**({'requestedUrl':url} if checked!=url and local else {}),'timeline':timeline,'url':page.url,'title':page.title(),'text':page.locator('body').inner_text()[:16000],'pageErrors':errors[:20],'consoleErrors':console[:20],**({'ignoredExtensionNoise':noise[:5]} if noise else {}),'networkFailures':network[:30],'horizontalOverflow':page.evaluate('document.documentElement.scrollWidth>innerWidth'),'screenshot':output.name,'viewport':{'width':width,'height':height}}
164
+ ended=page.url
165
+ if urlparse(ended).port!=urlparse(url).port:
166
+ moved=workspace_server(ended)
167
+ if moved.get('owner')=='foreign':return foreign_result(moved,ended,width,height,timeline)
168
+ owner=moved or owner
169
+ return {'success':not errors,**({'workspaceEvidence':True} if owner.get('owner') in ('ours','workspace') else {}),'interactive':interactive,'checkedAt':checked,**({'requestedUrl':url} if checked!=url and local else {}),'timeline':timeline,'url':page.url,'title':page.title(),'text':page.locator('body').inner_text()[:16000],'pageErrors':errors[:20],'consoleErrors':console[:20],**({'ignoredExtensionNoise':noise[:5]} if noise else {}),'networkFailures':network[:30],'horizontalOverflow':page.evaluate('document.documentElement.scrollWidth>innerWidth'),'screenshot':output.name,'viewport':{'width':width,'height':height}}
118
170
  except Exception as exc:
119
171
  if timeline and timeline[-1]['state']=='started':timeline[-1]['state']='failed'
120
172
  captured=False
@@ -32,7 +32,7 @@ DECK_IMPORT_TOOL = {'name': 'deck_import', 'description': "Import a file for a d
32
32
  'inputSchema': {'type': 'object', 'properties': {'path': {'type': 'string', 'description': 'Workspace file, e.g. uploads/brand-template.pptx or data/revenue.xlsx'},
33
33
  'mode': {'type': 'string', 'enum': ['theme', 'deck'], 'description': 'pptx only: theme (default) or deck'}, 'sheet': {'type': 'string', 'description': 'xlsx only: sheet name (default: the first)'},
34
34
  'range': {'type': 'string', 'description': 'xlsx/csv only: A1-style range such as A1:D13'}}, 'required': ['path'], 'additionalProperties': False}}
35
- FIND_IMAGE_TOOL = {'name': 'find_image', 'description': 'Find a freely licensed photo or illustration (CC0, public domain, CC BY, CC BY-SA) on Openverse or Wikimedia Commons and save it under public/stock/ with its credit (free, no credits). Best for real places, landmarks, historical images, people in the news, products, science and nature; stock_photo is better for generic business photos. Returns the saved path and a credit line to put in the slide\'s credit field, plus other matches (call again with pick).',
35
+ FIND_IMAGE_TOOL = {'name': 'find_image', 'description': 'Find a freely licensed photo or illustration (CC0, public domain, CC BY, CC BY-SA) on Openverse or Wikimedia Commons and save it under public/stock/ (or the project folder given in filename, e.g. images/peak) with its credit (free, no credits). Best for real places, landmarks, historical images, people in the news, products, science and nature; stock_photo is better for generic business photos. Returns the saved path and a credit line to put in the slide\'s credit field, plus other matches (call again with pick).',
36
36
  'inputSchema': {'type': 'object', 'properties': {'query': {'type': 'string', 'maxLength': 100}, 'filename': {'type': 'string', 'description': 'New two-word kebab filename'},
37
37
  'source': {'type': 'string', 'enum': ['auto', 'openverse', 'wikimedia']}, 'pick': {'type': 'string', 'description': 'id of an earlier match'}}, 'required': ['query', 'filename'], 'additionalProperties': False}}
38
38
  FIND_ICON_TOOL = {'name': 'find_icon', 'description': 'Find an icon or brand logo among about 200,000 open icons (Lucide, Tabler, Material Design, Phosphor, Simple Icons and SVG Logos for company and product logos) and save it as an SVG under public/icons/ in the colour you ask for. Use the saved path as an item icon or diagram node icon, or a logos-slide image. name="simple-icons:stripe" fetches an exact icon.',
@@ -723,8 +723,9 @@ def find_image(args, root, repo):
723
723
  _offline()
724
724
  query = ' '.join(str(args.get('query') or '').split())[:100]
725
725
  if not query: raise ValueError('query is required')
726
- stem = _stem(args.get('filename')); source = args.get('source') or 'auto'; pick = str(args.get('pick') or '')
727
- d = _public(repo, 'stock')
726
+ from media_tools import split_filename, asset_dir
727
+ folder, stem = split_filename(args.get('filename')); source = args.get('source') or 'auto'; pick = str(args.get('pick') or '')
728
+ d = asset_dir(repo, folder)[0] if folder else _public(repo, 'stock')
728
729
  if any(d.glob(stem + '.*')): raise ValueError('Asset filename already exists. Choose a new name.')
729
730
  _count(root, 'find_image')
730
731
  hits = []
@@ -231,7 +231,8 @@ def prepare(config,model,root,emit):
231
231
  def browser_review(records,current_fingerprint):
232
232
  fresh=[r for r in records if isinstance(r,dict) and r.get('sourceFingerprint')==current_fingerprint]
233
233
  def valid(r):
234
- return r.get('success') is True and r.get('horizontalOverflow') is False and not r.get('pageErrors') and not r.get('consoleErrors') and not r.get('networkFailures') and bool(r.get('screenshot')) and any(s.get('action')=='assert_text' and s.get('state')=='passed' for s in r.get('timeline',[]) if isinstance(s,dict))
234
+ # A check against another app's server (CLI 0.3.8: port 3000 served a different workspace) is not evidence here.
235
+ return r.get('workspaceEvidence') is not False and not r.get('foreignServer') and r.get('success') is True and r.get('horizontalOverflow') is False and not r.get('pageErrors') and not r.get('consoleErrors') and not r.get('networkFailures') and bool(r.get('screenshot')) and any(s.get('action')=='assert_text' and s.get('state')=='passed' for s in r.get('timeline',[]) if isinstance(s,dict))
235
236
  good=[r for r in fresh if valid(r)]
236
237
  mobile=any(320<=r.get('viewport',{}).get('width',0)<=480 for r in good)
237
238
  desktop=any(r.get('viewport',{}).get('width',0)>=1024 for r in good)