mlai-code 0.3.2 → 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 (157) 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 +178 -31
  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 +20 -1
  14. package/src/relay.mjs +1 -1
  15. package/src/render.mjs +12 -3
  16. package/src/runtime.mjs +23 -1
  17. package/src/sandbox.mjs +19 -3
  18. package/src/server.mjs +46 -7
  19. package/src/session.mjs +53 -10
  20. package/src/shared-data.mjs +1 -1
  21. package/src/tui/acp.mjs +121 -19
  22. package/src/tui/app.mjs +24 -5
  23. package/src/tui/chat.mjs +43 -16
  24. package/src/tui/cmd-config.mjs +3 -1
  25. package/src/tui/cmd-core.mjs +11 -7
  26. package/src/tui/cmd-extensibility.mjs +13 -2
  27. package/src/tui/commands.mjs +2 -1
  28. package/src/tui/extensions-local.mjs +2 -0
  29. package/src/tui/mcp-config.mjs +22 -4
  30. package/src/tui/review-cli.mjs +15 -4
  31. package/src/tui/snapshots.mjs +57 -16
  32. package/src/tui/statusline.mjs +2 -1
  33. package/src/two-words.mjs +14 -8
  34. package/src/view-sync.mjs +48 -0
  35. package/src/wakeups.mjs +2 -2
  36. package/src/winenv.mjs +1 -1
  37. package/src/workspace-api.mjs +21 -4
  38. package/vendor/client-sdk/index.cjs +5 -4
  39. package/vendor/cloud-cli/mlai.mjs +184 -28
  40. package/worker/architecture_worker.py +33 -4
  41. package/worker/browser_tool.py +19 -1
  42. package/worker/build_planner.py +75 -7
  43. package/worker/chat_fork.py +4 -1
  44. package/worker/checkpoints.py +71 -8
  45. package/worker/cloud_pty.py +91 -2
  46. package/worker/command_safety.py +80 -3
  47. package/worker/compaction_brief.py +186 -0
  48. package/worker/connected_turn.py +30 -0
  49. package/worker/context_manager.py +6 -0
  50. package/worker/conversation.py +139 -12
  51. package/worker/deck_render.js +11 -0
  52. package/worker/deck_tools.py +825 -0
  53. package/worker/git_sync.py +42 -17
  54. package/worker/goals.py +4 -0
  55. package/worker/image_generation.py +102 -23
  56. package/worker/kimi_bridge.py +580 -52
  57. package/worker/kimi_gates.py +74 -6
  58. package/worker/kimi_hook.py +213 -19
  59. package/worker/media_tools.py +182 -0
  60. package/worker/memory.py +2 -2
  61. package/worker/mlai_hooks.py +314 -5
  62. package/worker/mlai_mcp.py +49 -11
  63. package/worker/mlai_review/README.md +35 -0
  64. package/worker/mlai_review/__init__.py +1 -0
  65. package/worker/mlai_review/__main__.py +261 -0
  66. package/worker/mlai_review/_compat.py +29 -0
  67. package/worker/mlai_review/analysis/__init__.py +3 -0
  68. package/worker/mlai_review/analysis/detect.py +50 -0
  69. package/worker/mlai_review/analysis/main.py +128 -0
  70. package/worker/mlai_review/analysis/messages.py +8 -0
  71. package/worker/mlai_review/analysis/tools.py +194 -0
  72. package/worker/mlai_review/application/__init__.py +1 -0
  73. package/worker/mlai_review/application/asking.py +53 -0
  74. package/worker/mlai_review/application/challengers.py +142 -0
  75. package/worker/mlai_review/application/context_builder.py +194 -0
  76. package/worker/mlai_review/application/errors.py +17 -0
  77. package/worker/mlai_review/application/feedback.py +52 -0
  78. package/worker/mlai_review/application/matching.py +46 -0
  79. package/worker/mlai_review/application/messages.py +41 -0
  80. package/worker/mlai_review/application/ports.py +222 -0
  81. package/worker/mlai_review/application/prompts.py +342 -0
  82. package/worker/mlai_review/application/review_service.py +200 -0
  83. package/worker/mlai_review/application/reviewers.py +438 -0
  84. package/worker/mlai_review/application/streaming.py +91 -0
  85. package/worker/mlai_review/application/tools.py +138 -0
  86. package/worker/mlai_review/application/usage.py +145 -0
  87. package/worker/mlai_review/application/write_check.py +46 -0
  88. package/worker/mlai_review/contracts/__init__.py +5 -0
  89. package/worker/mlai_review/contracts/analysis.py +57 -0
  90. package/worker/mlai_review/contracts/review.py +42 -0
  91. package/worker/mlai_review/domain/__init__.py +4 -0
  92. package/worker/mlai_review/domain/changes.py +77 -0
  93. package/worker/mlai_review/domain/context.py +147 -0
  94. package/worker/mlai_review/domain/diagnostics.py +239 -0
  95. package/worker/mlai_review/domain/feedback.py +216 -0
  96. package/worker/mlai_review/domain/findings.py +505 -0
  97. package/worker/mlai_review/domain/lifecycle.py +85 -0
  98. package/worker/mlai_review/domain/partition.py +42 -0
  99. package/worker/mlai_review/domain/relations.py +166 -0
  100. package/worker/mlai_review/domain/relevance.py +202 -0
  101. package/worker/mlai_review/domain/report.py +99 -0
  102. package/worker/mlai_review/domain/structure.py +56 -0
  103. package/worker/mlai_review/domain/writes.py +86 -0
  104. package/worker/mlai_review/eval.py +221 -0
  105. package/worker/mlai_review/eval_cases/clean-rename.json +11 -0
  106. package/worker/mlai_review/eval_cases/missing-ownership-check.json +22 -0
  107. package/worker/mlai_review/eval_cases/off-by-one.json +22 -0
  108. package/worker/mlai_review/eval_cases/sql-injection.json +20 -0
  109. package/worker/mlai_review/feedback_report.py +60 -0
  110. package/worker/mlai_review/infrastructure/__init__.py +1 -0
  111. package/worker/mlai_review/infrastructure/analysis/__init__.py +1 -0
  112. package/worker/mlai_review/infrastructure/analysis/none.py +12 -0
  113. package/worker/mlai_review/infrastructure/analysis/translate.py +17 -0
  114. package/worker/mlai_review/infrastructure/github/__init__.py +0 -0
  115. package/worker/mlai_review/infrastructure/github/client.py +445 -0
  116. package/worker/mlai_review/infrastructure/github/feedback.py +212 -0
  117. package/worker/mlai_review/infrastructure/github/http.py +31 -0
  118. package/worker/mlai_review/infrastructure/github/rendering.py +398 -0
  119. package/worker/mlai_review/infrastructure/github/token.py +20 -0
  120. package/worker/mlai_review/infrastructure/local/__init__.py +1 -0
  121. package/worker/mlai_review/infrastructure/local/analyzer.py +48 -0
  122. package/worker/mlai_review/infrastructure/local/events.py +100 -0
  123. package/worker/mlai_review/infrastructure/local/git_reader.py +233 -0
  124. package/worker/mlai_review/infrastructure/local/publisher.py +138 -0
  125. package/worker/mlai_review/infrastructure/messages.py +54 -0
  126. package/worker/mlai_review/infrastructure/models/__init__.py +0 -0
  127. package/worker/mlai_review/infrastructure/models/openai_compatible.py +269 -0
  128. package/worker/mlai_review/infrastructure/structure/__init__.py +1 -0
  129. package/worker/mlai_review/infrastructure/structure/heuristic.py +186 -0
  130. package/worker/mlai_review/infrastructure/structure/tree_sitter.py +186 -0
  131. package/worker/mlai_review/infrastructure/workspace/__init__.py +1 -0
  132. package/worker/mlai_review/infrastructure/workspace/local.py +105 -0
  133. package/worker/mlai_review/infrastructure/workspace/memory.py +77 -0
  134. package/worker/mlai_review/infrastructure/workspace/paths.py +17 -0
  135. package/worker/mlai_review/pipeline.py +89 -0
  136. package/worker/mlai_review/runtime.py +194 -0
  137. package/worker/mlai_review/settings.py +139 -0
  138. package/worker/model_stream.py +21 -7
  139. package/worker/offline_guard.py +1 -1
  140. package/worker/preview.py +62 -4
  141. package/worker/product_facts.py +20 -0
  142. package/worker/project_context.py +33 -7
  143. package/worker/reply_language.py +92 -10
  144. package/worker/repo_policy.py +5 -0
  145. package/worker/roles.json +199 -37
  146. package/worker/roles.py +271 -9
  147. package/worker/runner.py +366 -53
  148. package/worker/runtime_control.py +64 -3
  149. package/worker/secret_scan.py +3 -2
  150. package/worker/server_memory.py +122 -0
  151. package/worker/site_check.py +279 -0
  152. package/worker/skill_library.py +15 -3
  153. package/worker/skill_pack.py +170 -16
  154. package/worker/subagents.py +6 -2
  155. package/worker/tool_catalog.py +4 -3
  156. package/worker/verification.py +156 -19
  157. package/worker/wakeups.py +56 -4
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';
28
- import {palette,renderEvent,approvalView,summaryLine,exitCode,EXIT,fmt} from './render.mjs';
27
+ import {ensureRuntime,runtimeInfo,PY_VERSION,hideEngineName} from './runtime.mjs';
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,18 +370,30 @@ 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')+' · '+fmt(tokens)+' 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
  }
