mlai-code 0.3.2 → 0.3.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/package.json +1 -1
- package/src/checkpoints.mjs +217 -0
- package/src/cli.mjs +178 -31
- package/src/cloud.mjs +2 -0
- package/src/engine.mjs +1 -1
- package/src/headless.mjs +25 -9
- package/src/home.mjs +3 -2
- package/src/host.mjs +141 -13
- package/src/ide-quick.mjs +147 -0
- package/src/ide.mjs +182 -0
- package/src/netbox.mjs +1 -1
- package/src/parity.mjs +20 -1
- package/src/relay.mjs +1 -1
- package/src/render.mjs +12 -3
- package/src/runtime.mjs +23 -1
- package/src/sandbox.mjs +19 -3
- package/src/server.mjs +46 -7
- package/src/session.mjs +53 -10
- package/src/shared-data.mjs +1 -1
- package/src/tui/acp.mjs +121 -19
- package/src/tui/app.mjs +24 -5
- package/src/tui/chat.mjs +43 -16
- package/src/tui/cmd-config.mjs +3 -1
- package/src/tui/cmd-core.mjs +11 -7
- package/src/tui/cmd-extensibility.mjs +13 -2
- package/src/tui/commands.mjs +2 -1
- package/src/tui/extensions-local.mjs +2 -0
- package/src/tui/mcp-config.mjs +22 -4
- package/src/tui/review-cli.mjs +15 -4
- package/src/tui/snapshots.mjs +57 -16
- package/src/tui/statusline.mjs +2 -1
- package/src/two-words.mjs +14 -8
- package/src/view-sync.mjs +48 -0
- package/src/wakeups.mjs +2 -2
- package/src/winenv.mjs +1 -1
- package/src/workspace-api.mjs +21 -4
- package/vendor/client-sdk/index.cjs +5 -4
- package/vendor/cloud-cli/mlai.mjs +184 -28
- package/worker/architecture_worker.py +33 -4
- package/worker/browser_tool.py +19 -1
- package/worker/build_planner.py +75 -7
- package/worker/chat_fork.py +4 -1
- package/worker/checkpoints.py +71 -8
- package/worker/cloud_pty.py +91 -2
- package/worker/command_safety.py +80 -3
- package/worker/compaction_brief.py +186 -0
- package/worker/connected_turn.py +30 -0
- package/worker/context_manager.py +6 -0
- package/worker/conversation.py +139 -12
- package/worker/deck_render.js +11 -0
- package/worker/deck_tools.py +825 -0
- package/worker/git_sync.py +42 -17
- package/worker/goals.py +4 -0
- package/worker/image_generation.py +102 -23
- package/worker/kimi_bridge.py +580 -52
- package/worker/kimi_gates.py +74 -6
- package/worker/kimi_hook.py +213 -19
- package/worker/media_tools.py +182 -0
- package/worker/memory.py +2 -2
- package/worker/mlai_hooks.py +314 -5
- package/worker/mlai_mcp.py +49 -11
- package/worker/mlai_review/README.md +35 -0
- package/worker/mlai_review/__init__.py +1 -0
- package/worker/mlai_review/__main__.py +261 -0
- package/worker/mlai_review/_compat.py +29 -0
- package/worker/mlai_review/analysis/__init__.py +3 -0
- package/worker/mlai_review/analysis/detect.py +50 -0
- package/worker/mlai_review/analysis/main.py +128 -0
- package/worker/mlai_review/analysis/messages.py +8 -0
- package/worker/mlai_review/analysis/tools.py +194 -0
- package/worker/mlai_review/application/__init__.py +1 -0
- package/worker/mlai_review/application/asking.py +53 -0
- package/worker/mlai_review/application/challengers.py +142 -0
- package/worker/mlai_review/application/context_builder.py +194 -0
- package/worker/mlai_review/application/errors.py +17 -0
- package/worker/mlai_review/application/feedback.py +52 -0
- package/worker/mlai_review/application/matching.py +46 -0
- package/worker/mlai_review/application/messages.py +41 -0
- package/worker/mlai_review/application/ports.py +222 -0
- package/worker/mlai_review/application/prompts.py +342 -0
- package/worker/mlai_review/application/review_service.py +200 -0
- package/worker/mlai_review/application/reviewers.py +438 -0
- package/worker/mlai_review/application/streaming.py +91 -0
- package/worker/mlai_review/application/tools.py +138 -0
- package/worker/mlai_review/application/usage.py +145 -0
- package/worker/mlai_review/application/write_check.py +46 -0
- package/worker/mlai_review/contracts/__init__.py +5 -0
- package/worker/mlai_review/contracts/analysis.py +57 -0
- package/worker/mlai_review/contracts/review.py +42 -0
- package/worker/mlai_review/domain/__init__.py +4 -0
- package/worker/mlai_review/domain/changes.py +77 -0
- package/worker/mlai_review/domain/context.py +147 -0
- package/worker/mlai_review/domain/diagnostics.py +239 -0
- package/worker/mlai_review/domain/feedback.py +216 -0
- package/worker/mlai_review/domain/findings.py +505 -0
- package/worker/mlai_review/domain/lifecycle.py +85 -0
- package/worker/mlai_review/domain/partition.py +42 -0
- package/worker/mlai_review/domain/relations.py +166 -0
- package/worker/mlai_review/domain/relevance.py +202 -0
- package/worker/mlai_review/domain/report.py +99 -0
- package/worker/mlai_review/domain/structure.py +56 -0
- package/worker/mlai_review/domain/writes.py +86 -0
- package/worker/mlai_review/eval.py +221 -0
- package/worker/mlai_review/eval_cases/clean-rename.json +11 -0
- package/worker/mlai_review/eval_cases/missing-ownership-check.json +22 -0
- package/worker/mlai_review/eval_cases/off-by-one.json +22 -0
- package/worker/mlai_review/eval_cases/sql-injection.json +20 -0
- package/worker/mlai_review/feedback_report.py +60 -0
- package/worker/mlai_review/infrastructure/__init__.py +1 -0
- package/worker/mlai_review/infrastructure/analysis/__init__.py +1 -0
- package/worker/mlai_review/infrastructure/analysis/none.py +12 -0
- package/worker/mlai_review/infrastructure/analysis/translate.py +17 -0
- package/worker/mlai_review/infrastructure/github/__init__.py +0 -0
- package/worker/mlai_review/infrastructure/github/client.py +445 -0
- package/worker/mlai_review/infrastructure/github/feedback.py +212 -0
- package/worker/mlai_review/infrastructure/github/http.py +31 -0
- package/worker/mlai_review/infrastructure/github/rendering.py +398 -0
- package/worker/mlai_review/infrastructure/github/token.py +20 -0
- package/worker/mlai_review/infrastructure/local/__init__.py +1 -0
- package/worker/mlai_review/infrastructure/local/analyzer.py +48 -0
- package/worker/mlai_review/infrastructure/local/events.py +100 -0
- package/worker/mlai_review/infrastructure/local/git_reader.py +233 -0
- package/worker/mlai_review/infrastructure/local/publisher.py +138 -0
- package/worker/mlai_review/infrastructure/messages.py +54 -0
- package/worker/mlai_review/infrastructure/models/__init__.py +0 -0
- package/worker/mlai_review/infrastructure/models/openai_compatible.py +269 -0
- package/worker/mlai_review/infrastructure/structure/__init__.py +1 -0
- package/worker/mlai_review/infrastructure/structure/heuristic.py +186 -0
- package/worker/mlai_review/infrastructure/structure/tree_sitter.py +186 -0
- package/worker/mlai_review/infrastructure/workspace/__init__.py +1 -0
- package/worker/mlai_review/infrastructure/workspace/local.py +105 -0
- package/worker/mlai_review/infrastructure/workspace/memory.py +77 -0
- package/worker/mlai_review/infrastructure/workspace/paths.py +17 -0
- package/worker/mlai_review/pipeline.py +89 -0
- package/worker/mlai_review/runtime.py +194 -0
- package/worker/mlai_review/settings.py +139 -0
- package/worker/model_stream.py +21 -7
- package/worker/offline_guard.py +1 -1
- package/worker/preview.py +62 -4
- package/worker/product_facts.py +20 -0
- package/worker/project_context.py +33 -7
- package/worker/reply_language.py +92 -10
- package/worker/repo_policy.py +5 -0
- package/worker/roles.json +199 -37
- package/worker/roles.py +271 -9
- package/worker/runner.py +366 -53
- package/worker/runtime_control.py +64 -3
- package/worker/secret_scan.py +3 -2
- package/worker/server_memory.py +122 -0
- package/worker/site_check.py +279 -0
- package/worker/skill_library.py +15 -3
- package/worker/skill_pack.py +170 -16
- package/worker/subagents.py +6 -2
- package/worker/tool_catalog.py +4 -3
- package/worker/verification.py +156 -19
- package/worker/wakeups.py +56 -4
package/src/render.mjs
CHANGED
|
@@ -11,6 +11,8 @@ export function prose(text){
|
|
|
11
11
|
}
|
|
12
12
|
const clip=(s,n)=>{s=String(s??'');return s.length>n?s.slice(0,n-1)+'…':s};
|
|
13
13
|
export const fmt=n=>Number(n||0).toLocaleString('en-US');
|
|
14
|
+
/** Usage for people is always credits (1 credit = 1M billable units), never a raw count. */
|
|
15
|
+
export const credits=n=>{const c=Math.max(0,Number(n)||0)/1e6;if(c>0&&c<0.01)return 'under 0.01 credits';const v=c>=1000?Math.round(c).toLocaleString('en-US'):c>=100?String(Math.round(c)):c>=1?String(Math.round(c*10)/10):String(Math.round(c*100)/100);return v+(v==='1'?' credit':' credits')};
|
|
14
16
|
|
|
15
17
|
/** Edit approvals arrive as "Edit path\nREMOVE:\n…\nREPLACE WITH:\n…"; show them as a diff. */
|
|
16
18
|
export function approvalView(a,c=palette(false)){
|
|
@@ -23,6 +25,12 @@ export function approvalView(a,c=palette(false)){
|
|
|
23
25
|
for(const l of strip(m[3]).slice(0,60))lines.push(c.green('+ '+l));
|
|
24
26
|
return {kind:'edit',path:m[1],text:lines.join('\n')};
|
|
25
27
|
}
|
|
28
|
+
// BUG-0514: a file write is shown as a file write, not as "Run command $ Write ...".
|
|
29
|
+
const w=/^Write (.+?)(?: \((\d+) characters\))?(?:\n([\s\S]*))?$/.exec(text);
|
|
30
|
+
if(w&&(a.kind!=='command'||w[2])&&!/[;&|`$<>]/.test(w[1])){
|
|
31
|
+
const body=(w[3]||'').replace(/\n$/,'').split('\n').slice(0,60);
|
|
32
|
+
return {kind:'edit',path:w[1],text:[c.bold('Write file '+w[1])+(w[2]?c.dim(' ('+w[2]+' characters)'):''),...(w[3]?body.map(l=>c.green('+ '+l)):[])].join('\n')};
|
|
33
|
+
}
|
|
26
34
|
if(a.kind==='plan')return {kind:'plan',text:c.bold('Review the plan')+'\n'+(a.items||[]).map(t=>' - '+t).join('\n')};
|
|
27
35
|
return {kind:'command',text:c.bold('Run command')+'\n '+c.cyan('$ '+clip(text,2000))};
|
|
28
36
|
}
|
|
@@ -57,10 +65,11 @@ export function renderEvent(e,{c=palette(false),verbose=false}={}){
|
|
|
57
65
|
}
|
|
58
66
|
}
|
|
59
67
|
|
|
60
|
-
export const EXIT={completed:0,error:1,usage:2,limited:3,auth:4,billing:5,stopped:130,interrupted:1}
|
|
68
|
+
export const EXIT={completed:0,error:1,usage:2,limited:3,auth:4,billing:5,cannotComplete:6,stopped:130,interrupted:1};// BUG-0523: 6 = the agent reported the request cannot be done
|
|
61
69
|
export function exitCode(result){
|
|
62
70
|
if(!result)return EXIT.error;
|
|
63
71
|
if(result.code==='billing_limit')return EXIT.billing;
|
|
72
|
+
if(result.state==='completed'&&result.cannotComplete)return EXIT.cannotComplete;
|
|
64
73
|
if(result.state==='completed')return EXIT.completed;
|
|
65
74
|
if(result.state==='limited')return EXIT.limited;
|
|
66
75
|
if(result.state==='stopped')return EXIT.stopped;
|
|
@@ -68,6 +77,6 @@ export function exitCode(result){
|
|
|
68
77
|
}
|
|
69
78
|
export function summaryLine(result,c=palette(false)){
|
|
70
79
|
const u=result.usage||{};
|
|
71
|
-
const state=result.state==='completed'?c.green('Done'):result.state==='limited'?c.yellow('Needs attention'):result.state==='stopped'?c.yellow('Stopped'):c.red('Failed');
|
|
72
|
-
return state+c.dim(' · '+
|
|
80
|
+
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');
|
|
81
|
+
return state+c.dim(' · '+credits(u.tokens)+' · '+fmt(u.calls)+' model calls');
|
|
73
82
|
}
|
package/src/runtime.mjs
CHANGED
|
@@ -9,6 +9,8 @@ const run=promisify(execFile);
|
|
|
9
9
|
export const PY_PACKAGES=['mini-swe-agent==2.4.6'];
|
|
10
10
|
export const PY_VERSION='3.12';
|
|
11
11
|
const key='py'+PY_VERSION+'-'+PY_PACKAGES.join('_').replace(/[^\w.]+/g,'-');
|
|
12
|
+
/** BUG-0474: user-facing text names the runtime folder "engine", not the third-party package it is built from. */
|
|
13
|
+
export const hideEngineName=t=>String(t??'').split(key).join('engine').replace(/mini[-_]?swe[-_]?agent(?:==[\w.]+)?/gi,'engine');
|
|
12
14
|
const bin=dir=>process.platform==='win32'?path.join(dir,'Scripts','python.exe'):path.join(dir,'bin','python');
|
|
13
15
|
|
|
14
16
|
async function which(name){
|
|
@@ -43,6 +45,26 @@ async function works(python){
|
|
|
43
45
|
* A private Python for the harness in ~/.mlai/runtime. Uses the bundled or installed uv, which also downloads
|
|
44
46
|
* a standalone Python, so the developer installs nothing. Falls back to python3 -m venv. Never touches system Python.
|
|
45
47
|
*/
|
|
48
|
+
/**
|
|
49
|
+
* Why a setup step failed, from its output. Some tools print the reason on stdout and nothing on stderr (Debian and
|
|
50
|
+
* Ubuntu's python3 -m venv without the python3-venv package), so stdout is used when stderr is empty.
|
|
51
|
+
*/
|
|
52
|
+
export function stepError(label,{stdout='',stderr=''}={}){
|
|
53
|
+
const out=String(stderr).trim()||String(stdout).trim();
|
|
54
|
+
const tail=out.split('\n').map(l=>l.trim()).filter(Boolean).slice(-3).join(' ');
|
|
55
|
+
const venv=/ensurepip|python3(\.\d+)?-venv/i.test(stdout+'\n'+stderr)?' Install the python3-venv package (for example: sudo apt install python3-venv) or uv (https://docs.astral.sh/uv/), then run mlai doctor --fix.':'';
|
|
56
|
+
const msg=label+' failed'+(tail?': '+tail:' with no output');
|
|
57
|
+
return new Error(venv?msg.replace(/[.\s]*$/,'.')+venv:msg);
|
|
58
|
+
}
|
|
59
|
+
/** Runs one setup command, keeping the end of both outputs for the error message. */
|
|
60
|
+
export function runStep(label,cmd,args,{onProgress=()=>{},spawnImpl=spawn}={}){
|
|
61
|
+
onProgress(label);
|
|
62
|
+
return new Promise((resolve,reject)=>{
|
|
63
|
+
const c=spawnImpl(cmd,args,{stdio:['ignore','pipe','pipe'],env:{UV_SYSTEM_CERTS:'1',UV_NATIVE_TLS:'1',...process.env,UV_PYTHON_PREFERENCE:'managed',PIP_DISABLE_PIP_VERSION_CHECK:'1'}});
|
|
64
|
+
let err='',out='';c.stderr?.on('data',d=>{err=(err+d).slice(-4000)});c.stdout?.on('data',d=>{out=(out+d).slice(-4000)});
|
|
65
|
+
c.on('error',reject);c.on('exit',code=>code===0?resolve():reject(stepError(label,{stdout:out,stderr:err})));
|
|
66
|
+
});
|
|
67
|
+
}
|
|
46
68
|
let inflight=null;
|
|
47
69
|
/** Single flight: the app warms the runtime when a folder opens, and the first task may ask for it at the same time. */
|
|
48
70
|
export function ensureRuntime(opts={}){
|
|
@@ -56,7 +78,7 @@ async function prepareRuntime({onProgress=()=>{},force=false}={}){
|
|
|
56
78
|
if(!force&&existsSync(marker)&&await works(python))return python;
|
|
57
79
|
await rm(dir,{recursive:true,force:true});
|
|
58
80
|
const uv=await which('uv');
|
|
59
|
-
const step=
|
|
81
|
+
const step=(label,cmd,args)=>runStep(label,cmd,args,{onProgress});
|
|
60
82
|
if(uv){
|
|
61
83
|
await step('Preparing Python '+PY_VERSION,uv,['venv','--quiet','--python',PY_VERSION,dir]);
|
|
62
84
|
await step('Installing the coding engine',uv,['pip','install','--quiet','--python',python,...PY_PACKAGES]);
|
package/src/sandbox.mjs
CHANGED
|
@@ -46,7 +46,7 @@ export function sandboxKind(){
|
|
|
46
46
|
* temp folders and package caches, and credential folders cannot be read. Network stays on (the model, package installs)
|
|
47
47
|
* unless network is false (see NETWORK_OFF).
|
|
48
48
|
*/
|
|
49
|
-
export function seatbeltProfile({home=os.homedir(),extraRead=[],extraDeny=[],network=true}={}){
|
|
49
|
+
export function seatbeltProfile({home=os.homedir(),extraRead=[],extraDeny=[],network=true,metaRead=[]}={}){
|
|
50
50
|
// Seatbelt matches resolved paths (/var is /private/var on macOS), so rules use the real home folder. macOS paths
|
|
51
51
|
// only: on another host (the profile tests) path.resolve would turn /Users/dev into D:\Users\dev.
|
|
52
52
|
home=process.platform==='win32'?home:real(home);
|
|
@@ -63,7 +63,7 @@ export function seatbeltProfile({home=os.homedir(),extraRead=[],extraDeny=[],net
|
|
|
63
63
|
${caches})
|
|
64
64
|
(deny file-read* ${secrets} (subpath (param "MLAI_HOME")))
|
|
65
65
|
(allow file-read* (subpath (param "STATE")) (subpath (param "RUNTIME")) (subpath (param "WORKER")))
|
|
66
|
-
${extraReadRules(extraRead)}${extraDenyRules(extraDeny)}${network===false?NETWORK_OFF:''}`;
|
|
66
|
+
${metaReadRules(metaRead)}${extraReadRules(extraRead)}${extraDenyRules(extraDeny)}${network===false?NETWORK_OFF:''}`;
|
|
67
67
|
}
|
|
68
68
|
/**
|
|
69
69
|
* Network off for Seatbelt (src/netbox.mjs): no network at all except loopback (the model relay, dev servers on
|
|
@@ -78,6 +78,22 @@ export const NETWORK_OFF=`(deny network*)
|
|
|
78
78
|
export function seatbeltNetworkProfile(){return '(version 1)\n(allow default)\n'+NETWORK_OFF}
|
|
79
79
|
/** Hard-deny roots come last so they win over every allow above. */
|
|
80
80
|
function extraDenyRules(list){return list.length?'(deny file-read* file-write* '+list.map(p=>'(subpath '+JSON.stringify(real(p))+')').join(' ')+')\n':''}
|
|
81
|
+
/**
|
|
82
|
+
* The folders between ~/.mlai and each allowed folder inside it (~/.mlai, ~/.mlai/runtime, ~/.mlai/sessions...), for
|
|
83
|
+
* metadata only: realpath() and stat() walk every parent, so without this Python cannot resolve its own bin folder
|
|
84
|
+
* ("realpath: Operation not permitted") in Ask, Plan and /side runs. Listing or reading these folders stays denied.
|
|
85
|
+
*/
|
|
86
|
+
export function metadataParents(mlaiHome,inside=[]){
|
|
87
|
+
const M=path.posix.normalize(mlaiHome).replace(/\/$/,'');const out=new Set();
|
|
88
|
+
for(const raw of inside){
|
|
89
|
+
if(typeof raw!=='string'||!raw)continue;let p=path.posix.normalize(raw).replace(/\/$/,'');
|
|
90
|
+
if(p!==M&&!p.startsWith(M+'/'))continue;
|
|
91
|
+
out.add(M);
|
|
92
|
+
for(p=path.posix.dirname(p);p.startsWith(M+'/');p=path.posix.dirname(p))out.add(p);
|
|
93
|
+
}
|
|
94
|
+
return [...out].sort();
|
|
95
|
+
}
|
|
96
|
+
function metaReadRules(list){return list.length?'(allow file-read-metadata '+list.map(p=>'(literal '+JSON.stringify(p)+')').join(' ')+')\n':''}
|
|
81
97
|
/** Read-only folders inside ~/.mlai the agent's processes need (the test browser in ~/.mlai/runtime/pw-browsers). Last rule wins, so these follow the MLAI_HOME deny. */
|
|
82
98
|
function extraReadRules(list){return list.length?'(allow file-read* '+list.map(p=>'(subpath '+JSON.stringify(real(p))+')').join(' ')+')\n':''}
|
|
83
99
|
/**
|
|
@@ -90,7 +106,7 @@ export function wrap(cmd,args,{repo,state,runtime,worker,mlaiHome,home=os.homedi
|
|
|
90
106
|
const R=real(repo),S=real(state),RT=real(runtime),W=real(worker),M=real(mlaiHome),T=real(tmp);
|
|
91
107
|
if(kind==='seatbelt'){
|
|
92
108
|
if(netOnly&&network)return {kind,network:'os',cmd:'/usr/bin/sandbox-exec',args:['-p',seatbeltNetworkProfile(),cmd,...args]};
|
|
93
|
-
return {kind,...(network?{network:'os'}:{}),cmd:'/usr/bin/sandbox-exec',args:['-p',seatbeltProfile({home,extraRead,extraDeny,network:!network}),'-D','REPO='+R,'-D','STATE='+S,'-D','TMP='+T,'-D','RUNTIME='+RT,'-D','WORKER='+W,'-D','MLAI_HOME='+M,cmd,...args]};
|
|
109
|
+
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]};
|
|
94
110
|
}
|
|
95
111
|
if(kind==='bwrap'){
|
|
96
112
|
// Network off: an empty network namespace, the relay's socket folder bound in, and netjail.py (run by the same
|
package/src/server.mjs
CHANGED
|
@@ -9,6 +9,7 @@ import {home,DEFAULT_SERVER} from './home.mjs';
|
|
|
9
9
|
import {Cloud,friendly} from './cloud.mjs';
|
|
10
10
|
import {loadLogin} from './credentials.mjs';
|
|
11
11
|
import {EngineHost,HostError} from './host.mjs';
|
|
12
|
+
import {createQuick,QUICK_ROUTES} from './ide-quick.mjs';
|
|
12
13
|
|
|
13
14
|
const WIN=process.platform==='win32';
|
|
14
15
|
/** Unix socket in ~/.mlai (owner-only), or on Windows a named pipe per user and data folder. */
|
|
@@ -29,9 +30,11 @@ function authorized(req,token){
|
|
|
29
30
|
return got.length===want.length&&timingSafeEqual(got,want);
|
|
30
31
|
}
|
|
31
32
|
const MAX_BODY=64000;
|
|
33
|
+
// Pasted images arrive base64 encoded (up to 5 MB each).
|
|
34
|
+
const IMAGE_BODY=7_200_000;
|
|
32
35
|
|
|
33
|
-
async function body(req){
|
|
34
|
-
let raw='';for await(const c of req){raw+=c;if(raw.length>
|
|
36
|
+
async function body(req,max=MAX_BODY){
|
|
37
|
+
let raw='';for await(const c of req){raw+=c;if(raw.length>max)throw new HostError('Request too large',413)}
|
|
35
38
|
if(!raw)return {};
|
|
36
39
|
try{const v=JSON.parse(raw);if(!v||typeof v!=='object'||Array.isArray(v))throw 0;return v}catch{throw new HostError('Invalid JSON')}
|
|
37
40
|
}
|
|
@@ -43,8 +46,16 @@ export async function terminalCloud(){
|
|
|
43
46
|
return new Cloud({server:(process.env.MLAI_SERVER||l.server||DEFAULT_SERVER).replace(/\/$/,''),token:l.token});
|
|
44
47
|
}
|
|
45
48
|
|
|
46
|
-
|
|
49
|
+
/** What this engine's API offers beyond the original routes, so editors can work with older installed engines. */
|
|
50
|
+
export const FEATURES=['login','models','context','modes','checkpoints','changes','revert','restore','fork','handoff','images','annotate','worktree','mcp','plan-review'];
|
|
51
|
+
const SERVER_URL=/^https?:\/\/[^\s/?#]+(\/[^\s?#]*)?$/;
|
|
52
|
+
export function createEngineServer({cloud:base=terminalCloud}={}){
|
|
53
|
+
// An editor plugin can hand the engine its own sign-in (POST /v1/login). It stays in memory for this process and
|
|
54
|
+
// wins over the CLI's saved login, so a plugin signed in to another server never changes the terminal's account.
|
|
55
|
+
let signIn=null;
|
|
56
|
+
const cloud=async()=>signIn?new Cloud(signIn):base();
|
|
47
57
|
const host=new EngineHost({cloud});
|
|
58
|
+
const quick=createQuick({cloud});
|
|
48
59
|
const subscribers=new Map(); // session id -> Set<res>
|
|
49
60
|
host.on('session',({id,type,data})=>{for(const r of subscribers.get(id)||[])sse(r,type,data)});
|
|
50
61
|
const token=WIN?engineToken():null;
|
|
@@ -53,8 +64,20 @@ export function createEngineServer({cloud=terminalCloud}={}){
|
|
|
53
64
|
if(!authorized(req,token))throw new HostError('Missing or wrong engine token',401);
|
|
54
65
|
const url=new URL(req.url,'http://mlaid');const [v,a,id,b]=url.pathname.split('/').filter(Boolean);
|
|
55
66
|
if(v!=='v1')throw new HostError('Not found',404);
|
|
56
|
-
if(req.method==='GET'&&a==='health')return send(res,200,host.health());
|
|
67
|
+
if(req.method==='GET'&&a==='health')return send(res,200,{...host.health(),features:[...FEATURES,...(Array.isArray(quick.features)?quick.features:QUICK_ROUTES)]});
|
|
57
68
|
if(req.method==='GET'&&a==='doctor')return send(res,200,await host.doctor());
|
|
69
|
+
if(a==='login'&&!id){
|
|
70
|
+
if(req.method==='DELETE'){signIn=null;return send(res,200,{ok:true})}
|
|
71
|
+
if(req.method!=='POST')throw new HostError('Method not allowed',405);
|
|
72
|
+
const d=await body(req);
|
|
73
|
+
if(typeof d.token!=='string'||d.token.length<8||d.token.length>4000||/\s/.test(d.token))throw new HostError('Send the sign-in token');
|
|
74
|
+
if(d.server!=null&&(typeof d.server!=='string'||!SERVER_URL.test(d.server)||!/^https:|^http:\/\/(127\.0\.0\.1|localhost)(:|\/|$)/.test(d.server)))throw new HostError('Server must be an https URL');
|
|
75
|
+
const next={server:String(d.server||process.env.MLAI_SERVER||DEFAULT_SERVER).replace(/\/$/,''),token:d.token};
|
|
76
|
+
if(d.verify===false){signIn=next;return send(res,200,{signedIn:true,server:next.server})}
|
|
77
|
+
try{const me=await new Cloud(next).whoami();signIn=next;return send(res,200,{signedIn:true,server:next.server,...me})}catch(e){throw new HostError(friendly(e),401,'not_signed_in')}
|
|
78
|
+
}
|
|
79
|
+
if(req.method==='GET'&&a==='models'&&!id)return send(res,200,await host.models());
|
|
80
|
+
if(req.method==='POST'&&QUICK_ROUTES.includes(a)&&!id)return quick.handle(a,req,res);
|
|
58
81
|
if(req.method==='GET'&&a==='account'){
|
|
59
82
|
try{const me=await (await cloud()).whoami();return send(res,200,{signedIn:true,...me})}catch(e){return send(res,200,{signedIn:false,error:friendly(e)})}
|
|
60
83
|
}
|
|
@@ -66,6 +89,9 @@ export function createEngineServer({cloud=terminalCloud}={}){
|
|
|
66
89
|
}
|
|
67
90
|
if(req.method==='GET'&&!b)return send(res,200,await host.get(id));
|
|
68
91
|
if(req.method==='GET'&&b==='transcript')return send(res,200,await host.transcript(id));
|
|
92
|
+
if(req.method==='GET'&&b==='checkpoints')return send(res,200,await host.checkpoints(id));
|
|
93
|
+
if(req.method==='GET'&&b==='changes')return send(res,200,await host.changes(id,{since:url.searchParams.get('since')||undefined}));
|
|
94
|
+
if(req.method==='GET'&&b==='images'&&url.searchParams.get('name'))return send(res,200,await host.image(id,url.searchParams.get('name')));
|
|
69
95
|
if(req.method==='GET'&&b==='events'){
|
|
70
96
|
const info=await host.get(id);
|
|
71
97
|
res.writeHead(200,{'Content-Type':'text/event-stream','Cache-Control':'no-store',Connection:'keep-alive'});
|
|
@@ -76,19 +102,32 @@ export function createEngineServer({cloud=terminalCloud}={}){
|
|
|
76
102
|
req.on('close',()=>{clearInterval(ping);subscribers.get(id)?.delete(res)});return;
|
|
77
103
|
}
|
|
78
104
|
if(req.method!=='POST')throw new HostError('Method not allowed',405);
|
|
79
|
-
|
|
105
|
+
if(b==='images'){
|
|
106
|
+
const d=await body(req,IMAGE_BODY);
|
|
107
|
+
if(typeof d.data!=='string'||!d.data)throw new HostError('Send the image as base64 data');
|
|
108
|
+
const raw=d.data.replace(/^data:image\/[\w+.-]+;base64,/,'');
|
|
109
|
+
return send(res,201,await host.addImage(id,Buffer.from(raw,'base64')));
|
|
110
|
+
}
|
|
111
|
+
const d=await body(req,b==='messages'?4*IMAGE_BODY:MAX_BODY);
|
|
80
112
|
if(b==='messages')return send(res,202,await host.start(id,d));
|
|
81
113
|
if(b==='decisions')return send(res,200,await host.decide(id,d));
|
|
82
114
|
if(b==='steer')return send(res,200,await host.steer(id,d));
|
|
83
115
|
if(b==='cancel')return send(res,200,await host.cancel(id));
|
|
84
116
|
if(b==='mode')return send(res,200,await host.mode(id,d));
|
|
117
|
+
if(b==='restore')return send(res,200,await host.restore(id,d));
|
|
118
|
+
if(b==='revert')return send(res,200,await host.revert(id,d));
|
|
119
|
+
if(b==='fork')return send(res,201,await host.fork(id,d));
|
|
120
|
+
if(b==='handoff')return send(res,200,await host.handoff(id,d));
|
|
121
|
+
if(b==='annotate')return send(res,200,await host.annotate(id,d));
|
|
122
|
+
if(b==='worktree')return send(res,200,await host.worktree(id,d));
|
|
123
|
+
if(b==='mcp')return send(res,200,await host.setMcp(id,d));
|
|
85
124
|
throw new HostError('Not found',404);
|
|
86
125
|
}catch(err){
|
|
87
126
|
if(res.headersSent)return res.end();
|
|
88
127
|
send(res,err instanceof HostError?err.status:500,{error:err instanceof HostError?err.message:friendly(err),...(err.code?{code:err.code}:{})});
|
|
89
128
|
}
|
|
90
129
|
});
|
|
91
|
-
server.host=host;
|
|
130
|
+
server.host=host;server.quick=quick;
|
|
92
131
|
return server;
|
|
93
132
|
}
|
|
94
133
|
|
|
@@ -105,6 +144,6 @@ export async function serve({socket=socketPath(),cloud}={}){
|
|
|
105
144
|
const old=WIN?null:process.umask(0o177);
|
|
106
145
|
try{await new Promise((resolve,reject)=>{server.once('error',e=>reject(e.code==='EADDRINUSE'?new Error('The ML AI Code engine is already running.'):e));server.listen(socket,resolve)})}finally{if(!WIN)process.umask(old)}
|
|
107
146
|
if(!WIN)await chmod(socket,0o600);
|
|
108
|
-
const close=async()=>{await server.host.close();server.closeAllConnections?.();server.close();if(!WIN)await rm(socket,{force:true})};
|
|
147
|
+
const close=async()=>{try{server.quick?.close()}catch{}await server.host.close();server.closeAllConnections?.();server.close();if(!WIN)await rm(socket,{force:true})};
|
|
109
148
|
return {server,socket,close};
|
|
110
149
|
}
|
package/src/session.mjs
CHANGED
|
@@ -9,7 +9,8 @@ import os from 'node:os';
|
|
|
9
9
|
import {home,sub} from './home.mjs';
|
|
10
10
|
import {prepareEngine} from './engine.mjs';
|
|
11
11
|
import {projectRoot,projectId,computerCard,gitRemote} from './project.mjs';
|
|
12
|
-
import {ensureRuntime} from './runtime.mjs';
|
|
12
|
+
import {ensureRuntime,hideEngineName} from './runtime.mjs';
|
|
13
|
+
import {browserEnv,browserReadPaths,installBrowserFor} from './browser-setup.mjs';
|
|
13
14
|
import {wrap,sandboxKind,SANDBOXES,denyRoots} from './sandbox.mjs';
|
|
14
15
|
import {windowsEnv,killTree,ensureBusybox} from './winenv.mjs';
|
|
15
16
|
import {twoWordTitle,isTwoWords} from './two-words.mjs';
|
|
@@ -21,7 +22,9 @@ export const MODES={guided:'approve',auto:'auto',plan:'plan'};
|
|
|
21
22
|
export const RUN_MODES={approve:'guided',auto:'auto',plan:'plan',brief:'guided'};
|
|
22
23
|
const ENTRIES=['runner.py','kimi_bridge.py'];
|
|
23
24
|
/** Only non-secret settings the server may hand to the harness (gateway URLs, versions, model names). */
|
|
24
|
-
|
|
25
|
+
// MINI_MEDIA_GATEWAY (stock photos, brand lookup): CLI bug list 0.3.3, every stock photo call said "not configured"
|
|
26
|
+
// because the server sent it and this list dropped it.
|
|
27
|
+
const SERVER_ENV=/^(MINI_IMAGE_GATEWAY|MINI_MEDIA_GATEWAY|MINI_RESEARCH_GATEWAY|MINI_KIMI_VERSION|OPENROUTER_IMAGE_MODEL|MLAI_HUB_URL)$/;
|
|
25
28
|
export function serverEnv(env){
|
|
26
29
|
const out={};
|
|
27
30
|
for(const [k,v] of Object.entries(env&&typeof env==='object'?env:{}))if(SERVER_ENV.test(k)&&typeof v==='string'&&v.length<2000)out[k]=v;
|
|
@@ -36,7 +39,7 @@ export function vaultEnv(secrets){
|
|
|
36
39
|
}
|
|
37
40
|
export function redact(text,values){let out=String(text||'');for(const v of values)if(typeof v==='string'&&v.length>=4)out=out.split(v).join('[redacted]');return out}
|
|
38
41
|
const FINAL=['completed','limited','error','stopped','interrupted'];
|
|
39
|
-
const RESET=['inference-progress.json','cancel','events.jsonl','pending.json','checks.json','todos.json','completion.json','steering.json','design-review.json','status.json'];
|
|
42
|
+
const RESET=['inference-progress.json','cancel','events.jsonl','pending.json','checks.json','todos.json','completion.json','steering.json','design-review.json','status.json','cannot-complete.json'];
|
|
40
43
|
/** Environment variables that look like credentials stay out of the agent's processes unless allowed. */
|
|
41
44
|
const SECRET_ENV=/(TOKEN|SECRET|PASSWORD|PASSWD|API_?KEY|PRIVATE_?KEY|CREDENTIAL|SESSION_?KEY|AUTH)/i;
|
|
42
45
|
export function agentEnv(base=process.env,allow=(base.MLAI_PASS_ENV||'').split(',').map(s=>s.trim()).filter(Boolean)){
|
|
@@ -55,7 +58,7 @@ export function serverRequest(built,{started,task,images=[]}){
|
|
|
55
58
|
...(rest.accountTokensLeft===undefined?{accountTokensLeft:started.budget??null}:{}),...(images.length?{images}:{})};
|
|
56
59
|
}
|
|
57
60
|
/** A title the engine made before two-word names (the first task cut at 80) becomes two words; a rename (meta.renamed) never changes. */
|
|
58
|
-
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):null}
|
|
61
|
+
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}
|
|
59
62
|
async function writeJson(file,data){const tmp=file+'.tmp';await writeFile(tmp,JSON.stringify(data));await rename(tmp,file)}
|
|
60
63
|
async function readJson(file,fallback){try{return JSON.parse(await readFile(file,'utf8'))}catch{return fallback}}
|
|
61
64
|
/** Images attached to a message (screenshots, mockups). Stored in the session folder; the harness shows them to the model. */
|
|
@@ -192,6 +195,11 @@ export class Session extends EventEmitter{
|
|
|
192
195
|
const wantSandbox=restricted?SANDBOXES.includes(kind):(mode==='auto'||mode==='plan')&&extensions?.sandbox?.enabled!==false;
|
|
193
196
|
const busybox=wantSandbox&&kind==='windows'?await ensureBusybox(home(),{onProgress,server:cloud?.server}):undefined;
|
|
194
197
|
const extraDeny=denyRoots(started.request?.extensions?.hardDeny?.paths,{repo:this.meta.root});
|
|
198
|
+
// The local test browser (src/browser-setup.mjs) for every local run, terminal ones included: without MINI_BROWSER_LOCAL
|
|
199
|
+
// the engine reports "browser runtime is not installed" instead of offering the one-time install. The Mac app passes it already.
|
|
200
|
+
if(!extraEnv?.MINI_BROWSER_LOCAL){const b=await browserEnv(this.dir).catch(()=>null);if(b)extraEnv={...b,...(extraEnv&&typeof extraEnv==='object'?extraEnv:{})}}
|
|
201
|
+
const readDirs=Array.isArray(extraRead)?extraRead.filter(d=>typeof d==='string'&&d):[];// BUG-0499: --add-dir folders, readable without asking
|
|
202
|
+
{const want=browserReadPaths(),have=Array.isArray(extraRead)?extraRead:[];const add=want.filter(p=>!have.includes(p));if(add.length)extraRead=[...have,...add]}
|
|
195
203
|
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}:{})};
|
|
196
204
|
const sandboxed=wantSandbox?wrap('x',[],box):null;
|
|
197
205
|
const secrets=started.secrets&&typeof started.secrets==='object'?started.secrets:{};
|
|
@@ -201,12 +209,18 @@ export class Session extends EventEmitter{
|
|
|
201
209
|
tools:[],mode:MODES[mode],reasoningEffort:effort,planApproval:'off',briefFirst:false,askFirst:'never',go:true,role:'engineer',steps:Math.min(160,Math.max(1,steps)),harness:'mini',...(images.length?{images}:{}),...(run?.goal?{goal:run.goal}:{}),...(run?.wake?{wake:run.wake}:{})};
|
|
202
210
|
// CLI extensions (tui/extensions-local.mjs): permission rules, local hooks, network, MCP servers. Their ${VAR}
|
|
203
211
|
// values travel in the environment like Vault secrets, never in request.json.
|
|
212
|
+
// Local-only stricter limits from the CLI (BUG-0492 --max-turns, BUG-0509 --max-budget-credits, BUG-0519 -p in auto
|
|
213
|
+
// mode): set here too, so they hold even when the server that built the request is older. They only ever tighten.
|
|
214
|
+
if(run?.hardSteps===true)request.hardSteps=true;
|
|
215
|
+
if(Number.isInteger(Number(run?.maxTokens))&&Number(run.maxTokens)>0)request.hardBudget=true;
|
|
216
|
+
if(run?.unattended===true)request.unattended=true;
|
|
217
|
+
if(readDirs.length)request.readDirs=readDirs.slice(0,20);
|
|
204
218
|
let mcpEnv=null;
|
|
205
219
|
if(extensions){const m=mergeExtensions(request.extensions,extensions);request.extensions=m.extensions;mcpEnv=m.mcpEnv}
|
|
206
220
|
// Network off (src/netbox.mjs): with Seatbelt or bubblewrap the harness gets no network at all, only a relay to
|
|
207
221
|
// the model gateway; elsewhere the engine's hook-level block is all there is (status says which).
|
|
208
222
|
const netOff=request.extensions?.network?.enabled===false;
|
|
209
|
-
const relay=netOff&&NET_KINDS.includes(kind)&&request.endpoint?await startRelay({targets:[request.endpoint,built?serverEnv(started.env).MINI_IMAGE_GATEWAY:null],deny:[built?serverEnv(started.env).MINI_RESEARCH_GATEWAY:null],kind}):null;
|
|
223
|
+
const relay=netOff&&NET_KINDS.includes(kind)&&request.endpoint?await startRelay({targets:[request.endpoint,built?serverEnv(started.env).MINI_IMAGE_GATEWAY:null,built?serverEnv(started.env).MINI_MEDIA_GATEWAY:null],deny:[built?serverEnv(started.env).MINI_RESEARCH_GATEWAY:null],kind}):null;
|
|
210
224
|
try{
|
|
211
225
|
if(relay)request.endpoint=relay.rewrite(request.endpoint);
|
|
212
226
|
await writeFile(path.join(this.dir,'computer.md'),await computerCard({sandbox:sandboxed?.kind||'none',mode,network:netOff?(relay?'os':'hooks'):'on',restricted}));
|
|
@@ -222,7 +236,8 @@ export class Session extends EventEmitter{
|
|
|
222
236
|
const log=await open(path.join(this.dir,'worker.log'),'a');
|
|
223
237
|
this.offset=0;
|
|
224
238
|
const child=spawn(launch.cmd,launch.args,{cwd:this.meta.root,env,stdio:['ignore',log.fd,log.fd],detached:process.platform!=='win32',windowsHide:true});
|
|
225
|
-
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}:{})
|
|
239
|
+
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
|
+
...(started.accountTokensLeft===null&&!started.offline?{uncapped:true}:{}),tokensLeft:started.accountTokensLeft===null?null:started.accountTokensLeft??started.budget??null});
|
|
226
241
|
const timer=setInterval(()=>this.poll().catch(()=>{}),150);
|
|
227
242
|
const exit=await new Promise(resolve=>{child.on('exit',(code,signal)=>resolve({code,signal}));child.on('error',e=>resolve({code:-1,error:e.message}))});
|
|
228
243
|
clearInterval(timer);await this.poll().catch(()=>{});await log.close().catch(()=>{});this.child=null;
|
|
@@ -230,9 +245,12 @@ export class Session extends EventEmitter{
|
|
|
230
245
|
let status=await readJson(path.join(this.dir,'status.json'),{});
|
|
231
246
|
if(!FINAL.includes(status.state)){
|
|
232
247
|
const tail=(await readFile(path.join(this.dir,'worker.log'),'utf8').catch(()=>'')).split('\n').filter(Boolean).slice(-6).join('\n');
|
|
233
|
-
const clean=redact(tail,[started.token,...Object.values(secrets)]);
|
|
248
|
+
const clean=hideEngineName(redact(tail,[started.token,...Object.values(secrets)]));
|
|
234
249
|
status={state:existsSync(path.join(this.dir,'cancel'))?'stopped':'error',error:exit.error||('The local engine exited unexpectedly.'+(clean?'\n'+clean:''))};
|
|
235
250
|
}
|
|
251
|
+
// A stop the person asked for ends as stopped, even when the engine reported an error on its way out (a command it
|
|
252
|
+
// was running got killed, an answer it was waiting on was withdrawn).
|
|
253
|
+
if(status.state==='error'&&existsSync(path.join(this.dir,'cancel'))){const {error,...rest}=status;status={...rest,state:'stopped',...(error?{stopDetail:String(error).slice(0,2000)}:{})}}
|
|
236
254
|
// Which harness ran is part of the final status (the harness rewrites status.json while it runs).
|
|
237
255
|
status={...status,engine:used};await writeJson(path.join(this.dir,'status.json'),status);
|
|
238
256
|
let usage=null;
|
|
@@ -240,6 +258,8 @@ export class Session extends EventEmitter{
|
|
|
240
258
|
Object.assign(turn,{state:status.state,finished:new Date().toISOString(),tokens:usage?.tokens??status.tokens??0,calls:usage?.calls??status.calls??0});
|
|
241
259
|
await this.save();
|
|
242
260
|
const result={...status,usage,completion:await readJson(path.join(this.dir,'completion.json'),null)};
|
|
261
|
+
// BUG-0523: the agent reported that the request cannot be done (cannot_complete tool); never a plain success.
|
|
262
|
+
{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)}}
|
|
243
263
|
// The gateway refuses calls once the plan allowance for this run is used; say so plainly.
|
|
244
264
|
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.'}
|
|
245
265
|
this.emit('done',result);
|
|
@@ -271,10 +291,25 @@ export class Session extends EventEmitter{
|
|
|
271
291
|
}
|
|
272
292
|
async pending(){return readJson(path.join(this.dir,'pending.json'),null)}
|
|
273
293
|
/** verdict: approve | approve_all | reject */
|
|
274
|
-
async decide(id,verdict){
|
|
294
|
+
async decide(id,verdict,{onProgress=()=>{},install=installBrowserFor}={}){
|
|
275
295
|
if(!/^[a-f0-9]{8,64}$/.test(String(id)))throw new Error('Invalid approval');
|
|
276
|
-
|
|
277
|
-
|
|
296
|
+
// Plan review answers (runner.py): approve:<item indexes> keeps some tasks, revise:<text> replies to the plan.
|
|
297
|
+
if(typeof verdict==='string'&&/^approve:\d{1,2}(,\d{1,2}){0,39}$/.test(verdict)){}
|
|
298
|
+
else if(typeof verdict==='string'&&/^revise:\S/.test(verdict.trim())&&verdict.length<=2100)verdict='revise:'+verdict.trim().slice(7).replace(/\s+/g,' ').trim().slice(0,2000);
|
|
299
|
+
else if(!['approve','approve_all','reject'].includes(verdict))throw new Error('Invalid decision');
|
|
300
|
+
// Approving the one-time browser download installs it before the engine reads the answer (the Mac app does the same
|
|
301
|
+
// in workspace-api.mjs). A failed install still sends the answer: the engine then continues without browser checks.
|
|
302
|
+
if(verdict!=='reject'){
|
|
303
|
+
const p=await readJson(path.join(this.dir,'pending.json'),null);
|
|
304
|
+
if(p?.id===id&&p.kind==='browser'&&p.install){
|
|
305
|
+
try{await install(this.dir,{python:await ensureRuntime({onProgress}),onProgress})}
|
|
306
|
+
catch(e){onProgress('The test browser could not be installed: '+(e?.message||e))}
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
// Write then rename: the engine polls for this file and reads it as soon as it exists, so it must never see it empty or
|
|
310
|
+
// half-written (Windows makes that window wide). Same as the workspace API's put().
|
|
311
|
+
const f=path.join(this.dir,'decision-'+id),tmp=path.join(this.dir,'.tmp-decision-'+id+'-'+randomUUID().slice(0,8));
|
|
312
|
+
await writeFile(tmp,verdict);await rename(tmp,f);
|
|
278
313
|
}
|
|
279
314
|
async steer(message){
|
|
280
315
|
const d=path.join(this.dir,'steering');await mkdir(d,{recursive:true});
|
|
@@ -285,6 +320,14 @@ export class Session extends EventEmitter{
|
|
|
285
320
|
const c=this.child;if(!c)return;
|
|
286
321
|
setTimeout(()=>{if(this.child===c)killTree(c.pid)},8000).unref();
|
|
287
322
|
}
|
|
323
|
+
/** BUG-0516: the terminal is closing. Ask the engine to stop, wait up to graceMs for it, then end its process group,
|
|
324
|
+
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
|
+
await writeFile(path.join(this.dir,'cancel'),'1').catch(()=>{});
|
|
328
|
+
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)})});
|
|
329
|
+
if(!ended)killTree(c.pid);
|
|
330
|
+
}
|
|
288
331
|
}
|
|
289
332
|
export {sandboxKind};
|
|
290
333
|
export const defaults={os:os.platform()};
|
package/src/shared-data.mjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// Generated from lib/skills.ts starterSkills and lib/safety-gates.ts POLICY_TEMPLATES; test/parity.test.mjs checks it.
|
|
2
2
|
// A module, not JSON: the Mac app bundle copies only .mjs and .py files from this folder.
|
|
3
|
-
export default {"starterSkills":[{"id":"glm-prd-builder","name":"
|
|
3
|
+
export default {"starterSkills":[{"id":"glm-prd-builder","name":"PRD builder · adapted","description":"Build from a written product specification.","content":"# PRD builder (text-only adaptation)\nRead all supplied written requirements. Separate required behavior from assumptions. Build a page map and data model, then implement one end-to-end vertical slice. Reuse provided assets only when accessible. Treat screenshots as unavailable unless the user supplies a text description; this model has no configured vision tool. Cover loading, empty and error states. Implement backend behavior instead of faking it. Run relevant checks with verify and local UI flows with browser when enabled. Provide reproducible start instructions and list incomplete integrations.","source":"Adapted from zai-org/GLM-skills/glmv-prd-to-app · Apache-2.0 · 2ecd31c","enabled":true},{"id":"glm-ui-workflow","name":"Frontend workflow · adapted","description":"Translate a design brief into working UI.","content":"# Frontend workflow (text-only adaptation)\nDerive page structure, components and interactions from the written design brief. Keep branding accurate and do not imply affiliation with another product. Match layout and interaction requirements using accessible semantic controls. Implement responsive desktop and mobile behavior. Use browser DOM, console errors and overflow checks on the local app; screenshots are user-review artifacts, not proof the model visually inspected them. Remote site exploration requires a separately connected browser MCP server. Do not claim backend parity from frontend appearance.","source":"Adapted from zai-org/GLM-skills/glmv-web-replication · Apache-2.0 · 2ecd31c","enabled":true},{"id":"build-app","name":"Build an app","description":"Turn a request into a tested, responsive app.","content":"# Build an app\nClarify only missing essentials. Inspect the repository. Write a short task list. Build the smallest working vertical slice first. Reuse existing design conventions. Check loading, empty and error states. Test desktop and mobile with the browser tool when enabled. Run relevant checks with verify. Report limitations honestly.","source":"ML AI Code","enabled":true},{"id":"debug","name":"Systematic debugging","description":"Reproduce, isolate, fix and verify.","content":"# Systematic debugging\nCapture the actual failure before editing. List hypotheses and test the cheapest discriminating check. Make the smallest relevant fix. Add a regression check when useful. Use verify for the reproduced failure and relevant tests. Do not call a failed or skipped check a pass.","source":"ML AI Code","enabled":true},{"id":"browser-testing","name":"Browser testing","description":"Exercise local app flows with Playwright.","content":"# Browser testing\nStart the app on port 3000. Use browser scenarios for navigation, accessible role/text selection, filling and clicks. Check mobile and desktop widths, console errors, page errors and overflow. Screenshots are artifacts for the user; do not claim visual inspection from DOM text alone. Browser interactions require approval. Avoid submitting purchases, messages or production actions without explicit authorization.","source":"ML AI Code","enabled":true},{"id":"review","name":"Review changes","description":"Use independent read-only reviewers.","content":"# Review changes\nUse subagents for independent exploration or review. Give each a narrow question and ask for file references and uncertainty. Reviewers cannot edit or call external tools. Verify their findings in the main agent before making changes. Never equate agent consensus with passing tests.","source":"ML AI Code","enabled":true},{"id":"create-skill","name":"Create a reusable skill","description":"Draft reusable SKILL.md instructions.","content":"# Create a skill\nUse skill_create with a short lowercase hyphenated id, a specific name and description, and Markdown content. Include when to use it, steps, required tools, verification and limits. Never embed secrets. Do not add instructions to override user permissions. New skills remain disabled until the user reviews and enables them. Supporting scripts and dependencies require separate review; Markdown import does not install them.","source":"ML AI Code","enabled":true}],"policyTemplates":{"starter":{"label":"Starter","hint":"PRs to main, secrets scanned, nothing else changes","text":"# .mlai/policy.yml — reviewed like code\nproduction:\n branch: main\n require_pr: true\nsecrets:\n scan: true\n"},"team":{"label":"Team","hint":"Guided by default, protected infra and payments, test commands run freely","text":"production:\n branch: main\n require_pr: true\n block_paths_without_review: [\"infra/**\", \"payments/**\", \".github/workflows/**\"]\n require_ci_green: true\n auto_promote: false\nagent:\n modes_allowed: [plan, brief, guided, auto]\n commands:\n allow: [\"npm test*\", \"npm run lint*\", \"pytest*\"]\n deny: [\"terraform apply*\", \"kubectl delete*\"]\nsecrets:\n scan: true\n"},"regulated":{"label":"Regulated","hint":"No Auto mode, allowlisted network, credit cap per run","text":"production:\n branch: main\n require_pr: true\n block_paths_without_review: [\"infra/**\", \"payments/**\", \"auth/**\", \"migrations/**\"]\n require_ci_green: true\n auto_promote: false\nagent:\n modes_allowed: [plan, brief, guided]\n max_tokens_per_run: 3000000\n network: allowlist\n network_allow: []\n commands:\n deny: [\"terraform *\", \"kubectl *\", \"aws *\", \"gcloud *\"]\nsecrets:\n scan: true\n"}}};
|