mlai-code 0.3.2 → 0.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/README.md +1 -1
  2. package/package.json +1 -1
  3. package/src/cli.mjs +27 -7
  4. package/src/engine.mjs +1 -1
  5. package/src/home.mjs +1 -1
  6. package/src/parity.mjs +3 -1
  7. package/src/render.mjs +3 -1
  8. package/src/runtime.mjs +21 -1
  9. package/src/sandbox.mjs +19 -3
  10. package/src/session.mjs +22 -2
  11. package/src/shared-data.mjs +1 -1
  12. package/src/tui/app.mjs +22 -4
  13. package/src/tui/chat.mjs +8 -6
  14. package/src/tui/cmd-core.mjs +2 -2
  15. package/src/tui/cmd-extensibility.mjs +8 -2
  16. package/src/tui/commands.mjs +2 -1
  17. package/src/tui/statusline.mjs +2 -1
  18. package/src/wakeups.mjs +2 -2
  19. package/vendor/client-sdk/index.cjs +3 -3
  20. package/vendor/cloud-cli/mlai.mjs +169 -25
  21. package/worker/build_planner.py +75 -7
  22. package/worker/cloud_pty.py +91 -2
  23. package/worker/command_safety.py +25 -1
  24. package/worker/compaction_brief.py +186 -0
  25. package/worker/context_manager.py +6 -0
  26. package/worker/conversation.py +58 -1
  27. package/worker/deck_render.js +11 -0
  28. package/worker/deck_tools.py +825 -0
  29. package/worker/git_sync.py +38 -13
  30. package/worker/goals.py +4 -0
  31. package/worker/image_generation.py +102 -23
  32. package/worker/kimi_bridge.py +340 -32
  33. package/worker/kimi_gates.py +49 -0
  34. package/worker/kimi_hook.py +65 -12
  35. package/worker/media_tools.py +179 -0
  36. package/worker/memory.py +2 -2
  37. package/worker/mlai_hooks.py +93 -3
  38. package/worker/mlai_mcp.py +23 -5
  39. package/worker/model_stream.py +21 -7
  40. package/worker/offline_guard.py +1 -1
  41. package/worker/preview.py +47 -4
  42. package/worker/product_facts.py +18 -0
  43. package/worker/project_context.py +33 -7
  44. package/worker/reply_language.py +92 -10
  45. package/worker/roles.json +199 -37
  46. package/worker/roles.py +243 -8
  47. package/worker/runner.py +241 -36
  48. package/worker/site_check.py +279 -0
  49. package/worker/skill_library.py +15 -3
  50. package/worker/skill_pack.py +170 -16
  51. package/worker/tool_catalog.py +3 -2
  52. package/worker/verification.py +43 -11
  53. package/worker/wakeups.py +56 -4
package/README.md CHANGED
@@ -1,4 +1,4 @@
1
- # mlai-code 0.3.2
1
+ # mlai-code 0.3.3
2
2
 
3
3
  ML AI Code in your terminal. The agent works in your project on this machine; models run in ML AI Code's cloud.
4
4
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mlai-code",
3
- "version": "0.3.2",
3
+ "version": "0.3.3",
4
4
  "description": "ML AI Code in your terminal: an agent that reads, edits and runs code in your project, on your machine.",
5
5
  "type": "module",
6
6
  "bin": {
package/src/cli.mjs CHANGED
@@ -25,7 +25,7 @@ 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} from './runtime.mjs';
28
- import {palette,renderEvent,approvalView,summaryLine,exitCode,EXIT,fmt} from './render.mjs';
28
+ import {palette,renderEvent,approvalView,summaryLine,exitCode,EXIT,fmt,credits} from './render.mjs';
29
29
  import {runHeadless,streamInputs,stdinLines,toolRules,loadSchema,HeadlessError} from './headless.mjs';
30
30
 
31
31
  /** Every option, for --help and shell completion (src/completion.mjs). value: the placeholder when it takes one. */
@@ -289,13 +289,23 @@ async function sessions(o,c){
289
289
  if(!all.length){process.stdout.write('No sessions yet. Run mlai in a project folder.\n');return 0}
290
290
  for(const m of all.slice(0,30)){
291
291
  const tokens=m.turns.reduce((a,t)=>a+(t.tokens||0),0),last=m.turns.at(-1);
292
- process.stdout.write(`${c.bold(m.id.slice(0,8))} ${m.folder.padEnd(18).slice(0,18)} ${String(m.title||'').slice(0,48).padEnd(48)} ${c.dim(m.turns.length+' turn'+(m.turns.length===1?'':'s')+' · '+fmt(tokens)+' tokens · '+(last?.state||'new')+' · '+String(m.updated||m.created).slice(0,16).replace('T',' '))}\n`);
292
+ process.stdout.write(`${c.bold(m.id.slice(0,8))} ${m.folder.padEnd(18).slice(0,18)} ${String(m.title||'').slice(0,48).padEnd(48)} ${c.dim(m.turns.length+' turn'+(m.turns.length===1?'':'s')+' · '+credits(tokens)+' · '+(last?.state||'new')+' · '+String(m.updated||m.created).slice(0,16).replace('T',' '))}\n`);
293
293
  }
294
294
  process.stdout.write(c.dim('Continue one with: mlai resume <id>')+'\n');return 0;
295
295
  }