384
+ /**
385
+ * Node.js for doctor: the CLI needs 20, and the default coding engine needs 22.19 or newer (older 22.x lacks a zlib
386
+ * export it uses, so runs fall back or fail). Below 22.19 is a warning, not an error, because the CLI itself works.
387
+ */
388
+ export function nodeCheck(version){
389
+ const [a,b]=String(version).replace(/^v/,'').split('.').map(Number);
390
+ if(!(a>=20))return {ok:false,detail:version+' (20 or newer needed)'};
391
+ if(a<22||(a===22&&b<19))return {ok:false,warn:true,detail:version+' (22.19 or newer recommended: the coding engine needs it; update Node.js from https://nodejs.org)'};
392
+ return {ok:true,detail:version};
393
+ }
296
394
  async function doctor(o,c){
297
- const rows=[];const add=(ok,label,detail)=>rows.push({ok,label,detail});
298
- const major=Number(process.versions.node.split('.')[0]);add(major>=20,'Node.js',process.versions.node+(major>=20?'':' (20 or newer needed)'));
395
+ const rows=[];const add=(ok,label,detail,extra)=>rows.push({ok,label,detail,...extra});
396
+ {const n=nodeCheck(process.versions.node);add(n.ok,'Node.js',n.detail,n.warn?{warn:true}:undefined)}
299
397
  const server=await serverFor(o);
300
398
  try{
301
399
  const caps=await new Client({baseUrl:server,surface:'laptop',version:VERSION,allowLoopback:loopback(server)}).capabilities();
@@ -303,13 +401,13 @@ async function doctor(o,c){
303
401
  }catch(e){add(false,'Server',server+': '+friendly(e))}
304
402
  const l=await loadLogin().catch(()=>null);
305
403
  if(!l?.token)add(false,'Sign-in','not signed in (run mlai login)');
306
- 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))}
307
405
  let git='';try{git=execFileSync('git',['--version'],{encoding:'utf8'}).trim()}catch{}add(Boolean(git),'git',git||'not found');
