mlai-code 0.3.8 → 0.3.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/bin/mlai.mjs +4 -1
- package/package.json +1 -1
- package/src/cli.mjs +67 -12
- package/src/headless.mjs +59 -9
- package/src/home.mjs +1 -1
- package/src/modes.mjs +5 -1
- package/src/render.mjs +4 -0
- package/src/session.mjs +15 -1
- package/src/tui/agents-cli.mjs +2 -0
- package/src/tui/app.mjs +1 -0
- package/src/tui/chat.mjs +7 -3
- package/src/tui/cmd-core.mjs +1 -1
- package/src/tui/extensions-local.mjs +5 -2
- package/src/tui/plain.mjs +16 -0
- package/src/tui/review-cli.mjs +2 -1
- package/src/tui/snapshots.mjs +30 -1
- package/src/tui/transcript.mjs +15 -1
- package/src/two-words.mjs +9 -0
- package/vendor/cloud-cli/mlai.mjs +41 -10
- package/worker/browser_tool.py +42 -4
- package/worker/checkpoints.py +23 -3
- package/worker/command_safety.py +18 -0
- package/worker/conversation.py +18 -1
- package/worker/design_director.py +2 -1
- package/worker/kimi_bridge.py +201 -47
- package/worker/kimi_gates.py +19 -2
- package/worker/kimi_hook.py +53 -10
- package/worker/mcp_local.py +33 -0
- package/worker/mlai_auto_review.py +25 -4
- package/worker/mlai_hooks.py +113 -7
- package/worker/mlai_mcp.py +16 -1
- package/worker/mlai_permissions.py +5 -3
- package/worker/mlai_review/__main__.py +3 -1
- package/worker/mlai_review/application/streaming.py +10 -0
- package/worker/mlai_review/infrastructure/local/publisher.py +25 -3
- package/worker/preview.py +399 -29
- package/worker/proc_watch.py +388 -50
- package/worker/runner.py +72 -1
- package/worker/verification.py +69 -3
package/README.md
CHANGED
package/bin/mlai.mjs
CHANGED
|
@@ -1,3 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import {main} from '../src/cli.mjs';
|
|
3
|
-
|
|
3
|
+
// BUG-0663: output to a pipe is written asynchronously; exit only once stdout and stderr have taken all of it.
|
|
4
|
+
const drained=s=>new Promise(r=>{if(!s.writable||s.destroyed)return r();s.write('',()=>r())});
|
|
5
|
+
const exit=code=>Promise.race([Promise.all([drained(process.stdout),drained(process.stderr)]),new Promise(r=>setTimeout(r,10000).unref())]).then(()=>process.exit(code));
|
|
6
|
+
main().then(exit,e=>{process.stderr.write(String(e?.stack||e)+'\n');return exit(1)});
|
package/package.json
CHANGED
package/src/cli.mjs
CHANGED
|
@@ -5,18 +5,19 @@ import {existsSync,statSync,readFileSync,fstatSync} from 'node:fs';
|
|
|
5
5
|
import {readFile} from 'node:fs/promises';
|
|
6
6
|
import os from 'node:os';
|
|
7
7
|
import path from 'node:path';
|
|
8
|
+
import zlib from 'node:zlib';
|
|
8
9
|
import {fileURLToPath} from 'node:url';
|
|
9
10
|
import {VERSION,DEFAULT_SERVER,home} from './home.mjs';
|
|
10
11
|
import {activeEngine} from './engine.mjs';
|
|
11
12
|
import {saveLogin,loadLogin,clearLogin} from './credentials.mjs';
|
|
12
13
|
import {Client,ClientError,deviceLogin} from './sdk.mjs';
|
|
13
14
|
import {Cloud,friendly} from './cloud.mjs';
|
|
14
|
-
import {Session,sandboxKind} from './session.mjs';
|
|
15
|
+
import {Session,sandboxKind,stopPreviews} from './session.mjs';
|
|
15
16
|
import {MODES as CLI_MODES,modeName,nextMode,engineMode,sessionMode} from './modes.mjs';
|
|
16
17
|
import {loadSettings} from './settings.mjs';
|
|
17
18
|
import * as registry from './tui/commands.mjs';
|
|
18
19
|
import {Chat,answerOf,modelList} from './tui/chat.mjs';
|
|
19
|
-
import {plainUi,trackWrappedInput,printAbove} from './tui/plain.mjs';
|
|
20
|
+
import {plainUi,trackWrappedInput,printAbove,pasteBurst} from './tui/plain.mjs';
|
|
20
21
|
import {projectRoot} from './project.mjs';
|
|
21
22
|
import {createWorktree} from './worktree.mjs';
|
|
22
23
|
import {EXT_FLAGS,EXT_COMMANDS,extFlag} from './cli-ext.mjs';
|
|
@@ -27,7 +28,7 @@ import {gitForWindows} from './winenv.mjs';
|
|
|
27
28
|
import {ensureRuntime,runtimeInfo,PY_VERSION,hideEngineName} from './runtime.mjs';
|
|
28
29
|
import {palette,colorAllowed,renderEvent,approvalView,summaryLine,exitCode,EXIT,fmt,credits,prose} from './render.mjs';
|
|
29
30
|
import {answerRest} from './tui/transcript.mjs';
|
|
30
|
-
import {runHeadless,streamInputs,stdinLines,toolRules,loadSchema,HeadlessError} from './headless.mjs';
|
|
31
|
+
import {runHeadless,streamInputs,stdinLines,toolRules,loadSchema,HeadlessError,pipedTask,schemaReserve} from './headless.mjs';
|
|
31
32
|
import {terminals,backgroundCommand} from './tui/bgterm.mjs';
|
|
32
33
|
|
|
33
34
|
/** Every option, for --help and shell completion (src/completion.mjs). value: the placeholder when it takes one. */
|
|
@@ -134,7 +135,32 @@ Sign out on this device and remove the stored credential.`,
|
|
|
134
135
|
whoami:`Usage: mlai whoami [--json]
|
|
135
136
|
|
|
136
137
|
Show the account and device this computer is signed in as.`,
|
|
138
|
+
// BUG-0670
|
|
139
|
+
serve:`Usage: mlai serve
|
|
140
|
+
|
|
141
|
+
Run the local engine for the Mac app and editors. It listens on a socket only you can open
|
|
142
|
+
and keeps running until Ctrl-C.
|
|
143
|
+
MLAI_SOCKET=<path> Listen on this socket instead of the default one`,
|
|
144
|
+
runner:`Usage: mlai runner
|
|
145
|
+
|
|
146
|
+
Run this computer as a remote machine for your account. Tasks you send to it from the web app
|
|
147
|
+
run here, under MLAI_WORK_ROOT. Keeps running until Ctrl-C.
|
|
148
|
+
MLAI_RUNNER_TOKEN=<token> The runner token from Settings, Machines (required)
|
|
149
|
+
MLAI_WORK_ROOT=<folder> Where the task folders go (default ~/mlai-work)
|
|
150
|
+
MLAI_RUNNER_LABEL=<name> The name shown for this machine (default the computer name)
|
|
151
|
+
MLAI_SERVER=<url> ML AI Code server`,
|
|
152
|
+
'remote-control':`Usage: mlai remote-control [task] [options]
|
|
153
|
+
|
|
154
|
+
Start a session in this terminal that you can also drive from the web app and your phone:
|
|
155
|
+
send messages, approve, stop and steer from there while the work stays here.
|
|
156
|
+
Takes the same options as mlai (see mlai --help); the same as mlai --rc.`,
|
|
157
|
+
attach:`Usage: mlai attach <id>
|
|
158
|
+
|
|
159
|
+
Follow a running session (a background agent or one in another terminal): type to steer it,
|
|
160
|
+
y / a / n answer approvals, /stop stops it, Ctrl-C detaches and it keeps working.
|
|
161
|
+
mlai agents lists the sessions and their ids.`,
|
|
137
162
|
};
|
|
163
|
+
export {SUB_HELP};
|
|
138
164
|
const LEGACY_MODES={guided:'agent'};
|
|
139
165
|
export function parseArgs(argv){
|
|
140
166
|
const o={_:[],mode:null,json:false,yes:false,sandbox:true,steps:120,verbose:false,server:null,print:null,fix:false,worktree:false,
|
|
@@ -151,7 +177,8 @@ export function parseArgs(argv){
|
|
|
151
177
|
if(a==='--')o._.push(...argv.slice(i+1)),i=argv.length;
|
|
152
178
|
else if(a==='-p'||a==='--print')o.print=inline!==null?inline:optional(i)?argv[++i]:'-';
|
|
153
179
|
else if(a==='--mode')o.mode=mode(next());
|
|
154
|
-
|
|
180
|
+
// BUG-0662: the name /model shows (with spaces) is accepted as well as the id.
|
|
181
|
+
else if(a==='--model'||a==='-m'){const v=next().trim();if(!/^[\w.:/-][\w.:/ -]{0,79}$/.test(v))throw new UsageError('Unknown model '+v+'. Run /model in a session to see the list.');o.model=v}
|
|
155
182
|
else if(a==='--effort'){const v=next();if(!['low','medium','high','max'].includes(v))throw new UsageError('--effort must be low, medium, high or max');o.effort=v}
|
|
156
183
|
else if(a==='--fallback-model'){const v=next().split(',').map(x=>x.trim()).filter(Boolean);if(!v.length||v.length>5||!v.every(x=>/^[\w.:/-]{1,80}$/.test(x)))throw new UsageError('--fallback-model takes up to 5 model ids, comma separated');o.fallbackModel=v}
|
|
157
184
|
else if(a==='--input-format'){const v=next();if(!['text','stream-json'].includes(v))throw new UsageError('--input-format must be text or stream-json');o.inputFormat=v}
|
|
@@ -298,6 +325,8 @@ export async function main(argv=process.argv.slice(2)){
|
|
|
298
325
|
// `mlai resume [id] [task]` is the older spelling of -r; without an id it continues the latest session here.
|
|
299
326
|
if(cmd==='resume'){const id=o._.shift();if(id)o.resume=id;else o.continue=true}
|
|
300
327
|
if(cmd==='remote-control')o.rc=true; // `mlai remote-control [task]`: an interactive session shared with the web and phone
|
|
328
|
+
// BUG-0691: the engine knows this session is shown only in a terminal (no slide or document viewer).
|
|
329
|
+
if(!o.rc)process.env.MINI_TERMINAL='1';
|
|
301
330
|
const streamIn=o.inputFormat==='stream-json';
|
|
302
331
|
let task=o.print!==null?(o.print==='-'?(streamIn?null:await readStdin()):o.print):o._.join(' ').trim()||null;
|
|
303
332
|
if(o.cloud)return await cloudRun(o,c,err,task);
|
|
@@ -305,7 +334,7 @@ export async function main(argv=process.argv.slice(2)){
|
|
|
305
334
|
const headlessRun=o.print!==null||!process.stdin.isTTY||streamIn;
|
|
306
335
|
if(o.teleport!==null){const s=await teleportRun(o,err,{interactive:!headlessRun});if(!s)return EXIT.usage;if(headlessRun&&task?.trim())return await headless(o,c,err,task.trim(),s);if(headlessRun){process.stdout.write(s.meta.id+'\n');return 0}return await interactive(o,c,s,task)}
|
|
307
336
|
if(headlessRun&&!streamIn&&!task&&!process.stdin.isTTY&&o.print===null)task=await readStdin();
|
|
308
|
-
else if(headlessRun&&!streamIn&&task?.trim()&&o.print!=='-'&&!process.stdin.isTTY){const piped=(await pipedInput()).trim();if(piped)task=task.
|
|
337
|
+
else if(headlessRun&&!streamIn&&task?.trim()&&o.print!=='-'&&!process.stdin.isTTY){const piped=(await pipedInput()).trim();if(piped)task=pipedTask(task,piped,{reserve:o.jsonSchema?schemaReserve(o.jsonSchema):0})}
|
|
309
338
|
if(headlessRun&&!streamIn&&!task?.trim())throw new UsageError('Give a task: mlai -p "what to do"');
|
|
310
339
|
if(headlessRun&&o.rc)throw new UsageError('Remote control needs an interactive terminal. Run mlai --rc in a terminal, or use --bg for unattended work.');
|
|
311
340
|
// Restricted mode (src/restricted.mjs): the flag, or forced by the administrator for everyone on this computer.
|
|
@@ -396,9 +425,11 @@ async function sessions(o,c){
|
|
|
396
425
|
export function nodeCheck(version){
|
|
397
426
|
const [a,b]=String(version).replace(/^v/,'').split('.').map(Number);
|
|
398
427
|
if(!(a>=20))return {ok:false,detail:version+' (20 or newer needed)'};
|
|
399
|
-
if(a<22||(a===22&&b<19))return {ok:false,warn:true,detail:version+' (22.19 or newer
|
|
428
|
+
if(a<22||(a===22&&b<19))return {ok:false,warn:true,detail:version+' (the coding engine needs 22.19 or newer; until then runs use the built-in engine. Update Node.js from https://nodejs.org)'};
|
|
400
429
|
return {ok:true,detail:version};
|
|
401
430
|
}
|
|
431
|
+
/** Whether this Node.js has the zlib zstd API the coding engine imports (worker/kimi_bridge.py node_too_old). */
|
|
432
|
+
export const zstdNode=(z=zlib)=>typeof z.createZstdDecompress==='function';
|
|
402
433
|
async function doctor(o,c){
|
|
403
434
|
const rows=[];const add=(ok,label,detail,extra)=>rows.push({ok,label,detail,...extra});
|
|
404
435
|
{const n=nodeCheck(process.versions.node);add(n.ok,'Node.js',n.detail,n.warn?{warn:true}:undefined)}
|
|
@@ -414,6 +445,8 @@ async function doctor(o,c){
|
|
|
414
445
|
try{const h=await activeEngine();add(true,'Coding harness',h.source==='updated'?'updated '+h.version.slice(0,8):h.source==='custom'?'MLAI_WORKER_DIR='+h.dir:'bundled '+h.version.slice(0,8))}catch(e){add(false,'Coding harness',e.message)}
|
|
415
446
|
const rt=await runtimeInfo();
|
|
416
447
|
if(process.env.MLAI_PYTHON)add(existsSync(process.env.MLAI_PYTHON),'Coding engine','MLAI_PYTHON='+process.env.MLAI_PYTHON);
|
|
448
|
+
// BUG-0717: the engine needs Node's zstd support (22.15+, 22.19+ asked for); without it every run uses the built-in engine.
|
|
449
|
+
else if(rt.ready&&!zstdNode())add(false,'Coding engine','ready, but runs use the built-in engine until Node.js is 22.19 or newer (update from https://nodejs.org)',{warn:true});
|
|
417
450
|
else if(rt.ready)add(true,'Coding engine','ready (ML AI Code engine '+VERSION+', Python '+PY_VERSION+')');
|
|
418
451
|
else if(o.fix){try{await ensureRuntime({onProgress:m=>process.stdout.write(c.dim(m+'...')+'\n')});add(true,'Coding engine','installed')}catch(e){add(false,'Coding engine',hideEngineName(e.message))}}
|
|
419
452
|
else add(false,'Coding engine','not installed yet; it installs on first run, or run mlai doctor --fix'+(rt.uv?' (uv found)':rt.python3?' (python3 found)':' (needs uv or python3)'));
|
|
@@ -508,6 +541,8 @@ async function newSession(o,task,err,root){
|
|
|
508
541
|
return s;
|
|
509
542
|
}
|
|
510
543
|
export const GO_AHEAD=/^\W*(?:(?:ok(?:ay)?|yes|yep|sure|great|perfect|looks good|lgtm|sounds good)\b[\s,.!]*)*(?:please\s+)?(?:go ahead|do it|build it|proceed|implement (?:it|this|that|the plan)|carry (?:it|this|the plan) out|make (?:the|those|these) changes?|write (?:it|the file))\b/i;
|
|
544
|
+
/** A message that asks for a change ("Fix it.", "Now add a test"): read-only ask mode cannot do it (BUG-0690). */
|
|
545
|
+
export const CHANGE_REQUEST=/^\W*(?:(?:ok(?:ay)?|yes|now|then|so|great|thanks)\b[\s,.!]*)*(?:please\s+)?(?:(?:can|could|would)\s+you\s+)?(?:fix|change|edit|update|apply|implement|add|remove|delete|rename|refactor|create|write)\b/i;
|
|
511
546
|
async function headless(o,c,err,task,s){
|
|
512
547
|
const cloud=await cloudFor(o);
|
|
513
548
|
const settings=settingsFor(o,s,err),chat=new Chat({session:s,settings,cloud,flags:chatFlags(o,settings)});
|
|
@@ -522,8 +557,14 @@ async function headless(o,c,err,task,s){
|
|
|
522
557
|
if(o.json)process.stdout.write(JSON.stringify({type:'result',subtype:'error_plan_mode',state:'limited',exitCode:EXIT.limited,sessionId:s.meta.id,mode:'plan',error:msg})+'\n');else process.stderr.write(err.yellow(msg)+'\n');
|
|
523
558
|
return EXIT.limited;
|
|
524
559
|
}
|
|
560
|
+
// BUG-0690: "Fix it." on a session left in ask mode only answered again (ask mode never edits) and ended as a success.
|
|
561
|
+
if(!o.mode&&chat.mode==='ask'&&(o.continue||o.resume!==null)&&(GO_AHEAD.test(String(task||''))||CHANGE_REQUEST.test(String(task||'')))){
|
|
562
|
+
const msg='This session is in ask mode, which only answers questions and never changes files. To make the change, run: mlai -c --mode agent -p "'+String(task).trim().slice(0,80).replace(/"/g,"'")+'"';
|
|
563
|
+
if(o.json)process.stdout.write(JSON.stringify({type:'result',subtype:'error_ask_mode',state:'limited',exitCode:EXIT.limited,sessionId:s.meta.id,mode:'ask',error:msg})+'\n');else process.stderr.write(err.yellow(msg)+'\n');
|
|
564
|
+
return EXIT.limited;
|
|
565
|
+
}
|
|
525
566
|
const inputs=o.inputFormat==='stream-json'?streamInputs(stdinLines()):[{text:task,files:o.images||[]}];
|
|
526
|
-
|
|
567
|
+
let code;try{code=await runHeadless(o,{s,chat,err,inputs})}finally{stopPreviews()}
|
|
527
568
|
// mlai --bg: record how the background run ended (tui/bg.mjs).
|
|
528
569
|
if(o.bgChild){const st=await readFile(path.join(s.dir,'status.json'),'utf8').then(JSON.parse).catch(()=>({}));await (await import('./tui/bg.mjs')).finishBackground(s.dir,{state:code===0?'completed':st.state&&!['running','starting'].includes(st.state)?st.state:'failed',exitCode:code}).catch(()=>{})}
|
|
529
570
|
return code;
|
|
@@ -546,7 +587,7 @@ function remoteOn(o,chat,ctx){
|
|
|
546
587
|
return ctx;
|
|
547
588
|
}
|
|
548
589
|
async function withRemote(chat,fn){
|
|
549
|
-
try{return await fn()}finally{if(chat.remote)await chat.remote.stop().catch(()=>{})}
|
|
590
|
+
try{return await fn()}finally{if(chat.remote)await chat.remote.stop().catch(()=>{});stopPreviews()}
|
|
550
591
|
}
|
|
551
592
|
|
|
552
593
|
/** The line-based session (no full-screen TUI): readline, slash commands from the registry, approvals, steering. */
|
|
@@ -569,7 +610,8 @@ async function plainLoop(o,c,chat,first){
|
|
|
569
610
|
ctx=remoteOn(o,chat,chat.ctx({...ui,setMode:()=>prompt(),setSession:()=>{},dismissApproval:id=>{if(pending?.id===id){pending=null;prompt()}}}));
|
|
570
611
|
const onEvent=e=>{
|
|
571
612
|
if(e.type==='approval'){
|
|
572
|
-
|
|
613
|
+
// BUG-0692: --yes does not answer the user's own ask rules (permissions.ask): those still ask.
|
|
614
|
+
if(o.yes&&!e.userRule){chat.session.decide(e.id,'approve_all').catch(()=>{});return}
|
|
573
615
|
pending=e;out(approvalView(e,c).text);prompt();return;
|
|
574
616
|
}
|
|
575
617
|
// The final answer repeats the agent's last reply; print only what it adds (a source list, a verification note).
|
|
@@ -627,10 +669,21 @@ async function plainLoop(o,c,chat,first){
|
|
|
627
669
|
if(bracketed)process.stdout.write('\x1b[?2004h');
|
|
628
670
|
process.stdin.on('keypress',(_s,k)=>{
|
|
629
671
|
if(k?.name==='paste-start')pasting=true;
|
|
630
|
-
else if(k?.name==='paste-end'){pasting=false;if(pasted.length)
|
|
672
|
+
else if(k?.name==='paste-end'){pasting=false;if(pasted.length)pasteNote()}
|
|
631
673
|
});
|
|
632
|
-
|
|
674
|
+
const pasteNote=()=>out(c.dim('(pasted '+pasted.length+' line'+(pasted.length===1?'':'s')+'; type your message and press Enter to send it all)'));
|
|
675
|
+
// BUG-0612: a terminal that does not mark pastes sends the pasted lines in one burst. Lines that arrive together are
|
|
676
|
+
// held the same way: sent as one message when the burst ends with Enter, else with the line the user then finishes.
|
|
677
|
+
const burst=pasteBurst();
|
|
678
|
+
process.stdin.prependListener('data',burst.data);
|
|
679
|
+
let burstTimer=null;
|
|
680
|
+
const onLine=async raw=>{
|
|
633
681
|
if(question){const q=question;question=null;q.resolve(raw);return}
|
|
682
|
+
if(!pending&&!pasting&&burst.now()){
|
|
683
|
+
pasted.push(raw);clearTimeout(burstTimer);
|
|
684
|
+
burstTimer=setTimeout(()=>{if(burst.now())return burstTimer.refresh();if(!pasted.length)return;if(rl.line){pasteNote();prompt();return}const all=pasted.join('\n');pasted=[];onLine(all)},40);
|
|
685
|
+
return;
|
|
686
|
+
}
|
|
634
687
|
if(!pending&&(pasting||pasted.length)){if(pasting){pasted.push(raw);return}raw=pasted.join('\n')+'\n'+raw;pasted=[]}
|
|
635
688
|
const line=raw.trim();
|
|
636
689
|
if(pending){
|
|
@@ -653,13 +706,15 @@ async function plainLoop(o,c,chat,first){
|
|
|
653
706
|
}
|
|
654
707
|
if(chat.running){await chat.session.steer(line);out(c.dim('Sent to the agent.'));prompt();return}
|
|
655
708
|
await run(input);
|
|
656
|
-
}
|
|
709
|
+
};
|
|
710
|
+
rl.on('line',onLine);
|
|
657
711
|
const closed=new Promise(r=>rl.on('close',r));
|
|
658
712
|
// BUG-0516: closing the terminal window (SIGHUP) or SIGTERM ends the engine too, even while an approval is waiting.
|
|
659
713
|
let hungUp=false;const onHangup=()=>{hungUp=true;rl.close()};process.once('SIGHUP',onHangup);process.once('SIGTERM',onHangup);
|
|
660
714
|
if(first)run(first);else prompt();
|
|
661
715
|
await closed;
|
|
662
716
|
if(bracketed)process.stdout.write('\x1b[?2004l');
|
|
717
|
+
process.stdin.off('data',burst.data);clearTimeout(burstTimer);
|
|
663
718
|
terminals.off('exit',onJobExit);
|
|
664
719
|
process.off('SIGHUP',onHangup);process.off('SIGTERM',onHangup);
|
|
665
720
|
if(chat.running||chat.session.child)await chat.session.stopNow(2500,{code:hungUp?'terminal_closed':null}).catch(()=>{});
|
package/src/headless.mjs
CHANGED
|
@@ -2,17 +2,19 @@
|
|
|
2
2
|
* mlai -p: one task, or a stream of them (--input-format stream-json), with no prompts. Shared by cli.mjs.
|
|
3
3
|
* --output-format text | json | stream-json (stream-json: the session line, every agent event, then a result per turn)
|
|
4
4
|
* --json-schema the final answer must be JSON matching the schema; one correction turn, then error_schema
|
|
5
|
-
* --max-turns caps agent steps; a run stopped by it ends with subtype error_max_turns
|
|
5
|
+
* --max-turns caps agent steps; a run stopped by it (or by --max-steps) ends with subtype error_max_turns, exit 3
|
|
6
6
|
* --max-budget-credits the server caps the run's tokens (run.maxTokens); the next turn never starts past it
|
|
7
7
|
* --fallback-model Chat.send switches model when the chosen one is overloaded or unavailable
|
|
8
8
|
* --allowedTools / --disallowedTools / --tools permission rules (worker/mlai_permissions.py syntax)
|
|
9
9
|
* Result subtypes: success, error_during_execution, error_max_turns, error_max_budget, error_schema, error_needs_approval,
|
|
10
|
-
* error_cannot_complete (exit 6: the agent reported the request cannot be done), stopped.
|
|
10
|
+
* error_cannot_complete (exit 6: the agent reported the request cannot be done), stopped. Before a run starts, cli.mjs may
|
|
11
|
+
* end it with error_plan_mode or error_ask_mode (exit 3: the session's read-only mode cannot make the change).
|
|
11
12
|
*/
|
|
12
13
|
import {readFileSync,existsSync} from 'node:fs';
|
|
13
14
|
import {readFile,rm} from 'node:fs/promises';
|
|
14
15
|
import {normalizeRule} from './tui/permissions.mjs';
|
|
15
16
|
import {TOKENS_PER_CREDIT,creditsFor,answerOf} from './tui/chat.mjs';
|
|
17
|
+
import {answerRest} from './tui/transcript.mjs';
|
|
16
18
|
import {renderEvent,summaryLine,exitCode,EXIT,prose as proseOf} from './render.mjs';
|
|
17
19
|
|
|
18
20
|
export const TOOL_NAMES=['Bash','Edit','Read','WebFetch','WebSearch','Agent'];
|
|
@@ -43,6 +45,28 @@ export function toolRules(o){
|
|
|
43
45
|
return allow.length||deny.length?{allow,deny}:null;
|
|
44
46
|
}
|
|
45
47
|
|
|
48
|
+
/** BUG-0669: the first mistake in a schema's own keywords (an unknown type, required that is not a list, ...), or ''. */
|
|
49
|
+
const TYPES=new Set(['string','number','integer','boolean','object','array','null']);
|
|
50
|
+
export function schemaIssue(sc,at='$'){
|
|
51
|
+
if(typeof sc==='boolean')return '';
|
|
52
|
+
if(!sc||typeof sc!=='object'||Array.isArray(sc))return at+' should be a schema (an object)';
|
|
53
|
+
const show=v=>JSON.stringify(v);
|
|
54
|
+
if('type' in sc){const t=sc.type,list=Array.isArray(t)?t:[t];
|
|
55
|
+
if(!list.length||!list.every(x=>typeof x==='string'))return at+'.type should be a type name or a list of them';
|
|
56
|
+
const unknown=list.find(x=>!TYPES.has(x));if(unknown!==undefined)return at+'.type '+show(unknown)+' is not a type (use '+[...TYPES].join(', ')+')'}
|
|
57
|
+
if('required' in sc&&!(Array.isArray(sc.required)&&sc.required.every(x=>typeof x==='string')))return at+'.required should be a list of property names';
|
|
58
|
+
if('enum' in sc&&!Array.isArray(sc.enum))return at+'.enum should be a list';
|
|
59
|
+
for(const k of ['minLength','maxLength','minItems','maxItems','minimum','maximum','minProperties','maxProperties','multipleOf'])
|
|
60
|
+
if(k in sc&&(typeof sc[k]!=='number'||!Number.isFinite(sc[k])))return at+'.'+k+' should be a number';
|
|
61
|
+
if('pattern' in sc){if(typeof sc.pattern!=='string')return at+'.pattern should be a string';try{new RegExp(sc.pattern)}catch{return at+'.pattern is not a valid regular expression'}}
|
|
62
|
+
if('properties' in sc){if(!sc.properties||typeof sc.properties!=='object'||Array.isArray(sc.properties))return at+'.properties should be an object';
|
|
63
|
+
for(const [k,v] of Object.entries(sc.properties)){const e=schemaIssue(v,at+'.properties.'+k);if(e)return e}}
|
|
64
|
+
for(const k of ['items','additionalProperties','not']){if(k in sc&&!(k==='items'&&Array.isArray(sc.items))){const e=schemaIssue(sc[k],at+'.'+k);if(e)return e}}
|
|
65
|
+
if(Array.isArray(sc.items))for(const [i,v] of sc.items.entries()){const e=schemaIssue(v,at+'.items['+i+']');if(e)return e}
|
|
66
|
+
for(const k of ['anyOf','oneOf','allOf']){if(!(k in sc))continue;if(!Array.isArray(sc[k])||!sc[k].length)return at+'.'+k+' should be a non-empty list of schemas';
|
|
67
|
+
for(const [i,v] of sc[k].entries()){const e=schemaIssue(v,at+'.'+k+'['+i+']');if(e)return e}}
|
|
68
|
+
return '';
|
|
69
|
+
}
|
|
46
70
|
/** --json-schema: inline JSON, or a file with it. */
|
|
47
71
|
export function loadSchema(v){
|
|
48
72
|
let text=String(v).trim();
|
|
@@ -50,6 +74,7 @@ export function loadSchema(v){
|
|
|
50
74
|
let schema;try{schema=JSON.parse(text)}catch{throw new HeadlessError('--json-schema is not valid JSON')}
|
|
51
75
|
if(!schema||typeof schema!=='object'||Array.isArray(schema))throw new HeadlessError('--json-schema must be a JSON object');
|
|
52
76
|
if(JSON.stringify(schema).length>20000)throw new HeadlessError('--json-schema is too large (20 KB at most)');
|
|
77
|
+
const bad=schemaIssue(schema);if(bad)throw new HeadlessError('--json-schema is not a valid JSON Schema: '+bad);
|
|
53
78
|
return schema;
|
|
54
79
|
}
|
|
55
80
|
const typeOf=v=>v===null?'null':Array.isArray(v)?'array':Number.isInteger(v)?'integer':typeof v;
|
|
@@ -90,6 +115,23 @@ export function extractJson(text){
|
|
|
90
115
|
for(const x of tries){if(x==null)continue;try{return {ok:true,value:JSON.parse(x)}}catch{}}
|
|
91
116
|
return {ok:false};
|
|
92
117
|
}
|
|
118
|
+
/**
|
|
119
|
+
* BUG-0664: piped text goes with the task (cat app.log | mlai -p "explain"). A task is at most TASK_MAX characters, so
|
|
120
|
+
* piped text that would not fit is cut in the middle (the start and, mostly, the end are kept) with a note saying so.
|
|
121
|
+
*/
|
|
122
|
+
export const TASK_MAX=30000;
|
|
123
|
+
export function pipedTask(task,piped,{reserve=0,max=TASK_MAX}={}){
|
|
124
|
+
const head=String(task).trim()+'\n\nInput piped to mlai:\n```\n',tail='\n```';
|
|
125
|
+
const room=max-reserve-head.length-tail.length-100;
|
|
126
|
+
if(piped.length<=room)return head+piped+tail;
|
|
127
|
+
const note=n=>'\n[... '+n.toLocaleString('en-US')+' characters cut from the middle; the piped input was '+piped.length.toLocaleString('en-US')+' characters]\n';
|
|
128
|
+
const keep=Math.max(0,room-note(piped.length).length);
|
|
129
|
+
if(keep<200)return head+note(piped.length).trim()+tail;
|
|
130
|
+
const first=Math.min(2000,Math.floor(keep/4)),last=keep-first;
|
|
131
|
+
return head+piped.slice(0,first)+note(piped.length-first-last)+piped.slice(piped.length-last)+tail;
|
|
132
|
+
}
|
|
133
|
+
/** Room the --json-schema instruction takes in the task. */
|
|
134
|
+
export function schemaReserve(o){try{return schemaTask(loadSchema(o)).length}catch{return 0}}
|
|
93
135
|
const schemaTask=schema=>'\n\nWhen you finish, reply with only a JSON value (no prose, no code fence) that matches this JSON Schema:\n'+JSON.stringify(schema);
|
|
94
136
|
|
|
95
137
|
/** Credits to the run's token cap, counted the way /usage counts them (TOKENS_PER_CREDIT). */
|
|
@@ -129,7 +171,7 @@ export async function runHeadless(o,{s,chat,err,inputs,out=t=>process.stdout.wri
|
|
|
129
171
|
// BUG-0492: --max-turns is an exact cap for the whole run (hardSteps), not the engine's usual minimum of 10.
|
|
130
172
|
if(o.maxTurns){chat.steps=Math.min(chat.steps,o.maxTurns);chat.hardSteps=true}
|
|
131
173
|
chat.unattended=true; // BUG-0519: nobody can answer a -p run, so a sandbox-blocked write ends it instead of looping
|
|
132
|
-
let events=[],refused=0,spent=0,turns=0,code=EXIT.completed,last=null;
|
|
174
|
+
let events=[],refused=0,ruleRefused=0,spent=0,turns=0,code=EXIT.completed,last=null;
|
|
133
175
|
// BUG-0557: the engine must not promise an automatic continue that a one-shot process will never run.
|
|
134
176
|
const oneShot=process.env.MINI_ONE_SHOT;process.env.MINI_ONE_SHOT='1';
|
|
135
177
|
// BUG-0561: the agent's last message is also the final answer on stdout; held back so a terminal shows it once.
|
|
@@ -146,7 +188,9 @@ export async function runHeadless(o,{s,chat,err,inputs,out=t=>process.stdout.wri
|
|
|
146
188
|
for(const p of shown){const raw=String(p||'').trim();if(!raw)continue;
|
|
147
189
|
if(String(text).replace(/\s+/g,' ').trim()===raw.replace(/\s+/g,' ').trim())return '';
|
|
148
190
|
if(raw.length>40&&String(text).includes(raw))return String(text).replace(raw,'').trim()}
|
|
149
|
-
|
|
191
|
+
// BUG-0613: compared as prose too (the answer can carry the finish command, or a short reply plus a note).
|
|
192
|
+
const p=proseOf(text),rest=answerRest(shown,p);
|
|
193
|
+
return rest===p?text:rest};
|
|
150
194
|
// Round 5: SIGHUP (the terminal closed) stops the run too; it used to end the CLI at once, leaving the engine running
|
|
151
195
|
// and the run open on the server. stdout may be gone after a hangup: a failed write must not end the CLI before the run closes.
|
|
152
196
|
const quiet=()=>{};
|
|
@@ -157,7 +201,9 @@ export async function runHeadless(o,{s,chat,err,inputs,out=t=>process.stdout.wri
|
|
|
157
201
|
if(stream)write(e);
|
|
158
202
|
else if(!json){const line=renderEvent(e,{c:err,verbose:o.verbose});if(line&&e.type!=='answer'){if(prose!=null&&CLOSING.has(e.type))after.push(line);else{flushProse();if(e.type==='assistant'){prose=line;proseRaw=e.content}else log(line+'\n')}}}
|
|
159
203
|
if(e.type==='approval'){
|
|
160
|
-
|
|
204
|
+
// BUG-0692: --yes does not answer the user's own ask rules (permissions.ask); a person has to.
|
|
205
|
+
if(o.yes&&e.userRule&&!o.bgChild){ruleRefused++;s.decide(e.id,'reject').catch(()=>{});if(!json&&!stream)log(err.yellow('Not run: your permission rule "'+String(e.rule||'').slice(0,80)+'" asks first, and --yes does not answer it.')+'\n')}
|
|
206
|
+
else if(o.yes&&!e.userRule)s.decide(e.id,'approve_all').catch(()=>{});
|
|
161
207
|
else if(o.bgChild){} // a background run (mlai --bg) waits for mlai attach to answer
|
|
162
208
|
else{refused++;s.decide(e.id,'reject').catch(()=>{});if(!json&&!stream)log(err.yellow('Rejected (no one to approve): pass --yes, or use --mode auto in a sandbox.')+'\n')}
|
|
163
209
|
}
|
|
@@ -173,7 +219,7 @@ export async function runHeadless(o,{s,chat,err,inputs,out=t=>process.stdout.wri
|
|
|
173
219
|
};
|
|
174
220
|
try{
|
|
175
221
|
for await(const input of inputs){
|
|
176
|
-
events=[];const turnRefused=refused;
|
|
222
|
+
events=[];const turnRefused=refused,turnRuled=ruleRefused;
|
|
177
223
|
const images=[];
|
|
178
224
|
for(const b of input.images||[])images.push(await s.addImage(b));
|
|
179
225
|
for(const f of input.files||[])images.push(await s.addImage(await readFile(f)));
|
|
@@ -184,7 +230,8 @@ export async function runHeadless(o,{s,chat,err,inputs,out=t=>process.stdout.wri
|
|
|
184
230
|
// BUG-0509: reaching the cap is never a success, even when the agent wrapped up on its own at the limit.
|
|
185
231
|
const budgetHit=cap!=null&&(r.code==='billing_limit'||spent>=cap);
|
|
186
232
|
if(budgetHit){r={...r,code:'budget_limit',error:'Stopped at the --max-budget-credits limit ('+o.maxBudgetCredits+' credits; this run used '+creditsFor(spent)+' because the model step in progress finishes). Changes so far are kept.'};subtype='error_max_budget'}
|
|
187
|
-
|
|
233
|
+
// BUG-0683: a run cut short by --max-steps (or /config maxSteps) is limited the same way.
|
|
234
|
+
else if(r.state==='limited'&&(o.maxTurns||r.code==='step_limit')&&r.result?.limit!=='tokens')subtype='error_max_turns';
|
|
188
235
|
else if(r.state==='stopped')subtype='stopped';
|
|
189
236
|
else if(r.state!=='completed')subtype='error_during_execution';
|
|
190
237
|
else subtype='success';
|
|
@@ -203,13 +250,16 @@ export async function runHeadless(o,{s,chat,err,inputs,out=t=>process.stdout.wri
|
|
|
203
250
|
// BUG-0544: approvals refused because nobody could answer them (-p without --yes): the run needs attention.
|
|
204
251
|
// BUG-0523: the agent decided the request cannot be done (no remote to push to, an unsupported feature): not a success.
|
|
205
252
|
if(subtype==='success'&&r.cannotComplete){subtype='error_cannot_complete';r={...r,error:r.cannotComplete.reason}}
|
|
206
|
-
if(subtype==='success'&&
|
|
253
|
+
if(subtype==='success'&&ruleRefused>turnRuled){const n=ruleRefused-turnRuled;subtype='error_needs_approval';r={...r,error:n+' action'+(n===1?'':'s')+' needed approval under your permission ask rules and did not run (--yes does not answer them). Run it interactively to answer, or change the rule.'}}
|
|
254
|
+
else if(subtype==='success'&&refused>turnRefused){subtype='error_needs_approval';r={...r,error:(refused-turnRefused)+' action'+(refused-turnRefused===1?'':'s')+' needed approval and did not run. Pass --yes (-y) or --allowedTools to allow them.'}}
|
|
207
255
|
const exit=subtype==='error_cannot_complete'?EXIT.cannotComplete:subtype==='error_needs_approval'?EXIT.limited:subtype==='success'?EXIT.completed:subtype==='error_max_turns'||subtype==='error_max_budget'?EXIT.limited:subtype==='error_schema'?EXIT.error:exitCode(r);
|
|
208
256
|
if(exit!==EXIT.completed)code=exit;
|
|
209
257
|
last={type:'result',subtype,state:r.state,exitCode:exit,sessionId:s.meta.id,name:s.meta.title||null,mode:chat.mode,model:chat.model||chat.info?.id||null,effort:chat.effort,text,
|
|
210
258
|
...(schema?{structuredOutput:structured??null}:{}),error:subtype==='success'?null:(r.error||null),usage:r.usage||null,
|
|
211
|
-
credits:creditsFor(spent),turns,changedFiles:r.completion?.changedFiles||[],checksPassed:(r.completion?.checksPassed||0)+(r.completion?.supportingChecksPassed||0),checksFailed:(r.completion?.checksFailed||0)+(r.completion?.supportingChecksFailed||0),rejectedApprovals:refused,
|
|
259
|
+
credits:creditsFor(spent),turns,changedFiles:r.completion?.changedFiles||[],checksPassed:(r.completion?.checksPassed||0)+(r.completion?.supportingChecksPassed||0),checksFailed:(r.completion?.checksFailed||0)+(r.completion?.supportingChecksFailed||0),rejectedApprovals:refused+ruleRefused,
|
|
212
260
|
persisted:!o.noSessionPersistence,
|
|
261
|
+
// BUG-0661/0717: warnings the engine raised (an MCP server that did not start, the built-in engine in use).
|
|
262
|
+
...(()=>{const w=[...new Set(events.filter(e=>e.type==='note'&&e.level==='warning'&&e.content).map(e=>String(e.content)))];return w.length?{warnings:w}:{}})(),
|
|
213
263
|
// BUG-0555: with -w the work is in its own worktree; say where, so scripts and people can find it.
|
|
214
264
|
...(s.meta.worktree&&!s.meta.worktree.removed?{worktree:{path:s.meta.worktree.path,branch:s.meta.worktree.branch}}:{})};
|
|
215
265
|
if(stream)write(last);
|
package/src/home.mjs
CHANGED
|
@@ -3,7 +3,7 @@ import path from 'node:path';
|
|
|
3
3
|
import {mkdirSync,chmodSync,statSync} from 'node:fs';
|
|
4
4
|
import {fileURLToPath} from 'node:url';
|
|
5
5
|
|
|
6
|
-
export const VERSION='0.3.
|
|
6
|
+
export const VERSION='0.3.10';
|
|
7
7
|
// BUG-0469: the production CLI signs in and calls the production domain.
|
|
8
8
|
export const DEFAULT_SERVER='https://code.ml.ai';
|
|
9
9
|
/** All local state lives here; nothing is written into the user's repository except what the agent edits. */
|
package/src/modes.mjs
CHANGED
|
@@ -28,7 +28,11 @@ export function nextMode(current,{sandbox=true}={}){
|
|
|
28
28
|
return order[(i+1)%order.length];
|
|
29
29
|
}
|
|
30
30
|
/** Text added in front of the task in ask mode, so the read-only run answers instead of planning. */
|
|
31
|
-
|
|
31
|
+
// BUG-0667: the engine's read-only rules talk about Plan mode and app buttons; in the terminal this is Ask mode, and the
|
|
32
|
+
// way out is Shift+Tab or --mode agent.
|
|
33
|
+
export const ASK_CARD='Answer the question from the code in this folder. Read files as needed; do not edit, do not run commands that change anything, and do not write a plan. Reply with a direct answer. '+
|
|
34
|
+
'This is Ask mode in the terminal, not Plan mode. If the message asks you to change files or run a command, do not try: say in one sentence that Ask mode only answers questions, '+
|
|
35
|
+
'and that they can press Shift+Tab to switch to agent mode, or run the request again with --mode agent. Do not mention Approve mode or a Build this plan button.';
|
|
32
36
|
/** The task as sent to the engine for a mode. */
|
|
33
37
|
export function taskFor(mode,task){return modeName(mode)==='ask'?ASK_CARD+'\n\nQuestion: '+task:task}
|
|
34
38
|
/** Applies a CLI mode to a Session: engine mode in meta.mode, CLI mode in meta.cliMode. */
|
package/src/render.mjs
CHANGED
|
@@ -49,6 +49,8 @@ export function renderEvent(e,{c=palette(false),verbose=false}={}){
|
|
|
49
49
|
case 'output':{
|
|
50
50
|
if(e.returncode===0&&!verbose)return null;
|
|
51
51
|
const tail=String(e.output||'').trim().split('\n').slice(verbose?-20:-4).join('\n');
|
|
52
|
+
// BUG-0666: after a declined approval the engine's instructions to the agent are not for the person (the TUI hides them too).
|
|
53
|
+
if(e.returncode!==0&&/(?:^|[\s:])(?:The user rejected (?:this action|a related action)|The user did not approve)\b/.test(String(e.output||'').slice(0,300)))return c.yellow('Not done: you declined it.');
|
|
52
54
|
if(e.blocked)return c.yellow('not run: '+tail); // refused before it ran: there is no exit code (CLI 0.3.4)
|
|
53
55
|
return e.returncode===0?c.gray(tail):c.yellow('exit '+e.returncode+(tail?'\n'+tail:''));
|
|
54
56
|
}
|
|
@@ -56,6 +58,8 @@ export function renderEvent(e,{c=palette(false),verbose=false}={}){
|
|
|
56
58
|
case 'todos':return (e.items||[]).map(t=>c.gray((t.status==='done'?'[x] ':t.status==='in_progress'?'[>] ':'[ ] ')+clip(t.text,120))).join('\n')||null;
|
|
57
59
|
case 'edit_guard':return c.yellow('blocked edit '+clip(e.path,120)+': '+clip(e.content,300));
|
|
58
60
|
case 'steering':return c.cyan('steering received');
|
|
61
|
+
case 'process_stopped':return c.yellow('stopped a hung command: '+clip(e.command,160)+(e.reason?' ('+clip(e.reason,160)+')':'')+'; the agent continues'); // worker/proc_watch.py (CLI r7)
|
|
62
|
+
case 'note':return e.level==='warning'&&e.content?c.yellow('warning: '+clip(e.content,600)):null; // BUG-0661/0717
|
|
59
63
|
case 'retry':return verbose?c.gray('retry: '+clip(e.content,200)):null;
|
|
60
64
|
case 'error':return c.red(clip(e.content||e.error||'Error',2000));
|
|
61
65
|
case 'completion':{
|
package/src/session.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {renameBranch} from './worktree.mjs';
|
|
2
2
|
import {EventEmitter} from 'node:events';
|
|
3
|
-
import {spawn} from 'node:child_process';
|
|
3
|
+
import {spawn,spawnSync} from 'node:child_process';
|
|
4
4
|
import {randomUUID,randomBytes} from 'node:crypto';
|
|
5
5
|
import {open,readFile,writeFile,rename,rm,mkdir,readdir,stat} from 'node:fs/promises';
|
|
6
6
|
import {existsSync} from 'node:fs';
|
|
@@ -102,6 +102,19 @@ const MIME={png:'image/png',jpg:'image/jpeg',webp:'image/webp',gif:'image/gif'};
|
|
|
102
102
|
* its repository. Each message is one run: the cloud issues a run token for the model gateway, the harness runs
|
|
103
103
|
* here, and the run is closed with the usage the gateway counted.
|
|
104
104
|
*/
|
|
105
|
+
/* BUG-0687: preview servers the agent starts (worker/preview.py) are stopped when the mlai session that started them
|
|
106
|
+
ends; they used to keep running, orphaned, after mlai exited. Only sessions that ran here are tracked. */
|
|
107
|
+
const previewOwners=new Map();
|
|
108
|
+
export function stopPreviews(owners=previewOwners){
|
|
109
|
+
const stopped=[];
|
|
110
|
+
for(const [dir,o] of owners){
|
|
111
|
+
owners.delete(dir);
|
|
112
|
+
if(!existsSync(path.join(dir,'preview-process.json')))continue;
|
|
113
|
+
try{const r=spawnSync(o.python,[path.join(o.worker,'preview.py'),'stop','--root',path.dirname(dir),'--repo',o.root,'--state',dir],{env:{...process.env,MINI_LAPTOP:'1'},stdio:['ignore','pipe','ignore'],timeout:15000,windowsHide:true,encoding:'utf8'});const out=JSON.parse(String(r.stdout||'').trim().split('\n').pop()||'{}');if(out.stopped?.length)stopped.push(...out.stopped)}catch{}
|
|
114
|
+
}
|
|
115
|
+
return stopped;
|
|
116
|
+
}
|
|
117
|
+
|
|
105
118
|
export class Session extends EventEmitter{
|
|
106
119
|
constructor(meta){super();this.meta=meta;this.dir=path.join(sub('sessions'),meta.id);this.child=null;this.offset=0}
|
|
107
120
|
static async create({cwd=process.cwd(),mode='guided',worktree=null,id=null}={}){
|
|
@@ -205,6 +218,7 @@ export class Session extends EventEmitter{
|
|
|
205
218
|
const python=await ensureRuntime({onProgress});
|
|
206
219
|
// The newest verified harness from the server, or the bundled one (src/engine.mjs); offline runs never check.
|
|
207
220
|
const engine=await prepareEngine({cloud:starter?null:cloud}),worker=engine.dir,used={version:engine.version,source:engine.source};
|
|
221
|
+
previewOwners.set(this.dir,{python,worker,root:this.meta.root});
|
|
208
222
|
// A worktree branch gets its real name from the first task (mlai/fix-login-redirect), if nothing was pushed yet.
|
|
209
223
|
if(this.meta.worktree&&!this.meta.worktree.named&&!this.meta.worktree.removed){try{const next=await renameBranch({...this.meta.worktree,parent:this.meta.parent},task);this.meta.worktree={...this.meta.worktree,branch:next.branch,named:true};await this.save()}catch{}}
|
|
210
224
|
// folderProject and repo let a chat that is not filed in a sidebar project get the context of the folder it runs in.
|
package/src/tui/agents-cli.mjs
CHANGED
|
@@ -92,6 +92,8 @@ async function live(list,{out,c,stdin,stdout,Session,sessionsDir,findSessions,re
|
|
|
92
92
|
|
|
93
93
|
/** `mlai attach <id>`: follow a running session (background or another terminal). Exit code from its result. */
|
|
94
94
|
export async function attachMain(argv,{out,c,stdin=process.stdin,Session,sessionsDir,findSessions,render}){
|
|
95
|
+
// BUG-0670: `mlai attach --help` shows how to use it.
|
|
96
|
+
if(argv.some(a=>a==='-h'||a==='--help')){const {SUB_HELP}=await import('../cli.mjs');out(SUB_HELP.attach);return 0}
|
|
95
97
|
const ref=argv.find(a=>a&&!a.startsWith('-'));
|
|
96
98
|
const s=await resolveAgent(ref,{Session,findSessions,sessionsDir});
|
|
97
99
|
const running=await stillRunning(s.dir);
|
package/src/tui/app.mjs
CHANGED
|
@@ -172,6 +172,7 @@ export async function runTui({session,settings={},cloud=null,flags={},first=null
|
|
|
172
172
|
if(e.type==='stage'&&e.content&&st.running){st.activity=strip(String(e.content)).slice(0,80);st.stageActivity=true}
|
|
173
173
|
if(e.type==='tool'&&e.name!=='todo'){st.activity=strip(tr.tool(e.name,e.target)[0]).replace(/^\S+ /,'');st.stageActivity=false}
|
|
174
174
|
if(e.type==='command'){st.activity='Running '+truncate(String(e.command||'').split('\n')[0],60);st.stageActivity=false}
|
|
175
|
+
if(e.type==='process_stopped'&&st.running){st.activity='Stopped a hung command; continuing';st.stageActivity=false}
|
|
175
176
|
tr.cols=screen.cols;let lines=tr.lines(e);
|
|
176
177
|
// An approved edit's card already printed its "● Edit file" row; the tool row that follows is not repeated.
|
|
177
178
|
if(e.type==='tool'&&st.cardHead&&lines.length===1&&strip(lines[0]).trim()===st.cardHead){st.cardHead=null;draw();return}
|
package/src/tui/chat.mjs
CHANGED
|
@@ -51,7 +51,9 @@ export function answerOf(turn){
|
|
|
51
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
52
|
const DELIVERABLES=/^\s*Declared deliverables remain unfinished:\s*(\[[\s\S]*?\])\./;
|
|
53
53
|
/** Engine-internal text (a tool call written as text, a deliverables dump) that is not an answer for a person. */
|
|
54
|
-
|
|
54
|
+
// BUG-0609: the old engine's finish marker written as the whole message (```bash echo COMPLETE_TASK_AND_SUBMIT_FINAL_OUTPUT ```).
|
|
55
|
+
const FINISH_MARK=/^\s*(?:```(?:bash|sh|shell)?\s*)?(?:echo\s+)?COMPLETE_TASK_AND_SUBMIT_FINAL_OUTPUT\s*(?:```)?\s*$/;
|
|
56
|
+
export function internalText(t){return TOOL_TEXT.test(String(t||''))||DELIVERABLES.test(String(t||''))||FINISH_MARK.test(String(t||''))}
|
|
55
57
|
/** A sentence in place of internal text, when there is nothing better to show. */
|
|
56
58
|
export function readableInternal(t){
|
|
57
59
|
const m=DELIVERABLES.exec(String(t||''));
|
|
@@ -97,10 +99,12 @@ export class Chat extends EventEmitter{
|
|
|
97
99
|
return this.models||FALLBACK_MODELS;
|
|
98
100
|
}
|
|
99
101
|
async setModel(id){
|
|
100
|
-
|
|
102
|
+
// BUG-0662: a model is found by its id or by the name /model shows, in any case, with spaces or dashes.
|
|
103
|
+
const slug=v=>String(v||'').trim().toLowerCase().replace(/[\s_]+/g,'-');
|
|
104
|
+
const list=await this.loadModels();let m=list.find(x=>x.id===id)||list.find(x=>slug(x.id)===slug(id)||slug(x.label)===slug(id));
|
|
101
105
|
// Without the server's list (older server, offline) any id is passed on; the server checks it.
|
|
102
106
|
if(!m&&!this.models&&/^[\w.:/-]{1,80}$/.test(String(id)))m={id:String(id),label:String(id),available:true,creditLabel:'Credits per your plan'};
|
|
103
|
-
if(!m)throw new Error('No model '+id+'. Run /model to see the list.');
|
|
107
|
+
if(!m)throw new Error('No model '+id+'. Run /model to see the list'+(list.length?' (ids: '+list.filter(x=>x.available!==false).map(x=>x.id).join(', ')+')':'')+'.');
|
|
104
108
|
if(m.available===false)throw new Error(m.label+' is not available yet.');
|
|
105
109
|
this.model=m.id;this.session.meta.model=m.id;await this.session.save();this.emit('change');return m;
|
|
106
110
|
}
|
package/src/tui/cmd-core.mjs
CHANGED
|
@@ -55,7 +55,7 @@ export function install(register){
|
|
|
55
55
|
ctx.out('Model: '+m.label+' · '+m.creditLabel+(levels.length?' · '+chat.effort+' effort':''));return {model:m.id,effort:chat.effort};
|
|
56
56
|
};
|
|
57
57
|
if(exact){const m=await chat.setModel(exact.id).catch(e=>{throw new CommandError(e.message)});return done({...exact,...m})}
|
|
58
|
-
const rows=list.map(m=>({label:(m.id===chat.info?.id?'* ':' ')+m.label,detail:m.available===false?'Not available yet':m.creditLabel+(m.vision===false?' · text only':'')+(m.efforts?.length?' · effort '+m.efforts.join('/'):''),value:m.id,disabled:m.available===false}));
|
|
58
|
+
const rows=list.map(m=>({label:(m.id===chat.info?.id?'* ':' ')+m.label,detail:(m.available===false?'Not available yet':m.creditLabel+(m.vision===false?' · text only':'')+(m.efforts?.length?' · effort '+m.efforts.join('/'):''))+(m.id!==m.label?' · -m '+m.id:''),value:m.id,disabled:m.available===false}));
|
|
59
59
|
const pick=await ctx.ui.pick(rows.filter(r=>!r.disabled).concat(rows.filter(r=>r.disabled)),{title:'Model (now '+chat.modelLabel+')',filter:a});
|
|
60
60
|
if(!pick)return;
|
|
61
61
|
if(pick.disabled){ctx.ui.error(pick.label.trim()+' is not available yet.');return}
|
|
@@ -83,7 +83,10 @@ export async function localExtensions({root,settings=null,skipPermissions=false,
|
|
|
83
83
|
let fresh=null;try{fresh=loadSettings({root})}catch{}
|
|
84
84
|
const sandbox=isObj(fresh?.sandbox)?fresh.sandbox:isObj(settings?.sandbox)?settings.sandbox:{};
|
|
85
85
|
const cur=fresh||settings||{};
|
|
86
|
-
const
|
|
86
|
+
const found=discoverSkills(root,{pluginDirs:extState.pluginDirs,disabled:Array.isArray(cur.skills?.disabled)?cur.skills.disabled:[]});
|
|
87
|
+
const skills=engineSkills(found);
|
|
88
|
+
// BUG-0665: a disabled skill is not read another way either (read_file or cat of its SKILL.md), as with BUG-0530.
|
|
89
|
+
const blocked=[...new Set([...(mcp.blockedFiles||[]),...found.filter(s=>!s.enabled&&s.dir).flatMap(s=>[s.dir,s.dir+'/**'])])];
|
|
87
90
|
const agents=engineAgents(discoverAgents(root,{flagAgents:extState.agents||[],pluginDirs:extState.pluginDirs}));
|
|
88
91
|
const memory=cur.memories===true?readMemory(root):null;
|
|
89
92
|
const ext={
|
|
@@ -93,7 +96,7 @@ export async function localExtensions({root,settings=null,skipPermissions=false,
|
|
|
93
96
|
...(sandbox.network===false?{network:{enabled:false}}:{}),
|
|
94
97
|
...(Object.keys(mcp.mcpServers).length?{mcpServers:mcp.mcpServers}:{}),
|
|
95
98
|
...(Object.keys(mcp.mcpEnv).length?{mcpEnv:mcp.mcpEnv}:{}),
|
|
96
|
-
...(
|
|
99
|
+
...(blocked.length?{hardDeny:{paths:blocked}}:{}),// BUG-0530: a disabled MCP server is not started another way
|
|
97
100
|
...(sandbox.enabled===false?{sandbox:{enabled:false}}:{}),
|
|
98
101
|
// Auto mode's reviewer pass (worker/mlai_auto_review.py); the engine ignores it in other modes.
|
|
99
102
|
autoReview:{enabled:(fresh??settings)?.autoReview!==false&&!skipPermissions,...(((fresh??settings)?.reviewModel)?{model:(fresh??settings).reviewModel}:{})},
|
package/src/tui/plain.mjs
CHANGED
|
@@ -66,3 +66,19 @@ export function printAbove(rl,stream,text,{clearLine,cursorTo,moveCursor,clearSc
|
|
|
66
66
|
stream.write(text+'\n');
|
|
67
67
|
if(rl&&!rl.closed){rl.prevRows=0;if(rl.line&&typeof rl._refreshLine==='function')rl._refreshLine()}
|
|
68
68
|
}
|
|
69
|
+
/**
|
|
70
|
+
* BUG-0612: tells lines that arrive in one burst (a paste the terminal did not mark) from typed lines. Feed it every
|
|
71
|
+
* input chunk before readline sees it; now() is true while the lines of a chunk with more than one line break (or a
|
|
72
|
+
* break before its end) are handled, and shortly after, so a long paste split over several chunks stays one burst.
|
|
73
|
+
*/
|
|
74
|
+
export function pasteBurst({gap=25,clock=Date.now}={}){
|
|
75
|
+
let active=false,last=-Infinity;
|
|
76
|
+
const data=chunk=>{
|
|
77
|
+
const s=String(chunk??'').replace(/\x1b\[20[01]~/g,'');
|
|
78
|
+
const breaks=(s.match(/\r\n|\r|\n/g)||[]).length;
|
|
79
|
+
const multi=breaks>1||(breaks===1&&!/[\r\n]$/.test(s));
|
|
80
|
+
active=multi||(breaks>0&&clock()-last<gap);
|
|
81
|
+
if(active){last=clock();setImmediate(()=>{active=false})}
|
|
82
|
+
};
|
|
83
|
+
return {data,now:()=>active||clock()-last<gap};
|
|
84
|
+
}
|
package/src/tui/review-cli.mjs
CHANGED
|
@@ -223,7 +223,8 @@ export async function runReview({root,dir,target,mode='standard',focus='',model=
|
|
|
223
223
|
const body=[focus?'Focus on: '+focus:'',target.body||''].filter(Boolean).join('\n\n');
|
|
224
224
|
const request=reviewRequest({mode,scope:target.scope,base:target.base,head:target.head,title:target.title||'',body,analysis},
|
|
225
225
|
{id,repo:root,reviews:dir,model:{endpoint:started.gateway,model:started.model?.id||'mlai-code',provider:started.model?.effort?'isoquant':'gateway'}});
|
|
226
|
-
|
|
226
|
+
// BUG-0658: a re-run reports earlier findings that are still there, so a retried CI gate cannot pass a known issue.
|
|
227
|
+
const file=path.join(dir,id+'.json');await writeFile(file,JSON.stringify({...request,repeatOpen:true}));
|
|
227
228
|
const py=await python(),worker=workerDir();
|
|
228
229
|
let closed=false;const close=st=>{if(closed)return;closed=true;Promise.resolve(cloud.finish(started.token,st)).catch(()=>{})};
|
|
229
230
|
const child=spawnImpl(py,['-m','mlai_review','run',file],{cwd:worker,stdio:['ignore','ignore','pipe'],windowsHide:true,
|