mlai-code 0.3.3 → 0.3.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (135) hide show
  1. package/README.md +1 -1
  2. package/package.json +1 -1
  3. package/src/checkpoints.mjs +217 -0
  4. package/src/cli.mjs +153 -26
  5. package/src/cloud.mjs +2 -0
  6. package/src/engine.mjs +1 -1
  7. package/src/headless.mjs +25 -9
  8. package/src/home.mjs +3 -2
  9. package/src/host.mjs +141 -13
  10. package/src/ide-quick.mjs +147 -0
  11. package/src/ide.mjs +182 -0
  12. package/src/netbox.mjs +1 -1
  13. package/src/parity.mjs +17 -0
  14. package/src/relay.mjs +1 -1
  15. package/src/render.mjs +9 -2
  16. package/src/runtime.mjs +2 -0
  17. package/src/server.mjs +46 -7
  18. package/src/session.mjs +31 -8
  19. package/src/tui/acp.mjs +121 -19
  20. package/src/tui/app.mjs +2 -1
  21. package/src/tui/chat.mjs +35 -10
  22. package/src/tui/cmd-config.mjs +3 -1
  23. package/src/tui/cmd-core.mjs +9 -5
  24. package/src/tui/cmd-extensibility.mjs +5 -0
  25. package/src/tui/extensions-local.mjs +2 -0
  26. package/src/tui/mcp-config.mjs +22 -4
  27. package/src/tui/review-cli.mjs +15 -4
  28. package/src/tui/snapshots.mjs +57 -16
  29. package/src/two-words.mjs +14 -8
  30. package/src/view-sync.mjs +48 -0
  31. package/src/winenv.mjs +1 -1
  32. package/src/workspace-api.mjs +21 -4
  33. package/vendor/client-sdk/index.cjs +2 -1
  34. package/vendor/cloud-cli/mlai.mjs +23 -11
  35. package/worker/architecture_worker.py +33 -4
  36. package/worker/browser_tool.py +19 -1
  37. package/worker/chat_fork.py +4 -1
  38. package/worker/checkpoints.py +71 -8
  39. package/worker/command_safety.py +56 -3
  40. package/worker/connected_turn.py +30 -0
  41. package/worker/conversation.py +81 -11
  42. package/worker/git_sync.py +4 -4
  43. package/worker/image_generation.py +2 -2
  44. package/worker/kimi_bridge.py +247 -27
  45. package/worker/kimi_gates.py +25 -6
  46. package/worker/kimi_hook.py +153 -12
  47. package/worker/media_tools.py +4 -1
  48. package/worker/mlai_hooks.py +222 -3
  49. package/worker/mlai_mcp.py +26 -6
  50. package/worker/mlai_review/README.md +35 -0
  51. package/worker/mlai_review/__init__.py +1 -0
  52. package/worker/mlai_review/__main__.py +261 -0
  53. package/worker/mlai_review/_compat.py +29 -0
  54. package/worker/mlai_review/analysis/__init__.py +3 -0
  55. package/worker/mlai_review/analysis/detect.py +50 -0
  56. package/worker/mlai_review/analysis/main.py +128 -0
  57. package/worker/mlai_review/analysis/messages.py +8 -0
  58. package/worker/mlai_review/analysis/tools.py +194 -0
  59. package/worker/mlai_review/application/__init__.py +1 -0
  60. package/worker/mlai_review/application/asking.py +53 -0
  61. package/worker/mlai_review/application/challengers.py +142 -0
  62. package/worker/mlai_review/application/context_builder.py +194 -0
  63. package/worker/mlai_review/application/errors.py +17 -0
  64. package/worker/mlai_review/application/feedback.py +52 -0
  65. package/worker/mlai_review/application/matching.py +46 -0
  66. package/worker/mlai_review/application/messages.py +41 -0
  67. package/worker/mlai_review/application/ports.py +222 -0
  68. package/worker/mlai_review/application/prompts.py +342 -0
  69. package/worker/mlai_review/application/review_service.py +200 -0
  70. package/worker/mlai_review/application/reviewers.py +438 -0
  71. package/worker/mlai_review/application/streaming.py +91 -0
  72. package/worker/mlai_review/application/tools.py +138 -0
  73. package/worker/mlai_review/application/usage.py +145 -0
  74. package/worker/mlai_review/application/write_check.py +46 -0
  75. package/worker/mlai_review/contracts/__init__.py +5 -0
  76. package/worker/mlai_review/contracts/analysis.py +57 -0
  77. package/worker/mlai_review/contracts/review.py +42 -0
  78. package/worker/mlai_review/domain/__init__.py +4 -0
  79. package/worker/mlai_review/domain/changes.py +77 -0
  80. package/worker/mlai_review/domain/context.py +147 -0
  81. package/worker/mlai_review/domain/diagnostics.py +239 -0
  82. package/worker/mlai_review/domain/feedback.py +216 -0
  83. package/worker/mlai_review/domain/findings.py +505 -0
  84. package/worker/mlai_review/domain/lifecycle.py +85 -0
  85. package/worker/mlai_review/domain/partition.py +42 -0
  86. package/worker/mlai_review/domain/relations.py +166 -0
  87. package/worker/mlai_review/domain/relevance.py +202 -0
  88. package/worker/mlai_review/domain/report.py +99 -0
  89. package/worker/mlai_review/domain/structure.py +56 -0
  90. package/worker/mlai_review/domain/writes.py +86 -0
  91. package/worker/mlai_review/eval.py +221 -0
  92. package/worker/mlai_review/eval_cases/clean-rename.json +11 -0
  93. package/worker/mlai_review/eval_cases/missing-ownership-check.json +22 -0
  94. package/worker/mlai_review/eval_cases/off-by-one.json +22 -0
  95. package/worker/mlai_review/eval_cases/sql-injection.json +20 -0
  96. package/worker/mlai_review/feedback_report.py +60 -0
  97. package/worker/mlai_review/infrastructure/__init__.py +1 -0
  98. package/worker/mlai_review/infrastructure/analysis/__init__.py +1 -0
  99. package/worker/mlai_review/infrastructure/analysis/none.py +12 -0
  100. package/worker/mlai_review/infrastructure/analysis/translate.py +17 -0
  101. package/worker/mlai_review/infrastructure/github/__init__.py +0 -0
  102. package/worker/mlai_review/infrastructure/github/client.py +445 -0
  103. package/worker/mlai_review/infrastructure/github/feedback.py +212 -0
  104. package/worker/mlai_review/infrastructure/github/http.py +31 -0
  105. package/worker/mlai_review/infrastructure/github/rendering.py +398 -0
  106. package/worker/mlai_review/infrastructure/github/token.py +20 -0
  107. package/worker/mlai_review/infrastructure/local/__init__.py +1 -0
  108. package/worker/mlai_review/infrastructure/local/analyzer.py +48 -0
  109. package/worker/mlai_review/infrastructure/local/events.py +100 -0
  110. package/worker/mlai_review/infrastructure/local/git_reader.py +233 -0
  111. package/worker/mlai_review/infrastructure/local/publisher.py +138 -0
  112. package/worker/mlai_review/infrastructure/messages.py +54 -0
  113. package/worker/mlai_review/infrastructure/models/__init__.py +0 -0
  114. package/worker/mlai_review/infrastructure/models/openai_compatible.py +269 -0
  115. package/worker/mlai_review/infrastructure/structure/__init__.py +1 -0
  116. package/worker/mlai_review/infrastructure/structure/heuristic.py +186 -0
  117. package/worker/mlai_review/infrastructure/structure/tree_sitter.py +186 -0
  118. package/worker/mlai_review/infrastructure/workspace/__init__.py +1 -0
  119. package/worker/mlai_review/infrastructure/workspace/local.py +105 -0
  120. package/worker/mlai_review/infrastructure/workspace/memory.py +77 -0
  121. package/worker/mlai_review/infrastructure/workspace/paths.py +17 -0
  122. package/worker/mlai_review/pipeline.py +89 -0
  123. package/worker/mlai_review/runtime.py +194 -0
  124. package/worker/mlai_review/settings.py +139 -0
  125. package/worker/preview.py +15 -0
  126. package/worker/product_facts.py +3 -1
  127. package/worker/repo_policy.py +5 -0
  128. package/worker/roles.py +29 -2
  129. package/worker/runner.py +126 -18
  130. package/worker/runtime_control.py +64 -3
  131. package/worker/secret_scan.py +3 -2
  132. package/worker/server_memory.py +122 -0
  133. package/worker/subagents.py +6 -2
  134. package/worker/tool_catalog.py +1 -1
  135. package/worker/verification.py +113 -8