308
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)}
309
407
  const rt=await runtimeInfo();
310
408
  if(process.env.MLAI_PYTHON)add(existsSync(process.env.MLAI_PYTHON),'Coding engine','MLAI_PYTHON='+process.env.MLAI_PYTHON);
311
- else if(rt.ready)add(true,'Coding engine',rt.dir);
312
- 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))}}
313
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)'));
314
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')}
315
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');
@@ -317,13 +415,24 @@ async function doctor(o,c){
317
415
  add(true,'Local data',home());
318
416
  if(o.json)process.stdout.write(JSON.stringify(rows)+'\n');
319
417
  else for(const r of rows)process.stdout.write((r.ok?c.green('ok '):c.yellow('!! '))+r.label.padEnd(15)+' '+r.detail+'\n');
320
- return rows.every(r=>r.ok||['Coding engine','OS sandbox','Laptop runs'].includes(r.label))?0:1;
418
+ return rows.every(r=>r.ok||r.warn||['Coding engine','OS sandbox','Laptop runs'].includes(r.label))?0:1;
321
419
  }
322
- async function cloud(args){
420
+ export async function cloud(args){
323
421
  const here=path.dirname(fileURLToPath(import.meta.url));
324
422
  const bin=[path.join(here,'..','vendor','cloud-cli','mlai.mjs'),path.join(here,'..','..','cli','bin','mlai.mjs')].find(existsSync);
325
423
  if(!bin)throw new Error('Cloud commands are not included in this install.');
326
- return await new Promise(resolve=>{const p=spawn(process.execPath,[bin,...args],{stdio:'inherit'});p.on('exit',code=>resolve(code??1))});
424
+ const env=await cloudEnv({login:await loadLogin().catch(()=>null)});
425
+ return await new Promise(resolve=>{const p=spawn(process.execPath,[bin,...args],{stdio:'inherit',env});p.on('exit',code=>resolve(code??1))});
426
+ }
427
+ /**
428
+ * The cloud workspace CLI uses the `mlai login` sign-in and its server (MLAI_TOKEN, MLAI_URL), so `mlai cloud doctor`
429
+ * shows the same account as `mlai doctor`. Without a sign-in it keeps its own config and default server.
430
+ */
431
+ export function cloudEnv({login,env=process.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};
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(/\/$/,'')}
435
+ return out;
327
436
  }
