mlai-code 0.3.3 → 0.3.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (135) hide show
  1. package/README.md +1 -1
  2. package/package.json +1 -1
  3. package/src/checkpoints.mjs +217 -0
  4. package/src/cli.mjs +153 -26
  5. package/src/cloud.mjs +2 -0
  6. package/src/engine.mjs +1 -1
  7. package/src/headless.mjs +25 -9
  8. package/src/home.mjs +3 -2
  9. package/src/host.mjs +141 -13
  10. package/src/ide-quick.mjs +147 -0
  11. package/src/ide.mjs +182 -0
  12. package/src/netbox.mjs +1 -1
  13. package/src/parity.mjs +17 -0
  14. package/src/relay.mjs +1 -1
  15. package/src/render.mjs +9 -2
  16. package/src/runtime.mjs +2 -0
  17. package/src/server.mjs +46 -7
  18. package/src/session.mjs +31 -8
  19. package/src/tui/acp.mjs +121 -19
  20. package/src/tui/app.mjs +2 -1
  21. package/src/tui/chat.mjs +35 -10
  22. package/src/tui/cmd-config.mjs +3 -1
  23. package/src/tui/cmd-core.mjs +9 -5
  24. package/src/tui/cmd-extensibility.mjs +5 -0
  25. package/src/tui/extensions-local.mjs +2 -0
  26. package/src/tui/mcp-config.mjs +22 -4
  27. package/src/tui/review-cli.mjs +15 -4
  28. package/src/tui/snapshots.mjs +57 -16
  29. package/src/two-words.mjs +14 -8
  30. package/src/view-sync.mjs +48 -0
  31. package/src/winenv.mjs +1 -1
  32. package/src/workspace-api.mjs +21 -4
  33. package/vendor/client-sdk/index.cjs +2 -1
  34. package/vendor/cloud-cli/mlai.mjs +23 -11
  35. package/worker/architecture_worker.py +33 -4
  36. package/worker/browser_tool.py +19 -1
  37. package/worker/chat_fork.py +4 -1
  38. package/worker/checkpoints.py +71 -8
  39. package/worker/command_safety.py +56 -3
  40. package/worker/connected_turn.py +30 -0
  41. package/worker/conversation.py +81 -11
  42. package/worker/git_sync.py +4 -4
  43. package/worker/image_generation.py +2 -2
  44. package/worker/kimi_bridge.py +247 -27
  45. package/worker/kimi_gates.py +25 -6
  46. package/worker/kimi_hook.py +153 -12
  47. package/worker/media_tools.py +4 -1
  48. package/worker/mlai_hooks.py +222 -3
  49. package/worker/mlai_mcp.py +26 -6
  50. package/worker/mlai_review/README.md +35 -0
  51. package/worker/mlai_review/__init__.py +1 -0
  52. package/worker/mlai_review/__main__.py +261 -0
  53. package/worker/mlai_review/_compat.py +29 -0
  54. package/worker/mlai_review/analysis/__init__.py +3 -0
  55. package/worker/mlai_review/analysis/detect.py +50 -0
  56. package/worker/mlai_review/analysis/main.py +128 -0
  57. package/worker/mlai_review/analysis/messages.py +8 -0
  58. package/worker/mlai_review/analysis/tools.py +194 -0
  59. package/worker/mlai_review/application/__init__.py +1 -0
  60. package/worker/mlai_review/application/asking.py +53 -0
  61. package/worker/mlai_review/application/challengers.py +142 -0
  62. package/worker/mlai_review/application/context_builder.py +194 -0
  63. package/worker/mlai_review/application/errors.py +17 -0
  64. package/worker/mlai_review/application/feedback.py +52 -0
  65. package/worker/mlai_review/application/matching.py +46 -0
  66. package/worker/mlai_review/application/messages.py +41 -0
  67. package/worker/mlai_review/application/ports.py +222 -0
  68. package/worker/mlai_review/application/prompts.py +342 -0
  69. package/worker/mlai_review/application/review_service.py +200 -0
  70. package/worker/mlai_review/application/reviewers.py +438 -0
  71. package/worker/mlai_review/application/streaming.py +91 -0
  72. package/worker/mlai_review/application/tools.py +138 -0
  73. package/worker/mlai_review/application/usage.py +145 -0
  74. package/worker/mlai_review/application/write_check.py +46 -0
  75. package/worker/mlai_review/contracts/__init__.py +5 -0
  76. package/worker/mlai_review/contracts/analysis.py +57 -0
  77. package/worker/mlai_review/contracts/review.py +42 -0
  78. package/worker/mlai_review/domain/__init__.py +4 -0
  79. package/worker/mlai_review/domain/changes.py +77 -0
  80. package/worker/mlai_review/domain/context.py +147 -0
  81. package/worker/mlai_review/domain/diagnostics.py +239 -0
  82. package/worker/mlai_review/domain/feedback.py +216 -0
  83. package/worker/mlai_review/domain/findings.py +505 -0
  84. package/worker/mlai_review/domain/lifecycle.py +85 -0
  85. package/worker/mlai_review/domain/partition.py +42 -0
  86. package/worker/mlai_review/domain/relations.py +166 -0
  87. package/worker/mlai_review/domain/relevance.py +202 -0
  88. package/worker/mlai_review/domain/report.py +99 -0
  89. package/worker/mlai_review/domain/structure.py +56 -0
  90. package/worker/mlai_review/domain/writes.py +86 -0
  91. package/worker/mlai_review/eval.py +221 -0
  92. package/worker/mlai_review/eval_cases/clean-rename.json +11 -0
  93. package/worker/mlai_review/eval_cases/missing-ownership-check.json +22 -0
  94. package/worker/mlai_review/eval_cases/off-by-one.json +22 -0
  95. package/worker/mlai_review/eval_cases/sql-injection.json +20 -0
  96. package/worker/mlai_review/feedback_report.py +60 -0
  97. package/worker/mlai_review/infrastructure/__init__.py +1 -0
  98. package/worker/mlai_review/infrastructure/analysis/__init__.py +1 -0
  99. package/worker/mlai_review/infrastructure/analysis/none.py +12 -0
  100. package/worker/mlai_review/infrastructure/analysis/translate.py +17 -0
  101. package/worker/mlai_review/infrastructure/github/__init__.py +0 -0
  102. package/worker/mlai_review/infrastructure/github/client.py +445 -0
  103. package/worker/mlai_review/infrastructure/github/feedback.py +212 -0
  104. package/worker/mlai_review/infrastructure/github/http.py +31 -0
  105. package/worker/mlai_review/infrastructure/github/rendering.py +398 -0
  106. package/worker/mlai_review/infrastructure/github/token.py +20 -0
  107. package/worker/mlai_review/infrastructure/local/__init__.py +1 -0
  108. package/worker/mlai_review/infrastructure/local/analyzer.py +48 -0
  109. package/worker/mlai_review/infrastructure/local/events.py +100 -0
  110. package/worker/mlai_review/infrastructure/local/git_reader.py +233 -0
  111. package/worker/mlai_review/infrastructure/local/publisher.py +138 -0
  112. package/worker/mlai_review/infrastructure/messages.py +54 -0
  113. package/worker/mlai_review/infrastructure/models/__init__.py +0 -0
  114. package/worker/mlai_review/infrastructure/models/openai_compatible.py +269 -0
  115. package/worker/mlai_review/infrastructure/structure/__init__.py +1 -0
  116. package/worker/mlai_review/infrastructure/structure/heuristic.py +186 -0
  117. package/worker/mlai_review/infrastructure/structure/tree_sitter.py +186 -0
  118. package/worker/mlai_review/infrastructure/workspace/__init__.py +1 -0
  119. package/worker/mlai_review/infrastructure/workspace/local.py +105 -0
  120. package/worker/mlai_review/infrastructure/workspace/memory.py +77 -0
  121. package/worker/mlai_review/infrastructure/workspace/paths.py +17 -0
  122. package/worker/mlai_review/pipeline.py +89 -0
  123. package/worker/mlai_review/runtime.py +194 -0
  124. package/worker/mlai_review/settings.py +139 -0
  125. package/worker/preview.py +15 -0
  126. package/worker/product_facts.py +3 -1
  127. package/worker/repo_policy.py +5 -0
  128. package/worker/roles.py +29 -2
  129. package/worker/runner.py +126 -18
  130. package/worker/runtime_control.py +64 -3
  131. package/worker/secret_scan.py +3 -2
  132. package/worker/server_memory.py +122 -0
  133. package/worker/subagents.py +6 -2
  134. package/worker/tool_catalog.py +1 -1
  135. package/worker/verification.py +113 -8