package/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
@@ -700,7 +700,8 @@ export async function runTui({session,settings={},cloud=null,flags={},first=null
700
700
  process.once('SIGCONT',()=>{setup();draw()});
701
701
  process.kill(process.pid,'SIGTSTP');
702
702
  }
703
- 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)};
704
705
  stdin.on('data',onData);stdout.on('resize',onResize);
705
706
  process.on('SIGTERM',onSignal);process.on('SIGHUP',onSignal);
706
707
  setup();
package/src/tui/chat.mjs CHANGED
@@ -18,7 +18,8 @@ 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
25
  export const FALLBACK_MODELS=[{id:'pixis',label:'Pixis',available:true,vision:true,creditLabel:'Uses your plan credits'}];
@@ -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,7 +81,7 @@ 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
  }
@@ -107,7 +122,7 @@ export class Chat extends EventEmitter{
107
122
 
108
123
  /** The run body the server builds the request from, exactly like the app's (Contract A). */
109
124
  runBody(){
110
- 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}:{})};
111
126
  }
112
127
  /** One turn. Takes a file snapshot first (for /rewind), applies the mode, model, effort and permissions. */
113
128
  async send(text,{images,onProgress=()=>{},raw=false}={}){
@@ -119,6 +134,10 @@ export class Chat extends EventEmitter{
119
134
  // Restricted mode fails closed: without its extensions the run would not be restricted, so it does not start.
120
135
  if(this.restricted&&!mod?.localExtensions)throw new Error('Restricted mode could not load its rules, so nothing ran.');
121
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})}
122
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]])];
123
142
  const w=this.extensions?.warnings;this.extensions={...(this.extensions||{}),permissions:p};if(w)Object.defineProperty(this.extensions,'warnings',{value:w})}