328
437
 
329
438
  /** Flags that override settings (settings.mjs), and the settings for a session's folder. */
@@ -365,6 +474,8 @@ async function chooseSession(o,task,err,{interactive}){
365
474
  if(found.length===1||!interactive)meta=found[0];
366
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)}
367
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');
368
479
  let s;
369
480
  // --no-session-persistence never deletes a saved session: it works on a copy.
370
481
  if(meta)s=o.fork||o.noSessionPersistence?await Chat.fork(meta.id):await Session.open(meta.id);
@@ -388,12 +499,21 @@ async function newSession(o,task,err,root){
388
499
  s.meta.cliMode=modeName(o.mode)||modeName(loadSettings({root}).mode)||'agent';if(o.model)s.meta.model=o.model;await s.save();
389
500
  return s;
390
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;
391
503
  async function headless(o,c,err,task,s){
392
504
  const cloud=await cloudFor(o);
393
505
  const settings=settingsFor(o,s,err),chat=new Chat({session:s,settings,cloud,flags:chatFlags(o,settings)});
394
506
  if(o.model)await chat.setModel(o.model).catch(e=>{throw new UsageError(e.message)});
395
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.')}
396
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
+ }
397
517
  const inputs=o.inputFormat==='stream-json'?streamInputs(stdinLines()):[{text:task,files:o.images||[]}];
398
518
  const code=await runHeadless(o,{s,chat,err,inputs});
399
519
  // mlai --bg: record how the background run ended (tui/bg.mjs).
@@ -445,7 +565,13 @@ async function plainLoop(o,c,chat,first){
445
565
  };
446
566
  let bound=chat.session;bound.on('event',onEvent);
447
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);
448
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=[]}
449
575
  prompt();