package/README.md CHANGED
@@ -1,4 +1,4 @@
1
- # mlai-code 0.3.3
1
+ # mlai-code 0.3.4
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.3",
3
+ "version": "0.3.4",
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": {
@@ -0,0 +1,217 @@
1
+ /**
2
+ * Step checkpoints for editor sessions (VS Code, JetBrains, ACP). The working tree is recorded in a private git store
3
+ * in the session folder (~/.mlai/sessions/<id>/checkpoints.git), never in the project's own repository: no commits,
4
+ * refs, index changes or stash entries appear there. Untracked files are included; .gitignore rules are honored.
5
+ *
6
+ * A checkpoint is taken at the start of every turn and after every agent step that changed files, so restoring one
7
+ * returns the folder to the moment before the next step wrote anything.
8
+ */
9
+ import {execFile} from 'node:child_process';
10
+ import {existsSync} from 'node:fs';
11
+ import {mkdir,readFile,writeFile,rm,rename,lstat} from 'node:fs/promises';
12
+ import path from 'node:path';
13
+
14
+ const LIMIT_MS=30000,MAX_BUFFER=64*1024*1024,KEEP=400;
15
+ export const TEXT_CAP=200_000;
16
+ const ID=/^[0-9a-f]{40}$/;
17
+
18
+ export class CheckpointError extends Error{constructor(message,status=400,code){super(message);this.status=status;this.code=code}}
19
+
20
+ export class Checkpoints{
21
+ /** session: a Session (meta.root is the folder, dir is the session folder). */
22
+ constructor(session){this.session=session;this.queue=Promise.resolve();this.cache=null}
23
+ get root(){return this.session.meta.root}
24
+ get store(){return path.join(this.session.dir,'checkpoints.git')}
25
+ get file(){return path.join(this.session.dir,'checkpoints.json')}
26
+ git(args,{input,encoding='utf8'}={}){
27
+ const dir=this.store;
28
+ const env={...process.env,GIT_DIR:dir,GIT_WORK_TREE:this.root,GIT_INDEX_FILE:path.join(dir,'mlai-index'),
29
+ GIT_AUTHOR_NAME:'ML AI Code',GIT_AUTHOR_EMAIL:'checkpoints@mlai.local',GIT_COMMITTER_NAME:'ML AI Code',GIT_COMMITTER_EMAIL:'checkpoints@mlai.local',GIT_TERMINAL_PROMPT:'0'};
30
+ for(const k of ['GIT_OBJECT_DIRECTORY','GIT_ALTERNATE_OBJECT_DIRECTORIES','GIT_CEILING_DIRECTORIES','GIT_NAMESPACE'])delete env[k];
31
+ return new Promise((resolve,reject)=>{
32
+ const p=execFile('git',['-c','core.autocrlf=false','-c','core.safecrlf=false','-c','gc.auto=0','-c','core.quotepath=false',...args],{cwd:this.root,env,timeout:LIMIT_MS,maxBuffer:MAX_BUFFER,encoding,windowsHide:true},
33
+ (e,stdout,stderr)=>e?reject(Object.assign(new Error(String(stderr||e.message).trim().split('\n').pop()),{code:e.code,killed:e.killed})):resolve(encoding==='utf8'?stdout.replace(/\n$/,''):stdout));
34
+ if(input!=null)p.stdin.end(input);
35
+ });
36
+ }
37
+ /** Serializes work on the store: the harness may finish steps faster than git records them. */
38
+ run(fn){const next=this.queue.then(fn,fn);this.queue=next.catch(()=>{});return next}
39
+ async ensure(){
40
+ if(existsSync(path.join(this.store,'HEAD')))return;
41
+ await mkdir(this.store,{recursive:true,mode:0o700});
42
+ await new Promise((res,rej)=>execFile('git',['init','-q','--bare',this.store],{timeout:LIMIT_MS,windowsHide:true},e=>e?rej(e):res()));
43
+ // The project's own excludes, plus the session store itself when the session lives inside the project.
44
+ const own=await readFile(path.join(this.root,'.git','info','exclude'),'utf8').catch(()=>'');
45
+ await mkdir(path.join(this.store,'info'),{recursive:true});
46
+ await writeFile(path.join(this.store,'info','exclude'),own+'\n.git\n.mlai/sessions/\n');
47
+ }
48
+ async list(){
49
+ if(this.cache)return this.cache;
50
+ try{const v=JSON.parse(await readFile(this.file,'utf8'));this.cache=Array.isArray(v)?v:[]}catch{this.cache=[]}
51
+ return this.cache;
52
+ }
53
+ async #save(list){this.cache=list;const tmp=this.file+'.tmp';await writeFile(tmp,JSON.stringify(list));await rename(tmp,this.file)}
54
+ /** The public shape: [{id, turn, step, at, label, files}]. */
55
+ async public(){return (await this.list()).filter(c=>!c.undo).map(({tree,parent,...c})=>c)}
56
+ async #tree(){await this.git(['add','-A','--','.']);return this.git(['write-tree'])}
57
+ /**
58
+ * Records the folder. Returns the new checkpoint, or null when nothing changed since the last one (unless `force`)
59
+ * or when checkpoints are off for this session (a folder too large to record in time).
60
+ */
61
+ capture({turn,step=0,label,force=false,undo=false}={}){
62
+ return this.run(async()=>{
63
+ if(this.session.meta.checkpoints===false)return null;
64
+ try{
65
+ await this.ensure();
66
+ const list=await this.list(),last=[...list].reverse().find(c=>!c.undo)||null;
67
+ const tree=await this.#tree();
68
+ if(!force&&last&&last.tree===tree)return null;
69
+ const files=last?await this.#names(last.tree,tree):[];
70
+ if(!force&&last&&!files.length)return null;
71
+ const id=await this.git(['commit-tree',tree,...(last?['-p',last.id]:[]),'-m',String(label||'Checkpoint').slice(0,200)]);
72
+ await this.git(['update-ref','refs/checkpoints/'+id,id]);
73
+ const cp={id,turn:Number.isInteger(turn)?turn:Math.max(0,this.session.meta.turns.length-1),step,at:new Date().toISOString(),label:String(label||'Checkpoint').slice(0,200),files:files.map(f=>f.path),changes:files,tree,...(undo?{undo:true}:{})};
74
+ const next=[...list,cp];
75
+ // Old checkpoints drop off the list (and their refs), oldest first; turn starts are kept longest.
76
+ while(next.length>KEEP){const i=next.findIndex(c=>c.step!==0||c.undo);const [gone]=next.splice(i>=0?i:0,1);await this.git(['update-ref','-d','refs/checkpoints/'+gone.id]).catch(()=>{})}
77
+ await this.#save(next);
78
+ return cp;
79
+ }catch(e){
80
+ if(e.killed||e.code==='ETIMEDOUT'||/timed out|ENOBUFS|maxBuffer/i.test(e.message)){this.session.meta.checkpoints=false;await this.session.save().catch(()=>{})}
81
+ return null;
82
+ }
83
+ });
84
+ }
85
+ /** The checkpoint for an id, or for 'turn-start' (the start of the latest turn). */
86
+ async find(ref){
87
+ const list=(await this.list()).filter(c=>!c.undo);
88
+ if(ref==null||ref===''||ref==='turn-start'){const t=[...list].reverse().find(c=>c.step===0);if(!t)throw new CheckpointError('No checkpoint yet. Checkpoints start with the first task.',404,'no_checkpoint');return t}
89
+ if(/^turn-\d+$/.test(String(ref))){const n=Number(String(ref).slice(5));const t=list.find(c=>c.step===0&&c.turn===n);if(!t)throw new CheckpointError('No checkpoint for that turn',404,'no_checkpoint');return t}
90
+ const s=String(ref);if(!/^[0-9a-f]{7,40}$/.test(s))throw new CheckpointError('Unknown checkpoint',404,'no_checkpoint');
91
+ const hit=list.filter(c=>c.id.startsWith(s));if(hit.length!==1)throw new CheckpointError('Unknown checkpoint',404,'no_checkpoint');
92
+ return hit[0];
93
+ }
94
+ async #names(a,b){
95
+ const out=await this.git(['diff','--name-status','--no-renames','-z',a,b]);
96
+ const parts=out.split('\0').filter(Boolean),files=[];
97
+ for(let i=0;i+1<parts.length;i+=2)files.push({path:parts[i+1],status:parts[i][0]==='A'?'added':parts[i][0]==='D'?'deleted':'modified'});
98
+ return files;
99
+ }
100
+ /**
101
+ * Files that differ between a checkpoint and the folder now:
102
+ * [{path, status, before, after, additions, deletions, hunks}] (text up to TEXT_CAP; {binary:true} or {tooLarge:true} otherwise).
103
+ */
104
+ changes(since){
105
+ return this.run(async()=>{
106
+ await this.ensure();
107
+ const cp=await this.find(since),now=await this.#tree();
108
+ const files=await this.#names(cp.tree,now);
109
+ const stat=await this.git(['diff','--numstat','--no-renames','-z',cp.tree,now]);
110
+ const counts=new Map();for(const rec of stat.split('\0').filter(Boolean)){const m=/^(-|\d+)\t(-|\d+)\t(.*)$/s.exec(rec);if(m)counts.set(m[3],{additions:m[1]==='-'?null:Number(m[1]),deletions:m[2]==='-'?null:Number(m[2]),binary:m[1]==='-'})}
111
+ const out=[];
112
+ for(const f of files){
113
+ const c=counts.get(f.path)||{additions:0,deletions:0,binary:false};
114
+ const item={path:f.path,status:f.status,additions:c.additions||0,deletions:c.deletions||0,checkpoint:cp.id};
115
+ if(c.binary){out.push({...item,binary:true});continue}
116
+ const before=f.status==='added'?'':await this.#blob(cp.tree,f.path);
117
+ const after=f.status==='deleted'?'':await this.#blob(now,f.path);
118
+ if(before==null||after==null||before.length>TEXT_CAP||after.length>TEXT_CAP){out.push({...item,tooLarge:true});continue}
119
+ out.push({...item,before,after,hunks:await this.#hunks(cp.tree,now,f.path)});
120
+ }
121
+ return {since:cp.id,files:out};
122
+ });
123
+ }
124
+ async #blob(tree,file){try{return (await this.git(['cat-file','blob',tree+':'+file],{encoding:'buffer'})).toString('utf8')}catch{return null}}
125
+ async #hunks(a,b,file){
126
+ const d=await this.git(['diff','-U0','--no-color','--no-ext-diff',a,b,'--',file]).catch(()=>'');
127
+ return parseHunks(d);
128
+ }
129
+ /**
130
+ * Restores the folder to a checkpoint. The current state is recorded first (an undo checkpoint), so a restore can
131
+ * itself be undone. Returns {restored, removed}.
132
+ */
133
+ restoreFiles(ref){
134
+ return this.run(async()=>{
135
+ await this.ensure();
136
+ const cp=await this.find(ref),now=await this.#tree();
137
+ const undo=await this.git(['commit-tree',now,'-m','Before restore']);await this.git(['update-ref','refs/checkpoints/undo-'+Date.now(),undo]);
138
+ const changes=await this.#names(cp.tree,now);
139
+ const created=changes.filter(c=>c.status==='added').map(c=>c.path);
140
+ for(const f of created){const abs=path.resolve(this.root,f);if(abs.startsWith(path.resolve(this.root)+path.sep))await rm(abs,{force:true})}
141
+ await this.git(['read-tree',cp.tree]);
142
+ await this.git(['checkout-index','-a','-f']);
143
+ return {checkpoint:cp.id,undo,restored:changes.length-created.length,removed:created.length,files:changes.map(c=>c.path)};
144
+ });
145
+ }
146
+ /**
147
+ * Reverts one file to a checkpoint (default: the start of the latest turn). With `hunks`, only those hunks
148
+ * ({oldStart, oldLines, newStart, newLines} from changes()) are reverted; the rest of the file stays as it is.
149
+ */
150
+ revert(file,{hunks=null,since='turn-start'}={}){
151
+ return this.run(async()=>{
152
+ await this.ensure();
153
+ const rel=safeRel(this.root,file),abs=path.join(this.root,rel);
154
+ const cp=await this.find(since);
155
+ const before=await this.git(['cat-file','blob',cp.tree+':'+rel],{encoding:'buffer'}).catch(()=>null);
156
+ if(!Array.isArray(hunks)||!hunks.length){
157
+ if(before==null){await rm(abs,{force:true});return {path:rel,status:'removed',checkpoint:cp.id}}
158
+ await mkdir(path.dirname(abs),{recursive:true});await writeFile(abs,before);return {path:rel,status:'restored',checkpoint:cp.id};
159
+ }
160
+ let current;try{if((await lstat(abs)).isSymbolicLink())throw new CheckpointError('This file is a link; revert the whole file');current=await readFile(abs)}catch(e){if(e instanceof CheckpointError)throw e;throw new CheckpointError('The file no longer exists. Revert the whole file instead.',409,'file_missing')}
161
+ if(before==null)throw new CheckpointError('This file is new since the checkpoint. Revert the whole file instead.',409,'file_added');
162
+ const blob=await this.git(['hash-object','-w','--stdin'],{input:current});
163
+ const oldBlob=await this.git(['rev-parse',cp.tree+':'+rel]);
164
+ const diff=await this.git(['diff','-U0','--no-color','--no-ext-diff',oldBlob,blob]);
165
+ const all=parseHunks(diff,{lines:true});
166
+ const key=h=>[h.oldStart,h.oldLines,h.newStart,h.newLines].join(',');
167
+ const want=new Set(hunks.map(h=>key({oldStart:Number(h?.oldStart),oldLines:Number(h?.oldLines),newStart:Number(h?.newStart),newLines:Number(h?.newLines)})));
168
+ const pick=all.filter(h=>want.has(key(h)));
169
+ if(pick.length!==want.size)throw new CheckpointError('The file changed since these hunks were listed. Refresh the changes and try again.',409,'stale_hunks');
170
+ const out=applyReverse(current.toString('utf8'),pick);
171
+ await writeFile(abs,out);
172
+ // Every hunk reverted: the file is back to the checkpoint.
173
+ return {path:rel,status:pick.length===all.length?'restored':'partially_restored',checkpoint:cp.id,hunks:pick.length};
174
+ });
175
+ }
176
+ /** Drops checkpoints of turns after `turn` (they belong to turns that no longer exist after a chat restore). */
177
+ async forgetAfter(turn,{keep:id=null}={}){
178
+ return this.run(async()=>{const list=await this.list(),gone=c=>c.turn>turn&&c.id!==id;const keep=list.filter(c=>!gone(c));for(const c of list)if(gone(c))await this.git(['update-ref','-d','refs/checkpoints/'+c.id]).catch(()=>{});await this.#save(keep)});
179
+ }
180
+ }
181
+
182
+ export function safeRel(root,file){
183
+ if(typeof file!=='string'||!file||file.includes('\0'))throw new CheckpointError('Choose a file');
184
+ const abs=path.resolve(root,file),r=path.resolve(root);
185
+ if(!abs.startsWith(r+path.sep))throw new CheckpointError('That file is outside this folder');
186
+ const rel=path.relative(r,abs).split(path.sep).join('/');
187
+ if(rel.split('/').includes('.git'))throw new CheckpointError('That file is outside this folder');
188
+ return rel;
189
+ }
190
+ /** Hunks from a -U0 unified diff: [{oldStart, oldLines, newStart, newLines}] (with `lines`, also the removed lines). */
191
+ export function parseHunks(diff,{lines=false}={}){
192
+ const out=[];let cur=null;
193
+ for(const l of String(diff||'').split('\n')){
194
+ const m=/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/.exec(l);
195
+ if(m){cur={oldStart:Number(m[1]),oldLines:m[2]==null?1:Number(m[2]),newStart:Number(m[3]),newLines:m[4]==null?1:Number(m[4])};if(lines)cur.removed=[];out.push(cur);continue}
196
+ if(!cur||!lines)continue;
197
+ if(l.startsWith('-'))cur.removed.push({text:l.slice(1),nl:true});
198
+ else if(l.startsWith('\\')&&cur.removed.length&&cur.lastWasRemoved)cur.removed[cur.removed.length-1].nl=false;
199
+ cur.lastWasRemoved=l.startsWith('-')||(l.startsWith('\\')&&cur.lastWasRemoved);
200
+ }
201
+ for(const h of out)delete h.lastWasRemoved;
202
+ return out;
203
+ }
204
+ /** Puts the removed lines of `hunks` back in place of their added lines. */
205
+ export function applyReverse(text,hunks){
206
+ const lines=text.match(/[^\n]*\n|[^\n]+$/g)||[];
207
+ for(const h of [...hunks].sort((a,b)=>b.newStart-a.newStart)){
208
+ const at=h.newLines===0?h.newStart:h.newStart-1;
209
+ const old=h.removed.map(r=>r.text+(r.nl?'\n':''));
210
+ // A hunk ending the file without a newline, restored in the middle: the line before it needs its newline back.
211
+ lines.splice(at,h.newLines,...old);
212
+ }
213
+ // Lines that now sit before restored text must end with a newline.
214
+ for(let i=0;i<lines.length-1;i++)if(!lines[i].endsWith('\n'))lines[i]+='\n';
215
+ return lines.join('');
216
+ }
217
+ export {ID as CHECKPOINT_ID};
package/src/cli.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  // mlai: ML AI Code in the terminal. The agent works in this folder on this machine; the model runs in ML AI Code's cloud.
2
2
  import readline from 'node:readline';
3
3
  import {spawn,execFileSync} from 'node:child_process';
4
- import {existsSync} from 'node:fs';
4
+ import {existsSync,statSync,readFileSync,fstatSync} from 'node:fs';
5
5
  import {readFile} from 'node:fs/promises';
6
6
  import os from 'node:os';
7
7
  import path from 'node:path';
@@ -15,7 +15,7 @@ import {Session,sandboxKind} from './session.mjs';
15
15
  import {MODES as CLI_MODES,modeName,nextMode,engineMode} from './modes.mjs';
16
16
  import {loadSettings} from './settings.mjs';
17
17
  import * as registry from './tui/commands.mjs';
18
- import {Chat,answerOf} from './tui/chat.mjs';
18
+ import {Chat,answerOf,modelList} from './tui/chat.mjs';
19
19
  import {plainUi} from './tui/plain.mjs';
20
20
  import {projectRoot} from './project.mjs';
21
21
  import {createWorktree} from './worktree.mjs';
@@ -24,9 +24,10 @@ import {worktreeFromArg} from './tui/session-ops.mjs';
24
24
  import {SANDBOXES} from './sandbox.mjs';
25
25
  import {restrictedForced,refusedFlag} from './restricted.mjs';
26
26
  import {gitForWindows} from './winenv.mjs';
27
- import {ensureRuntime,runtimeInfo} from './runtime.mjs';
27
+ import {ensureRuntime,runtimeInfo,PY_VERSION,hideEngineName} from './runtime.mjs';
28
28
  import {palette,renderEvent,approvalView,summaryLine,exitCode,EXIT,fmt,credits} from './render.mjs';
29
29
  import {runHeadless,streamInputs,stdinLines,toolRules,loadSchema,HeadlessError} from './headless.mjs';
30
+ import {terminals,backgroundCommand} from './tui/bgterm.mjs';
30
31
 
31
32
  /** Every option, for --help and shell completion (src/completion.mjs). value: the placeholder when it takes one. */
32
33
  export const FLAGS=[
@@ -41,7 +42,7 @@ export const FLAGS=[
41
42
  {flag:'--fork',summary:'With -c or -r: continue in a copy, leaving the original session as it was'},
42
43
  {flag:'--output-format',value:'<format>',summary:'Headless output: text (default), json (one result object) or stream-json (one\nevent per line, then the result)',choices:['text','json','stream-json']},
43
44
  {flag:'--max-steps',value:'<n>',summary:'Maximum agent steps per turn, 1 to 160 (default 120)'},
44
- {flag:'--add-dir',value:'<path>',summary:'Let the agent read another folder too (repeatable)'},
45
+ {flag:'--add-dir',value:'<path>',summary:'Let the agent read another folder without asking (repeatable); other reads outside the project ask first'},
45
46
  {flag:'--image',value:'<path>',summary:'Attach an image (PNG, JPEG, WebP or GIF) to the first message (repeatable)'},
46
47
  {flag:'--tui',summary:'Use the full terminal interface (overrides the tui setting)'},
47
48
  {flag:'--no-tui',summary:'Use the plain line-based interface'},
@@ -104,18 +105,41 @@ Options
104
105
  ${options()}
105
106
 
106
107
  Exit codes: 0 done, 1 failed, 2 usage, 3 needs attention, 4 sign-in needed, 5 plan limit reached,
107
- 130 stopped.
108
+ 6 cannot be done (the agent reported the request impossible), 130 stopped.
108
109
 
109
110
  In a session: type a task; while it works, type to steer it. y / a / n answer approvals.
110
111
  Type / for commands (/help lists them), Shift+Tab switches mode, Ctrl-C stops the task,
111
112
  Ctrl-C twice exits.`;
112
113
 
114
+ // BUG-0536: `mlai sessions|doctor|login|logout|whoami --help` show that command's own help.
115
+ const SUB_HELP={
116
+ sessions:`Usage: mlai sessions [--json]
117
+
118
+ List recent sessions on this computer, newest first (times are local).
119
+ --json Print the list as JSON
120
+ Continue one with mlai resume <id>, or mlai -r <id> -p "task".`,
121
+ doctor:`Usage: mlai doctor [--fix]
122
+
123
+ Check this computer: Node.js, the coding engine, sign-in and the server.
124
+ --fix Install the coding engine now`,
125
+ login:`Usage: mlai login [--server <url>]
126
+
127
+ Sign in to ML AI Code in your browser. This device stays signed in until you run mlai logout.
128
+ --server <url> Sign in to another ML AI Code server
129
+ Set MLAI_NO_BROWSER=1 to print the sign-in link instead of opening the browser.`,
130
+ logout:`Usage: mlai logout
131
+
132
+ Sign out on this device and remove the stored credential.`,
133
+ whoami:`Usage: mlai whoami [--json]
134
+
135
+ Show the account and device this computer is signed in as.`,
136
+ };
113
137
  const LEGACY_MODES={guided:'agent'};
114
138
  export function parseArgs(argv){
115
139
  const o={_:[],mode:null,json:false,yes:false,sandbox:true,steps:120,verbose:false,server:null,print:null,fix:false,worktree:false,
116
140
  model:null,effort:null,continue:false,resume:null,name:null,fork:false,outputFormat:'text',addDirs:[],skipPermissions:false,maxStepsSet:false,
117
141
  fallbackModel:null,inputFormat:'text',jsonSchema:null,maxTurns:null,maxBudgetCredits:null,sessionId:null,noSessionPersistence:false,allowedTools:[],disallowedTools:[],tools:null,appendSystemPrompt:null,cloud:false,teleport:null,bg:false,bgChild:false};
118
- o.images=[];o.tui=null;
142
+ o.images=[];o.tui=null;let wtWord=null;
119
143
  const mode=v=>{const m=modeName(LEGACY_MODES[v]||v);if(!m)throw new UsageError('Mode must be agent, plan, ask or auto');return m};
120
144
  const steps=v=>{const n=Number(v);if(!Number.isInteger(n)||n<1||n>160)throw new UsageError('--max-steps must be 1 to 160');o.steps=n;o.maxStepsSet=true};
121
145
  const optional=i=>argv[i+1]!==undefined&&!argv[i+1].startsWith('-');
@@ -146,7 +170,8 @@ export function parseArgs(argv){
146
170
  else if(a==='--output-format'){const v=next();if(!['text','json','stream-json'].includes(v))throw new UsageError('--output-format must be text, json or stream-json');o.outputFormat=v;o.json=v!=='text'}
147
171
  else if(a==='--json'){o.outputFormat='stream-json';o.json=true}
148
172
  else if(a==='--max-steps'||a==='--steps')steps(next());
149
- else if(a==='--add-dir'){const d=path.resolve(next());if(!existsSync(d))throw new UsageError('--add-dir: no folder '+d);o.addDirs.push(d)}
173
+ else if(a==='--add-dir'){const d=path.resolve(next());if(!existsSync(d))throw new UsageError('--add-dir: no folder '+d);if(!statSync(d).isDirectory())throw new UsageError('--add-dir: '+d+' is not a folder'); // BUG-0538
174
+ o.addDirs.push(d)}
150
175
  else if(a==='--image'){const f=path.resolve(next());if(!/\.(png|jpe?g|webp|gif)$/i.test(f))throw new UsageError('--image takes a PNG, JPEG, WebP or GIF file');if(!existsSync(f))throw new UsageError('--image: no file '+f);o.images.push(f)}
151
176
  else if(a==='--tui')o.tui='full';
152
177
  else if(a==='--no-tui')o.tui='plain';
@@ -155,7 +180,10 @@ export function parseArgs(argv){
155
180
  else if(a==='--dangerously-skip-permissions')o.skipPermissions=true;
156
181
  else if(a==='--restricted')o.restricted=true;
157
182
  else if(a==='--fix')o.fix=true;
158
- else if(a==='--worktree'||a==='-w')o.worktree=inline!==null?inline:argv[i+1]!==undefined&&/^(#\d+|https?:\/\/\S+\/(pull|merge_requests)\/\d+)/.test(argv[i+1])?argv[++i]:true;
183
+ else if(a==='--worktree'||a==='-w'){
184
+ o.worktree=inline!==null?inline:argv[i+1]!==undefined&&/^(#\d+|https?:\/\/\S+\/(pull|merge_requests)\/\d+)/.test(argv[i+1])?argv[++i]:true;
185
+ if(o.worktree===true&&/^[A-Za-z0-9][A-Za-z0-9._\/-]{0,79}$/.test(argv[i+1]||''))wtWord=argv[i+1];
186
+ }
159
187
  else if(a==='--server')o.server=next();
160
188
  // CLI2 cloud and background (tui/cloud-cli.mjs, tui/bg.mjs).
161
189
  else if(a==='--cloud')o.cloud=true;
@@ -170,6 +198,11 @@ export function parseArgs(argv){
170
198
  else if(a.startsWith('-')&&a.length>1)throw new UsageError('Unknown option '+a+'. Run mlai --help.');
171
199
  else o._.push(a);
172
200
  }
201
+ // BUG-0498: `mlai -w mywt -p "task"`: the plain word after -w names the worktree when the task comes from elsewhere
202
+ // (-p "task" or more words); a lone `mlai -w fix` still means the task "fix".
203
+ if(wtWord&&o._.includes(wtWord)&&((o.print!==null&&o.print!=='-')||o._.length>1)){o.worktree=wtWord;o._.splice(o._.indexOf(wtWord),1)}
204
+ // BUG-0493: `mlai -p --mode agent "task"`: the task after the options belongs to -p (it used to wait on stdin).
205
+ if(o.print==='-'&&o._.length&&!COMMANDS.includes(o._[0])){o.print=o._.join(' ');o._=[]}
173
206
  if(o.fork&&!o.continue&&o.resume===null)throw new UsageError('--fork goes with -c or -r.');
174
207
  if(o.cloud&&o.teleport!==null)throw new UsageError('Use --cloud or --teleport, not both.');
175
208
  if(o.teleport!==null&&(o.continue||o.resume!==null))throw new UsageError('--teleport starts its own session; leave out -c and -r.');
@@ -183,6 +216,26 @@ export function parseArgs(argv){
183
216
  class UsageError extends Error{}
184
217
  const COMMANDS=['help','version','login','logout','whoami','sessions','resume','doctor','cloud','serve','runner','acp','remote-control'];
185
218
 
219
+ const jsonArgv=argv=>argv.includes('--json')||argv.some((a,i)=>a==='--output-format=json'||a==='--output-format=stream-json'||(a==='--output-format'&&/^(stream-)?json$/.test(argv[i+1]||'')));
220
+ /** BUG-0547/BUG-0503: session times in the local time zone (the stored value is UTC). */
221
+ export function localStamp(iso){const d=new Date(iso);if(isNaN(d))return String(iso||'').slice(0,16).replace('T',' ');const p=n=>String(n).padStart(2,'0');return d.getFullYear()+'-'+p(d.getMonth()+1)+'-'+p(d.getDate())+' '+p(d.getHours())+':'+p(d.getMinutes())}
222
+ /** BUG-0524: a turn left "running" by an mlai process that was killed shows what status.json says, or interrupted. */
223
+ export function shownState(dir,state){
224
+ if(state!=='running'&&state!=='starting')return state;
225
+ const pid=Number((()=>{try{return readFileSync(path.join(dir,'running.lock'),'utf8')}catch{return ''}})());
226
+ if(pid>0){if(pid===process.pid)return state;try{process.kill(pid,0);return state}catch(e){if(e.code==='EPERM')return state}}
227
+ let st={};try{st=JSON.parse(readFileSync(path.join(dir,'status.json'),'utf8'))}catch{}
228
+ return st.state&&!['running','starting','idle'].includes(st.state)?st.state:'interrupted';
229
+ }
230
+ /** BUG-0545: text piped in with a task (cat err.log | mlai -p "explain") goes with the task. Only a real pipe or file. */
231
+ async function pipedInput(){
232
+ try{const st=fstatSync(0);if(!(st.isFIFO()||st.isFile()))return ''}catch{return ''}
233
+ // A pipe that stays open and silent (a script's inherited stdin) must not hang the run: no first data in 3s, no input.
234
+ const t=await new Promise(resolve=>{let s='',got=false;const done=()=>{clearTimeout(timer);process.stdin.off('data',on);process.stdin.off('end',done);process.stdin.destroy();resolve(s)};
235
+ const on=c=>{got=true;s+=c;if(s.length>200000)done()};const timer=setTimeout(()=>{if(!got)done()},3000);
236
+ process.stdin.setEncoding('utf8');process.stdin.on('data',on);process.stdin.once('end',done)});
237
+ return t.length>200000?t.slice(0,200000)+'\n[... cut at 200,000 characters]':t;
238
+ }
186
239
  async function readStdin(){let s='';for await(const c of process.stdin)s+=c;return s}
187
240
  function openBrowser(url){
188
241
  const cmd=process.platform==='darwin'?'open':process.platform==='win32'?'cmd':'xdg-open';
@@ -211,16 +264,17 @@ export async function main(argv=process.argv.slice(2)){
211
264
  if(argv[0]==='review')return await (await import('./tui/review-cli.mjs')).reviewMain(argv.slice(1),{cloud:o=>cloudFor(o),color:palette(process.stdout.isTTY&&!process.env.NO_COLOR&&!argv.includes('--json'))});
212
265
  if(EXT_COMMANDS[argv[0]])return await EXT_COMMANDS[argv[0]](argv.slice(1));
213
266
  let o;
214
- try{o=parseArgs(argv)}catch(e){process.stderr.write(e.message+'\n');return EXIT.usage}
267
+ try{o=parseArgs(argv)}catch(e){if(jsonArgv(argv))process.stdout.write(JSON.stringify({type:'result',state:'error',subtype:'error_usage',error:e.message,exitCode:EXIT.usage})+'\n');else process.stderr.write(e.message+'\n');return EXIT.usage}
215
268
  const cmd=COMMANDS.includes(o._[0])?o._.shift():null;
269
+ if(!cmd){const slip=commandSlip(o);if(slip){process.stderr.write(slip+'\n');return EXIT.usage}}
216
270
  const c=palette(process.stdout.isTTY&&!process.env.NO_COLOR&&!o.json);
217
271
  const err=palette(process.stderr.isTTY&&!process.env.NO_COLOR);
218
272
  try{
219
- if(cmd==='help'){process.stdout.write(HELP+'\n');return 0}
273
+ if(cmd==='help'){process.stdout.write((SUB_HELP[o._[0]]||HELP)+'\n');return 0}
220
274
  if(cmd==='version'){process.stdout.write(VERSION+'\n');return 0}
221
275
  if(cmd==='login')return await login(o);
222
276
  if(cmd==='logout')return await logout(o);
223
- if(cmd==='whoami'){const me=await (await cloudFor(o)).whoami();const l=await loadLogin();process.stdout.write(o.json?JSON.stringify({...me,server:await serverFor(o)})+'\n':`Signed in on this device as account ${me.owner}\nDevice: ${me.label||'this laptop'} · server ${await serverFor(o)} · stored in ${l?.store||'?'}\n`);return 0}
277
+ if(cmd==='whoami'){const me=await (await cloudFor(o)).whoami();const l=await loadLogin();process.stdout.write(o.json?JSON.stringify({...me,server:await serverFor(o)})+'\n':whoamiText(me,{server:await serverFor(o),store:l?.store}));return 0}
224
278
  if(cmd==='sessions')return await sessions(o,c);
225
279
  if(cmd==='doctor')return await doctor(o,c);
226
280
  if(cmd==='cloud')return await cloud(argv.slice(argv.indexOf('cloud')+1));
@@ -230,7 +284,9 @@ export async function main(argv=process.argv.slice(2)){
230
284
  await new Promise(r=>{process.once('SIGINT',r);process.once('SIGTERM',r)});await s.close();return 0;
231
285
  }
232
286
  if(cmd==='runner')return await (await import('./runner.mjs')).runnerMain();
233
- if(cmd==='acp')return await (await import('./tui/acp.mjs')).acpMain(o);
287
+ // `mlai acp login` is the editor's terminal sign-in; the ACP server's own sign-in writes to stderr (stdout is the protocol).
288
+ if(cmd==='acp'&&o._[0]==='login')return await login(o);
289
+ if(cmd==='acp')return await (await import('./tui/acp.mjs')).acpMain({...o,login:()=>login(o,{out:process.stderr})});
234
290
  // `mlai resume [id] [task]` is the older spelling of -r; without an id it continues the latest session here.
235
291
  if(cmd==='resume'){const id=o._.shift();if(id)o.resume=id;else o.continue=true}
236
292
  if(cmd==='remote-control')o.rc=true; // `mlai remote-control [task]`: an interactive session shared with the web and phone
@@ -241,6 +297,7 @@ export async function main(argv=process.argv.slice(2)){
241
297
  const headlessRun=o.print!==null||!process.stdin.isTTY||streamIn;
242
298
  if(o.teleport!==null){const s=await teleportRun(o,err,{interactive:!headlessRun});if(!s)return EXIT.usage;if(headlessRun&&task?.trim())return await headless(o,c,err,task.trim(),s);if(headlessRun){process.stdout.write(s.meta.id+'\n');return 0}return await interactive(o,c,s,task)}
243
299
  if(headlessRun&&!streamIn&&!task&&!process.stdin.isTTY&&o.print===null)task=await readStdin();
300
+ else if(headlessRun&&!streamIn&&task?.trim()&&o.print!=='-'&&!process.stdin.isTTY){const piped=(await pipedInput()).trim();if(piped)task=task.trim()+'\n\nInput piped to mlai:\n```\n'+piped+'\n```'}
244
301
  if(headlessRun&&!streamIn&&!task?.trim())throw new UsageError('Give a task: mlai -p "what to do"');
245
302
  if(headlessRun&&o.rc)throw new UsageError('Remote control needs an interactive terminal. Run mlai --rc in a terminal, or use --bg for unattended work.');
246
303
  // Restricted mode (src/restricted.mjs): the flag, or forced by the administrator for everyone on this computer.
@@ -248,10 +305,13 @@ export async function main(argv=process.argv.slice(2)){
248
305
  if(o.restricted){const no=refusedFlag(o);if(no){process.stderr.write(no+(forced?' It is forced on this computer ('+forced+').':'')+'\n');return EXIT.usage}}
249
306
  if(o.skipPermissions&&!await confirmSkip(o,headlessRun))return EXIT.usage;
250
307
  const s=await chooseSession(o,task,err,{interactive:!headlessRun});
308
+ // BUG-0506: --no-sandbox only changes auto mode; say so instead of accepting it silently (interactive can still switch to auto).
309
+ if(headlessRun&&o.sandbox===false&&(s.meta.cliMode?engineMode(s.meta.cliMode):s.meta.mode)!=='auto')process.stderr.write(err.yellow('Note: --no-sandbox only applies to --mode auto; this run is in '+(modeName(s.meta.cliMode)||(s.meta.mode==='plan'?'plan':'agent'))+' mode, so it changes nothing.')+'\n');
251
310
  if(headlessRun)return await headless(o,c,err,task?.trim()||null,s);
252
311
  return await interactive(o,c,s,task);
253
312
  }catch(e){
254
- if(e instanceof UsageError||e instanceof HeadlessError){process.stderr.write(e.message+'\n');return EXIT.usage}
313
+ // BUG-0535: in JSON output modes a usage error is a JSON result too.
314
+ if(e instanceof UsageError||e instanceof HeadlessError){if(o.json)process.stdout.write(JSON.stringify({type:'result',state:'error',subtype:'error_usage',error:e.message,exitCode:EXIT.usage})+'\n');else process.stderr.write(e.message+'\n');return EXIT.usage}
255
315
  const message=friendly(e);
256
316
  if(o.json)process.stdout.write(JSON.stringify({type:'result',state:'error',error:message,code:e.code||null,exitCode:e.exit||codeFor(e)})+'\n');
257
317
  else process.stderr.write(err.red('error: ')+message+'\n');
@@ -259,20 +319,46 @@ export async function main(argv=process.argv.slice(2)){
259
319
  return e.exit||codeFor(e);
260
320
  }
261
321
  }
322
+ /** BUG-0501: one unambiguous date format for login and doctor ("25 Nov 2026"), whatever the system locale. */
323
+ export const dayText=d=>new Date(d).toLocaleDateString('en-GB',{day:'numeric',month:'short',year:'numeric'});
324
+ /** BUG-0511: `mlai projects` (a cloud command) or a typo such as `mlai sesions` used to start a paid run with that one
325
+ word as the task. A single bare word that names a cloud command or is one or two letters off a command gets a hint instead;
326
+ `mlai -p "<word>"` still sends it to the agent. */
327
+ const CLOUD_ONLY=['projects','new','link','open','run','watch','status','stop','steer','approve','reject','reply','ls','cat','diff','patch','pull','sh','push','pr','deploys','preview','promote','rollback','roles','skills','modes'];
328
+ const KNOWN=[...COMMANDS,'review','agents','attach','update','completion','mcp','unarchive'];
329
+ function editDistance(a,b){
330
+ const d=Array.from({length:a.length+1},(_,i)=>[i,...Array(b.length).fill(0)]);for(let j=1;j<=b.length;j++)d[0][j]=j;
331
+ for(let i=1;i<=a.length;i++)for(let j=1;j<=b.length;j++)d[i][j]=Math.min(d[i-1][j]+1,d[i][j-1]+1,d[i-1][j-1]+(a[i-1]===b[j-1]?0:1));
332
+ return d[a.length][b.length];
333
+ }
334
+ export function commandSlip(o){
335
+ if(o.print!==null||o._.length!==1)return null;
336
+ const w=String(o._[0]).trim().toLowerCase();if(!/^[a-z][a-z-]{1,30}$/.test(w))return null;
337
+ const asTask=' To give the agent this one-word task, run: mlai -p "'+w+'"';
338
+ if(CLOUD_ONLY.includes(w))return '`mlai '+w+'` is a cloud workspace command. Run: mlai cloud '+w+'.'+asTask;
339
+ if(w.length<4)return null;
340
+ const near=KNOWN.map(k=>[k,editDistance(w,k)]).filter(([k,n])=>n>0&&n<=2&&n<k.length/2).sort((a,b)=>a[1]-b[1])[0];
341
+ return near?'Unknown command `'+w+'`. Did you mean: mlai '+near[0]+'?'+asTask:null;
342
+ }
343
+ /** BUG-0473: whoami names the account by its email (and name) when the server sends them; the id is kept below. */
344
+ export function whoamiText(me,{server,store}={}){
345
+ const who=me.email?(me.name?me.name+' <'+me.email+'>':me.email):me.name||'account '+me.owner;
346
+ return `Signed in on this device as ${who}\n${me.email||me.name?'Account '+me.owner+' · ':''}Device: ${me.label||'this laptop'} · server ${server} · stored in ${store||'?'}\n`;
347
+ }
262
348
  function codeFor(e){
263
349
  if(e instanceof ClientError){if(e.status===401)return EXIT.auth;if(e.code==='billing_limit'||e.status===402)return EXIT.billing}
264
350
  return EXIT.error;
265
351
  }
266
352
 
267
- async function login(o){
353
+ async function login(o,{out=process.stdout}={}){
268
354
  const server=(o.server||process.env.MLAI_SERVER||DEFAULT_SERVER).replace(/\/$/,'');
269
355
  const label=(os.hostname().replace(/\.local$/,'')||'Laptop').slice(0,60);
270
- process.stdout.write('Opening your browser to sign in to ML AI Code...\n');
356
+ out.write('Opening your browser to sign in to ML AI Code...\n');
271
357
  const result=await deviceLogin({baseUrl:server,surface:'laptop',label,allowLoopback:loopback(server),openExternal:async url=>{
272
- process.stdout.write('If it does not open, visit:\n '+url+'\n');if(!process.env.MLAI_NO_BROWSER)openBrowser(url);
358
+ out.write('If it does not open, visit:\n '+url+'\n');if(!process.env.MLAI_NO_BROWSER)openBrowser(url);
273
359
  }});
274
360
  const store=await saveLogin({server,token:result.token,expires:result.expires,deviceId:result.deviceId||result.device?.id||null,label});
275
- process.stdout.write(`Signed in. This device stays signed in until ${new Date(result.expires).toLocaleDateString()}; the credential is in your ${store==='keychain'?'system keychain':'~/.mlai folder (owner-only)'}.\n`);
361
+ out.write(`Signed in. This device stays signed in until ${dayText(result.expires)}; the credential is in your ${store==='keychain'?'system keychain':'~/.mlai folder (owner-only)'}.\n`);
276
362
  return 0;
277
363
  }
278
364
  async function logout(o){
@@ -284,12 +370,14 @@ async function logout(o){
284
370
  await clearLogin();process.stdout.write('Signed out on this device.\n');return 0;
285
371
  }
286
372
  async function sessions(o,c){
287
- const all=await Session.list();
373
+ const listed=await Session.list();
374
+ // BUG-0503: a run that never started a turn (bad arguments, a crash before the first message) is not a session to resume.
375
+ const all=o.json?listed:listed.filter(m=>m.turns?.length);
288
376
  if(o.json){process.stdout.write(JSON.stringify(all.map(m=>({id:m.id,folder:m.folder,root:m.root,mode:m.mode,title:m.title,turns:m.turns.length,tokens:m.turns.reduce((a,t)=>a+(t.tokens||0),0),updated:m.updated||m.created})))+'\n');return 0}
289
377
  if(!all.length){process.stdout.write('No sessions yet. Run mlai in a project folder.\n');return 0}
290
378
  for(const m of all.slice(0,30)){
291
379
  const tokens=m.turns.reduce((a,t)=>a+(t.tokens||0),0),last=m.turns.at(-1);
292
- process.stdout.write(`${c.bold(m.id.slice(0,8))} ${m.folder.padEnd(18).slice(0,18)} ${String(m.title||'').slice(0,48).padEnd(48)} ${c.dim(m.turns.length+' turn'+(m.turns.length===1?'':'s')+' · '+credits(tokens)+' · '+(last?.state||'new')+' · '+String(m.updated||m.created).slice(0,16).replace('T',' '))}\n`);
380
+ process.stdout.write(`${c.bold(m.id.slice(0,8))} ${m.folder.padEnd(18).slice(0,18)} ${String(m.title||'').slice(0,48).padEnd(48)} ${c.dim(m.turns.length+' turn'+(m.turns.length===1?'':'s')+' · '+credits(tokens)+' · '+(last?shownState(path.join(home(),'sessions',m.id),last.state):'new')+' · '+localStamp(m.updated||m.created))}\n`);
293
381
  }
294
382
  process.stdout.write(c.dim('Continue one with: mlai resume <id>')+'\n');return 0;
295
383
  }
@@ -313,13 +401,13 @@ async function doctor(o,c){
313
401
  }catch(e){add(false,'Server',server+': '+friendly(e))}
314
402
  const l=await loadLogin().catch(()=>null);
315
403
  if(!l?.token)add(false,'Sign-in','not signed in (run mlai login)');
316
- else try{const me=await new Cloud({server,token:l.token}).whoami();add(true,'Sign-in',(me.label||'device')+' · '+l.store+(l.expires?' · until '+new Date(l.expires).toLocaleDateString():''))}catch(e){add(false,'Sign-in',friendly(e))}
404
+ else try{const me=await new Cloud({server,token:l.token}).whoami();add(true,'Sign-in',(me.label||'device')+' · '+l.store+(l.expires?' · until '+dayText(l.expires):''))}catch(e){add(false,'Sign-in',friendly(e))}
317
405
  let git='';try{git=execFileSync('git',['--version'],{encoding:'utf8'}).trim()}catch{}add(Boolean(git),'git',git||'not found');
318
406
  try{const h=await activeEngine();add(true,'Coding harness',h.source==='updated'?'updated '+h.version.slice(0,8):h.source==='custom'?'MLAI_WORKER_DIR='+h.dir:'bundled '+h.version.slice(0,8))}catch(e){add(false,'Coding harness',e.message)}
319
407
  const rt=await runtimeInfo();
320
408
  if(process.env.MLAI_PYTHON)add(existsSync(process.env.MLAI_PYTHON),'Coding engine','MLAI_PYTHON='+process.env.MLAI_PYTHON);
321
- else if(rt.ready)add(true,'Coding engine',rt.dir);
322
- else if(o.fix){try{await ensureRuntime({onProgress:m=>process.stdout.write(c.dim(m+'...')+'\n')});add(true,'Coding engine','installed')}catch(e){add(false,'Coding engine',e.message)}}
409
+ else if(rt.ready)add(true,'Coding engine','ready (ML AI Code engine '+VERSION+', Python '+PY_VERSION+')');
410
+ else if(o.fix){try{await ensureRuntime({onProgress:m=>process.stdout.write(c.dim(m+'...')+'\n')});add(true,'Coding engine','installed')}catch(e){add(false,'Coding engine',hideEngineName(e.message))}}
323
411
  else add(false,'Coding engine','not installed yet; it installs on first run, or run mlai doctor --fix'+(rt.uv?' (uv found)':rt.python3?' (python3 found)':' (needs uv or python3)'));
324
412
  if(process.platform==='win32'){const g=gitForWindows();add(Boolean(g),'Git Bash',g?path.join(g,'bin','bash.exe'):'not found: install Git for Windows from https://git-scm.com/download/win')}
325
413
  const kind=sandboxKind();add(SANDBOXES.includes(kind),'OS sandbox',kind==='seatbelt'?'macOS Seatbelt (network off is enforced by the OS)':kind==='bwrap'?'bubblewrap (network off is enforced by the OS)':kind==='windows'?'Windows restricted token (writes limited; reads not limited; network off is the engine check only)':kind==='off'?'turned off (MLAI_SANDBOX=off)':'none: auto mode needs --no-sandbox; guided mode still works');
@@ -341,7 +429,8 @@ export async function cloud(args){
341
429
  * shows the same account as `mlai doctor`. Without a sign-in it keeps its own config and default server.
342
430
  */
343
431
  export function cloudEnv({login,env=process.env}={}){
344
- const out={...env};
432
+ // BUG-0470/0472: the cloud CLI shows this version and its commands as `mlai cloud <command>`.
433
+ const out={...env,MLAI_CLOUD_PARENT:VERSION};
345
434
  if(login?.token){out.MLAI_TOKEN=login.token;const server=env.MLAI_SERVER||login.server;if(server&&!env.MLAI_URL)out.MLAI_URL=String(server).replace(/\/$/,'')}
346
435
  return out;
347
436
  }
@@ -385,6 +474,8 @@ async function chooseSession(o,task,err,{interactive}){
385
474
  if(found.length===1||!interactive)meta=found[0];
386
475
  else{const pick=await plainUi({ask:q=>askLine(q),write:t=>process.stderr.write(t)}).pick(found.slice(0,30).map(sessionRow),{title:'Resume a session'});if(!pick)throw new UsageError('No session chosen.');meta=found.find(m=>m.id===pick.value)}
387
476
  }
477
+ // BUG-0556: a session resumed from another folder keeps working in its own project; say so.
478
+ if(meta&&meta.root&&meta.root!==root&&meta.parent!==root)process.stderr.write(err.yellow('Session '+(meta.title?meta.title+' ('+meta.id.slice(0,8)+')':meta.id.slice(0,8))+' belongs to '+meta.root+'; it works there, not in '+root+'. To work here, start a new session (leave out -r).')+'\n');
388
479
  let s;
389
480
  // --no-session-persistence never deletes a saved session: it works on a copy.
390
481
  if(meta)s=o.fork||o.noSessionPersistence?await Chat.fork(meta.id):await Session.open(meta.id);
@@ -408,12 +499,21 @@ async function newSession(o,task,err,root){
408
499
  s.meta.cliMode=modeName(o.mode)||modeName(loadSettings({root}).mode)||'agent';if(o.model)s.meta.model=o.model;await s.save();
409
500
  return s;
410
501
  }
502
+ export const GO_AHEAD=/^\W*(?:(?:ok(?:ay)?|yes|yep|sure|great|perfect|looks good|lgtm|sounds good)\b[\s,.!]*)*(?:please\s+)?(?:go ahead|do it|build it|proceed|implement (?:it|this|that|the plan)|carry (?:it|this|the plan) out|make (?:the|those|these) changes?|write (?:it|the file))\b/i;
411
503
  async function headless(o,c,err,task,s){
412
504
  const cloud=await cloudFor(o);
413
505
  const settings=settingsFor(o,s,err),chat=new Chat({session:s,settings,cloud,flags:chatFlags(o,settings)});
414
506
  if(o.model)await chat.setModel(o.model).catch(e=>{throw new UsageError(e.message)});
415
507
  else await chat.loadModels();
508
+ // BUG-0513: an unknown --fallback-model fails now, like -m, instead of when the main model is down.
509
+ if(o.fallbackModel&&chat.models){const bad=modelList(o.fallbackModel).find(id=>!chat.models.some(m=>m.id===id||String(m.label).toLowerCase()===id.toLowerCase()));if(bad)throw new UsageError('No model '+bad+' (in --fallback-model). Run /model to see the list.')}
416
510
  if(o.effort)await chat.setEffort(o.effort).catch(e=>{throw new UsageError(e.message)});
511
+ // BUG-0554: "go ahead" on a session left in plan mode would plan again (plan mode never edits). Say how to build it.
512
+ if(!o.mode&&chat.mode==='plan'&&(o.continue||o.resume!==null)&&GO_AHEAD.test(String(task||''))){
513
+ const msg='This session is in plan mode, which never changes files. To carry out the plan, run: mlai -c --mode agent -p "'+String(task).trim().slice(0,80).replace(/"/g,"'")+'"';
514
+ if(o.json)process.stdout.write(JSON.stringify({type:'result',subtype:'error_plan_mode',state:'limited',exitCode:EXIT.limited,sessionId:s.meta.id,mode:'plan',error:msg})+'\n');else process.stderr.write(err.yellow(msg)+'\n');
515
+ return EXIT.limited;
516
+ }
417
517
  const inputs=o.inputFormat==='stream-json'?streamInputs(stdinLines()):[{text:task,files:o.images||[]}];
418
518
  const code=await runHeadless(o,{s,chat,err,inputs});
419
519
  // mlai --bg: record how the background run ended (tui/bg.mjs).
@@ -465,7 +565,13 @@ async function plainLoop(o,c,chat,first){
465
565
  };
466
566
  let bound=chat.session;bound.on('event',onEvent);
467
567
  chat.on('session',n=>{bound.off('event',onEvent);bound=n;n.on('event',onEvent);banner();prompt()});
568
+ // BUG-0532: `!` output (and finished background terminals) go with the next message, as in the full-screen TUI.
569
+ let shellContext=[];
570
+ const addShell=t=>{shellContext.push(t);if(shellContext.length>8)shellContext.shift()};
571
+ const onJobExit=job=>{if(job.stopping)return;addShell(terminals.contextOf(job));out(c.dim('Background #'+job.id+' ended ('+terminals.status(job)+') · added to the next message'));prompt()};
572
+ terminals.on('exit',onJobExit);
468
573
  const run=async task=>{
574
+ if(shellContext.length){task='Output of commands I ran in the terminal:\n\n'+shellContext.join('\n\n')+'\n\n'+task;shellContext=[]}
469
575
  prompt();
470
576
  try{
471
577
  const r=await chat.send(task,{onProgress:m=>out(c.dim(m+'...'))});
@@ -489,8 +595,18 @@ async function plainLoop(o,c,chat,first){
489
595
  if(Date.now()-lastCtrlC<1500){rl.close();return}
490
596
  lastCtrlC=Date.now();out(c.dim('Press Ctrl-C again to exit.'));prompt();
491
597
  });
598
+ // BUG-0560: a multi-line paste is one message. The terminal marks pastes (bracketed paste); lines inside a paste are
599
+ // held and sent with the line the user then ends with Enter.
600
+ let pasting=false,pasted=[];
601
+ const bracketed=process.stdout.isTTY&&process.stdin.isTTY&&!process.env.MLAI_NO_BRACKETED_PASTE;
602
+ if(bracketed)process.stdout.write('\x1b[?2004h');
603
+ process.stdin.on('keypress',(_s,k)=>{
604
+ if(k?.name==='paste-start')pasting=true;
605
+ else if(k?.name==='paste-end'){pasting=false;if(pasted.length)out(c.dim('(pasted '+pasted.length+' line'+(pasted.length===1?'':'s')+'; type your message and press Enter to send it all)'))}
606
+ });
492
607
  rl.on('line',async raw=>{
493
608
  if(question){const q=question;question=null;q.resolve(raw);return}
609
+ if(!pending&&(pasting||pasted.length)){if(pasting){pasted.push(raw);return}raw=pasted.join('\n')+'\n'+raw;pasted=[]}
494
610
  const line=raw.trim();
495
611
  if(pending){
496
612
  const v=line.toLowerCase();const verdict=v==='y'||v==='yes'?'approve':v==='a'||v==='all'?'approve_all':v==='n'||v==='no'?'reject':null;
@@ -498,7 +614,13 @@ async function plainLoop(o,c,chat,first){
498
614
  const p=pending;pending=null;await chat.session.decide(p.id,verdict).catch(e=>out(c.red(e.message)));prompt();return;
499
615
  }
500
616
  if(!line){prompt();return}
501
- if(line.startsWith('!')&&line.length>1){const r=await ctx.exec(line.slice(1));const t=(r.stdout+r.stderr).trimEnd();if(t)out(t);if(r.code)out(c.dim('exit '+r.code));prompt();return}
617
+ if(line.startsWith('!')&&line.length>1){
618
+ // BUG-0521: `!command &` starts a background terminal (/ps, /stop), as /keys says.
619
+ const bg=backgroundCommand(line.slice(1).trim());
620
+ if(bg){try{const job=terminals.start(bg,{cwd:chat.session.meta.root});out(c.dim('Background #'+job.id+' running: '+job.command+' · /ps '+job.id+' shows its output, /stop '+job.id+' ends it.'))}catch(e){out(c.red(e.message))}prompt();return}
621
+ const cmd=line.slice(1).trim(),r=await ctx.exec(cmd);const t=(r.stdout+r.stderr).trimEnd();if(t)out(t);if(r.code)out(c.dim('exit '+r.code));
622
+ addShell('$ '+cmd+'\n```\n'+(t.length>20000?'...'+t.slice(-20000):t)+'\n```\n(exit '+(r.code||0)+')');out(c.dim('(output added to the next message)'));prompt();return;
623
+ }
502
624
  const input=registry.rewrite(line);
503
625
  if(input.startsWith('/')){
504
626
  const d=await registry.dispatch(ctx,input);
@@ -508,10 +630,15 @@ async function plainLoop(o,c,chat,first){
508
630
  await run(input);
509
631
  });
510
632
  const closed=new Promise(r=>rl.on('close',r));
633
+ // BUG-0516: closing the terminal window (SIGHUP) or SIGTERM ends the engine too, even while an approval is waiting.
634
+ let hungUp=false;const onHangup=()=>{hungUp=true;rl.close()};process.once('SIGHUP',onHangup);process.once('SIGTERM',onHangup);
511
635
  if(first)run(first);else prompt();
512
636
  await closed;
513
- if(chat.running)await chat.session.cancel().catch(()=>{});
514
- return 0;
637
+ if(bracketed)process.stdout.write('\x1b[?2004l');
638
+ terminals.off('exit',onJobExit);
639
+ process.off('SIGHUP',onHangup);process.off('SIGTERM',onHangup);
640
+ if(chat.running||chat.session.child)await chat.session.stopNow().catch(()=>{});
641
+ return hungUp?129:0;
515
642
  }
516
643
 
517
644
  // ---- CLI2 cloud and background agents (owner: agents_hub_engineer) ----