124
143
  const dirs=this.addDirs.length?'\n\nYou may also read these folders: '+this.addDirs.join(', '):'';
@@ -127,17 +146,21 @@ export class Chat extends EventEmitter{
127
146
  if(task!==body&&!this.session.meta.title)this.session.meta.title=twoWordTitle(text);// name it after the task, not the instructions
128
147
  const queue=this.fallbacks.filter(m=>m!==this.model);let r;
129
148
  for(;;){
130
- 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
131
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};
132
152
  try{r=await s.send(task,{cloud:this.cloud,steps:this.steps,effort:this.effort,onProgress,allowUnsandboxed:this.allowUnsandboxed,images,run:this.runBody(),
133
153
  ...(this.addDirs.length?{extraRead:this.addDirs}:{}),...(this.extensions?{extensions:this.extensions}:{})})}
134
- catch(e){if(modelBusy(e)&&next())continue;throw e}
154
+ catch(e){await after();if(modelBusy(e)&&next())continue;throw e}
155
+ await after();
135
156
  this.usage.tokens+=r.usage?.tokens||0;this.usage.calls+=r.usage?.calls||0;
136
157
  // Retry only a run that changed nothing: a half-done task is never repeated on another model.
137
158
  if(!['completed','stopped','limited'].includes(r.state)&&!r.code&&!(r.completion?.changedFiles||[]).length&&modelBusy(r.error)&&next())continue;
138
159
  break;
139
160
  }
140
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);
141
164
  this.emit('turn',r);
142
165
  return r;