450
576
  try{
451
577
  const r=await chat.send(task,{onProgress:m=>out(c.dim(m+'...'))});
@@ -469,8 +595,18 @@ async function plainLoop(o,c,chat,first){
469
595
  if(Date.now()-lastCtrlC<1500){rl.close();return}
470
596
  lastCtrlC=Date.now();out(c.dim('Press Ctrl-C again to exit.'));prompt();
471
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
+ });
472
607
  rl.on('line',async raw=>{
473
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=[]}
474
610
  const line=raw.trim();
475
611
  if(pending){
476
612
  const v=line.toLowerCase();const verdict=v==='y'||v==='yes'?'approve':v==='a'||v==='all'?'approve_all':v==='n'||v==='no'?'reject':null;
@@ -478,7 +614,13 @@ async function plainLoop(o,c,chat,first){
478
614
  const p=pending;pending=null;await chat.session.decide(p.id,verdict).catch(e=>out(c.red(e.message)));prompt();return;
479
615
  }
480
616
  if(!line){prompt();return}
481
- 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
+ }
482
624
  const input=registry.rewrite(line);
483
625
  if(input.startsWith('/')){
484
626
  const d=await registry.dispatch(ctx,input);
@@ -488,10 +630,15 @@ async function plainLoop(o,c,chat,first){
488
630
  await run(input);
489
631
  });
490
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);
491
635
  if(first)run(first);else prompt();
492
636
  await closed;
493
- if(chat.running)await chat.session.cancel().catch(()=>{});
494
- 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;
495
642
  }
496
643
 
497
644
  // ---- CLI2 cloud and background agents (owner: agents_hub_engineer) ----
package/src/cloud.mjs CHANGED
@@ -25,5 +25,7 @@ export function friendly(error){
25
25
  if(error.code==='billing_limit')return error.message+' Manage your plan at code.ml.ai.';
26
26
  if(error.status===429)return error.message;
27
27
  if(error.code==='not_configured')return 'Laptop runs are not enabled on this server yet.';
28
+ // BUG-0504: nothing was connected, so "Refresh status before retrying a write" only confused people.
29
+ if(error.code==='connection_interrupted')return 'Cannot reach the ML AI Code server'+(error.server?' at '+error.server:'')+'. Check your internet connection'+(error.server?' and the server address (--server or MLAI_SERVER)':'')+'.';
28
30
  return error.message;
29
31
  }
package/src/engine.mjs CHANGED
@@ -14,7 +14,7 @@ import {pinnedPublicKey,ed25519PublicKey} from './engine-key.mjs';
14
14
  export const ENGINE_PROTOCOL=1;
15
15
  export const CHECK_EVERY=10*60*1000,WAIT_MS=3000,DOWNLOAD_MS=60000;
16
16
  /** Copy of lib/laptop-engine.ts ENGINE_FILES (parity test): the bundled copy's version is hashed over these. */
