mlai-code 0.3.6 → 0.3.8
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/package.json +1 -1
- package/src/browser-setup.mjs +1 -1
- package/src/cli.mjs +32 -7
- package/src/cloud.mjs +2 -0
- package/src/headless.mjs +6 -2
- package/src/home.mjs +1 -1
- package/src/netjail.py +7 -1
- package/src/render.mjs +1 -1
- package/src/run-record.mjs +114 -0
- package/src/sandbox.mjs +32 -0
- package/src/session.mjs +97 -17
- package/src/tui/agents-cli.mjs +2 -1
- package/src/tui/ansi.mjs +15 -2
- package/src/tui/app.mjs +56 -41
- package/src/tui/bg.mjs +5 -1
- package/src/tui/chat.mjs +3 -1
- package/src/tui/editor.mjs +83 -6
- package/src/tui/plain.mjs +36 -0
- package/src/tui/statusline.mjs +3 -3
- package/src/tui/transcript.mjs +24 -10
- package/src/two-words.mjs +2 -0
- package/worker/browser_local.py +2 -2
- package/worker/browser_tool.py +16 -2
- package/worker/command_safety.py +14 -0
- package/worker/deck_tools.py +4 -3
- package/worker/kimi_bridge.py +174 -35
- package/worker/kimi_gates.py +53 -7
- package/worker/kimi_hook.py +29 -6
- package/worker/lifecycle.py +26 -0
- package/worker/media_tools.py +115 -20
- package/worker/mlai_hooks.py +40 -2
- package/worker/mlai_mcp.py +3 -3
- package/worker/preview.py +11 -3
- package/worker/repo_policy.py +28 -1
- package/worker/roles.py +5 -1
- package/worker/runner.py +2 -1
- package/worker/runtime_control.py +15 -5
- package/worker/site_check.py +1 -1
- package/worker/tool_catalog.py +1 -1
- package/worker/verification.py +102 -0
- package/worker/winproc.py +23 -0
package/README.md
CHANGED
package/package.json
CHANGED
package/src/browser-setup.mjs
CHANGED
|
@@ -74,4 +74,4 @@ const runEnv=new Set();
|
|
|
74
74
|
export function addRunEnv(fn){if(typeof fn==='function')runEnv.add(fn);return ()=>runEnv.delete(fn)}
|
|
75
75
|
|
|
76
76
|
/** What the install approval card says. */
|
|
77
|
-
export const INSTALL_NOTE='Install the test browser on this
|
|
77
|
+
export const INSTALL_NOTE='Install the test browser on this computer (one-time download of about 150 MB into ~/.mlai/runtime). It opens only your local preview.';
|
package/src/cli.mjs
CHANGED
|
@@ -12,11 +12,11 @@ import {saveLogin,loadLogin,clearLogin} from './credentials.mjs';
|
|
|
12
12
|
import {Client,ClientError,deviceLogin} from './sdk.mjs';
|
|
13
13
|
import {Cloud,friendly} from './cloud.mjs';
|
|
14
14
|
import {Session,sandboxKind} from './session.mjs';
|
|
15
|
-
import {MODES as CLI_MODES,modeName,nextMode,engineMode} from './modes.mjs';
|
|
15
|
+
import {MODES as CLI_MODES,modeName,nextMode,engineMode,sessionMode} from './modes.mjs';
|
|
16
16
|
import {loadSettings} from './settings.mjs';
|
|
17
17
|
import * as registry from './tui/commands.mjs';
|
|
18
18
|
import {Chat,answerOf,modelList} from './tui/chat.mjs';
|
|
19
|
-
import {plainUi} from './tui/plain.mjs';
|
|
19
|
+
import {plainUi,trackWrappedInput,printAbove} from './tui/plain.mjs';
|
|
20
20
|
import {projectRoot} from './project.mjs';
|
|
21
21
|
import {createWorktree} from './worktree.mjs';
|
|
22
22
|
import {EXT_FLAGS,EXT_COMMANDS,extFlag} from './cli-ext.mjs';
|
|
@@ -25,7 +25,8 @@ import {SANDBOXES} from './sandbox.mjs';
|
|
|
25
25
|
import {restrictedForced,refusedFlag} from './restricted.mjs';
|
|
26
26
|
import {gitForWindows} from './winenv.mjs';
|
|
27
27
|
import {ensureRuntime,runtimeInfo,PY_VERSION,hideEngineName} from './runtime.mjs';
|
|
28
|
-
import {palette,colorAllowed,renderEvent,approvalView,summaryLine,exitCode,EXIT,fmt,credits} from './render.mjs';
|
|
28
|
+
import {palette,colorAllowed,renderEvent,approvalView,summaryLine,exitCode,EXIT,fmt,credits,prose} from './render.mjs';
|
|
29
|
+
import {answerRest} from './tui/transcript.mjs';
|
|
29
30
|
import {runHeadless,streamInputs,stdinLines,toolRules,loadSchema,HeadlessError} from './headless.mjs';
|
|
30
31
|
import {terminals,backgroundCommand} from './tui/bgterm.mjs';
|
|
31
32
|
|
|
@@ -252,6 +253,11 @@ async function cloudFor(o){
|
|
|
252
253
|
return new Cloud({server:await serverFor(o),token:login.token});
|
|
253
254
|
}
|
|
254
255
|
const loopback=u=>/^http:\/\/(127\.0\.0\.1|\[::1\])(:\d+)?$/.test(u);
|
|
256
|
+
/** Runs left open by an earlier mlai (src/run-record.mjs): closed with their own run token, at most a few seconds. */
|
|
257
|
+
async function closeLeftRuns(){
|
|
258
|
+
try{const {recoverRuns}=await import('./run-record.mjs');return await recoverRuns({finish:(server,token,state,usage)=>new Cloud({server,token:''}).finish(token,state,usage),timeoutMs:4000})}
|
|
259
|
+
catch{return []}
|
|
260
|
+
}
|
|
255
261
|
|
|
256
262
|
export async function main(argv=process.argv.slice(2)){
|
|
257
263
|
if(['update','completion','__install','__complete'].includes(argv[0]))return (await import('./distribution.mjs')).distMain(argv);
|
|
@@ -271,6 +277,8 @@ export async function main(argv=process.argv.slice(2)){
|
|
|
271
277
|
const err=palette(colorAllowed(process.stderr));
|
|
272
278
|
try{
|
|
273
279
|
if(cmd==='help'){process.stdout.write((SUB_HELP[o._[0]]||HELP)+'\n');return 0}
|
|
280
|
+
// Round 5: close runs an earlier mlai left open on the server (killed, crashed, or offline when it ended).
|
|
281
|
+
if(!cmd||['sessions','resume','remote-control'].includes(cmd))await closeLeftRuns();
|
|
274
282
|
if(cmd==='version'){process.stdout.write(VERSION+'\n');return 0}
|
|
275
283
|
if(cmd==='login')return await login(o);
|
|
276
284
|
if(cmd==='logout')return await logout(o);
|
|
@@ -373,7 +381,7 @@ async function sessions(o,c){
|
|
|
373
381
|
const listed=await Session.list();
|
|
374
382
|
// BUG-0503: a run that never started a turn (bad arguments, a crash before the first message) is not a session to resume.
|
|
375
383
|
const all=o.json?listed:listed.filter(m=>m.turns?.length);
|
|
376
|
-
if(o.json){process.stdout.write(JSON.stringify(all.map(m=>({id:m.id,folder:m.folder,root:m.root,mode:m
|
|
384
|
+
if(o.json){process.stdout.write(JSON.stringify(all.map(m=>({id:m.id,folder:m.folder,root:m.root,mode:sessionMode(m),title:m.title,turns:m.turns.length,tokens:m.turns.reduce((a,t)=>a+(t.tokens||0),0),updated:m.updated||m.created})))+'\n');return 0}
|
|
377
385
|
if(!all.length){process.stdout.write('No sessions yet. Run mlai in a project folder.\n');return 0}
|
|
378
386
|
for(const m of all.slice(0,30)){
|
|
379
387
|
const tokens=m.turns.reduce((a,t)=>a+(t.tokens||0),0),last=m.turns.at(-1);
|
|
@@ -543,14 +551,17 @@ async function withRemote(chat,fn){
|
|
|
543
551
|
|
|
544
552
|
/** The line-based session (no full-screen TUI): readline, slash commands from the registry, approvals, steering. */
|
|
545
553
|
async function plainLoop(o,c,chat,first){
|
|
546
|
-
|
|
554
|
+
// A long typed line wraps over several rows; output printed while it is there clears all of them (R6).
|
|
555
|
+
let rl=null;
|
|
556
|
+
const out=t=>printAbove(rl,process.stdout,t,readline);
|
|
547
557
|
const kind=sandboxKind(),sandboxed=SANDBOXES.includes(kind);
|
|
548
558
|
const banner=()=>out(c.bold('ML AI Code')+c.dim(` · ${chat.session.meta.folder} · ${chat.modelLabel} · ${chat.mode} mode · sandbox ${sandboxed?kind:'none'}`));
|
|
549
559
|
banner();
|
|
550
560
|
out(c.dim('Type a task. While it works, type to steer it. Ctrl-C stops. Type / for commands, Shift+Tab switches mode.'));
|
|
551
561
|
let ctx=null;
|
|
552
|
-
|
|
562
|
+
rl=readline.createInterface({input:process.stdin,output:process.stdout,terminal:true,historySize:500,
|
|
553
563
|
completer:(line,cb)=>{if(!line.startsWith('/'))return cb(null,[[],line]);registry.complete(ctx,line).then(l=>cb(null,[l,line]),()=>cb(null,[[],line]))}});
|
|
564
|
+
trackWrappedInput(rl);
|
|
554
565
|
let pending=null,lastCtrlC=0,question=null;
|
|
555
566
|
const prompt=()=>{rl.setPrompt(question?question.text:pending?c.yellow('approve? [y]es / [a]ll / [n]o › '):chat.running?c.dim('steer › '):c.cyan(chat.mode==='agent'?'› ':chat.mode+' › '));rl.prompt(true)};
|
|
556
567
|
const ask=text=>new Promise(resolve=>{question={text,resolve};prompt()});
|
|
@@ -561,8 +572,15 @@ async function plainLoop(o,c,chat,first){
|
|
|
561
572
|
if(o.yes){chat.session.decide(e.id,'approve_all').catch(()=>{});return}
|
|
562
573
|
pending=e;out(approvalView(e,c).text);prompt();return;
|
|
563
574
|
}
|
|
575
|
+
// The final answer repeats the agent's last reply; print only what it adds (a source list, a verification note).
|
|
576
|
+
// A reply restated with a line added prints only the new part (shared with the full interface).
|
|
577
|
+
if(e.type==='assistant'||e.type==='answer'){
|
|
578
|
+
const p=prose(e.content),rest=answerRest(shown,p);if(p)shown=[...shown,p].slice(-8);
|
|
579
|
+
if(rest){out(rest);prompt()}return;
|
|
580
|
+
}
|
|
564
581
|
const line=renderEvent(e,{c,verbose:o.verbose});if(line){out(line);prompt()}
|
|
565
582
|
};
|
|
583
|
+
let shown=[];
|
|
566
584
|
let bound=chat.session;bound.on('event',onEvent);
|
|
567
585
|
chat.on('session',n=>{bound.off('event',onEvent);bound=n;n.on('event',onEvent);banner();prompt()});
|
|
568
586
|
// BUG-0532: `!` output (and finished background terminals) go with the next message, as in the full-screen TUI.
|
|
@@ -574,9 +592,16 @@ async function plainLoop(o,c,chat,first){
|
|
|
574
592
|
if(shellContext.length){task='Output of commands I ran in the terminal:\n\n'+shellContext.join('\n\n')+'\n\n'+task;shellContext=[]}
|
|
575
593
|
prompt();
|
|
576
594
|
try{
|
|
595
|
+
shown=[];
|
|
577
596
|
const r=await chat.send(task,{onProgress:m=>out(c.dim(m+'...'))});
|
|
578
597
|
if(r.state!=='completed'&&r.error)out(c.yellow(r.error));
|
|
579
598
|
out(summaryLine(r,c));
|
|
599
|
+
// A line typed to steer after the agent stopped reading never reached it: run it now, or put it back when stopped.
|
|
600
|
+
const late=await chat.session.takeSteering?.().catch(()=>[])||[];
|
|
601
|
+
if(late.length){
|
|
602
|
+
if(r.state==='stopped'){out(c.dim('The agent finished before it read your message; it is back on the prompt.'));pending=null;prompt();rl.write(late.join(' '));return}
|
|
603
|
+
out(c.dim('The agent finished before it read your message; sending it now.'));pending=null;return await run(late.join('\n'));
|
|
604
|
+
}
|
|
580
605
|
// Plan mode ends with an offer to build the plan (like the app's Build it).
|
|
581
606
|
if(chat.mode==='plan'&&r.state==='completed'&&await ui.confirm('Build it? Switches to agent mode.',{default:false})){await chat.setMode('agent');pending=null;return run('Build the plan you proposed above.')}
|
|
582
607
|
}catch(e){out(c.red('error: ')+friendly(e))}
|
|
@@ -637,7 +662,7 @@ async function plainLoop(o,c,chat,first){
|
|
|
637
662
|
if(bracketed)process.stdout.write('\x1b[?2004l');
|
|
638
663
|
terminals.off('exit',onJobExit);
|
|
639
664
|
process.off('SIGHUP',onHangup);process.off('SIGTERM',onHangup);
|
|
640
|
-
if(chat.running||chat.session.child)await chat.session.stopNow().catch(()=>{});
|
|
665
|
+
if(chat.running||chat.session.child)await chat.session.stopNow(2500,{code:hungUp?'terminal_closed':null}).catch(()=>{});
|
|
641
666
|
return hungUp?129:0;
|
|
642
667
|
}
|
|
643
668
|
|
package/src/cloud.mjs
CHANGED
|
@@ -27,5 +27,7 @@ export function friendly(error){
|
|
|
27
27
|
if(error.code==='not_configured')return 'Laptop runs are not enabled on this server yet.';
|
|
28
28
|
// BUG-0504: nothing was connected, so "Refresh status before retrying a write" only confused people.
|
|
29
29
|
if(error.code==='connection_interrupted')return 'Cannot reach the ML AI Code server'+(error.server?' at '+error.server:'')+'. Check your internet connection'+(error.server?' and the server address (--server or MLAI_SERVER)':'')+'.';
|
|
30
|
+
// Round 5: an HTTP 500/502 on start printed only "Internal error".
|
|
31
|
+
if(error.status>=500&&error.status<600&&(!error.message||/^(internal error|internal server error|bad gateway|service unavailable|request failed)\.?$/i.test(error.message.trim())))return 'The ML AI Code server had a problem (HTTP '+error.status+'). Nothing was started. Try again in a minute.';
|
|
30
32
|
return error.message;
|
|
31
33
|
}
|
package/src/headless.mjs
CHANGED
|
@@ -147,7 +147,11 @@ export async function runHeadless(o,{s,chat,err,inputs,out=t=>process.stdout.wri
|
|
|
147
147
|
if(String(text).replace(/\s+/g,' ').trim()===raw.replace(/\s+/g,' ').trim())return '';
|
|
148
148
|
if(raw.length>40&&String(text).includes(raw))return String(text).replace(raw,'').trim()}
|
|
149
149
|
return text};
|
|
150
|
-
|
|
150
|
+
// Round 5: SIGHUP (the terminal closed) stops the run too; it used to end the CLI at once, leaving the engine running
|
|
151
|
+
// 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
|
+
const quiet=()=>{};
|
|
153
|
+
const stop=sig=>{if(sig==='SIGHUP'){process.stdout.on('error',quiet);process.stderr.on('error',quiet)}s.stopCode=sig==='SIGHUP'?'terminal_closed':sig==='SIGTERM'?'terminated':null;s.cancel().catch(()=>{})};
|
|
154
|
+
process.once('SIGINT',stop);process.once('SIGTERM',stop);process.once('SIGHUP',stop);
|
|
151
155
|
const onEvent=e=>{
|
|
152
156
|
events.push(e);
|
|
153
157
|
if(stream)write(e);
|
|
@@ -217,7 +221,7 @@ export async function runHeadless(o,{s,chat,err,inputs,out=t=>process.stdout.wri
|
|
|
217
221
|
return code;
|
|
218
222
|
}finally{
|
|
219
223
|
if(oneShot===undefined)delete process.env.MINI_ONE_SHOT;else process.env.MINI_ONE_SHOT=oneShot;
|
|
220
|
-
process.off('SIGINT',stop);process.off('SIGTERM',stop);
|
|
224
|
+
process.off('SIGINT',stop);process.off('SIGTERM',stop);process.off('SIGHUP',stop);
|
|
221
225
|
s.off('event',onEvent);s.off('started',onStarted);chat.off('fallback',onFallback);
|
|
222
226
|
if(o.noSessionPersistence)await rm(s.dir,{recursive:true,force:true}).catch(()=>{});
|
|
223
227
|
}
|
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.8';
|
|
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/netjail.py
CHANGED
|
@@ -48,7 +48,13 @@ def main(argv):
|
|
|
48
48
|
listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
|
49
49
|
listener.bind(('127.0.0.1', port)); listener.listen(64)
|
|
50
50
|
threading.Thread(target=serve, args=(listener, path), daemon=True).start()
|
|
51
|
-
|
|
51
|
+
# The CLI's parent pipe (MINI_PARENT_FD, worker/lifecycle.py watch_parent) passes through to the engine.
|
|
52
|
+
keep = ()
|
|
53
|
+
fd = os.environ.get('MINI_PARENT_FD', '')
|
|
54
|
+
if fd.isdigit():
|
|
55
|
+
try: os.fstat(int(fd)); keep = (int(fd),)
|
|
56
|
+
except OSError: keep = ()
|
|
57
|
+
child = subprocess.Popen(cmd, pass_fds=keep)
|
|
52
58
|
for sig in (signal.SIGTERM, signal.SIGINT, signal.SIGHUP):
|
|
53
59
|
signal.signal(sig, lambda s, _f: child.send_signal(s))
|
|
54
60
|
code = child.wait()
|
package/src/render.mjs
CHANGED
|
@@ -89,5 +89,5 @@ export function exitCode(result){
|
|
|
89
89
|
export function summaryLine(result,c=palette(false)){
|
|
90
90
|
const u=result.usage||{};
|
|
91
91
|
const state=result.state==='completed'&&result.cannotComplete?c.yellow('Could not be done'):result.state==='completed'?c.green('Done'):result.state==='limited'?c.yellow('Needs attention'):result.state==='stopped'?c.yellow('Stopped'):c.red('Failed');
|
|
92
|
-
return state+c.dim(' · '+credits(u.tokens)+' · '+fmt(u.calls)+(Number(u.calls)===1?' model call':' model calls'));
|
|
92
|
+
return state+c.dim(' · '+credits(u.tokens)+' · '+fmt(u.calls)+(Number(u.calls)===1?' model call':' model calls'))+((result.code==='time_limit'||result.code==='step_limit')&&result.error?'\n'+c.yellow(result.error):'');
|
|
93
93
|
}
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
// Run lifecycle on this computer: every laptop run the server opened is closed, whatever way the CLI ends.
|
|
2
|
+
// While a run is open its session folder holds run.json (owner-only): the run id, the run token (good for this one
|
|
3
|
+
// run on the model gateway and for closing it, for at most 12 hours) and the server. A normal end closes the run and
|
|
4
|
+
// removes the file. When the CLI was killed (kill -9, a crash, a closed laptop that never woke the process, a failed
|
|
5
|
+
// close because the network was down), the next mlai start finds the file and closes the run as interrupted.
|
|
6
|
+
import {readFile,writeFile,rename,rm,readdir} from 'node:fs/promises';
|
|
7
|
+
import {existsSync} from 'node:fs';
|
|
8
|
+
import path from 'node:path';
|
|
9
|
+
import {sub} from './home.mjs';
|
|
10
|
+
|
|
11
|
+
const FINAL=['completed','limited','error','stopped','interrupted'];
|
|
12
|
+
const CODE=/^[a-z][a-z0-9_]{1,39}$/;
|
|
13
|
+
async function readJson(file,fallback){try{return JSON.parse(await readFile(file,'utf8'))}catch{return fallback}}
|
|
14
|
+
async function writePrivate(file,data){const tmp=file+'.'+process.pid+'.tmp';await writeFile(tmp,JSON.stringify(data),{mode:0o600});await rename(tmp,file)}
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* A short reason code for a run that did not complete, sent with the run's close as usage.errorCode. Only a fixed
|
|
18
|
+
* word: never the error text, a path or a secret. Null for runs that completed or were stopped or limited normally.
|
|
19
|
+
*/
|
|
20
|
+
export function errorCode(status={},{exit={},stopCode=null}={}){
|
|
21
|
+
const state=status?.state;
|
|
22
|
+
if(stopCode&&(state==='stopped'||state==='error'||state==='interrupted'))return CODE.test(stopCode)?stopCode:'stopped_signal';
|
|
23
|
+
if(state!=='error'&&state!=='interrupted')return null;
|
|
24
|
+
if(typeof status.errorCode==='string'&&CODE.test(status.errorCode))return status.errorCode;
|
|
25
|
+
const text=String(status.error||'')+'\n'+String(status.stopDetail||'');
|
|
26
|
+
if(exit?.error)return 'engine_spawn';
|
|
27
|
+
if(/\bbwrap:|sandbox-exec|sandbox_apply|Operation not permitted.*namespace|setting up uid map|Creating new namespace failed/i.test(text))return 'sandbox_unavailable';
|
|
28
|
+
if(/Model HTTP 40[13]\b|run_token_invalid|expired or was revoked/i.test(text))return 'run_token';
|
|
29
|
+
if(/Model HTTP 402\b|billing_limit|allowance ran out|credits_exhausted|out of credits/i.test(text))return 'billing_limit';
|
|
30
|
+
if(/Model HTTP 409\b|run_finished|This run has ended/i.test(text))return 'run_closed';
|
|
31
|
+
if(/Model HTTP 429\b/i.test(text))return 'model_busy';
|
|
32
|
+
if(/Model HTTP 5\d\d\b|overloaded|model is unavailable/i.test(text))return 'model_unavailable';
|
|
33
|
+
if(/\b(ECONNRESET|ECONNREFUSED|ENOTFOUND|EAI_AGAIN)\b/.test(text)||/Model stream stalled|Model connection failed|Network is unreachable|timed out/i.test(text))return 'model_network';
|
|
34
|
+
if(/No module named|ModuleNotFoundError|ImportError|SyntaxError/i.test(text))return 'engine_broken';
|
|
35
|
+
if(/exited unexpectedly/i.test(text))return 'engine_crash';
|
|
36
|
+
if(/Traceback \(most recent call last\)/i.test(text))return 'engine_exception';
|
|
37
|
+
return state==='interrupted'?null:'run_error';
|
|
38
|
+
}
|
|
39
|
+
/** The usage sent when a run closes: the harness's own counters plus endReason and errorCode. */
|
|
40
|
+
export function closeUsage(status={},code=null){
|
|
41
|
+
const u=status?.usage&&typeof status.usage==='object'?{...status.usage}:{};
|
|
42
|
+
if(!u.endReason&&FINAL.includes(status?.state))u.endReason=status.state;
|
|
43
|
+
if(code)u.errorCode=code;
|
|
44
|
+
return Object.keys(u).length?u:undefined;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export const runFile=dir=>path.join(dir,'run.json');
|
|
48
|
+
/** Remembers an open run (before the engine starts). */
|
|
49
|
+
export async function saveRun(dir,{runId,token,server,pid=process.pid}){
|
|
50
|
+
if(!runId||typeof token!=='string'||!token||!server)return false;
|
|
51
|
+
await writePrivate(runFile(dir),{runId,token,server,pid,started:Date.now()});
|
|
52
|
+
return true;
|
|
53
|
+
}
|
|
54
|
+
/** The run could not be closed (network down, server error): keep it with what to send, for the next start. */
|
|
55
|
+
export async function deferClose(dir,state,usage){
|
|
56
|
+
const r=await readJson(runFile(dir),null);if(!r)return;
|
|
57
|
+
await writePrivate(runFile(dir),{...r,pending:{state,...(usage?{usage}:{})},pid:null});
|
|
58
|
+
}
|
|
59
|
+
export const forgetRun=dir=>rm(runFile(dir),{force:true});
|
|
60
|
+
|
|
61
|
+
const alive=pid=>{if(!(pid>0))return false;if(pid===process.pid)return true;try{process.kill(pid,0);return true}catch(e){return e.code==='EPERM'}};
|
|
62
|
+
async function lockHeld(dir){const pid=Number(await readFile(path.join(dir,'running.lock'),'utf8').catch(()=>''));return pid>0&&pid!==process.pid&&alive(pid)}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Closes runs left open by a CLI that ended without closing them. `finish(server,token,state,usage)` closes one run
|
|
66
|
+
* (src/cloud.mjs). Runs whose session is still in use by a live process are left alone. Returns what it did.
|
|
67
|
+
*/
|
|
68
|
+
export async function recoverRuns({finish,dir=sub('sessions'),timeoutMs=5000,now=Date.now()}={}){
|
|
69
|
+
const out=[];
|
|
70
|
+
const ids=await readdir(dir).catch(()=>[]);
|
|
71
|
+
const work=[];
|
|
72
|
+
for(const id of ids){
|
|
73
|
+
const d=path.join(dir,id),f=runFile(d);if(!existsSync(f))continue;
|
|
74
|
+
work.push((async()=>{
|
|
75
|
+
const r=await readJson(f,null);
|
|
76
|
+
if(!r||typeof r.token!=='string'){await rm(f,{force:true});return}
|
|
77
|
+
if(await lockHeld(d)||(r.pid&&r.pid!==process.pid&&alive(r.pid)&&!r.pending))return;
|
|
78
|
+
// Older than the token (12 hours): the server's watchdog closes it; nothing to send.
|
|
79
|
+
if(now-Number(r.started||0)>12*3600000){await rm(f,{force:true});out.push({id,runId:r.runId,action:'expired'});return}
|
|
80
|
+
const status=await readJson(path.join(d,'status.json'),{});
|
|
81
|
+
let state,usage;
|
|
82
|
+
if(r.pending){state=r.pending.state;usage=r.pending.usage}
|
|
83
|
+
else{
|
|
84
|
+
// The engine may still be running on its own (the CLI was killed): ask it to stop.
|
|
85
|
+
if(!FINAL.includes(status.state))await writeFile(path.join(d,'cancel'),'1').catch(()=>{});
|
|
86
|
+
state=FINAL.includes(status.state)&&status.state!=='completed'?status.state:FINAL.includes(status.state)?'completed':'interrupted';
|
|
87
|
+
usage=closeUsage({...status,state},status.state==='completed'?null:'cli_exited');
|
|
88
|
+
if(usage&&state==='interrupted')usage.endReason='interrupted';
|
|
89
|
+
}
|
|
90
|
+
try{
|
|
91
|
+
const res=await finish(r.server,r.token,state,usage);
|
|
92
|
+
await rm(f,{force:true});await markTurn(d,r.runId,state,res);
|
|
93
|
+
out.push({id,runId:r.runId,action:'closed',state});
|
|
94
|
+
}catch(e){
|
|
95
|
+
// The token expired or the run is unknown: nothing more this computer can do.
|
|
96
|
+
if(e?.status===401||e?.status===400||e?.code==='run_token_invalid'){await rm(f,{force:true});await markTurn(d,r.runId,state,null);out.push({id,runId:r.runId,action:'expired'})}
|
|
97
|
+
else out.push({id,runId:r.runId,action:'deferred'});
|
|
98
|
+
}
|
|
99
|
+
})().catch(()=>{}));
|
|
100
|
+
}
|
|
101
|
+
if(!work.length)return out;
|
|
102
|
+
await Promise.race([Promise.all(work),new Promise(r=>setTimeout(r,timeoutMs).unref())]);
|
|
103
|
+
return out;
|
|
104
|
+
}
|
|
105
|
+
/** The local history says how the turn ended too (mlai sessions showed killed runs as running forever). */
|
|
106
|
+
async function markTurn(dir,runId,state,res){
|
|
107
|
+
const f=path.join(dir,'session.json');const m=await readJson(f,null);if(!m||!Array.isArray(m.turns))return;
|
|
108
|
+
const t=m.turns.find(x=>x&&x.runId===runId);if(!t)return;
|
|
109
|
+
if(t.state==='running'||!FINAL.includes(t.state))t.state=state;
|
|
110
|
+
if(!t.finished)t.finished=new Date().toISOString();
|
|
111
|
+
if(res&&Number.isFinite(Number(res.tokens)))t.tokens=Number(res.tokens);
|
|
112
|
+
if(res&&Number.isFinite(Number(res.calls)))t.calls=Number(res.calls);
|
|
113
|
+
await writePrivate(f,m).catch(()=>{});
|
|
114
|
+
}
|
package/src/sandbox.mjs
CHANGED
|
@@ -104,6 +104,12 @@ function extraReadRules(list){return list.length?'(allow file-read* '+list.map(p
|
|
|
104
104
|
export function wrap(cmd,args,{repo,state,runtime,worker,mlaiHome,home=os.homedir(),tmp=os.tmpdir(),busybox,extraRead=[],extraDeny=[],network=null,netOnly=false}){
|
|
105
105
|
const kind=sandboxKind();
|
|
106
106
|
const R=real(repo),S=real(state),RT=real(runtime),W=real(worker),M=real(mlaiHome),T=real(tmp);
|
|
107
|
+
// CLI r5: ~/.mlai is hidden and only the resolved runtime and worker folders are bound back, so a symlinked
|
|
108
|
+
// ~/.mlai/runtime or ~/.mlai/engine made the launcher path vanish inside the box ("execvp ... No such file").
|
|
109
|
+
// Launch through the resolved folder; the file name itself is kept (a venv's python must not be resolved further).
|
|
110
|
+
const under=(p,from,to)=>typeof p==='string'&&from!==to&&(p===from||p.startsWith(from+path.sep))?path.join(to,path.relative(from,p)):p;
|
|
111
|
+
const relink=p=>under(under(p,path.resolve(runtime),RT),path.resolve(worker),W);
|
|
112
|
+
cmd=relink(cmd);args=args.map(relink);if(network?.python)network={...network,python:relink(network.python)};
|
|
107
113
|
if(kind==='seatbelt'){
|
|
108
114
|
if(netOnly&&network)return {kind,network:'os',cmd:'/usr/bin/sandbox-exec',args:['-p',seatbeltNetworkProfile(),cmd,...args]};
|
|
109
115
|
return {kind,...(network?{network:'os'}:{}),cmd:'/usr/bin/sandbox-exec',args:['-p',seatbeltProfile({home,extraRead,extraDeny,network:!network,metaRead:metadataParents(M,[S,RT,W,...extraRead.map(real)])}),'-D','REPO='+R,'-D','STATE='+S,'-D','TMP='+T,'-D','RUNTIME='+RT,'-D','WORKER='+W,'-D','MLAI_HOME='+M,cmd,...args]};
|
|
@@ -119,7 +125,11 @@ export function wrap(cmd,args,{repo,state,runtime,worker,mlaiHome,home=os.homedi
|
|
|
119
125
|
for(const d of CACHE_DIRS){const p=path.join(home,d);if(existsSync(p))b.push('--bind',p,p)}
|
|
120
126
|
for(const d of PRIVATE_DIRS){const p=path.join(home,d);if(existsSync(p))b.push(...(isDir(p)?['--tmpfs',p]:['--ro-bind','/dev/null',p]))}
|
|
121
127
|
b.push('--tmpfs',M,'--ro-bind',RT,RT,'--ro-bind',W,W,'--bind',S,S,'--bind',R,R);
|
|
128
|
+
// A folder inside ~/.mlai that is a symlink (runtime -> a shared install) vanishes under the tmpfs above, and the
|
|
129
|
+
// engine started by that path fails with "execvp ... No such file or directory": bind the target at the link's path too.
|
|
130
|
+
const linked=[[runtime,'--ro-bind'],[worker,'--ro-bind'],[state,'--bind'],...extraRead.map(p=>[p,'--ro-bind'])];
|
|
122
131
|
for(const p of extraRead.map(real))if(existsSync(p))b.push('--ro-bind',p,p);
|
|
132
|
+
for(const [p,mode] of linked){const at=path.resolve(p),r=real(p);if(at!==r&&existsSync(r)&&(at.startsWith(M+'/')||at.startsWith(path.resolve(mlaiHome)+'/')))b.push(mode,r,at)}
|
|
123
133
|
if(T!=='/tmp'&&!T.startsWith('/tmp/'))b.push('--bind',T,T);
|
|
124
134
|
for(const p of extraDeny.map(real))if(existsSync(p))b.push(...(isDir(p)?['--tmpfs',p]:['--ro-bind','/dev/null',p]));
|
|
125
135
|
return {kind,...(network?{network:'os'}:{}),cmd:'bwrap',args:[...b,...net.args,'--chdir',R,...net.launch,cmd,...args]};
|
|
@@ -149,3 +159,25 @@ export function windowsSandboxSid(mlaiHome){
|
|
|
149
159
|
writeFileSync(f,v);return v;
|
|
150
160
|
}
|
|
151
161
|
function isDir(p){try{return statSync(p).isDirectory()}catch{return false}}
|
|
162
|
+
/**
|
|
163
|
+
* Whether the OS sandbox can start here, checked once per process before a run is opened on the server. On Ubuntu
|
|
164
|
+
* 24.04 and some containers bubblewrap is installed but refused ("setting up uid map: Permission denied"); every
|
|
165
|
+
* auto or plan run then ended as an error after zero model calls with no reason recorded.
|
|
166
|
+
* Returns {ok:true} or {ok:false,detail} (the sandbox's first error line, no paths of the project).
|
|
167
|
+
*/
|
|
168
|
+
let probed=null;
|
|
169
|
+
export function sandboxWorks(kind=sandboxKind(),{run=execFileSync,fresh=false}={}){
|
|
170
|
+
if(probed&&!fresh&&probed.kind===kind)return probed.result;
|
|
171
|
+
let result={ok:true};
|
|
172
|
+
const tries=kind==='bwrap'?['bwrap',['--die-with-parent','--ro-bind','/','/','--dev','/dev','--proc','/proc','--tmpfs','/tmp','true']]
|
|
173
|
+
:kind==='seatbelt'?['/usr/bin/sandbox-exec',['-p','(version 1)\n(allow default)','/usr/bin/true']]:null;
|
|
174
|
+
if(tries){
|
|
175
|
+
try{run(tries[0],tries[1],{stdio:['ignore','ignore','pipe'],timeout:10000})}
|
|
176
|
+
catch(e){
|
|
177
|
+
const line=String(e?.stderr||e?.message||'').split('\n').map(s=>s.trim()).find(Boolean)||'it exited with an error';
|
|
178
|
+
result={ok:false,detail:line.replace(/\/[^\s:'"]+/g,'').slice(0,200)};
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
probed={kind,result};
|
|
182
|
+
return result;
|
|
183
|
+
}
|
package/src/session.mjs
CHANGED
|
@@ -11,9 +11,10 @@ import {prepareEngine} from './engine.mjs';
|
|
|
11
11
|
import {projectRoot,projectId,computerCard,gitRemote} from './project.mjs';
|
|
12
12
|
import {ensureRuntime,hideEngineName} from './runtime.mjs';
|
|
13
13
|
import {browserEnv,browserReadPaths,installBrowserFor} from './browser-setup.mjs';
|
|
14
|
-
import {wrap,sandboxKind,SANDBOXES,denyRoots} from './sandbox.mjs';
|
|
14
|
+
import {wrap,sandboxKind,SANDBOXES,denyRoots,sandboxWorks} from './sandbox.mjs';
|
|
15
|
+
import {saveRun,deferClose,forgetRun,errorCode,closeUsage} from './run-record.mjs';
|
|
15
16
|
import {windowsEnv,killTree,ensureBusybox} from './winenv.mjs';
|
|
16
|
-
import {twoWordTitle,isTwoWords} from './two-words.mjs';
|
|
17
|
+
import {twoWordTitle,isTwoWords,titleWords} from './two-words.mjs';
|
|
17
18
|
import {mergeExtensions} from './tui/extensions-local.mjs';
|
|
18
19
|
import {NET_KINDS,startRelay,offlineEnv} from './netbox.mjs';
|
|
19
20
|
|
|
@@ -59,6 +60,28 @@ export function serverRequest(built,{started,task,images=[]}){
|
|
|
59
60
|
}
|
|
60
61
|
/** A title the engine made before two-word names (the first task cut at 80) becomes two words; a rename (meta.renamed) never changes. */
|
|
61
62
|
export function legacyTitle(m){const t=String(m?.title||''),first=String(m?.turns?.[0]?.task||'');return t&&!m.renamed&&!isTwoWords(t)&&first&&first.slice(0,80)===t&&twoWordTitle(first)!==t?twoWordTitle(first):null}
|
|
63
|
+
/** Round 5: what the CLI says when a run reaches the time limit for one run (it used to stop with only "Needs attention"). */
|
|
64
|
+
export const STEP_LIMIT_NOTE='This task used all of its steps for one turn and stopped. Work done so far is kept. To keep going, send "continue" (or later: mlai -c "continue"); -p runs can raise --max-steps.';
|
|
65
|
+
/** Which limit stopped a run. The engine's step limit ends with exit_status LimitsExceeded and no limit field; it used to
|
|
66
|
+
* be reported as the 30-minute limit (a -p run with --max-steps 40 stopped after 3 minutes "at the 30-minute limit"), and so
|
|
67
|
+
* was a run stopped for unfinished verification. */
|
|
68
|
+
export function limitKind(r){
|
|
69
|
+
if(r?.limit)return String(r.limit);
|
|
70
|
+
if(r?.exit_status==='LimitsExceeded')return 'steps';
|
|
71
|
+
if(r?.exit_status==='VerificationIncomplete')return 'verification';
|
|
72
|
+
return 'time';
|
|
73
|
+
}
|
|
74
|
+
export const TIME_LIMIT_NOTE='This task reached the 30-minute limit for one run and stopped. Work done so far is kept. To keep going, send "continue" (or later: mlai -c "continue").';
|
|
75
|
+
/** The error code for a failure before the engine started: the error's own code when it is a plain word. */
|
|
76
|
+
const CODE_OF=e=>typeof e?.code==='string'&&/^[a-z][a-z0-9_]{1,39}$/.test(e.code)?e.code:'start_failed';
|
|
77
|
+
/**
|
|
78
|
+
* The server's title for one run. A follow-up such as "yes", "continue" or "do it" says nothing on its own (it became
|
|
79
|
+
* "Laptop Task" or "Continue Task" on the web); it carries the session's name instead. Up to five meaningful words.
|
|
80
|
+
*/
|
|
81
|
+
export function runTitle(task,sessionTitle){
|
|
82
|
+
const named=String(sessionTitle||'').replace(/\s+/g,' ').trim().slice(0,80);
|
|
83
|
+
return titleWords(task)>=2||!named?twoWordTitle(task,named||'Laptop Task'):named;
|
|
84
|
+
}
|
|
62
85
|
async function writeJson(file,data){const tmp=file+'.tmp';await writeFile(tmp,JSON.stringify(data));await rename(tmp,file)}
|
|
63
86
|
async function readJson(file,fallback){try{return JSON.parse(await readFile(file,'utf8'))}catch{return fallback}}
|
|
64
87
|
/** Images attached to a message (screenshots, mockups). Stored in the session folder; the harness shows them to the model. */
|
|
@@ -158,7 +181,10 @@ export class Session extends EventEmitter{
|
|
|
158
181
|
const sandboxOff=extensions?.sandbox?.enabled===false;
|
|
159
182
|
if(mode==='auto'&&!SANDBOXES.includes(kind)&&!allowUnsandboxed&&!sandboxOff)throw new Error('Auto mode needs an OS sandbox, which is not available here. Use guided mode, or pass --no-sandbox to accept running commands with your full permissions.');
|
|
160
183
|
await this.lock();
|
|
161
|
-
|
|
184
|
+
this.stopCode=null;
|
|
185
|
+
const p=this.#run(task,{cloud,steps,effort,onProgress,mode,kind,images,run,extraEnv,extraRead,starter,finisher,extensions,allowUnsandboxed});
|
|
186
|
+
this.inflight=p;
|
|
187
|
+
try{return await p}finally{this.inflight=null;await rm(path.join(this.dir,'running.lock'),{force:true})}
|
|
162
188
|
}
|
|
163
189
|
/** One task at a time per session across processes: the terminal and the Mac app share ~/.mlai. */
|
|
164
190
|
async lock(){
|
|
@@ -175,7 +201,7 @@ export class Session extends EventEmitter{
|
|
|
175
201
|
}
|
|
176
202
|
throw Object.assign(new Error('This session is busy. Try again.'),{code:'session_busy'});
|
|
177
203
|
}
|
|
178
|
-
async #run(task,{cloud,steps,effort,onProgress,mode,kind,images=[],run,extraEnv,extraRead,starter,finisher,extensions=null}){
|
|
204
|
+
async #run(task,{cloud,steps,effort,onProgress,mode,kind,images=[],run,extraEnv,extraRead,starter,finisher,extensions=null,allowUnsandboxed=false}){
|
|
179
205
|
const python=await ensureRuntime({onProgress});
|
|
180
206
|
// The newest verified harness from the server, or the bundled one (src/engine.mjs); offline runs never check.
|
|
181
207
|
const engine=await prepareEngine({cloud:starter?null:cloud}),worker=engine.dir,used={version:engine.version,source:engine.source};
|
|
@@ -183,23 +209,36 @@ export class Session extends EventEmitter{
|
|
|
183
209
|
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{}}
|
|
184
210
|
// folderProject and repo let a chat that is not filed in a sidebar project get the context of the folder it runs in.
|
|
185
211
|
const repo=this.meta.git?await gitRemote(this.meta.parent||this.meta.root):'';
|
|
186
|
-
|
|
212
|
+
// Restricted mode (src/restricted.mjs) runs every mode in the OS sandbox and never accepts /sandbox off.
|
|
213
|
+
const restricted=extensions?.restricted?.enabled===true;
|
|
214
|
+
let wantSandbox=restricted?SANDBOXES.includes(kind):(mode==='auto'||mode==='plan')&&extensions?.sandbox?.enabled!==false;
|
|
215
|
+
// The sandbox must start before a run is opened (round 5: a refused bubblewrap ended every auto/plan run as an error
|
|
216
|
+
// after zero model calls). --no-sandbox is the person's explicit choice to go on without it; restricted mode never does.
|
|
217
|
+
if(wantSandbox){const w=sandboxWorks(kind);if(!w.ok){
|
|
218
|
+
if(allowUnsandboxed&&!restricted)wantSandbox=false;
|
|
219
|
+
else throw Object.assign(new Error('The OS sandbox ('+(kind==='bwrap'?'bubblewrap':kind==='seatbelt'?'macOS Seatbelt':kind)+') cannot start on this computer: '+w.detail+'. '+(restricted?'Restricted mode cannot run without it.':(mode==='plan'?'Plan':'Auto')+' mode runs commands inside it. Use agent mode (--mode agent, or Shift+Tab), or pass --no-sandbox to run commands with your full permissions.')),{code:'sandbox_unavailable'});
|
|
220
|
+
}}
|
|
221
|
+
const startBody={project:this.meta.cloudProject||this.meta.project,folder:this.meta.folder,folderProject:this.meta.project,...(repo?{repo}:{}),title:runTitle(task,this.meta.title),...(run?{run:{...run,task,...(images.length?{images}:{})}}:{})};
|
|
187
222
|
const started=starter?await starter(startBody):await cloud.start(startBody);
|
|
188
223
|
// The server answered with intake questions instead of starting: nothing ran and no run token was issued.
|
|
189
224
|
if(started?.intake&&!started.token){this.emit('intake',started.intake);return {intake:started.intake}}
|
|
225
|
+
// The run is open on the server from here: every way out below closes it (src/run-record.mjs).
|
|
226
|
+
const close=async(state,usage)=>finisher?await finisher(started.token,state,usage):await cloud.finish(started.token,state,usage);
|
|
227
|
+
const recorded=!finisher&&cloud?.server?await saveRun(this.dir,{runId:started.runId,token:started.token,server:cloud.server}).catch(()=>false):false;
|
|
228
|
+
let spawned=false;
|
|
229
|
+
try{
|
|
190
230
|
await this.archive();
|
|
191
231
|
for(const n of RESET)await rm(path.join(this.dir,n),{force:true});
|
|
192
232
|
for(const f of await readdir(this.dir).catch(()=>[]))if(f.startsWith('decision-'))await rm(path.join(this.dir,f),{force:true});
|
|
193
|
-
// Restricted mode (src/restricted.mjs) runs every mode in the OS sandbox and never accepts /sandbox off.
|
|
194
|
-
const restricted=extensions?.restricted?.enabled===true;
|
|
195
|
-
const wantSandbox=restricted?SANDBOXES.includes(kind):(mode==='auto'||mode==='plan')&&extensions?.sandbox?.enabled!==false;
|
|
196
233
|
const busybox=wantSandbox&&kind==='windows'?await ensureBusybox(home(),{onProgress,server:cloud?.server}):undefined;
|
|
197
234
|
const extraDeny=denyRoots(started.request?.extensions?.hardDeny?.paths,{repo:this.meta.root});
|
|
198
235
|
// The local test browser (src/browser-setup.mjs) for every local run, terminal ones included: without MINI_BROWSER_LOCAL
|
|
199
236
|
// the engine reports "browser runtime is not installed" instead of offering the one-time install. The Mac app passes it already.
|
|
200
237
|
if(!extraEnv?.MINI_BROWSER_LOCAL){const b=await browserEnv(this.dir).catch(()=>null);if(b)extraEnv={...b,...(extraEnv&&typeof extraEnv==='object'?extraEnv:{})}}
|
|
201
238
|
const readDirs=Array.isArray(extraRead)?extraRead.filter(d=>typeof d==='string'&&d):[];// BUG-0499: --add-dir folders, readable without asking
|
|
202
|
-
|
|
239
|
+
// The main coding engine (~/.mlai/kimi-runtime) is read-only inside the sandbox too: hidden with the rest of ~/.mlai,
|
|
240
|
+
// every Auto, Plan and --restricted run fell back to the built-in engine (or reinstalled it into a throwaway folder).
|
|
241
|
+
{const want=[...browserReadPaths(),...(wantSandbox&&existsSync(path.join(home(),'kimi-runtime'))?[path.join(home(),'kimi-runtime')]:[])],have=Array.isArray(extraRead)?extraRead:[];const add=want.filter(p=>!have.includes(p));if(add.length)extraRead=[...have,...add]}
|
|
203
242
|
const box={repo:this.meta.root,state:this.dir,runtime:path.dirname(path.dirname(python)),worker,mlaiHome:home(),busybox,...(Array.isArray(extraRead)&&extraRead.length?{extraRead}:{}),...(extraDeny.length?{extraDeny}:{})};
|
|
204
243
|
const sandboxed=wantSandbox?wrap('x',[],box):null;
|
|
205
244
|
const secrets=started.secrets&&typeof started.secrets==='object'?started.secrets:{};
|
|
@@ -235,12 +274,17 @@ export class Session extends EventEmitter{
|
|
|
235
274
|
env=windowsEnv({...env,PYTHONUTF8:'1',...(launch.env||{})});
|
|
236
275
|
const log=await open(path.join(this.dir,'worker.log'),'a');
|
|
237
276
|
this.offset=0;
|
|
238
|
-
|
|
277
|
+
// fd 3: a pipe this process never writes to. When the CLI ends in any way (kill -9 included) the engine sees it close
|
|
278
|
+
// and stops the run (worker/lifecycle.py watch_parent); it used to keep calling the model with nobody watching.
|
|
279
|
+
const pipe=process.platform!=='win32';
|
|
280
|
+
if(pipe)env.MINI_PARENT_FD='3';
|
|
281
|
+
const child=spawn(launch.cmd,launch.args,{cwd:this.meta.root,env,stdio:['ignore',log.fd,log.fd,...(pipe?['pipe']:[])],detached:process.platform!=='win32',windowsHide:true});
|
|
282
|
+
spawned=true;
|
|
239
283
|
this.child=child;this.emit('started',{runId:started.runId,harness:request.harness||'mini',engine:used,sandbox:sandboxed?.kind||'none',...(netOff?{network:launch.network==='os'?'off (OS)':'off (engine check only)'}:{}),...(restricted?{restricted:true}:{}),// BUG-0477: null account credits means no credit limit (company Unlimited, or a pass for this model); never show the per-run ceiling as "credits left".
|
|
240
284
|
...(started.accountTokensLeft===null&&!started.offline?{uncapped:true}:{}),tokensLeft:started.accountTokensLeft===null?null:started.accountTokensLeft??started.budget??null});
|
|
241
285
|
const timer=setInterval(()=>this.poll().catch(()=>{}),150);
|
|
242
286
|
const exit=await new Promise(resolve=>{child.on('exit',(code,signal)=>resolve({code,signal}));child.on('error',e=>resolve({code:-1,error:e.message}))});
|
|
243
|
-
clearInterval(timer);await this.poll().catch(()=>{});await log.close().catch(()=>{});this.child=null;
|
|
287
|
+
clearInterval(timer);await this.poll().catch(()=>{});await log.close().catch(()=>{});this.child=null;try{child.stdio?.[3]?.destroy?.()}catch{}
|
|
244
288
|
if(relay)await relay.close().catch(()=>{});
|
|
245
289
|
let status=await readJson(path.join(this.dir,'status.json'),{});
|
|
246
290
|
if(!FINAL.includes(status.state)){
|
|
@@ -254,7 +298,12 @@ export class Session extends EventEmitter{
|
|
|
254
298
|
// Which harness ran is part of the final status (the harness rewrites status.json while it runs).
|
|
255
299
|
status={...status,engine:used};await writeJson(path.join(this.dir,'status.json'),status);
|
|
256
300
|
let usage=null;
|
|
257
|
-
|
|
301
|
+
// usage.errorCode: a short fixed reason for an unfinished run (never the error text or a path), so failed runs say why.
|
|
302
|
+
const code=status.state==='completed'?null:errorCode(status,{exit,stopCode:this.stopCode});
|
|
303
|
+
if(code)status={...status,errorCode:code};
|
|
304
|
+
const sent=closeUsage(status,code);
|
|
305
|
+
try{usage=await close(status.state,sent);if(recorded)await forgetRun(this.dir).catch(()=>{})}
|
|
306
|
+
catch(e){usage={error:e.message};if(recorded)await deferClose(this.dir,status.state,sent).catch(()=>{})}
|
|
258
307
|
Object.assign(turn,{state:status.state,finished:new Date().toISOString(),tokens:usage?.tokens??status.tokens??0,calls:usage?.calls??status.calls??0});
|
|
259
308
|
await this.save();
|
|
260
309
|
const result={...status,usage,completion:await readJson(path.join(this.dir,'completion.json'),null)};
|
|
@@ -262,9 +311,23 @@ export class Session extends EventEmitter{
|
|
|
262
311
|
{const cc=await readJson(path.join(this.dir,'cannot-complete.json'),null);if(status.state==='completed'&&cc&&typeof cc.reason==='string'&&cc.reason.trim())result.cannotComplete={reason:cc.reason.trim().slice(0,600)}}
|
|
263
312
|
// The gateway refuses calls once the plan allowance for this run is used; say so plainly.
|
|
264
313
|
if(status.state!=='completed'&&started.budget!=null&&Number(usage?.tokens)>=started.budget){result.code='billing_limit';result.error='Your plan allowance ran out during this task. Changes so far are kept. Upgrade or wait for the allowance to reset, then continue.'}
|
|
314
|
+
// Round 5: the 30-minute limit for one run; the person is told the work is saved and how to go on (src/render.mjs).
|
|
315
|
+
else if(status.state==='limited'&&limitKind(status.result)==='time'){result.code='time_limit';result.error=TIME_LIMIT_NOTE}
|
|
316
|
+
else if(status.state==='limited'&&limitKind(status.result)==='steps'){result.code='step_limit';result.error=STEP_LIMIT_NOTE}
|
|
265
317
|
this.emit('done',result);
|
|
266
318
|
return result;
|
|
267
319
|
}finally{if(relay)await relay.close().catch(()=>{})}
|
|
320
|
+
}catch(e){
|
|
321
|
+
// Failed after the server opened the run but before the engine started (busybox, relay, sandbox wrap, disk): close
|
|
322
|
+
// it as an error with a reason. These runs used to stay "running" on the server for 13 hours.
|
|
323
|
+
if(!spawned){
|
|
324
|
+
const code=CODE_OF(e);
|
|
325
|
+
try{await close('error',{endReason:'error',errorCode:code});if(recorded)await forgetRun(this.dir).catch(()=>{})}
|
|
326
|
+
catch{if(recorded)await deferClose(this.dir,'error',{endReason:'error',errorCode:code}).catch(()=>{})}
|
|
327
|
+
const turn=this.meta.turns.at(-1);if(turn&&turn.runId===started.runId&&turn.state==='running'){turn.state='error';turn.finished=new Date().toISOString();await this.save().catch(()=>{})}
|
|
328
|
+
}
|
|
329
|
+
throw e;
|
|
330
|
+
}
|
|
268
331
|
}
|
|
269
332
|
/** Earlier turns plus the current one, for showing a resumed session. */
|
|
270
333
|
async transcript(){
|
|
@@ -315,6 +378,18 @@ export class Session extends EventEmitter{
|
|
|
315
378
|
const d=path.join(this.dir,'steering');await mkdir(d,{recursive:true});
|
|
316
379
|
await writeJson(path.join(d,Date.now()+'-'+randomUUID().slice(0,8)+'.json'),{message:String(message).slice(0,5000),created:Date.now()});
|
|
317
380
|
}
|
|
381
|
+
/** Steering notes the engine has not read (it consumes and deletes them as it goes), removed and returned oldest
|
|
382
|
+
first. Called after a turn ends, so a late message is sent again instead of being lost or leaking into the next turn. */
|
|
383
|
+
async takeSteering(){
|
|
384
|
+
const d=path.join(this.dir,'steering');let names=[];
|
|
385
|
+
try{names=(await readdir(d)).filter(n=>/^\d+-[\w-]+\.json$/.test(n)).sort()}catch{return []}
|
|
386
|
+
const out=[];
|
|
387
|
+
for(const n of names){
|
|
388
|
+
const f=path.join(d,n);const v=await readJson(f,null);await rm(f,{force:true}).catch(()=>{});
|
|
389
|
+
const m=typeof v?.message==='string'?v.message.trim():'';if(m)out.push(m);
|
|
390
|
+
}
|
|
391
|
+
return out;
|
|
392
|
+
}
|
|
318
393
|
async cancel(){
|
|
319
394
|
await writeFile(path.join(this.dir,'cancel'),'1');
|
|
320
395
|
const c=this.child;if(!c)return;
|
|
@@ -322,11 +397,16 @@ export class Session extends EventEmitter{
|
|
|
322
397
|
}
|
|
323
398
|
/** BUG-0516: the terminal is closing. Ask the engine to stop, wait up to graceMs for it, then end its process group,
|
|
324
399
|
so nothing keeps running (a pending approval kept the engine and its helpers alive after the window closed). */
|
|
325
|
-
async stopNow(graceMs=2500){
|
|
326
|
-
const c=this.child;if(!c)return;
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
400
|
+
async stopNow(graceMs=2500,{closeMs=8000,code='terminal_closed'}={}){
|
|
401
|
+
const c=this.child,p=this.inflight;if(!c&&!p)return;
|
|
402
|
+
this.stopCode=code;
|
|
403
|
+
if(c){
|
|
404
|
+
await writeFile(path.join(this.dir,'cancel'),'1').catch(()=>{});
|
|
405
|
+
const ended=await new Promise(r=>{if(c.exitCode!==null||c.signalCode!==null)return r(true);const t=setTimeout(()=>r(false),graceMs);c.once('exit',()=>{clearTimeout(t);r(true)})});
|
|
406
|
+
if(!ended)killTree(c.pid);
|
|
407
|
+
}
|
|
408
|
+
// Round 5: wait (bounded) until the run is closed on the server; quitting right away left it running there.
|
|
409
|
+
if(p)await Promise.race([p.catch(()=>{}),new Promise(r=>setTimeout(r,closeMs).unref())]);
|
|
330
410
|
}
|
|
331
411
|
}
|
|
332
412
|
export {sandboxKind};
|
package/src/tui/agents-cli.mjs
CHANGED
|
@@ -107,7 +107,8 @@ export async function attachMain(argv,{out,c,stdin=process.stdin,Session,session
|
|
|
107
107
|
const r=await a.done;rl?.close();
|
|
108
108
|
if(r.detached){out(c.dim('Detached. It keeps working: mlai attach '+s.meta.id.slice(0,8)));return 0}
|
|
109
109
|
const status=await import('node:fs/promises').then(f=>f.readFile(path.join(s.dir,'status.json'),'utf8')).then(JSON.parse).catch(()=>({state:r.state}));
|
|
110
|
-
|
|
110
|
+
// CLI r5: status.json keeps tokens and calls at the top level (its usage is the engine's breakdown), so the summary said 0.
|
|
111
|
+
out(render.summaryLine?.({...status,usage:{tokens:status.tokens??status.usage?.tokens,calls:status.calls??status.usage?.calls}},c)||('Finished: '+r.state));
|
|
111
112
|
out(c.dim('Continue it with: mlai -r '+s.meta.id.slice(0,8)));
|
|
112
113
|
return render.exitCode?render.exitCode(status):(r.state==='completed'?0:1);
|
|
113
114
|
}
|