143
166
  }finally{this.running=false;this.emit('change');this.#drain()}
@@ -155,7 +178,7 @@ export class Chat extends EventEmitter{
155
178
  /** The conversation as Markdown, for /export. */
156
179
  async markdown(){
157
180
  const m=this.session.meta,turns=await this.transcript();
158
- 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()}`,''];
159
182
  for(const t of turns){
160
183
  lines.push('## You','',String(t.task||'').replace(/^Answer the question from the code[^\n]*\n\nQuestion: /,''),'');
161
184
  const files=t.completion?.changedFiles||[];
@@ -230,3 +253,5 @@ export class Chat extends EventEmitter{
230
253
  };
231
254
  }
232
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
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
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=>{
@@ -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};
@@ -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:{})};
@@ -9,7 +9,7 @@
9
9
  * ${VAR} and ${VAR:-default} expand from this terminal's environment. Expanded env and header values are not written
10
10
  * to the session files: they travel to the engine like Vault secrets (MINI_MCP_ENV), see worker/mcp_local.py.
11
11
  */
12
- import {readFileSync} from 'node:fs';
12
+ import {readFileSync,statSync} from 'node:fs';
13
13
  import {mkdir,readFile,writeFile,rename} from 'node:fs/promises';
14
14
  import {spawn} from 'node:child_process';
15
15
  import path from 'node:path';
@@ -78,9 +78,9 @@ const hasRef=v=>typeof v==='string'&&/\$\{[A-Za-z_]/.test(v);
78
78
  * Values with ${VAR} references in env/headers move to mcpEnv (name -> {VAR: value} or {headers: {...}}).
79
79
  */
80
80
  export function engineServers(root,{env=process.env}={}){
81
- const out={},secret={},skipped=[];
81
+ const out={},secret={},skipped=[],blockedFiles=[];
82
82
  for(const s of listServers(root)){
83
- if(!s.enabled)continue;
83
+ if(!s.enabled){blockedFiles.push(...serverFiles(root,s.spec,env));continue}
84
84
  if(s.problem){skipped.push({name:s.name,reason:s.problem});continue}
85
85
  if(!s.trusted){skipped.push({name:s.name,reason:'defined by the repository and not trusted yet (/mcp trust)'});continue}
86
86
  const spec=s.spec,clean={...(spec.readOnly===true?{readOnly:true}:{})};
@@ -100,7 +100,25 @@ export function engineServers(root,{env=process.env}={}){
100
100
  }
101
101
  out[s.name]=clean;
102
102
  }
103
- return {mcpServers:out,mcpEnv:secret,skipped};
103
+ return {mcpServers:out,mcpEnv:secret,skipped,blockedFiles:[...new Set(blockedFiles)]};
104
+ }
105
+ /**
106
+ * BUG-0530: the program files of a stdio server (its script, not the interpreter on PATH). For a disabled server they
107
+ * become hard-deny paths, so the agent cannot start the server itself through the shell.
108
+ */
109
+ export function serverFiles(root,spec,env=process.env){
110
+ if(!isObj(spec)||spec.url||typeof spec.command!=='string')return [];
111
+ const base=typeof spec.cwd==='string'?path.resolve(root||process.cwd(),expand(spec.cwd,env)):(root||process.cwd());
112
+ const onPath=String(env.PATH||'').split(path.delimiter).filter(Boolean).map(d=>path.resolve(d));
113
+ const out=[];
114
+ for(const raw of [spec.command,...(Array.isArray(spec.args)?spec.args:[])]){
115
+ if(typeof raw!=='string'||!raw||raw.startsWith('-'))continue;
116
+ const p=path.resolve(base,expand(raw,env));
117
+ try{if(!statSync(p).isFile())continue}catch{continue}
118
+ if(onPath.includes(path.dirname(p)))continue;
119
+ out.push(p);
120
+ }
121
+ return out;
104
122
  }
105
123
  export async function trustRepoServers(root){await setTrusted(root,'mcp',repoServers(root))}
106
124
 
@@ -6,6 +6,7 @@ import {spawn,execFile} from 'node:child_process';
6
6
  import {readFile,writeFile,mkdir,rename} from 'node:fs/promises';
7
7
  import path from 'node:path';
8
8
  import {reviewRequest,addDismissal} from '../review.mjs';
9
+ import {hideEngineName} from '../runtime.mjs';
9
10
 
10
11
  export const SEVERITIES=['critical','high','medium','low','info'];
11
12
  const RANK={critical:0,high:1,medium:2,low:3,info:4};
@@ -61,7 +62,7 @@ export function parseReviewArgs(input){
61
62
  const REF=/^(?!-)[A-Za-z0-9._\/~^@{}-]{1,200}$/;
62
63
  export function gitRunner(root,execImpl=execFile){
63
64
  return (args,{allowFail=false}={})=>new Promise((resolve,reject)=>execImpl('git',args,{cwd:root,maxBuffer:8<<20,windowsHide:true},(e,stdout,stderr)=>{
64
- if(e&&!allowFail)reject(Object.assign(new Error(String(stderr||e.message).trim().split('\n').slice(-1)[0]||'git failed'),{code:e.code}));
65
+ if(e&&!allowFail)reject(Object.assign(new Error(gitReason(stderr||e.message)),{code:e.code}));
65
66
  else resolve(e?null:String(stdout).trim())}));
66
67
  }
67
68
  /** origin's default branch, else main or master (remote first). */
@@ -75,6 +76,12 @@ export async function defaultBase(git){
75
76
  * The reviewer's scope for a parsed target: {scope, base, head, title, body, label} or {empty:true, label}.
76
77
  * gh (optional): (args) => stdout|null, for a pull request's base branch and title.
77
78
  */
79
+ /** The line of a git error that says what went wrong ("fatal: ..."), not the trailing advice. */
80
+ export function gitReason(msg){
81
+ const lines=String(msg||'').split('\n').map(l=>l.trim()).filter(Boolean);
82
+ const fatal=lines.find(l=>/^(fatal|error):/i.test(l));
83
+ return (fatal||lines[0]||'git failed').replace(/^(fatal|error):\s*/i,'');
84
+ }
78
85
  export async function resolveTarget(o,{git,gh=async()=>null}){
79
86
  if(o.target==='repo')return {scope:'repo',label:'the whole repository'};
80
87
  if(await git(['rev-parse','--is-inside-work-tree'],{allowFail:true})!=='true')throw new ReviewUsage('This folder is not a git repository. Use /review repo to scan every file.');
@@ -83,8 +90,10 @@ export async function resolveTarget(o,{git,gh=async()=>null}){
83
90
  const n=o.pr;let info=null;
84
91
  try{info=JSON.parse(await gh(['pr','view',String(n),'--json','baseRefName,title,body'])||'null')}catch{info=null}
85
92
  const head='refs/mlai/pr/'+n;
93
+ // BUG-0512: say plainly when there is no origin remote, and show git's first error line, not its last.
94
+ if(await git(['remote','get-url','origin'],{allowFail:true})===null)throw new ReviewUsage('This repository has no remote named origin, so pull request #'+n+' cannot be fetched. Add one with: git remote add origin <url>');
86
95
  try{await git(['fetch','-q','--no-tags','origin','+refs/pull/'+n+'/head:'+head])}
87
- catch(e){throw new ReviewUsage('Could not fetch pull request #'+n+' from origin: '+e.message)}
96
+ catch(e){throw new ReviewUsage('Could not fetch pull request #'+n+' from origin: '+gitReason(e.message))}
88
97
  let base=o.base;
89
98
  if(!base&&info?.baseRefName&&REF.test(info.baseRefName)){
90
99
  const ref='refs/mlai/pr/'+n+'-base';
@@ -174,7 +183,9 @@ export function countsLine(s){
174
183
  export function renderReview(s,{label='',failOn='high',c=plain}={}){
175
184
  const lines=[];
176
185
  const kind=s.mode==='security'?'Security scan':s.mode==='deep'?'Deep review':'Review';
177
- lines.push(c.bold(kind+(label?' of '+label:''))+': '+countsLine(s));
186
+ // BUG-0494: a review that crashed or stopped never says "No issues found".
187
+ const head=s.state==='done'||s.findings.length?countsLine(s):s.state==='stopped'?c.yellow('stopped before it finished'):c.red('the review failed, nothing was checked');
188
+ lines.push(c.bold(kind+(label?' of '+label:''))+': '+head);
178
189
  if(s.findings.length)lines.push('',...s.findings.map((f,i)=>renderFinding(f,i+1,c)));
179
190
  if(s.resolved.length)lines.push('',c.dim(s.resolved.length+' earlier finding'+(s.resolved.length===1?' is':'s are')+' resolved.'));
180
191
  if(s.summary)lines.push('',oneLine(s.summary).slice(0,1200));
@@ -230,7 +241,7 @@ export async function runReview({root,dir,target,mode='standard',focus='',model=
230
241
  const state=foldReview(text,id);
231
242
  if(stopped){state.state='stopped'}
232
243
  else if(code===-1){state.state='error';state.error='The review could not start on this computer. Run mlai doctor --fix.'}
233
- else if(state.state==='running'){state.state='error';state.error='The reviewer stopped without a result.'+(err.trim()?' '+err.trim().split('\n').slice(-1)[0].slice(0,200):'')}
244
+ else if(state.state==='running'){state.state='error';state.error='The reviewer stopped without a result.'+(err.trim()?' '+hideEngineName(err.trim().split('\n').slice(-1)[0].slice(0,200)):'')}
234
245
  close(stopped?'stopped':state.state==='done'?'done':'error');
235
246
  return {state,target,id};
236
247
  }