17
- export const ENGINE_FILES=['ask_first.py','attachment_reader.py','background_jobs.py','brief_questions.py','browser_local.py','browser_pane.py','browser_tool.py','build_planner.py','checkpoints.py','command_policy.py','command_safety.py','computer_card.sh','computer_setup.sh','computer_use.py','connector_search.py','context_manager.py','conversation.py','deploy_pack.py','design_director.py','dev_jobs.py','edit_guard.py','env_setup.py','evidence.py','fast_search.py','goals.py','handover.py','harness_memory.py','image_generation.py','intelligence.py','intent_model.py','intent_weights.json','ios_simulator.py','kimi_bridge.py','kimi_compact.py','kimi_gates.py','kimi_hook.py','lifecycle.py','lsp.py','mcp_local.py','memory.py','mlai_auto_review.py','mlai_hooks.py','mlai_mcp.py','mlai_permissions.py','model_stream.py','nested_repos.py','obs_mask.py','offline_guard.py','preview.py','proc_watch.py','project_context.py','project_rules.py','quality.py','reply_language.py','repo_hygiene.py','repo_memory.py','repo_policy.py','roles.json','roles.py','runner.py','runtime_control.py','secret_scan.py','session_hub.py','skill_library.py','skill_pack.py','subagents.py','task_controller.py','task_skills.py','token_count.py','tool_catalog.py','verification.py','vision.py','wakeups.py','web_tools.py','winproc.py','work_ledger.py','worktrees.py'];
17
+ export const ENGINE_FILES=['ask_first.py','attachment_reader.py','background_jobs.py','brief_questions.py','browser_local.py','browser_pane.py','browser_tool.py','build_planner.py','checkpoints.py','command_policy.py','command_safety.py','compaction_brief.py','computer_card.sh','computer_setup.sh','computer_use.py','connected_turn.py','connector_search.py','context_manager.py','conversation.py','deck_render.js','deck_tools.py','deploy_pack.py','design_director.py','dev_jobs.py','edit_guard.py','env_setup.py','evidence.py','fast_search.py','goals.py','handover.py','harness_memory.py','image_generation.py','intelligence.py','intent_model.py','intent_weights.json','ios_simulator.py','kimi_bridge.py','kimi_compact.py','kimi_gates.py','kimi_hook.py','lifecycle.py','lsp.py','mcp_local.py','media_tools.py','memory.py','mlai_auto_review.py','mlai_hooks.py','mlai_mcp.py','mlai_permissions.py','model_stream.py','nested_repos.py','obs_mask.py','offline_guard.py','preview.py','proc_watch.py','product_facts.py','project_context.py','project_rules.py','quality.py','reply_language.py','repo_hygiene.py','repo_memory.py','repo_policy.py','roles.json','roles.py','runner.py','runtime_control.py','secret_scan.py','server_memory.py','session_hub.py','site_check.py','skill_library.py','skill_pack.py','subagents.py','task_controller.py','task_skills.py','token_count.py','tool_catalog.py','verification.py','vision.py','wakeups.py','web_tools.py','winproc.py','work_ledger.py','worktrees.py'];
18
18
  /** The entry scripts; a manifest without them is not a harness. */
19
19
  export const REQUIRED=['runner.py','kimi_bridge.py'];
20
20
  const NAME=/^[A-Za-z0-9][A-Za-z0-9_.-]{0,99}$/,SHA=/^[a-f0-9]{64}$/,VERSION=/^[a-f0-9]{32}$/;
package/src/headless.mjs CHANGED
@@ -6,7 +6,8 @@
6
6
  * --max-budget-credits the server caps the run's tokens (run.maxTokens); the next turn never starts past it
7
7
  * --fallback-model Chat.send switches model when the chosen one is overloaded or unavailable
8
8
  * --allowedTools / --disallowedTools / --tools permission rules (worker/mlai_permissions.py syntax)
9
- * Result subtypes: success, error_during_execution, error_max_turns, error_max_budget, error_schema, stopped.
9
+ * Result subtypes: success, error_during_execution, error_max_turns, error_max_budget, error_schema, error_needs_approval,
10
+ * error_cannot_complete (exit 6: the agent reported the request cannot be done), stopped.
10
11
  */
11
12
  import {readFileSync,existsSync} from 'node:fs';
12
13
  import {readFile,rm} from 'node:fs/promises';