296
+ /**
297
+ * Node.js for doctor: the CLI needs 20, and the default coding engine needs 22.19 or newer (older 22.x lacks a zlib
298
+ * export it uses, so runs fall back or fail). Below 22.19 is a warning, not an error, because the CLI itself works.
299
+ */
300
+ export function nodeCheck(version){
301
+ const [a,b]=String(version).replace(/^v/,'').split('.').map(Number);
302
+ if(!(a>=20))return {ok:false,detail:version+' (20 or newer needed)'};
303
+ if(a<22||(a===22&&b<19))return {ok:false,warn:true,detail:version+' (22.19 or newer recommended: the coding engine needs it; update Node.js from https://nodejs.org)'};
304
+ return {ok:true,detail:version};
305
+ }
296
306
  async function doctor(o,c){
297
- const rows=[];const add=(ok,label,detail)=>rows.push({ok,label,detail});
298
- const major=Number(process.versions.node.split('.')[0]);add(major>=20,'Node.js',process.versions.node+(major>=20?'':' (20 or newer needed)'));
307
+ const rows=[];const add=(ok,label,detail,extra)=>rows.push({ok,label,detail,...extra});
308
+ {const n=nodeCheck(process.versions.node);add(n.ok,'Node.js',n.detail,n.warn?{warn:true}:undefined)}
299
309
  const server=await serverFor(o);
300
310
  try{
301
311
  const caps=await new Client({baseUrl:server,surface:'laptop',version:VERSION,allowLoopback:loopback(server)}).capabilities();
@@ -317,13 +327,23 @@ async function doctor(o,c){
317
327
  add(true,'Local data',home());
318
328
  if(o.json)process.stdout.write(JSON.stringify(rows)+'\n');
319
329
  else for(const r of rows)process.stdout.write((r.ok?c.green('ok '):c.yellow('!! '))+r.label.padEnd(15)+' '+r.detail+'\n');
320
- return rows.every(r=>r.ok||['Coding engine','OS sandbox','Laptop runs'].includes(r.label))?0:1;
330
+ return rows.every(r=>r.ok||r.warn||['Coding engine','OS sandbox','Laptop runs'].includes(r.label))?0:1;
321
331
  }
322
- async function cloud(args){
332
+ export async function cloud(args){
323
333
  const here=path.dirname(fileURLToPath(import.meta.url));
324
334
  const bin=[path.join(here,'..','vendor','cloud-cli','mlai.mjs'),path.join(here,'..','..','cli','bin','mlai.mjs')].find(existsSync);
325
335
  if(!bin)throw new Error('Cloud commands are not included in this install.');
326
- return await new Promise(resolve=>{const p=spawn(process.execPath,[bin,...args],{stdio:'inherit'});p.on('exit',code=>resolve(code??1))});
336
+ const env=await cloudEnv({login:await loadLogin().catch(()=>null)});
337
+ return await new Promise(resolve=>{const p=spawn(process.execPath,[bin,...args],{stdio:'inherit',env});p.on('exit',code=>resolve(code??1))});
338
+ }
339
+ /**
340
+ * The cloud workspace CLI uses the `mlai login` sign-in and its server (MLAI_TOKEN, MLAI_URL), so `mlai cloud doctor`
341
+ * shows the same account as `mlai doctor`. Without a sign-in it keeps its own config and default server.
342
+ */
343
+ export function cloudEnv({login,env=process.env}={}){
344
+ const out={...env};
345
+ if(login?.token){out.MLAI_TOKEN=login.token;const server=env.MLAI_SERVER||login.server;if(server&&!env.MLAI_URL)out.MLAI_URL=String(server).replace(/\/$/,'')}
346
+ return out;
327
347
  }
328
348
 
329
349
  /** Flags that override settings (settings.mjs), and the settings for a session's folder. */
package/src/engine.mjs CHANGED
@@ -14,7 +14,7 @@ import {pinnedPublicKey,ed25519PublicKey} from './engine-key.mjs';
14
14
  export const ENGINE_PROTOCOL=1;
15
15
  export const CHECK_EVERY=10*60*1000,WAIT_MS=3000,DOWNLOAD_MS=60000;
16
16
  /** Copy of lib/laptop-engine.ts ENGINE_FILES (parity test): the bundled copy's version is hashed over these. */
17
- export const ENGINE_FILES=['ask_first.py','attachment_reader.py','background_jobs.py','brief_questions.py','browser_local.py','browser_pane.py','browser_tool.py','build_planner.py','checkpoints.py','command_policy.py','command_safety.py','computer_card.sh','computer_setup.sh','computer_use.py','connector_search.py','context_manager.py','conversation.py','deploy_pack.py','design_director.py','dev_jobs.py','edit_guard.py','env_setup.py','evidence.py','fast_search.py','goals.py','handover.py','harness_memory.py','image_generation.py','intelligence.py','intent_model.py','intent_weights.json','ios_simulator.py','kimi_bridge.py','kimi_compact.py','kimi_gates.py','kimi_hook.py','lifecycle.py','lsp.py','mcp_local.py','memory.py','mlai_auto_review.py','mlai_hooks.py','mlai_mcp.py','mlai_permissions.py','model_stream.py','nested_repos.py','obs_mask.py','offline_guard.py','preview.py','proc_watch.py','project_context.py','project_rules.py','quality.py','reply_language.py','repo_hygiene.py','repo_memory.py','repo_policy.py','roles.json','roles.py','runner.py','runtime_control.py','secret_scan.py','session_hub.py','skill_library.py','skill_pack.py','subagents.py','task_controller.py','task_skills.py','token_count.py','tool_catalog.py','verification.py','vision.py','wakeups.py','web_tools.py','winproc.py','work_ledger.py','worktrees.py'];
17
+ export const ENGINE_FILES=['ask_first.py','attachment_reader.py','background_jobs.py','brief_questions.py','browser_local.py','browser_pane.py','browser_tool.py','build_planner.py','checkpoints.py','command_policy.py','command_safety.py','compaction_brief.py','computer_card.sh','computer_setup.sh','computer_use.py','connector_search.py','context_manager.py','conversation.py','deck_render.js','deck_tools.py','deploy_pack.py','design_director.py','dev_jobs.py','edit_guard.py','env_setup.py','evidence.py','fast_search.py','goals.py','handover.py','harness_memory.py','image_generation.py','intelligence.py','intent_model.py','intent_weights.json','ios_simulator.py','kimi_bridge.py','kimi_compact.py','kimi_gates.py','kimi_hook.py','lifecycle.py','lsp.py','mcp_local.py','media_tools.py','memory.py','mlai_auto_review.py','mlai_hooks.py','mlai_mcp.py','mlai_permissions.py','model_stream.py','nested_repos.py','obs_mask.py','offline_guard.py','preview.py','proc_watch.py','product_facts.py','project_context.py','project_rules.py','quality.py','reply_language.py','repo_hygiene.py','repo_memory.py','repo_policy.py','roles.json','roles.py','runner.py','runtime_control.py','secret_scan.py','session_hub.py','site_check.py','skill_library.py','skill_pack.py','subagents.py','task_controller.py','task_skills.py','token_count.py','tool_catalog.py','verification.py','vision.py','wakeups.py','web_tools.py','winproc.py','work_ledger.py','worktrees.py'];
18
18
  /** The entry scripts; a manifest without them is not a harness. */
19
19
  export const REQUIRED=['runner.py','kimi_bridge.py'];
20
20
  const NAME=/^[A-Za-z0-9][A-Za-z0-9_.-]{0,99}$/,SHA=/^[a-f0-9]{64}$/,VERSION=/^[a-f0-9]{32}$/;
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.2';
6
+ export const VERSION='0.3.3';
7
7
  export const DEFAULT_SERVER='https://mlai-mini-code.vercel.app';
8
8
  /** All local state lives here; nothing is written into the user's repository except what the agent edits. */
9
9
  export function home(){
package/src/parity.mjs CHANGED
@@ -37,6 +37,8 @@ export function importSession(source){
37
37
 
38
38
  /** lib/checkpoints.ts */
39
39
  export const STEP_MARK='mini-step: ';
40
+ /** The pre-task checkpoint: a snapshot like a step's (parent = HEAD, never on a branch). Older ones were commits on the branch. */
41
+ export const TASK_MARK='mini-task: ';
40
42
  export function checkpointRef(value){if(!value||value==='HEAD')return 'HEAD';if(typeof value!=='string'||!/^mini-checkpoints\/\d{13}$/.test(value))throw new Error('Invalid checkpoint');return 'refs/'+value}
41
43
  export function parseCheckpoints(output,limit=40){
42
44
  return output.trim().split('\n').filter(Boolean).slice(0,limit).map(line=>{
@@ -50,7 +52,7 @@ export async function rewind(value,git){
50
52
  const dirty=(await git(['status','--porcelain'])).trim();let rescue;
51
53
  if(dirty){await git(['stash','push','--include-untracked','-m','Mini Code rescue before checkpoint restore']);rescue=(await git(['rev-parse','refs/stash'])).trim();}
52
54
  const subject=ref==='HEAD'?'':(await git(['log','-1','--format=%s',ref])).trim();
53
- if(subject.startsWith(STEP_MARK)){
55
+ if(subject.startsWith(STEP_MARK)||subject.startsWith(TASK_MARK)){
54
56
  const parents=(await git(['rev-list','--parents','-n','1',ref])).trim().split(' ').slice(1);
55
57
  if(parents[0])await git(['reset','--hard',parents[0]]);
56
58
  await git(['clean','-fd']);
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)){
@@ -69,5 +71,5 @@ export function exitCode(result){
69
71
  export function summaryLine(result,c=palette(false)){
70
72
  const u=result.usage||{};
71
73
  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(' · '+fmt(u.tokens)+' tokens · '+fmt(u.calls)+' model calls');
74
+ return state+c.dim(' · '+credits(u.tokens)+' · '+fmt(u.calls)+' model calls');
73
75
  }
package/src/runtime.mjs CHANGED
@@ -43,6 +43,26 @@ async function works(python){
43
43
  * A private Python for the harness in ~/.mlai/runtime. Uses the bundled or installed uv, which also downloads
44
44
  * a standalone Python, so the developer installs nothing. Falls back to python3 -m venv. Never touches system Python.
45
45
  */
46
+ /**
47
+ * Why a setup step failed, from its output. Some tools print the reason on stdout and nothing on stderr (Debian and
48
+ * Ubuntu's python3 -m venv without the python3-venv package), so stdout is used when stderr is empty.
49
+ */
50
+ export function stepError(label,{stdout='',stderr=''}={}){
51
+ const out=String(stderr).trim()||String(stdout).trim();
52
+ const tail=out.split('\n').map(l=>l.trim()).filter(Boolean).slice(-3).join(' ');
53
+ 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.':'';
54
+ const msg=label+' failed'+(tail?': '+tail:' with no output');
55
+ return new Error(venv?msg.replace(/[.\s]*$/,'.')+venv:msg);
56
+ }
57
+ /** Runs one setup command, keeping the end of both outputs for the error message. */
58
+ export function runStep(label,cmd,args,{onProgress=()=>{},spawnImpl=spawn}={}){
59
+ onProgress(label);
60
+ return new Promise((resolve,reject)=>{
61
+ 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'}});
62
+ let err='',out='';c.stderr?.on('data',d=>{err=(err+d).slice(-4000)});c.stdout?.on('data',d=>{out=(out+d).slice(-4000)});
63
+ c.on('error',reject);c.on('exit',code=>code===0?resolve():reject(stepError(label,{stdout:out,stderr:err})));
64
+ });
65
+ }
46
66
  let inflight=null;
47
67
  /** Single flight: the app warms the runtime when a folder opens, and the first task may ask for it at the same time. */
48
68
  export function ensureRuntime(opts={}){
@@ -56,7 +76,7 @@ async function prepareRuntime({onProgress=()=>{},force=false}={}){
56
76
  if(!force&&existsSync(marker)&&await works(python))return python;
57
77
  await rm(dir,{recursive:true,force:true});
58
78
  const uv=await which('uv');
59
- const step=async(label,cmd,args)=>{onProgress(label);await new Promise((resolve,reject)=>{const c=spawn(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'}});let err='';c.stderr.on('data',d=>{err=(err+d).slice(-4000)});c.on('error',reject);c.on('exit',code=>code===0?resolve():reject(new Error(label+' failed: '+err.trim().split('\n').slice(-3).join(' '))))})};
79
+ const step=(label,cmd,args)=>runStep(label,cmd,args,{onProgress});
60
80
  if(uv){
61
81
  await step('Preparing Python '+PY_VERSION,uv,['venv','--quiet','--python',PY_VERSION,dir]);
62
82
  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/session.mjs CHANGED
@@ -10,6 +10,7 @@ import {home,sub} from './home.mjs';
10
10
  import {prepareEngine} from './engine.mjs';
11
11
  import {projectRoot,projectId,computerCard,gitRemote} from './project.mjs';
12
12
  import {ensureRuntime} 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';
@@ -192,6 +193,10 @@ export class Session extends EventEmitter{
192
193
  const wantSandbox=restricted?SANDBOXES.includes(kind):(mode==='auto'||mode==='plan')&&extensions?.sandbox?.enabled!==false;
193
194
  const busybox=wantSandbox&&kind==='windows'?await ensureBusybox(home(),{onProgress,server:cloud?.server}):undefined;
194
195
  const extraDeny=denyRoots(started.request?.extensions?.hardDeny?.paths,{repo:this.meta.root});
196
+ // The local test browser (src/browser-setup.mjs) for every local run, terminal ones included: without MINI_BROWSER_LOCAL
197
+ // the engine reports "browser runtime is not installed" instead of offering the one-time install. The Mac app passes it already.
198
+ if(!extraEnv?.MINI_BROWSER_LOCAL){const b=await browserEnv(this.dir).catch(()=>null);if(b)extraEnv={...b,...(extraEnv&&typeof extraEnv==='object'?extraEnv:{})}}
199
+ {const want=browserReadPaths(),have=Array.isArray(extraRead)?extraRead:[];const add=want.filter(p=>!have.includes(p));if(add.length)extraRead=[...have,...add]}
195
200
  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
201
  const sandboxed=wantSandbox?wrap('x',[],box):null;
197
202
  const secrets=started.secrets&&typeof started.secrets==='object'?started.secrets:{};
@@ -233,6 +238,9 @@ export class Session extends EventEmitter{
233
238
  const clean=redact(tail,[started.token,...Object.values(secrets)]);
234
239
  status={state:existsSync(path.join(this.dir,'cancel'))?'stopped':'error',error:exit.error||('The local engine exited unexpectedly.'+(clean?'\n'+clean:''))};
235
240
  }
241
+ // A stop the person asked for ends as stopped, even when the engine reported an error on its way out (a command it
242
+ // was running got killed, an answer it was waiting on was withdrawn).
243
+ 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
244
  // Which harness ran is part of the final status (the harness rewrites status.json while it runs).
237
245
  status={...status,engine:used};await writeJson(path.join(this.dir,'status.json'),status);
238
246
  let usage=null;
@@ -271,10 +279,22 @@ export class Session extends EventEmitter{
271
279
  }
272
280
  async pending(){return readJson(path.join(this.dir,'pending.json'),null)}
273
281
  /** verdict: approve | approve_all | reject */
274
- async decide(id,verdict){
282
+ async decide(id,verdict,{onProgress=()=>{},install=installBrowserFor}={}){
275
283
  if(!/^[a-f0-9]{8,64}$/.test(String(id)))throw new Error('Invalid approval');
276
284
  if(!['approve','approve_all','reject'].includes(verdict))throw new Error('Invalid decision');
277
- await writeFile(path.join(this.dir,'decision-'+id),verdict);
285
+ // Approving the one-time browser download installs it before the engine reads the answer (the Mac app does the same
286
+ // in workspace-api.mjs). A failed install still sends the answer: the engine then continues without browser checks.
287
+ if(verdict!=='reject'){
288
+ const p=await readJson(path.join(this.dir,'pending.json'),null);
289
+ if(p?.id===id&&p.kind==='browser'&&p.install){
290
+ try{await install(this.dir,{python:await ensureRuntime({onProgress}),onProgress})}
291
+ catch(e){onProgress('The test browser could not be installed: '+(e?.message||e))}
292
+ }
293
+ }
294
+ // 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
295
+ // half-written (Windows makes that window wide). Same as the workspace API's put().
296
+ const f=path.join(this.dir,'decision-'+id),tmp=path.join(this.dir,'.tmp-decision-'+id+'-'+randomUUID().slice(0,8));
297
+ await writeFile(tmp,verdict);await rename(tmp,f);
278
298
  }
279
299
  async steer(message){
280
300
  const d=path.join(this.dir,'steering');await mkdir(d,{recursive:true});
@@ -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":"GLM PRD builder · adapted","description":"Build from a written product specification.","content":"# GLM 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":"GLM 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":"Mini Code — authored for GLM 5.3 Flash","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":"Mini Code — authored for GLM 5.3 Flash","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":"Mini Code — authored for GLM 5.3 Flash","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":"Mini Code — authored for GLM 5.3 Flash","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":"Mini Code — authored for GLM 5.3 Flash","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, token 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"}}};
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"}}};
package/src/tui/app.mjs CHANGED
@@ -197,7 +197,9 @@ export async function runTui({session,settings={},cloud=null,flags={},first=null
197
197
  async function decide(verdict,{feedback=null,always=false}={}){
198
198
  const m=st.modal;if(!m||m.type!=='approval'&&m.type!=='feedback')return;
199
199
  const a=m.a;st.modal=null;
200
- try{await session.decide(a.id,verdict)}catch(e){print(t.bad('Could not answer: '+e.message))}
200
+ const install=verdict!=='reject'&&a.kind==='browser'&&a.install;
201
+ if(install)print(tr.elbow()+t.dim('Installing the test browser (one-time download)...'));
202
+ try{await session.decide(a.id,verdict,install?{onProgress:msg=>{st.activity=String(msg).slice(0,80);draw()}}:undefined)}catch(e){print(t.bad('Could not answer: '+e.message))}
201
203
  const plan=parseApproval(a).kind==='plan';
202
204
  if(verdict==='approve'){
203
205
  if(always&&m.rule){st.rules.add(m.rule);try{await ctx.settings?.save?.('local','permissions',{allow:[m.rule]});print(tr.elbow()+t.ok('Approved')+t.dim(' · always allowing '+m.rule+' (saved to .mlai/settings.local.json)'))}catch(e){print(tr.elbow()+t.ok('Approved')+t.dim(' · allowing '+m.rule+' for this session ('+e.message+')'))}}
@@ -506,6 +508,20 @@ export async function runTui({session,settings={},cloud=null,flags={},first=null
506
508
  const n=terminals.running().length;if(n){st.exiting=false;print(t.dim(' Stopping '+n+' background terminal'+(n===1?'':'s')+'...'));st.exiting=true;await terminals.stopAll()}
507
509
  exitResolve(code);
508
510
  }
511
+ /**
512
+ * Stops the running turn once: later presses only remind that it is stopping. An open approval card is answered
513
+ * (rejected) quietly so the engine is not left waiting on it, and the queued cards are dropped.
514
+ */
515
+ function stopRun(){
516
+ if(st.cancelled){flash('Stopping the agent...',1500);return}
517
+ st.cancelled=true;
518
+ print(t.warn(' Stopping...'));
519
+ // The cancel flag goes first, so the engine sees it as soon as the withdrawn approval lets it continue.
520
+ const cards=[...(st.modal?.type==='approval'||st.modal?.type==='feedback'?[st.modal.a]:[]),...st.approvals.splice(0)];
521
+ if(cards.length)st.modal=null;
522
+ session.cancel().catch(()=>{}).then(()=>Promise.all(cards.map(a=>session.decide(a.id,'reject').catch(()=>{}))));
523
+ setTitle();draw();
524
+ }
509
525
  function onKey(k){
510
526
  Promise.resolve(handleKey(k)).catch(e=>print(t.bad('error: '+(e?.message||e))));
511
527
  }
@@ -514,8 +530,9 @@ export async function runTui({session,settings={},cloud=null,flags={},first=null
514
530
  // Ctrl-C: stop the agent, close a popup, clear the line, or (twice) exit.
515
531
  if(k.ctrl&&k.name==='c'){
516
532
  if(st.shellChild){try{st.shellChild.kill('SIGINT')}catch{}return}
533
+ if((m?.type==='approval'||m?.type==='feedback')&&st.running){stopRun();return}
517
534
  if(m){closeModal();return}
518
- if(st.running){st.cancelled=true;print(t.warn(' Stopping...'));session.cancel().catch(()=>{});return}
535
+ if(st.running){stopRun();return}
519
536
  if(editor.text){editor.clear();draw();return}
520
537
  if(Date.now()-st.lastCtrlC<1500)return quit(0);
521
538
  st.lastCtrlC=Date.now();flash('Press Ctrl-C again to exit',1500);return;
@@ -558,7 +575,8 @@ export async function runTui({session,settings={},cloud=null,flags={},first=null
558
575
  if(c==='a'){if(m.rule)return decide('approve',{always:true});flash('No narrow rule for this one; answer y or n');return}
559
576
  if(c==='n'){st.modal={type:'feedback',a:m.a,rule:m.rule,plan:parseApproval(m.a).kind==='plan',editor:new Editor()};draw();return}
560
577
  }
561
- if(k.name==='escape')return decide('reject');
578
+ // Esc on an approval card stops the run, like Esc anywhere else while the agent works; n rejects.
579
+ if(k.name==='escape'){if(st.running){stopRun();return}return decide('reject')}
562
580
  if(k.ctrl&&k.name==='o'){toggleTools();const v=approvalLines(m.a,{t,cols:screen.cols,box,expanded:tr.expanded,rule:m.rule});if(tr.expanded)print(['',...v.lines]);return}
563
581
  flash('Answer y, a or n');return;
564
582
  }
@@ -599,7 +617,7 @@ export async function runTui({session,settings={},cloud=null,flags={},first=null
599
617
  if(k.ctrl&&k.name==='z'&&process.platform!=='win32'){suspend();return}
600
618
  if(k.name==='escape'&&!editor.search&&!(editor.vim&&editor.vimMode==='insert'&&editor.text)){
601
619
  if(st.popup){editor.text.startsWith('/')&&!editor.text.includes(' ')?editor.clear():null;st.popup=null;st.sel=0;draw();if(!editor.text)return}
602
- if(st.running){st.cancelled=true;print(t.warn(' Stopping...'));session.cancel().catch(()=>{});return}
620
+ if(st.running){stopRun();return}
603
621
  const now=Date.now(),dbl=now-st.lastEsc<600;st.lastEsc=now;
604
622
  if(dbl){st.lastEsc=0;if(editor.text){editor.clear();draw();return}
605
623
  if(registry.find('rewind')){const {result}=await registry.dispatch(ctx,'/rewind');if(typeof result?.send==='string')await runTask(result.send);draw()}else flash('Rewind is not available');return}
package/src/tui/chat.mjs CHANGED
@@ -21,11 +21,11 @@ import {plainUi} from './plain.mjs';
21
21
  import {snapshot,restore,forget} from './snapshots.mjs';
22
22
 
23
23
  /** Used when the server does not list models (older servers, offline). */
24
- export const FALLBACK_MODELS=[{id:'pixis',label:'Pixis',available:true,vision:true,credits:1,creditLabel:'Standard credits'}];
24
+ export const FALLBACK_MODELS=[{id:'pixis',label:'Pixis',available:true,vision:true,creditLabel:'Uses your plan credits'}];
25
25
  /** Credits like the app shows them (lib/plans.ts TOKENS_PER_CREDIT; tests/cli-credits.test.mjs keeps them in step). */
26
- export const TOKENS_PER_CREDIT=60_000;
27
- export const creditsFor=tokens=>Math.round(Math.max(0,Number(tokens)||0)/TOKENS_PER_CREDIT*100)/100;
28
- export function formatCredits(n){const v=Math.max(0,Number(n)||0);return v>=1000?Math.round(v).toLocaleString('en-US'):v>=100?String(Math.round(v)):String(Math.round(v*10)/10)}
26
+ export const TOKENS_PER_CREDIT=1_000_000;
27
+ export const creditsFor=tokens=>Math.round(Math.max(0,Number(tokens)||0)/TOKENS_PER_CREDIT*1000)/1000;
28
+ export function formatCredits(n){const v=Math.max(0,Number(n)||0);return v>=1000?Math.round(v).toLocaleString('en-US'):v>=100?String(Math.round(v)):v>=1?String(Math.round(v*10)/10):String(Math.round(v*100)/100)}
29
29
  /** Engine run modes the server understands (lib/run-request.ts). */
30
30
  const RUN_MODE={guided:'approve',plan:'plan',auto:'auto'};
31
31
  /** An overloaded or unavailable model (start refused, or the run failed on model errors): try the next fallback model. */
@@ -72,7 +72,7 @@ export class Chat extends EventEmitter{
72
72
  }
73
73
  get info(){const list=this.models||FALLBACK_MODELS;return list.find(m=>m.id===this.model)||(this.model&&!this.models?{id:this.model,label:this.model,available:true,creditLabel:'Credits per your plan'}:null)||list.find(m=>m.id===(this.defaultModel||'pixis'))||list[0]}
74
74
  get modelLabel(){return this.info?.label||this.model||'Pixis'}
75
- get credits(){return this.info?.creditLabel||'Standard credits'}
75
+ get credits(){return this.info?.creditLabel||'Uses your plan credits'}
76
76
  get branch(){try{return execFileSync('git',['branch','--show-current'],{cwd:this.session.meta.root,encoding:'utf8',stdio:['ignore','pipe','ignore']}).trim()||null}catch{return null}}
77
77
 
78
78
  /** The account's model list from the server (GET /api/clients); falls back to the default model. */
@@ -97,7 +97,9 @@ export class Chat extends EventEmitter{
97
97
  get efforts(){const e=this.info?.efforts;return Array.isArray(e)?e:['low','medium','high','max']}
98
98
  async setEffort(e){if(!['low','medium','high','max'].includes(e))throw new Error('Effort is low, medium, high or max');
99
99
  const ok=this.efforts;if(ok.length&&!ok.includes(e))throw new Error(this.modelLabel+' takes '+ok.join(', ')+' effort');this.effort=e;this.session.meta.effort=e;await this.session.save();this.emit('change')}
100
- async setSession(s){this.#bind(s);this.mode=sessionMode(s.meta);if(s.meta.model)this.model=s.meta.model;this.emit('session',s);this.emit('change')}
100
+ async setSession(s){this.#bind(s);this.mode=sessionMode(s.meta);if(s.meta.model)this.model=s.meta.model;
101
+ // Effort belongs to the session: a new one (/cd, /clear) starts from the --effort flag or the saved default, not the last session's choice.
102
+ this.effort=s.meta.effort||this.flags.effort||this.settings?.effort||'medium';this.emit('session',s);this.emit('change')}
101
103
  async rename(title){
102
104
  const t=String(title||'').replace(/[\x00-\x1f\x7f]/g,'').trim().slice(0,80);if(!t)throw new Error('Give a name: /rename <name>');
103
105
  this.session.meta.title=t;this.session.meta.renamed=true;await this.session.save();this.emit('change');return t;
@@ -129,9 +129,9 @@ export function install(register){
129
129
  ctx.out('Rewound to before turn '+(turn+1)+(r.files?' · '+r.files.restored+' file'+(r.files.restored===1?'':'s')+' restored, '+r.files.removed+' removed':'')+'.');
130
130
  return {rewound:turn};
131
131
  }});
132
- register({name:'usage',aliases:['cost'],summary:'Credits and tokens used, and what is left',run:async ctx=>{
132
+ register({name:'usage',aliases:['cost'],summary:'Credits used, and what is left',run:async ctx=>{
133
133
  const chat=need(ctx),u=chat.usage;
134
- ctx.out(['This session: '+formatCredits(creditsFor(u.tokens))+' credits · '+u.tokens.toLocaleString('en-US')+' tokens · '+u.calls+' model call'+(u.calls===1?'':'s')+' · '+ctx.session.meta.turns.length+' turn'+(ctx.session.meta.turns.length===1?'':'s'),
134
+ ctx.out(['This session: '+formatCredits(creditsFor(u.tokens))+' credits · '+u.calls+' model call'+(u.calls===1?'':'s')+' · '+ctx.session.meta.turns.length+' turn'+(ctx.session.meta.turns.length===1?'':'s'),
135
135
  'Model: '+chat.modelLabel+' · '+chat.credits,
136
136
  chat.tokensLeft!=null?'Plan: about '+formatCredits(creditsFor(chat.tokensLeft))+' credits left':'Plan: credits left show after the first turn',
137
137
  'Plan and billing: the account menu in the app'].join('\n'));
@@ -123,7 +123,7 @@ function sandboxStatus(ctx){
123
123
  const on=s.enabled!==false,net=s.network!==false;
124
124
  const how=SANDBOXES.includes(kind)?{seatbelt:'macOS Seatbelt',bwrap:'bubblewrap',windows:'a restricted Windows token'}[kind]:null;
125
125
  const netHow=osNetwork(kind)==='os'?'; enforced by the OS, only the model gateway is reachable':'; enforced by the engine check, not the OS, on this computer';
126
- return [...(ctx.chat?.restricted?['Restricted mode: shell commands are off, file tools stay in this project, and the sandbox stays on.']:[]),'Sandbox: '+(on?'on':'off')+(on?how?' ('+how+'; Auto and Plan runs can only write in the repository and caches)':' (not available on this computer; Auto mode cannot start)':' (Auto mode runs commands without the OS sandbox)'),
126
+ return [...(ctx.chat?.restricted?['Restricted mode: shell commands are off, file tools stay in this project, and the sandbox stays on.']:[]),'Sandbox: '+(on?'on':'off')+(on?how?' ('+how+'; Auto runs can only write in the repository and caches; Plan and Ask are read-only)':' (not available on this computer; Auto mode cannot start)':' (Auto mode runs commands without the OS sandbox)'),
127
127
  'Network: '+(net?'on':'off'+' (web tools, remote hosts and package installs are refused'+netHow+')')].join('\n');
128
128
  }
129
129
  async function sandboxCmd(ctx,args){
@@ -277,6 +277,12 @@ async function hooksCmd(ctx,args){
277
277
  }
278
278
 
279
279
  // ------------------------------------------------------------------ /plugin
280
+ /** Shortens text to at most n characters at a word boundary, with an ellipsis when anything was cut. */
281
+ export function clipWords(s,n){
282
+ const t=String(s||'').replace(/\s+/g,' ').trim();if(t.length<=n)return t;
283
+ const cut=t.slice(0,n-1),sp=cut.lastIndexOf(' ');
284
+ return (sp>n/2?cut.slice(0,sp):cut).replace(/[\s,;:.-]+$/,'')+'\u2026';
285
+ }
280
286
  async function pluginCmd(ctx,args){
281
287
  const [sub]=String(args||'').trim().split(/\s+/);
282
288
  const web='Settings, Plugins in the web app';
@@ -287,7 +293,7 @@ async function pluginCmd(ctx,args){
287
293
  const L=[installed.length?'Installed plugins:':'No plugins installed.'];
288
294
  for(const p of installed){const m=p.manifest||{};L.push(' '+String(m.name||m.id).padEnd(24)+' '+String(m.version||'').padEnd(8)+' '+(p.enabled?.all?'on everywhere':p.enabled?.projects?.length?'on in '+p.enabled.projects.length+' project(s)':'off'))}
289
295
  const cat=(Array.isArray(x.catalog)?x.catalog:[]).filter(m=>!installed.some(p=>p.manifest?.id===m.id));
290
- if(cat.length)L.push('','Available:',...cat.map(m=>' '+String(m.name||m.id).padEnd(24)+' '+String(m.description||'').slice(0,70)));
296
+ if(cat.length)L.push('','Available:',...cat.map(m=>' '+String(m.name||m.id).padEnd(24)+' '+clipWords(m.description,70)));
291
297
  L.push('','Manage plugins in '+web+'.');
292
298
  ctx.out(L.join('\n'));return {plugins:installed.map(p=>p.manifest?.id)};
293
299
  }
@@ -145,7 +145,8 @@ export async function dispatch(ctx,line){
145
145
  /** /help text from the registry. */
146
146
  export function helpText(ctx){
147
147
  const rows=list(ctx);const w=Math.min(28,Math.max(...rows.map(r=>(r.name+' '+r.args).length))+2);
148
- return rows.map(r=>('/'+r.name+(r.args?' '+r.args:'')).padEnd(w+1)+r.summary+(r.aliases.length?' (also /'+r.aliases.join(', /')+')':'')).join('\n');
148
+ // A name longer than the column still gets a space before its description.
149
+ return rows.map(r=>{const n='/'+r.name+(r.args?' '+r.args:'');return n.padEnd(w+1)+(n.length>=w+1?' ':'')+r.summary+(r.aliases.length?' (also /'+r.aliases.join(', /')+')':'')}).join('\n');
149
150
  }
150
151
 
151
152
  /** Imports src/tui/cmd-*.mjs and calls each install(register). Returns the module names; a broken module is reported, not fatal. */
@@ -5,6 +5,7 @@
5
5
  */
6
6
  import {execFile,spawn} from 'node:child_process';
7
7
  import {width,truncate} from './ansi.mjs';
8
+ import {credits} from '../render.mjs';
8
9
  import {MODES,modeName,sessionMode} from '../modes.mjs';
9
10
 
10
11
  export const compact=n=>{n=Number(n)||0;const a=Math.abs(n);return a>=1e9?(n/1e9).toFixed(1).replace(/\.0$/,'')+'B':a>=1e6?(n/1e6).toFixed(1).replace(/\.0$/,'')+'M':a>=1e4?Math.round(n/1e3)+'k':a>=1e3?(n/1e3).toFixed(1).replace(/\.0$/,'')+'k':String(Math.round(n))};
@@ -57,7 +58,7 @@ function piece(name,d,t){
57
58
  case 'cwd':return d.folder?t.dim(d.folder):'';
58
59
  case 'session':return d.sessionName||d.session?t.dim(String(d.sessionName||d.session).slice(0,24)):'';
59
60
  case 'context':{if(!d.context)return '';const p=d.context.percent,style=p>=85?t.bad:p>=65?t.warn:t.dim;return style(p+'% context')}
60
- case 'credits':return d.tokensLeft!=null?t.dim(compact(d.tokensLeft)+' tokens left'):d.usage?.tokens?t.dim(compact(d.usage.tokens)+' tokens'):'';
61
+ case 'credits':return d.tokensLeft!=null?t.dim(credits(d.tokensLeft)+' left'):d.usage?.tokens?t.dim(credits(d.usage.tokens)):'';
61
62
  case 'time':{const n=d.now?new Date(d.now):new Date();return t.dim(String(n.getHours()).padStart(2,'0')+':'+String(n.getMinutes()).padStart(2,'0'))}
62
63
  }
63
64
  return '';
package/src/wakeups.mjs CHANGED
@@ -11,12 +11,12 @@ async function writeJson(file,data){const tmp=file+'.'+process.pid+'.tmp';await
11
11
  export function dueWake(w,now=Date.now()){
12
12
  if(!w||typeof w!=='object'||w.state!=='pending'||!ID.test(String(w.id)))return null;
13
13
  const at=Date.parse(String(w.at));if(!Number.isFinite(at)||at>now)return null;
14
- return {id:w.id,kind:w.kind==='goal'?'goal':'agent',note:String(w.note||'').slice(0,1000),at:w.at};
14
+ return {id:w.id,kind:w.kind==='goal'||w.kind==='verify'?w.kind:'agent',note:String(w.note||'').slice(0,1000),at:w.at};
15
15
  }
16
16
  /** Run fields for the wake run, carried over from the session's last request (the worker keeps its own context). */
17
17
  export function wakeRun(request,wake){
18
18
  const r=request&&typeof request==='object'?request:{};
19
- return {task:wake.note||(wake.kind==='goal'?'Continue the goal':'Scheduled check-in'),wake:{id:wake.id,kind:wake.kind,note:wake.note},
19
+ return {task:wake.note||(wake.kind==='goal'?'Continue the goal':wake.kind==='verify'?'Continue and fix the open checks':'Scheduled check-in'),wake:{id:wake.id,kind:wake.kind,note:wake.note},
20
20
  ...(['plan','approve','auto','brief'].includes(r.mode)?{mode:r.mode}:{}),...(typeof r.role==='string'&&r.role?{role:r.role}:{}),
21
21
  ...(typeof r.modelId==='string'?{model:r.modelId}:{}),...(['low','medium','high'].includes(r.reasoningEffort)?{effort:r.reasoningEffort}:{}),
22
22
  ...(typeof r.planApproval==='string'?{planApproval:r.planApproval}:{}),...(Number(r.steps)>0?{steps:Math.min(160,Number(r.steps))}:{})};
@@ -47,7 +47,7 @@ function diagnostic({surface,version,os,arch,code,status,protocol=PROTOCOL}={}){
47
47
  class Client{
48
48
  constructor({baseUrl=DEFAULT_URL,tokenProvider=()=>null,fetchImpl=globalThis.fetch,surface='desktop',version='0.1.0',allowLoopback=false,timeoutMs=30000}={}){
49
49
  this.baseUrl=serverOrigin(baseUrl,{allowLoopback});this.tokenProvider=tokenProvider;this.fetch=fetchImpl;
50
- if(!['desktop','vscode','jetbrains','acp','laptop'].includes(surface))throw new ClientError('Invalid client surface');
50
+ if(!['desktop','vscode','jetbrains','acp','laptop','mobile'].includes(surface))throw new ClientError('Invalid client surface');
51
51
  this.surface=surface;this.version=string(version,'version',60);this.timeoutMs=timeoutMs;
52
52
  }
53
53
  async request(path,body,{method='POST',signal,authenticated=true,readOnly=false}={}){
@@ -102,9 +102,9 @@ class Client{
102
102
  if(!/^[a-f0-9-]{36}$/.test(requestId))throw new ClientError('Invalid request ID');
103
103
  return this.workspace(token,'run',{task,mode,planApproval:'guided',requestId},{signal});
104
104
  }
105
- approve(token,id,approved,{signal,revise}={}){
105
+ approve(token,id,approved,{signal,revise,all}={}){
106
106
  string(id,'approval ID',150);if(typeof approved!=='boolean')throw new ClientError('Approval must be explicit');
107
- return this.workspace(token,'approve',{id,approved,...(revise?{revise:string(revise,'revision',5000)}:{})},{signal});
107
+ return this.workspace(token,'approve',{id,approved,...(approved&&all===true?{all:true}:{}),...(revise?{revise:string(revise,'revision',5000)}:{})},{signal});
108
108
  }
109
109
  stop(token,options){return this.workspace(token,'stop',{},options)}
110
110
  async files(token,options){const s=await this.status(token,options);return {files:s.files||[]}}