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/tui/acp.mjs CHANGED
@@ -5,6 +5,7 @@ import readline from 'node:readline';
5
5
  import path from 'node:path';
6
6
  import {randomUUID} from 'node:crypto';
7
7
  import {MODES,MODE_NAMES,modeName,applyMode,taskFor,sessionMode} from '../modes.mjs';
8
+ import {validMcpServers,folderKey} from '../ide.mjs';
8
9
 
9
10
  export const PROTOCOL_VERSION=1;
10
11
  const ERR={parse:-32700,invalid:-32600,method:-32601,params:-32602,internal:-32603,auth:-32000,session:-32002};
@@ -16,46 +17,141 @@ export function toolKind(e){
16
17
  const n=String(e.name||'').toLowerCase();
17
18
  return /edit|write|patch|replace|create_file/.test(n)?'edit':/read|open|view|cat/.test(n)?'read':/search|grep|find|glob|list/.test(n)?'search':/fetch|web|browse/.test(n)?'fetch':/delete|remove/.test(n)?'delete':'other';
18
19
  }
19
- /** Prompt content blocks -> task text. Text, embedded text resources and resource links (by path) are accepted. */
20
- export function promptText(blocks){
20
+ /** Prompt content blocks -> task text. Text, embedded text resources and resource links (by path) are accepted. Image blocks are read by promptImages. */
21
+ export function promptText(blocks,{allowEmpty=false}={}){
21
22
  if(!Array.isArray(blocks))throw new RpcError(ERR.params,'prompt must be a list of content blocks');
22
- const parts=blocks.map(b=>{
23
+ const parts=blocks.filter(b=>b?.type!=='image').map(b=>{
23
24
  if(b?.type==='text')return String(b.text||'');
24
25
  if(b?.type==='resource'&&typeof b.resource?.text==='string')return 'File '+(b.resource.uri||'')+':\n'+b.resource.text;
25
26
  if(b?.type==='resource_link')return '@'+String(b.uri||b.name||'').replace(/^file:\/\//,'');
26
- throw new RpcError(ERR.params,'Only text, embedded text and file links are supported.');
27
+ throw new RpcError(ERR.params,'Only text, images, embedded text and file links are supported.');
27
28
  });
28
29
  const task=parts.join('\n\n').trim();
30
+ if(allowEmpty&&!task)return '';
29
31
  if(!task||task.length>30000)throw new RpcError(ERR.params,'Use a text prompt under 30,000 characters');
30
32
  return task;
31
33
  }
34
+ const IMAGE_MIME=/^image\/(png|jpeg|jpg|webp|gif)$/;
35
+ /** Image blocks ({type:'image', data: base64, mimeType}) -> byte buffers, at most 4. */
36
+ export function promptImages(blocks){
37
+ const out=[];
38
+ for(const b of Array.isArray(blocks)?blocks:[]){
39
+ if(b?.type!=='image')continue;
40
+ if(!IMAGE_MIME.test(String(b.mimeType||''))||typeof b.data!=='string'||!b.data)throw new RpcError(ERR.params,'Use a PNG, JPEG, WebP or GIF image.');
41
+ out.push(Buffer.from(b.data,'base64'));
42
+ }
43
+ if(out.length>4)throw new RpcError(ERR.params,'Attach up to 4 images.');
44
+ return out;
45
+ }
46
+ /**
47
+ * ACP MCP servers (stdio {name, command, args, env:[{name,value}]}, http/sse {type, name, url, headers:[{name,value}]})
48
+ * -> the session's MCP extension ({mcpServers, mcpEnv}); header and env values only go into mcpEnv.
49
+ * Editors pass their own MCP servers here, for example the IntelliJ MCP server.
50
+ */
51
+ export function acpMcpServers(list){
52
+ if(list==null||(Array.isArray(list)&&!list.length))return null;
53
+ if(!Array.isArray(list))throw new RpcError(ERR.params,'mcpServers must be a list');
54
+ const used=new Set(),pairs=a=>Object.fromEntries((Array.isArray(a)?a:[]).filter(x=>x&&typeof x.name==='string').map(x=>[x.name,String(x.value??'')]));
55
+ const conv=list.slice(0,10).map(m=>{
56
+ let name=String(m?.name||'mcp').replace(/[^A-Za-z0-9_-]+/g,'-').replace(/^-+|-+$/g,'').slice(0,40)||'mcp';
57
+ if(name==='mlai')name='mlai-editor';
58
+ let n=name,i=2;while(used.has(n))n=name+'-'+i++;used.add(n);
59
+ if(m?.type==='http'||m?.type==='sse'||typeof m?.url==='string')return {name:n,url:m.url,headers:pairs(m.headers),...(m.type==='sse'?{transport:'sse'}:{})};
60
+ return {name:n,command:m?.command,args:m?.args||[],env:pairs(m?.env)};
61
+ });
62
+ try{return validMcpServers(conv)}catch(e){throw new RpcError(ERR.params,e.message)}
63
+ }
64
+ const RUN_MODE={guided:'approve',plan:'plan',auto:'auto'};
32
65
  const planStatus=s=>s==='done'||s==='completed'?'completed':s==='in_progress'?'in_progress':'pending';
33
66
  const modesFor=current=>({currentModeId:current,availableModes:MODE_NAMES.map(id=>({id,name:MODES[id].label,description:MODES[id].summary}))});
34
67
 
35
68
  /**
36
69
  * write(obj): sends one protocol message. deps: createSession({cwd,mode}) => Session, cloud() => signed-in Cloud,
37
- * version, log(text) for stderr. Returns {handle(message), close()}; handle resolves after a request is answered.
70
+ * version, log(text) for stderr. Optional: openSession(id) => Session and listSessions() => [meta] (session/load and
71
+ * session/list), models() => {models:[{id,label,description,offline,available,default}]} (our model picker),
72
+ * login() for the agent sign-in method. Returns {handle(message), close()}; handle resolves after a request is answered.
38
73
  */
39
- export function createAcpServer({write,createSession,cloud,version='0',log=()=>{},steps=120}){
74
+ export function createAcpServer({write,createSession,openSession=null,listSessions=null,models=null,login=null,cloud,version='0',log=()=>{},steps=120}){
40
75
  const sessions=new Map(),waiting=new Map();
76
+ let terminalAuth=false,modelList=null;
77
+ // Our models only; offline ones are left out (an editor run always goes through the cloud gateway).
78
+ const loadModels=async()=>{
79
+ if(!models)return [];
80
+ if(modelList)return modelList;
81
+ const r=await Promise.race([models().catch(()=>null),new Promise(r=>setTimeout(()=>r(null),8000).unref?.())]);
82
+ const list=(r?.models||[]).filter(m=>m&&!m.offline&&m.available!==false&&typeof m.id==='string');
83
+ if(r?.signedIn!==false&&list.length)modelList=list;
84
+ return list;
85
+ };
86
+ const configFor=async entry=>{
87
+ const list=await loadModels();if(!list.length)return {};
88
+ const current=list.some(m=>m.id===entry.model)?entry.model:(list.find(m=>m.default)||list[0]).id;
89
+ return {configOptions:[{id:'model',name:'Model',category:'model',type:'select',currentValue:current,options:list.map(m=>({value:m.id,name:m.label||m.id,...(m.description?{description:m.description}:{})}))}],
90
+ models:{currentModelId:current,availableModels:list.map(m=>({modelId:m.id,name:m.label||m.id,...(m.description?{description:m.description}:{})}))}};
91
+ };
92
+ const setModel=async(p,value)=>{
93
+ const entry=need(p?.sessionId),list=await loadModels();
94
+ if(!list.some(m=>m.id===value))throw new RpcError(ERR.params,'Choose one of the listed models');
95
+ entry.model=value;
96
+ };
97
+ const open=async(s,mcpServers)=>{
98
+ const entry={s,busy:null,model:null,mcp:acpMcpServers(mcpServers)};sessions.set(s.meta.id,entry);
99
+ return {sessionId:s.meta.id,modes:modesFor(sessionMode(s.meta)),...await configFor(entry)};
100
+ };
101
+ const say=(sid,text,kind='agent_message_chunk')=>text&&notify(sid,{sessionUpdate:kind,content:{type:'text',text}});
41
102
  const send=m=>write({jsonrpc:'2.0',...m});
42
103
  const notify=(sessionId,update)=>send({method:'session/update',params:{sessionId,update}});
43
104
  const request=(method,params)=>new Promise((resolve,reject)=>{const id='mlai-'+randomUUID();waiting.set(id,{resolve,reject});send({id,method,params})});
44
105
  const need=id=>{const s=sessions.get(id);if(!s)throw new RpcError(ERR.session,'Unknown session');return s};
45
106
 
46
107
  const methods={
47
- initialize:async p=>({protocolVersion:Math.min(Number(p?.protocolVersion)||PROTOCOL_VERSION,PROTOCOL_VERSION),
48
- agentInfo:{name:'mlai',title:'ML AI Code',version},
49
- agentCapabilities:{loadSession:false,promptCapabilities:{image:false,audio:false,embeddedContext:true},mcpCapabilities:{http:false,sse:false}},
50
- authMethods:[]}),
51
- authenticate:async()=>({}),
108
+ initialize:async p=>{
109
+ terminalAuth=p?.clientCapabilities?.auth?.terminal===true;
110
+ return {protocolVersion:Math.min(Number(p?.protocolVersion)||PROTOCOL_VERSION,PROTOCOL_VERSION),
111
+ agentInfo:{name:'mlai',title:'ML AI Code',version},
112
+ agentCapabilities:{loadSession:!!openSession,promptCapabilities:{image:true,audio:false,embeddedContext:true},mcpCapabilities:{http:true,sse:true},
113
+ ...(listSessions?{sessionCapabilities:{list:{}}}:{})},
114
+ // Sign-in: the agent opens the browser itself (authenticate), or the editor runs `mlai acp login` in a terminal.
115
+ authMethods:[...(login?[{id:'mlai-login',name:'Sign in with ML AI Code',description:'Opens your browser to sign in'}]:[]),
116
+ ...(terminalAuth?[{id:'mlai-login-terminal',name:'Sign in in a terminal',description:'Runs mlai login',type:'terminal',args:['login']}]:[])]};
117
+ },
118
+ authenticate:async p=>{
119
+ if(p?.methodId!=='mlai-login'||!login)return {};
120
+ try{await login()}catch(e){throw new RpcError(ERR.auth,e?.message||'Sign-in did not finish')}
121
+ modelList=null;return {};
122
+ },
52
123
  'session/new':async p=>{
53
124
  if(typeof p?.cwd!=='string'||!path.isAbsolute(p.cwd))throw new RpcError(ERR.params,'The working directory must be an absolute path');
54
125
  if(sessions.size>=20)throw new RpcError(ERR.internal,'Too many sessions in this connection. Restart the agent.');
55
- const s=await createSession({cwd:p.cwd,mode:'guided'});
56
- const id=s.meta.id;sessions.set(id,{s,busy:null});
57
- return {sessionId:id,modes:modesFor(sessionMode(s.meta))};
126
+ acpMcpServers(p.mcpServers);
127
+ return open(await createSession({cwd:p.cwd,mode:'guided'}),p.mcpServers);
128
+ },
129
+ 'session/load':async p=>{
130
+ if(!openSession)throw new RpcError(ERR.method,'Method not found: session/load');
131
+ if(typeof p?.sessionId!=='string'||!/^[A-Za-z0-9_-]{1,80}$/.test(p.sessionId))throw new RpcError(ERR.params,'Unknown session');
132
+ if(sessions.get(p.sessionId)?.busy)throw new RpcError(ERR.internal,'This session is already working on a prompt');
133
+ acpMcpServers(p.mcpServers);
134
+ let s;try{s=await openSession(p.sessionId)}catch{throw new RpcError(ERR.session,'Unknown session')}
135
+ if(typeof p.cwd==='string'&&p.cwd&&s.meta.root&&folderKey(p.cwd)!==folderKey(s.meta.root)&&!(s.meta.parent&&folderKey(p.cwd)===folderKey(s.meta.parent)))throw new RpcError(ERR.params,'This session belongs to another folder');
136
+ // Replay the conversation so the editor can show it, then answer.
137
+ for(const t of await s.transcript().catch(()=>[])){
138
+ say(s.meta.id,String(t.task||''),'user_message_chunk');
139
+ for(const e of t.events||[])if(e?.type==='assistant'||e?.type==='answer')say(s.meta.id,String(e.content||'')+'\n\n');
140
+ }
141
+ const {sessionId,...rest}=await open(s,p.mcpServers);return rest;
142
+ },
143
+ 'session/list':async p=>{
144
+ if(!listSessions)throw new RpcError(ERR.method,'Method not found: session/list');
145
+ const cwd=typeof p?.cwd==='string'&&p.cwd?folderKey(p.cwd):null;
146
+ const all=(await listSessions()).filter(m=>m?.id&&m.root&&(!cwd||folderKey(m.root)===cwd||(m.parent&&folderKey(m.parent)===cwd))).slice(0,50);
147
+ return {sessions:all.map(m=>({sessionId:m.id,cwd:m.root,...(m.title?{title:String(m.title).slice(0,200)}:{}),updatedAt:m.updated||m.created||null}))};
148
+ },
149
+ 'session/set_config_option':async p=>{
150
+ if(p?.configId!=='model')throw new RpcError(ERR.params,'Unknown option');
151
+ await setModel(p,p.value);return {configOptions:(await configFor(need(p.sessionId))).configOptions||[]};
58
152
  },
153
+ // Older editors use the draft model selector.
154
+ 'session/set_model':async p=>{await setModel(p,p?.modelId);return {}},
59
155
  'session/set_mode':async p=>{
60
156
  const {s}=need(p?.sessionId);const m=modeName(p?.modeId);if(!m)throw new RpcError(ERR.params,'Modes: '+MODE_NAMES.join(', '));
61
157
  await applyMode(s,m);notify(p.sessionId,{sessionUpdate:'current_mode_update',currentModeId:m});return {};
@@ -63,8 +159,11 @@ export function createAcpServer({write,createSession,cloud,version='0',log=()=>{
63
159
  'session/prompt':async p=>{
64
160
  const entry=need(p?.sessionId),{s}=entry,sid=p.sessionId;
65
161
  if(entry.busy)throw new RpcError(ERR.internal,'This session is already working on a prompt');
66
- const task=taskFor(sessionMode(s.meta),promptText(p.prompt));
162
+ const pics=promptImages(p.prompt);
163
+ const text=promptText(p.prompt,{allowEmpty:pics.length>0})||'Look at the attached image.';
164
+ const mode=sessionMode(s.meta),task=taskFor(mode,text);
67
165
  let client;try{client=await cloud()}catch(e){throw new RpcError(ERR.auth,e.message||'Sign in first: run mlai login in a terminal.')}
166
+ const images=[];for(const b of pics){try{images.push(await s.addImage(b))}catch(e){throw new RpcError(ERR.params,e.message)}}
68
167
  const tools=[],say=text=>text&&notify(sid,{sessionUpdate:'agent_message_chunk',content:{type:'text',text}});
69
168
  entry.cancelled=false;
70
169
  const onEvent=async e=>{
@@ -92,7 +191,9 @@ export function createAcpServer({write,createSession,cloud,version='0',log=()=>{
92
191
  };
93
192
  s.on('event',onEvent);entry.busy=true;
94
193
  try{
95
- const r=await s.send(task,{cloud:client,steps,onProgress:m=>log(m+'...')});
194
+ const r=await s.send(task,{cloud:client,steps,onProgress:m=>log(m+'...'),...(images.length?{images}:{}),
195
+ ...(entry.model?{run:{mode:RUN_MODE[MODES[mode].engine],model:entry.model,effort:'medium',role:'engineer',planApproval:'off',askFirst:'never',steps}}:{}),
196
+ ...(entry.mcp&&Object.keys(entry.mcp.mcpServers).length?{extensions:{mcpServers:entry.mcp.mcpServers,...(Object.keys(entry.mcp.mcpEnv).length?{mcpEnv:entry.mcp.mcpEnv}:{})}}:{})});
96
197
  for(const id of tools)notify(sid,{sessionUpdate:'tool_call_update',toolCallId:id,status:'completed'});
97
198
  if(entry.cancelled||r?.state==='stopped')return {stopReason:'cancelled'};
98
199
  if(r?.state!=='completed'&&r?.error)say(String(r.error)+'\n');
@@ -129,16 +230,17 @@ export async function serveStdio(server,{input=process.stdin,write}={}){
129
230
  await Promise.allSettled([...inflight]);server.close();
130
231
  }
131
232
 
132
- /** Entry point for `mlai acp` (cli.mjs). */
233
+ /** Entry point for `mlai acp` (cli.mjs). o.login(): the browser sign-in, writing only to stderr. */
133
234
  export async function acpMain(o={}){
134
- const [{Session},{loadLogin},{Cloud},{VERSION,DEFAULT_SERVER}]=await Promise.all([import('../session.mjs'),import('../credentials.mjs'),import('../cloud.mjs'),import('../home.mjs')]);
235
+ const [{Session},{loadLogin},{Cloud},{VERSION,DEFAULT_SERVER},{pickerModels}]=await Promise.all([import('../session.mjs'),import('../credentials.mjs'),import('../cloud.mjs'),import('../home.mjs'),import('../ide.mjs')]);
135
236
  const write=m=>process.stdout.write(JSON.stringify(m)+'\n');
136
237
  const cloud=async()=>{
137
238
  const login=await loadLogin().catch(()=>null);
138
239
  if(!login?.token)throw new Error('Not signed in. Run mlai login in a terminal, then try again.');
139
240
  return new Cloud({server:(o.server||process.env.MLAI_SERVER||login.server||DEFAULT_SERVER).replace(/\/$/,''),token:login.token});
140
241
  };
141
- const server=createAcpServer({write,version:VERSION,cloud,createSession:a=>Session.create(a),log:t=>process.stderr.write(t+'\n'),steps:o.steps||120});
242
+ const server=createAcpServer({write,version:VERSION,cloud,createSession:a=>Session.create(a),openSession:id=>Session.open(id),listSessions:()=>Session.list(),
243
+ models:()=>pickerModels({cloud}),login:typeof o.login==='function'?o.login:null,log:t=>process.stderr.write(t+'\n'),steps:o.steps||120});
142
244
  process.stderr.write('ML AI Code ACP server ready on stdio.\n');
143
245
  await serveStdio(server,{write});
144
246
  return 0;
package/src/tui/app.mjs CHANGED
@@ -197,7 +197,9 @@ export async function runTui({session,settings={},cloud=null,flags={},first=null
197
197
  async function decide(verdict,{feedback=null,always=false}={}){
198
198
  const m=st.modal;if(!m||m.type!=='approval'&&m.type!=='feedback')return;
199
199
  const a=m.a;st.modal=null;
200
- try{await session.decide(a.id,verdict)}catch(e){print(t.bad('Could not answer: '+e.message))}
200
+ const install=verdict!=='reject'&&a.kind==='browser'&&a.install;
201
+ if(install)print(tr.elbow()+t.dim('Installing the test browser (one-time download)...'));
202
+ try{await session.decide(a.id,verdict,install?{onProgress:msg=>{st.activity=String(msg).slice(0,80);draw()}}:undefined)}catch(e){print(t.bad('Could not answer: '+e.message))}
201
203
  const plan=parseApproval(a).kind==='plan';
202
204
  if(verdict==='approve'){
203
205
  if(always&&m.rule){st.rules.add(m.rule);try{await ctx.settings?.save?.('local','permissions',{allow:[m.rule]});print(tr.elbow()+t.ok('Approved')+t.dim(' · always allowing '+m.rule+' (saved to .mlai/settings.local.json)'))}catch(e){print(tr.elbow()+t.ok('Approved')+t.dim(' · allowing '+m.rule+' for this session ('+e.message+')'))}}
@@ -506,6 +508,20 @@ export async function runTui({session,settings={},cloud=null,flags={},first=null
506
508
  const n=terminals.running().length;if(n){st.exiting=false;print(t.dim(' Stopping '+n+' background terminal'+(n===1?'':'s')+'...'));st.exiting=true;await terminals.stopAll()}
507
509
  exitResolve(code);
508
510
  }
511
+ /**
512
+ * Stops the running turn once: later presses only remind that it is stopping. An open approval card is answered
513
+ * (rejected) quietly so the engine is not left waiting on it, and the queued cards are dropped.
514
+ */
515
+ function stopRun(){
516
+ if(st.cancelled){flash('Stopping the agent...',1500);return}
517
+ st.cancelled=true;
518
+ print(t.warn(' Stopping...'));
519
+ // The cancel flag goes first, so the engine sees it as soon as the withdrawn approval lets it continue.
520
+ const cards=[...(st.modal?.type==='approval'||st.modal?.type==='feedback'?[st.modal.a]:[]),...st.approvals.splice(0)];
521
+ if(cards.length)st.modal=null;
522
+ session.cancel().catch(()=>{}).then(()=>Promise.all(cards.map(a=>session.decide(a.id,'reject').catch(()=>{}))));
523
+ setTitle();draw();
524
+ }
509
525
  function onKey(k){
510
526
  Promise.resolve(handleKey(k)).catch(e=>print(t.bad('error: '+(e?.message||e))));
511
527
  }
@@ -514,8 +530,9 @@ export async function runTui({session,settings={},cloud=null,flags={},first=null
514
530
  // Ctrl-C: stop the agent, close a popup, clear the line, or (twice) exit.
515
531
  if(k.ctrl&&k.name==='c'){
516
532
  if(st.shellChild){try{st.shellChild.kill('SIGINT')}catch{}return}
533
+ if((m?.type==='approval'||m?.type==='feedback')&&st.running){stopRun();return}
517
534
  if(m){closeModal();return}
518
- if(st.running){st.cancelled=true;print(t.warn(' Stopping...'));session.cancel().catch(()=>{});return}
535
+ if(st.running){stopRun();return}
519
536
  if(editor.text){editor.clear();draw();return}
520
537
  if(Date.now()-st.lastCtrlC<1500)return quit(0);
521
538
  st.lastCtrlC=Date.now();flash('Press Ctrl-C again to exit',1500);return;
@@ -558,7 +575,8 @@ export async function runTui({session,settings={},cloud=null,flags={},first=null
558
575
  if(c==='a'){if(m.rule)return decide('approve',{always:true});flash('No narrow rule for this one; answer y or n');return}
559
576
  if(c==='n'){st.modal={type:'feedback',a:m.a,rule:m.rule,plan:parseApproval(m.a).kind==='plan',editor:new Editor()};draw();return}
560
577
  }
561
- if(k.name==='escape')return decide('reject');
578
+ // Esc on an approval card stops the run, like Esc anywhere else while the agent works; n rejects.
579
+ if(k.name==='escape'){if(st.running){stopRun();return}return decide('reject')}
562
580
  if(k.ctrl&&k.name==='o'){toggleTools();const v=approvalLines(m.a,{t,cols:screen.cols,box,expanded:tr.expanded,rule:m.rule});if(tr.expanded)print(['',...v.lines]);return}
563
581
  flash('Answer y, a or n');return;
564
582
  }
@@ -599,7 +617,7 @@ export async function runTui({session,settings={},cloud=null,flags={},first=null
599
617
  if(k.ctrl&&k.name==='z'&&process.platform!=='win32'){suspend();return}
600
618
  if(k.name==='escape'&&!editor.search&&!(editor.vim&&editor.vimMode==='insert'&&editor.text)){
601
619
  if(st.popup){editor.text.startsWith('/')&&!editor.text.includes(' ')?editor.clear():null;st.popup=null;st.sel=0;draw();if(!editor.text)return}
602
- if(st.running){st.cancelled=true;print(t.warn(' Stopping...'));session.cancel().catch(()=>{});return}
620
+ if(st.running){stopRun();return}
603
621
  const now=Date.now(),dbl=now-st.lastEsc<600;st.lastEsc=now;
604
622
  if(dbl){st.lastEsc=0;if(editor.text){editor.clear();draw();return}
605
623
  if(registry.find('rewind')){const {result}=await registry.dispatch(ctx,'/rewind');if(typeof result?.send==='string')await runTask(result.send);draw()}else flash('Rewind is not available');return}
@@ -682,7 +700,8 @@ export async function runTui({session,settings={},cloud=null,flags={},first=null
682
700
  process.once('SIGCONT',()=>{setup();draw()});
683
701
  process.kill(process.pid,'SIGTSTP');
684
702
  }
685
- const onSignal=()=>quit(130);
703
+ // BUG-0516: on a closed terminal (SIGHUP) or SIGTERM the engine is stopped for sure before exiting.
704
+ const onSignal=()=>{session.stopNow?.().catch(()=>{});quit(130)};
686
705
  stdin.on('data',onData);stdout.on('resize',onResize);
687
706
  process.on('SIGTERM',onSignal);process.on('SIGHUP',onSignal);
688
707
  setup();
package/src/tui/chat.mjs CHANGED
@@ -18,14 +18,15 @@ import {sub} from '../home.mjs';
18
18
  import {twoWordTitle} from '../two-words.mjs';
19
19
  import {MODES,modeName,sessionMode,taskFor,applyMode} from '../modes.mjs';
20
20
  import {plainUi} from './plain.mjs';
21
- import {snapshot,restore,forget} from './snapshots.mjs';
21
+ import {snapshot,snapshotAfter,restore,forget} from './snapshots.mjs';
22
+ import {pushTranscript} from '../view-sync.mjs';
22
23
 
23
24
  /** Used when the server does not list models (older servers, offline). */
24
- export const FALLBACK_MODELS=[{id:'pixis',label:'Pixis',available:true,vision:true,credits:1,creditLabel:'Standard credits'}];
25
+ export const FALLBACK_MODELS=[{id:'pixis',label:'Pixis',available:true,vision:true,creditLabel:'Uses your plan credits'}];
25
26
  /** Credits like the app shows them (lib/plans.ts TOKENS_PER_CREDIT; tests/cli-credits.test.mjs keeps them in step). */
26
- export const TOKENS_PER_CREDIT=60_000;
27
- export const creditsFor=tokens=>Math.round(Math.max(0,Number(tokens)||0)/TOKENS_PER_CREDIT*100)/100;
28
- export function formatCredits(n){const v=Math.max(0,Number(n)||0);return v>=1000?Math.round(v).toLocaleString('en-US'):v>=100?String(Math.round(v)):String(Math.round(v*10)/10)}
27
+ export const TOKENS_PER_CREDIT=1_000_000;
28
+ export const creditsFor=tokens=>Math.round(Math.max(0,Number(tokens)||0)/TOKENS_PER_CREDIT*1000)/1000;
29
+ export function formatCredits(n){const v=Math.max(0,Number(n)||0);return v>=1000?Math.round(v).toLocaleString('en-US'):v>=100?String(Math.round(v)):v>=1?String(Math.round(v*10)/10):String(Math.round(v*100)/100)}
29
30
  /** Engine run modes the server understands (lib/run-request.ts). */
30
31
  const RUN_MODE={guided:'approve',plan:'plan',auto:'auto'};
31
32
  /** An overloaded or unavailable model (start refused, or the run failed on model errors): try the next fallback model. */
@@ -38,10 +39,24 @@ const COMPACT_TASK='Summarize our conversation so far so it can continue from th
38
39
  /** The final answer of a turn from its events and status, like the app shows it. */
39
40
  export function answerOf(turn){
40
41
  const ev=turn?.events||[];
41
- const a=[...ev].reverse().find(e=>e.type==='answer'&&e.content);if(a)return String(a.content);
42
- const sub=turn?.status?.result?.submission;if(typeof sub==='string'&&sub&&sub!=='Task complete')return sub;
43
- const last=[...ev].reverse().find(e=>e.type==='assistant'&&typeof e.content==='string'&&e.content.trim());
44
- return last?String(last.content):(turn?.status?.error||'');
42
+ // BUG-0520: a tool call the model wrote as text, or the engine's deliverables dump, is never shown as the answer.
43
+ const ok=t=>typeof t==='string'&&t.trim()&&!internalText(t);
44
+ const a=[...ev].reverse().find(e=>e.type==='answer'&&ok(e.content));if(a)return String(a.content);
45
+ const sub=turn?.status?.result?.submission;if(ok(sub)&&sub!=='Task complete')return sub;
46
+ const last=[...ev].reverse().find(e=>e.type==='assistant'&&ok(e.content));
47
+ if(last)return String(last.content);
48
+ const raw=[...ev].reverse().find(e=>(e.type==='answer'||e.type==='assistant')&&typeof e.content==='string'&&e.content.trim())?.content||(typeof sub==='string'?sub:'');
49
+ return turn?.status?.error||(raw?readableInternal(raw):'');
50
+ }
51
+ const TOOL_TEXT=/^\s*```(?:tool|json)?\s*\{\s*"(?:connection|name|tool|tool_name|function)"\s*:[\s\S]*\}\s*```\s*$|^\s*\{\s*"(?:connection|tool_name|function)"\s*:[\s\S]*"(?:arguments|args|parameters)"\s*:[\s\S]*\}\s*$/;
52
+ const DELIVERABLES=/^\s*Declared deliverables remain unfinished:\s*(\[[\s\S]*?\])\./;
53
+ /** Engine-internal text (a tool call written as text, a deliverables dump) that is not an answer for a person. */
54
+ export function internalText(t){return TOOL_TEXT.test(String(t||''))||DELIVERABLES.test(String(t||''))}
55
+ /** A sentence in place of internal text, when there is nothing better to show. */
56
+ export function readableInternal(t){
57
+ const m=DELIVERABLES.exec(String(t||''));
58
+ if(m){try{const items=JSON.parse(m[1]);if(Array.isArray(items)&&items.length)return 'The run ended with work not finished: '+items.slice(0,6).map(i=>String(i?.title||i?.id||'item')+(i?.status?' ('+i.status+(i.reason||i.blocker?': '+String(i.reason||i.blocker).slice(0,160):'')+')':'')).join('; ')+'.'}catch{}}
59
+ return 'The run ended without a final message for you. Ask a follow-up (mlai -c) to get a summary of what was done.';
45
60
  }
46
61
  const sortHistory=names=>names.filter(n=>n.endsWith('.json')).sort((a,b)=>a.length-b.length||a.localeCompare(b));
47
62
 
@@ -66,13 +81,13 @@ export class Chat extends EventEmitter{
66
81
  #bind(s){
67
82
  if(this.session)this.session.off('started',this.onStarted);
68
83
  this.session=s;
69
- this.onStarted=e=>{if(e.tokensLeft!=null)this.tokensLeft=e.tokensLeft;this.emit('change')};
84
+ this.onStarted=e=>{if(e.tokensLeft!=null)this.tokensLeft=e.tokensLeft;if(e.uncapped){this.uncapped=true;this.tokensLeft=null}else if(e.tokensLeft!=null)this.uncapped=false;this.emit('change')};
70
85
  s.on('started',this.onStarted);
71
86
  this.usage={tokens:s.meta.turns.reduce((a,t)=>a+(t.tokens||0),0),calls:s.meta.turns.reduce((a,t)=>a+(t.calls||0),0)};
72
87
  }
73
88
  get info(){const list=this.models||FALLBACK_MODELS;return list.find(m=>m.id===this.model)||(this.model&&!this.models?{id:this.model,label:this.model,available:true,creditLabel:'Credits per your plan'}:null)||list.find(m=>m.id===(this.defaultModel||'pixis'))||list[0]}
74
89
  get modelLabel(){return this.info?.label||this.model||'Pixis'}
75
- get credits(){return this.info?.creditLabel||'Standard credits'}
90
+ get credits(){return this.info?.creditLabel||'Uses your plan credits'}
76
91
  get branch(){try{return execFileSync('git',['branch','--show-current'],{cwd:this.session.meta.root,encoding:'utf8',stdio:['ignore','pipe','ignore']}).trim()||null}catch{return null}}
77
92
 
78
93
  /** The account's model list from the server (GET /api/clients); falls back to the default model. */
@@ -97,7 +112,9 @@ export class Chat extends EventEmitter{
97
112
  get efforts(){const e=this.info?.efforts;return Array.isArray(e)?e:['low','medium','high','max']}
98
113
  async setEffort(e){if(!['low','medium','high','max'].includes(e))throw new Error('Effort is low, medium, high or max');
99
114
  const ok=this.efforts;if(ok.length&&!ok.includes(e))throw new Error(this.modelLabel+' takes '+ok.join(', ')+' effort');this.effort=e;this.session.meta.effort=e;await this.session.save();this.emit('change')}
100
- async setSession(s){this.#bind(s);this.mode=sessionMode(s.meta);if(s.meta.model)this.model=s.meta.model;this.emit('session',s);this.emit('change')}
115
+ async setSession(s){this.#bind(s);this.mode=sessionMode(s.meta);if(s.meta.model)this.model=s.meta.model;
116
+ // Effort belongs to the session: a new one (/cd, /clear) starts from the --effort flag or the saved default, not the last session's choice.
117
+ this.effort=s.meta.effort||this.flags.effort||this.settings?.effort||'medium';this.emit('session',s);this.emit('change')}
101
118
  async rename(title){
102
119
  const t=String(title||'').replace(/[\x00-\x1f\x7f]/g,'').trim().slice(0,80);if(!t)throw new Error('Give a name: /rename <name>');
103
120
  this.session.meta.title=t;this.session.meta.renamed=true;await this.session.save();this.emit('change');return t;
@@ -105,7 +122,7 @@ export class Chat extends EventEmitter{
105
122
 
106
123
  /** The run body the server builds the request from, exactly like the app's (Contract A). */
107
124
  runBody(){
108
- return {mode:RUN_MODE[MODES[this.mode].engine],model:this.model||undefined,effort:this.effort,role:'engineer',planApproval:'off',askFirst:'never',steps:this.steps,...(this.maxTokens?{maxTokens:this.maxTokens}:{})};
125
+ return {mode:RUN_MODE[MODES[this.mode].engine],model:this.model||undefined,effort:this.effort,role:'engineer',planApproval:'off',askFirst:'never',steps:this.steps,...(this.hardSteps?{hardSteps:true}:{}),...(this.unattended?{unattended:true}:{}),...(this.maxTokens?{maxTokens:this.maxTokens}:{})};
109
126
  }
110
127
  /** One turn. Takes a file snapshot first (for /rewind), applies the mode, model, effort and permissions. */
111
128
  async send(text,{images,onProgress=()=>{},raw=false}={}){
@@ -117,6 +134,10 @@ export class Chat extends EventEmitter{
117
134
  // Restricted mode fails closed: without its extensions the run would not be restricted, so it does not start.
118
135
  if(this.restricted&&!mod?.localExtensions)throw new Error('Restricted mode could not load its rules, so nothing ran.');
119
136
  this.extensions=mod?.localExtensions?await mod.localExtensions({root:s.meta.root,settings:this.settings,skipPermissions:this.skipPermissions,restricted:this.restricted}).catch(e=>{if(this.restricted)throw e;return undefined}):undefined;
137
+ // Editor sessions (host.mjs): the IDE's own MCP servers for this session only, with their secrets kept out of request.json.
138
+ if(this.sessionMcp&&Object.keys(this.sessionMcp.mcpServers||{}).length){const x=this.extensions||{},w=x.warnings;
139
+ this.extensions={...x,mcpServers:{...(x.mcpServers||{}),...this.sessionMcp.mcpServers},...(Object.keys(this.sessionMcp.mcpEnv||{}).length||x.mcpEnv?{mcpEnv:{...(x.mcpEnv||{}),...(this.sessionMcp.mcpEnv||{})}}:{})};
140
+ if(w)Object.defineProperty(this.extensions,'warnings',{value:w})}
120
141
  if(this.toolRules){const p={...(this.extensions?.permissions||{})};for(const k of this.restricted?['deny','ask']:['allow','deny','ask'])if(this.toolRules[k]?.length)p[k]=[...new Set([...(p[k]||[]),...this.toolRules[k]])];
121
142
  const w=this.extensions?.warnings;this.extensions={...(this.extensions||{}),permissions:p};if(w)Object.defineProperty(this.extensions,'warnings',{value:w})}
122
143
  const dirs=this.addDirs.length?'\n\nYou may also read these folders: '+this.addDirs.join(', '):'';
@@ -125,17 +146,21 @@ export class Chat extends EventEmitter{
125
146
  if(task!==body&&!this.session.meta.title)this.session.meta.title=twoWordTitle(text);// name it after the task, not the instructions
126
147
  const queue=this.fallbacks.filter(m=>m!==this.model);let r;
127
148
  for(;;){
128
- await snapshot(s,s.meta.turns.length);
149
+ const idx=s.meta.turns.length;await snapshot(s,idx);
150
+ const after=()=>s.meta.turns.length>idx?snapshotAfter(s,idx):null;// BUG-0525: what the agent changed this turn, for /rewind
129
151
  const next=()=>{const to=queue.shift();if(!to)return null;const from=this.model;this.model=to;this.emit('fallback',{from:from||this.defaultModel||'pixis',to});this.emit('change');return to};
130
152
  try{r=await s.send(task,{cloud:this.cloud,steps:this.steps,effort:this.effort,onProgress,allowUnsandboxed:this.allowUnsandboxed,images,run:this.runBody(),
131
153
  ...(this.addDirs.length?{extraRead:this.addDirs}:{}),...(this.extensions?{extensions:this.extensions}:{})})}
132
- catch(e){if(modelBusy(e)&&next())continue;throw e}
154
+ catch(e){await after();if(modelBusy(e)&&next())continue;throw e}
155
+ await after();
133
156
  this.usage.tokens+=r.usage?.tokens||0;this.usage.calls+=r.usage?.calls||0;
134
157
  // Retry only a run that changed nothing: a half-done task is never repeated on another model.
135
158
  if(!['completed','stopped','limited'].includes(r.state)&&!r.code&&!(r.completion?.changedFiles||[]).length&&modelBusy(r.error)&&next())continue;
136
159
  break;
137
160
  }
138
161
  if(r.contextTokens)this.context={used:r.contextTokens,window:r.contextWindow||null};
162
+ // BUG-0478: the web shows this chat as a read-only transcript (never waits on the network).
163
+ if(!raw)void pushTranscript(s,this.cloud);
139
164
  this.emit('turn',r);
140
165
  return r;
141
166
  }finally{this.running=false;this.emit('change');this.#drain()}
@@ -153,7 +178,7 @@ export class Chat extends EventEmitter{
153
178
  /** The conversation as Markdown, for /export. */
154
179
  async markdown(){
155
180
  const m=this.session.meta,turns=await this.transcript();
156
- const lines=['# '+(m.title||'ML AI Code session'),'',`Folder: ${m.root} `,`Session: ${m.id} `,`Exported: ${new Date().toISOString().slice(0,16).replace('T',' ')}`,''];
181
+ const lines=['# '+(m.title||'ML AI Code session'),'',`Folder: ${m.root} `,`Session: ${m.id} `,`Exported: ${localExportTime()}`,''];
157
182
  for(const t of turns){
158
183
  lines.push('## You','',String(t.task||'').replace(/^Answer the question from the code[^\n]*\n\nQuestion: /,''),'');
159
184
  const files=t.completion?.changedFiles||[];
@@ -228,3 +253,5 @@ export class Chat extends EventEmitter{
228
253
  };
229
254
  }
230
255
  }
256
+ /** BUG-0547: the export time in local time, with its UTC offset. */
257
+ function localExportTime(d=new Date()){const p=n=>String(n).padStart(2,'0'),off=-d.getTimezoneOffset();return d.getFullYear()+'-'+p(d.getMonth()+1)+'-'+p(d.getDate())+' '+p(d.getHours())+':'+p(d.getMinutes())+' (UTC'+(off<0?'-':'+')+p(Math.floor(Math.abs(off)/60))+':'+p(Math.abs(off)%60)+')'}
@@ -17,7 +17,7 @@ export const KEYS={
17
17
  vim:{about:'Vim keys in the input',choices:[true,false]},
18
18
  statusLine:{about:'The status line under the input',hint:'{"enabled":true,"command":null}'},
19
19
  autoUpdate:{about:'Install CLI updates in the background',choices:[true,false]},
20
- maxSteps:{about:'Agent steps per turn, 1 to 160',hint:'number'},
20
+ maxSteps:{about:'Agent steps per turn, 1 to 160',hint:'a whole number from 1 to 160'},
21
21
  reviewModel:{about:'Model for /review and mlai review (null: the chat model)',hint:'model id or null'},
22
22
  autoReview:{about:'In auto mode, a reviewer checks risky actions first',choices:[true,false]},
23
23
  memories:{about:'Send .mlai/MEMORY.md with each turn (/memories; opt-in)',choices:[true,false]},
@@ -61,6 +61,8 @@ export function install(register){
61
61
  if(!key)throw new CommandError('Usage: /config '+verb+' <key>'+(verb==='set'?' <value>':'')+' [--user|--project|--local]');
62
62
  if(verb==='unset'){await save(ctx,scope,key,undefined);return {key,scope}}
63
63
  const raw=words.slice(2).join(' ');if(!raw)throw new CommandError('Give a value: /config set '+key+' <value>');
64
+ // BUG-0534: unknown keys are refused (a typo would be saved and silently ignored).
65
+ if(!KEYS[key]&&!(key in DEFAULTS)&&!CHECKS[key]&&ctx.settings?.[key]===undefined)throw new CommandError('Unknown setting '+key+'. Settings: '+[...new Set([...Object.keys(KEYS),...Object.keys(DEFAULTS)])].sort().join(', ')+'.');
64
66
  const value=parseValue(raw);
65
67
  if(CHECKS[key]&&!CHECKS[key](value))throw new CommandError('Invalid value for '+key+(KEYS[key]?.choices?': use '+KEYS[key].choices.join(', '):KEYS[key]?.hint?': '+KEYS[key].hint:''));
66
68
  await save(ctx,scope,key,value);return {key,scope,value};
@@ -1,11 +1,12 @@
1
1
  // Core session commands (lead). Other areas add their own cmd-<area>.mjs; see commands.mjs.
2
2
  import {execFileSync,spawn} from 'node:child_process';
3
3
  import {writeFile} from 'node:fs/promises';
4
+ import {existsSync} from 'node:fs';
4
5
  import path from 'node:path';
5
6
  import {helpText,CommandError} from './commands.mjs';
6
7
  import {MODES,MODE_NAMES,modeName} from '../modes.mjs';
7
8
  import {Session} from '../session.mjs';
8
- import {VERSION,home} from '../home.mjs';
9
+ import {VERSION,home,DEFAULT_SERVER} from '../home.mjs';
9
10
  import {creditsFor,formatCredits,answerOf} from './chat.mjs';
10
11
 
11
12
  const need=ctx=>{if(!ctx.chat)throw new CommandError('This command needs an interactive session.');return ctx.chat};
@@ -88,7 +89,7 @@ export function install(register){
88
89
  }});
89
90
  register({name:'about',summary:'Version, coding engine and where data lives',run:async ctx=>{
90
91
  let engine='bundled';try{const {activeEngine}=await import('../engine.mjs');const h=await activeEngine();engine=h.source+' '+String(h.version).slice(0,8)}catch{}
91
- ctx.out(['ML AI Code '+VERSION,'Coding engine: '+engine,'Node '+process.versions.node+' · '+process.platform+' '+process.arch,'Local data: '+home(),'Server: '+(ctx.server?.server||'not signed in'),'Docs: '+(ctx.server?.server||'https://mlai-mini-code.vercel.app')+'/docs'].join('\n'));
92
+ ctx.out(['ML AI Code '+VERSION,'Coding engine: '+engine,'Node '+process.versions.node+' · '+process.platform+' '+process.arch,'Local data: '+home(),'Server: '+(ctx.server?.server||'not signed in'),'Docs: '+(ctx.server?.server||DEFAULT_SERVER)+'/docs'].join('\n'));
92
93
  }});
93
94
  register({name:'rename',args:'<name>',summary:'Name this session (mlai -r <name> resumes it)',run:async(ctx,a)=>{const t=await need(ctx).rename(a).catch(e=>{throw new CommandError(e.message)});ctx.out('Renamed to '+t)}});
94
95
 
@@ -126,20 +127,23 @@ export function install(register){
126
127
  const what=(await ctx.ui.pick([{label:'Files and conversation',value:'both'},{label:'Conversation only',value:'chat'},{label:'Files only',value:'files'}],{title:'Restore'}))?.value;
127
128
  if(!what)return;
128
129
  const r=await chat.rewind(turn,what).catch(e=>{throw new CommandError(e.message)});
129
- ctx.out('Rewound to before turn '+(turn+1)+(r.files?' · '+r.files.restored+' file'+(r.files.restored===1?'':'s')+' restored, '+r.files.removed+' removed':'')+'.');
130
+ ctx.out('Rewound to before turn '+(turn+1)+(r.files?' · '+r.files.restored+' file'+(r.files.restored===1?'':'s')+' restored, '+r.files.removed+' removed':'')+'.'+(r.files?.kept?' Kept '+r.files.kept+' file'+(r.files.kept===1?'':'s')+' you edited after the agent did.':''));
130
131
  return {rewound:turn};
131
132
  }});
132
- register({name:'usage',aliases:['cost'],summary:'Credits and tokens used, and what is left',run:async ctx=>{
133
+ register({name:'usage',aliases:['cost'],summary:'Credits used, and what is left',run:async ctx=>{
133
134
  const chat=need(ctx),u=chat.usage;
134
- ctx.out(['This session: '+formatCredits(creditsFor(u.tokens))+' credits · '+u.tokens.toLocaleString('en-US')+' tokens · '+u.calls+' model call'+(u.calls===1?'':'s')+' · '+ctx.session.meta.turns.length+' turn'+(ctx.session.meta.turns.length===1?'':'s'),
135
+ ctx.out(['This session: '+formatCredits(creditsFor(u.tokens))+' credits · '+u.calls+' model call'+(u.calls===1?'':'s')+' · '+ctx.session.meta.turns.length+' turn'+(ctx.session.meta.turns.length===1?'':'s'),
135
136
  'Model: '+chat.modelLabel+' · '+chat.credits,
136
- chat.tokensLeft!=null?'Plan: about '+formatCredits(creditsFor(chat.tokensLeft))+' credits left':'Plan: credits left show after the first turn',
137
+ chat.uncapped?'Plan: no credit limit for this model on your account':chat.tokensLeft!=null?'Plan: about '+formatCredits(creditsFor(chat.tokensLeft))+' credits left':'Plan: credits left show after the first turn',
137
138
  'Plan and billing: the account menu in the app'].join('\n'));
138
139
  }});
139
140
  register({name:'export',args:'[file]',summary:'Save the conversation as Markdown',run:async(ctx,a)=>{
140
141
  const chat=need(ctx),md=await chat.markdown();
141
142
  const name=a||('mlai-'+String(ctx.session.meta.title||'session').toLowerCase().replace(/[^a-z0-9]+/g,'-').replace(/^-|-$/g,'')+'-'+new Date().toISOString().slice(0,10)+'.md');
142
- const file=path.resolve(ctx.session.meta.root,name);
143
+ let file=path.resolve(ctx.session.meta.root,name);
144
+ // BUG-0533: never replace a file without asking; the default name gets a number instead.
145
+ if(!a)for(let n=2;existsSync(file);n++)file=path.resolve(ctx.session.meta.root,name.replace(/\.md$/,'-'+n+'.md'));
146
+ else if(existsSync(file)&&!(ctx.ui?.confirm&&await ctx.ui.confirm(file+' exists. Replace it?',{default:false}))){ctx.out('Not saved: '+file+' exists. Give another name: /export <file>');return {file:null}}
143
147
  await writeFile(file,md);ctx.out('Saved '+file);return {file};
144
148
  }});
145
149
  register({name:'copy',summary:'Copy the last answer to the clipboard',run:async ctx=>{
@@ -123,7 +123,7 @@ function sandboxStatus(ctx){
123
123
  const on=s.enabled!==false,net=s.network!==false;
124
124
  const how=SANDBOXES.includes(kind)?{seatbelt:'macOS Seatbelt',bwrap:'bubblewrap',windows:'a restricted Windows token'}[kind]:null;
125
125
  const netHow=osNetwork(kind)==='os'?'; enforced by the OS, only the model gateway is reachable':'; enforced by the engine check, not the OS, on this computer';
126
- return [...(ctx.chat?.restricted?['Restricted mode: shell commands are off, file tools stay in this project, and the sandbox stays on.']:[]),'Sandbox: '+(on?'on':'off')+(on?how?' ('+how+'; Auto and Plan runs can only write in the repository and caches)':' (not available on this computer; Auto mode cannot start)':' (Auto mode runs commands without the OS sandbox)'),
126
+ return [...(ctx.chat?.restricted?['Restricted mode: shell commands are off, file tools stay in this project, and the sandbox stays on.']:[]),'Sandbox: '+(on?'on':'off')+(on?how?' ('+how+'; Auto runs can only write in the repository and caches; Plan and Ask are read-only)':' (not available on this computer; Auto mode cannot start)':' (Auto mode runs commands without the OS sandbox)'),
127
127
  'Network: '+(net?'on':'off'+' (web tools, remote hosts and package installs are refused'+netHow+')')].join('\n');
128
128
  }
129
129
  async function sandboxCmd(ctx,args){
@@ -163,6 +163,11 @@ async function mcpCmd(ctx,args){
163
163
  if(!url&&!rest.length)throw new CommandError('Give a command to start the server, or --url for a remote server.');
164
164
  if(url&&!/^https?:\/\//.test(url))throw new CommandError('The URL must start with https:// (or http:// for localhost).');
165
165
  const spec=url?{url,...(f.header?{headers:parseKV(f.header,':','--header')}:{}),...(f.transport?.at(-1)==='sse'?{transport:'sse'}:{})}:{command:rest[0],args:rest.slice(1).map(unquote),...(f.env?{env:parseKV(f.env,'=','--env')}:{})};
166
+ // BUG-0539: a server with this name already exists: ask before replacing it.
167
+ const had=listServers(root).find(x=>x.name===name);
168
+ if(had&&!(ctx.ui?.confirm&&await ctx.ui.confirm('An MCP server named '+name+' exists ('+(had.spec?.url||[had.spec?.command,...(had.spec?.args||[])].filter(Boolean).join(' '))+'). Replace it?',{default:false}))){
169
+ ctx.out('Kept the existing MCP server '+name+'. Pick another name, or remove it first with /mcp remove '+name+'.');return {name,kept:true};
170
+ }
166
171
  const scope=scopeOf(f);const where=await addServer({root,settings:{save:async(...a)=>{await save(ctx,...a)}},scope,name,spec});
167
172
  ctx.out('Added MCP server '+name+' ('+scope+', '+where+'). Use ${VAR} in values to read secrets from your environment. /mcp tools '+name+' checks it.');
168
173
  return {name,scope};
@@ -277,6 +282,12 @@ async function hooksCmd(ctx,args){
277
282
  }
278
283
 
279
284
  // ------------------------------------------------------------------ /plugin
285
+ /** Shortens text to at most n characters at a word boundary, with an ellipsis when anything was cut. */
286
+ export function clipWords(s,n){
287
+ const t=String(s||'').replace(/\s+/g,' ').trim();if(t.length<=n)return t;
288
+ const cut=t.slice(0,n-1),sp=cut.lastIndexOf(' ');
289
+ return (sp>n/2?cut.slice(0,sp):cut).replace(/[\s,;:.-]+$/,'')+'\u2026';
290
+ }
280
291
  async function pluginCmd(ctx,args){
281
292
  const [sub]=String(args||'').trim().split(/\s+/);
282
293
  const web='Settings, Plugins in the web app';
@@ -287,7 +298,7 @@ async function pluginCmd(ctx,args){
287
298
  const L=[installed.length?'Installed plugins:':'No plugins installed.'];
288
299
  for(const p of installed){const m=p.manifest||{};L.push(' '+String(m.name||m.id).padEnd(24)+' '+String(m.version||'').padEnd(8)+' '+(p.enabled?.all?'on everywhere':p.enabled?.projects?.length?'on in '+p.enabled.projects.length+' project(s)':'off'))}
289
300
  const cat=(Array.isArray(x.catalog)?x.catalog:[]).filter(m=>!installed.some(p=>p.manifest?.id===m.id));
290
- if(cat.length)L.push('','Available:',...cat.map(m=>' '+String(m.name||m.id).padEnd(24)+' '+String(m.description||'').slice(0,70)));
301
+ if(cat.length)L.push('','Available:',...cat.map(m=>' '+String(m.name||m.id).padEnd(24)+' '+clipWords(m.description,70)));
291
302
  L.push('','Manage plugins in '+web+'.');
292
303
  ctx.out(L.join('\n'));return {plugins:installed.map(p=>p.manifest?.id)};
293
304
  }
@@ -145,7 +145,8 @@ export async function dispatch(ctx,line){
145
145
  /** /help text from the registry. */
146
146
  export function helpText(ctx){
147
147
  const rows=list(ctx);const w=Math.min(28,Math.max(...rows.map(r=>(r.name+' '+r.args).length))+2);
148
- return rows.map(r=>('/'+r.name+(r.args?' '+r.args:'')).padEnd(w+1)+r.summary+(r.aliases.length?' (also /'+r.aliases.join(', /')+')':'')).join('\n');
148
+ // A name longer than the column still gets a space before its description.
149
+ return rows.map(r=>{const n='/'+r.name+(r.args?' '+r.args:'');return n.padEnd(w+1)+(n.length>=w+1?' ':'')+r.summary+(r.aliases.length?' (also /'+r.aliases.join(', /')+')':'')}).join('\n');
149
150
  }
150
151
 
151
152
  /** Imports src/tui/cmd-*.mjs and calls each install(register). Returns the module names; a broken module is reported, not fatal. */
@@ -93,6 +93,7 @@ export async function localExtensions({root,settings=null,skipPermissions=false,
93
93
  ...(sandbox.network===false?{network:{enabled:false}}:{}),
94
94
  ...(Object.keys(mcp.mcpServers).length?{mcpServers:mcp.mcpServers}:{}),
95
95
  ...(Object.keys(mcp.mcpEnv).length?{mcpEnv:mcp.mcpEnv}:{}),
96
+ ...(mcp.blockedFiles?.length?{hardDeny:{paths:mcp.blockedFiles}}:{}),// BUG-0530: a disabled MCP server is not started another way
96
97
  ...(sandbox.enabled===false?{sandbox:{enabled:false}}:{}),
97
98
  // Auto mode's reviewer pass (worker/mlai_auto_review.py); the engine ignores it in other modes.
98
99
  autoReview:{enabled:(fresh??settings)?.autoReview!==false&&!skipPermissions,...(((fresh??settings)?.reviewModel)?{model:(fresh??settings).reviewModel}:{})},
@@ -122,6 +123,7 @@ export function mergeExtensions(server,local){
122
123
  out.permissions={...cur,...(permissions.bypass?{bypass:true}:{})};
123
124
  for(const k of ['allow','deny','ask'])out.permissions[k]=[...new Set([...(Array.isArray(cur[k])?cur[k]:[]),...(Array.isArray(permissions[k])?permissions[k]:[])])];
124
125
  }
126
+ if(isObj(rest.hardDeny)){const b=isObj(base.hardDeny)?base.hardDeny:{};out.hardDeny={...b};for(const k of ['commands','paths','hosts'])if(Array.isArray(b[k])||Array.isArray(rest.hardDeny[k]))out.hardDeny[k]=[...new Set([...(Array.isArray(b[k])?b[k]:[]),...(Array.isArray(rest.hardDeny[k])?rest.hardDeny[k]:[])])]}// local rules only add
125
127
  if(base.localRepoHooks===true)out.localRepoHooks=true;
126
128
  if(isObj(base.network)&&base.network.enabled===false)out.network=base.network;
127
129
  if(isObj(base.mcpServers)||isObj(rest.mcpServers))out.mcpServers={...(isObj(base.mcpServers)?base.mcpServers:{}),...(isObj(rest.mcpServers)?rest.mcpServers:{})};