@@ -125,13 +126,20 @@ export async function runHeadless(o,{s,chat,err,inputs,out=t=>process.stdout.wri
125
126
  const stream=o.outputFormat==='stream-json',json=o.outputFormat==='json';
126
127
  const write=x=>out(JSON.stringify(x)+'\n');
127
128
  const schema=o.jsonSchema?loadSchema(o.jsonSchema):null;
128
- if(o.maxTurns)chat.steps=Math.min(chat.steps,o.maxTurns);
129
+ // BUG-0492: --max-turns is an exact cap for the whole run (hardSteps), not the engine's usual minimum of 10.
130
+ if(o.maxTurns){chat.steps=Math.min(chat.steps,o.maxTurns);chat.hardSteps=true}
131
+ chat.unattended=true; // BUG-0519: nobody can answer a -p run, so a sandbox-blocked write ends it instead of looping
129
132
  let events=[],refused=0,spent=0,turns=0,code=EXIT.completed,last=null;
133
+ // BUG-0557: the engine must not promise an automatic continue that a one-shot process will never run.
134
+ const oneShot=process.env.MINI_ONE_SHOT;process.env.MINI_ONE_SHOT='1';
135
+ // BUG-0561: the agent's last message is also the final answer on stdout; held back so a terminal shows it once.
136
+ let prose=null,proseRaw=null;const flushProse=()=>{if(prose!=null){log(prose+'\n');prose=null}};
137
+ const sameText=(a,b)=>{const x=String(a||'').replace(/\s+/g,' ').trim();return !!x&&String(b||'').replace(/\s+/g,' ').includes(x)};
130
138
  const stop=()=>{s.cancel().catch(()=>{})};process.once('SIGINT',stop);process.once('SIGTERM',stop);
131
139
  const onEvent=e=>{
132
140
  events.push(e);
133
141
  if(stream)write(e);
134
- else if(!json){const line=renderEvent(e,{c:err,verbose:o.verbose});if(line&&e.type!=='answer')log(line+'\n')}
142
+ else if(!json){const line=renderEvent(e,{c:err,verbose:o.verbose});if(line&&e.type!=='answer'){flushProse();if(e.type==='assistant'){prose=line;proseRaw=e.content}else log(line+'\n')}}
135
143
  if(e.type==='approval'){
136
144
  if(o.yes)s.decide(e.id,'approve_all').catch(()=>{});
137
145
  else if(o.bgChild){} // a background run (mlai --bg) waits for mlai attach to answer
@@ -149,7 +157,7 @@ export async function runHeadless(o,{s,chat,err,inputs,out=t=>process.stdout.wri
149
157
  };
150
158
  try{
151
159
  for await(const input of inputs){
152
- events=[];
160
+ events=[];const turnRefused=refused;
153
161
  const images=[];
154
162
  for(const b of input.images||[])images.push(await s.addImage(b));
155
163
  for(const f of input.files||[])images.push(await s.addImage(await readFile(f)));
@@ -157,8 +165,9 @@ export async function runHeadless(o,{s,chat,err,inputs,out=t=>process.stdout.wri
157
165
  if(cap!=null&&spent>=cap){r={state:'limited',error:'The --max-budget-credits limit was reached before this turn.'};subtype='error_max_budget'}
158
166
  else{
159
167
  r=await send(input.text+(schema?schemaTask(schema):''),images.length?images:undefined);
160
- const budgetHit=cap!=null&&(r.code==='billing_limit'||(r.state!=='completed'&&spent>=cap));
161
- if(budgetHit){r={...r,code:'budget_limit',error:'Stopped at the --max-budget-credits limit ('+o.maxBudgetCredits+' credits). Changes so far are kept.'};subtype='error_max_budget'}
168
+ // BUG-0509: reaching the cap is never a success, even when the agent wrapped up on its own at the limit.
169
+ const budgetHit=cap!=null&&(r.code==='billing_limit'||spent>=cap);
170
+ if(budgetHit){r={...r,code:'budget_limit',error:'Stopped at the --max-budget-credits limit ('+o.maxBudgetCredits+' credits; this run used '+creditsFor(spent)+' because the model step in progress finishes). Changes so far are kept.'};subtype='error_max_budget'}
162
171
  else if(r.state==='limited'&&o.maxTurns&&r.result?.limit!=='tokens')subtype='error_max_turns';
163
172
  else if(r.state==='stopped')subtype='stopped';
164
173
  else if(r.state!=='completed')subtype='error_during_execution';
@@ -175,20 +184,27 @@ export async function runHeadless(o,{s,chat,err,inputs,out=t=>process.stdout.wri
175
184
  }
176
185
  }
177
186
  const text=finalText(r,events);
178
- const exit=subtype==='success'?EXIT.completed:subtype==='error_max_turns'||subtype==='error_max_budget'?EXIT.limited:subtype==='error_schema'?EXIT.error:exitCode(r);
187
+ // BUG-0544: approvals refused because nobody could answer them (-p without --yes): the run needs attention.
188
+ // BUG-0523: the agent decided the request cannot be done (no remote to push to, an unsupported feature): not a success.
189
+ if(subtype==='success'&&r.cannotComplete){subtype='error_cannot_complete';r={...r,error:r.cannotComplete.reason}}
190
+ if(subtype==='success'&&refused>turnRefused){subtype='error_needs_approval';r={...r,error:(refused-turnRefused)+' action'+(refused-turnRefused===1?'':'s')+' needed approval and did not run. Pass --yes (-y) or --allowedTools to allow them.'}}
191
+ const exit=subtype==='error_cannot_complete'?EXIT.cannotComplete:subtype==='error_needs_approval'?EXIT.limited:subtype==='success'?EXIT.completed:subtype==='error_max_turns'||subtype==='error_max_budget'?EXIT.limited:subtype==='error_schema'?EXIT.error:exitCode(r);
179
192
  if(exit!==EXIT.completed)code=exit;
180
193
  last={type:'result',subtype,state:r.state,exitCode:exit,sessionId:s.meta.id,name:s.meta.title||null,mode:chat.mode,model:chat.model||chat.info?.id||null,effort:chat.effort,text,
181
194
  ...(schema?{structuredOutput:structured??null}:{}),error:subtype==='success'?null:(r.error||null),usage:r.usage||null,
182
195
  credits:creditsFor(spent),turns,changedFiles:r.completion?.changedFiles||[],checksPassed:r.completion?.checksPassed||0,checksFailed:r.completion?.checksFailed||0,rejectedApprovals:refused,
183
- persisted:!o.noSessionPersistence};
196
+ persisted:!o.noSessionPersistence,
197
+ // BUG-0555: with -w the work is in its own worktree; say where, so scripts and people can find it.
198
+ ...(s.meta.worktree&&!s.meta.worktree.removed?{worktree:{path:s.meta.worktree.path,branch:s.meta.worktree.branch}}:{})};
184
199
  if(stream)write(last);
185
- else if(!json){if(schema&&structured!==undefined)out(JSON.stringify(structured)+'\n');else if(text)out(text.trim()+'\n');log(summaryLine(r,err)+'\n')}
200
+ else if(!json){if(prose!=null&&(sameText(proseRaw,text)||sameText(prose,text)))prose=null;flushProse();if(schema&&structured!==undefined)out(JSON.stringify(structured)+'\n');else if(text)out(text.trim()+'\n');log(summaryLine(r,err)+'\n');if(last.worktree&&last.changedFiles.length)log(err.dim('The changes are in the worktree '+last.worktree.path+' on branch '+last.worktree.branch+', not in your folder. Look with: cd '+last.worktree.path+' · bring them back with: git merge '+last.worktree.branch+' (after committing them there)')+'\n')}
186
201
  if(['error_max_budget','stopped'].includes(subtype))break;
187
202
  }
188
203
  if(json&&last)write(last);
189
204
  if(!last)throw new HeadlessError('No task: pass one with -p "task" or send {"type":"user",...} lines on stdin.');
190
205
  return code;
191
206
  }finally{
207
+ if(oneShot===undefined)delete process.env.MINI_ONE_SHOT;else process.env.MINI_ONE_SHOT=oneShot;
192
208
  process.off('SIGINT',stop);process.off('SIGTERM',stop);
193
209
  s.off('event',onEvent);s.off('started',onStarted);chat.off('fallback',onFallback);
194
210
  if(o.noSessionPersistence)await rm(s.dir,{recursive:true,force:true}).catch(()=>{});
package/src/home.mjs CHANGED
@@ -3,8 +3,9 @@ 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.2';
7
- export const DEFAULT_SERVER='https://mlai-mini-code.vercel.app';
6
+ export const VERSION='0.3.4';
7
+ // BUG-0469: the production CLI signs in and calls the production domain.
8
+ export const DEFAULT_SERVER='https://code.ml.ai';
8
9
  /** All local state lives here; nothing is written into the user's repository except what the agent edits. */
9
10
  export function home(){
10
11
  const dir=process.env.MLAI_HOME||path.join(os.homedir(),'.mlai');