mlai-code 0.3.1 → 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.
- package/README.md +1 -1
- package/package.json +2 -2
- package/src/cli.mjs +27 -7
- package/src/distribution.mjs +5 -5
- package/src/engine-key.mjs +18 -4
- package/src/engine.mjs +4 -9
- package/src/home.mjs +1 -1
- package/src/parity.mjs +3 -1
- package/src/render.mjs +3 -1
- package/src/runtime.mjs +21 -1
- package/src/sandbox.mjs +19 -3
- package/src/session.mjs +22 -2
- package/src/shared-data.mjs +1 -1
- package/src/tui/app.mjs +22 -4
- package/src/tui/chat.mjs +8 -6
- package/src/tui/cmd-core.mjs +2 -2
- package/src/tui/cmd-extensibility.mjs +8 -2
- package/src/tui/commands.mjs +2 -1
- package/src/tui/statusline.mjs +2 -1
- package/src/wakeups.mjs +2 -2
- package/vendor/client-sdk/index.cjs +3 -3
- package/vendor/cloud-cli/mlai.mjs +169 -25
- package/worker/build_planner.py +75 -7
- package/worker/cloud_pty.py +91 -2
- package/worker/command_safety.py +25 -1
- package/worker/compaction_brief.py +186 -0
- package/worker/context_manager.py +9 -3
- package/worker/conversation.py +58 -1
- package/worker/deck_render.js +11 -0
- package/worker/deck_tools.py +825 -0
- package/worker/git_sync.py +38 -13
- package/worker/goals.py +4 -0
- package/worker/image_generation.py +102 -23
- package/worker/kimi_bridge.py +406 -40
- package/worker/kimi_gates.py +84 -1
- package/worker/kimi_hook.py +113 -12
- package/worker/media_tools.py +179 -0
- package/worker/memory.py +2 -2
- package/worker/mlai_hooks.py +93 -3
- package/worker/mlai_mcp.py +23 -5
- package/worker/model_stream.py +21 -7
- package/worker/obs_mask.py +97 -0
- package/worker/offline_guard.py +1 -1
- package/worker/preview.py +47 -4
- package/worker/product_facts.py +18 -0
- package/worker/project_context.py +33 -7
- package/worker/reply_language.py +92 -10
- package/worker/roles.json +199 -37
- package/worker/roles.py +243 -8
- package/worker/runner.py +253 -42
- package/worker/site_check.py +279 -0
- package/worker/skill_library.py +15 -3
- package/worker/skill_pack.py +170 -16
- package/worker/tool_catalog.py +3 -2
- package/worker/verification.py +43 -11
- package/worker/wakeups.py +56 -4
package/README.md
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "mlai-code",
|
|
3
|
-
"version": "0.3.
|
|
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": {
|
|
@@ -18,4 +18,4 @@
|
|
|
18
18
|
],
|
|
19
19
|
"homepage": "https://mlai-mini-code.vercel.app/downloads",
|
|
20
20
|
"license": "UNLICENSED"
|
|
21
|
-
}
|
|
21
|
+
}
|
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')+' · '+
|
|
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
|
|
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
|
-
|
|
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/distribution.mjs
CHANGED
|
@@ -16,7 +16,7 @@
|
|
|
16
16
|
* managed install stages the new build so it starts next time; others print a one-line notice next time. It never
|
|
17
17
|
* runs for -p/--print, --json, non-TTY or CI, and is off with settings autoUpdate=false or MLAI_AUTO_UPDATE=0.
|
|
18
18
|
*/
|
|
19
|
-
import {createHash,
|
|
19
|
+
import {createHash,verify as edVerify} from 'node:crypto';
|
|
20
20
|
import {gunzipSync} from 'node:zlib';
|
|
21
21
|
import fs from 'node:fs';
|
|
22
22
|
import fsp from 'node:fs/promises';
|
|
@@ -24,7 +24,7 @@ import path from 'node:path';
|
|
|
24
24
|
import {spawn} from 'node:child_process';
|
|
25
25
|
import {fileURLToPath} from 'node:url';
|
|
26
26
|
import {VERSION,DEFAULT_SERVER,home} from './home.mjs';
|
|
27
|
-
import {
|
|
27
|
+
import {pinnedPublicKey,ed25519PublicKey} from './engine-key.mjs';
|
|
28
28
|
|
|
29
29
|
export const PROTOCOL=1;
|
|
30
30
|
export const NPM_PACKAGE='mlai-code';
|
|
@@ -67,13 +67,13 @@ export function canonical(m){return ['mlai-cli',m.protocol,m.version,m.id,m.sha2
|
|
|
67
67
|
export const sha256=bytes=>createHash('sha256').update(bytes).digest('hex');
|
|
68
68
|
|
|
69
69
|
/** Throws unless the manifest is well formed and (when this copy pins a key) signed with that key. */
|
|
70
|
-
export function checkManifest(m,{publicKey=
|
|
70
|
+
export function checkManifest(m,{publicKey=pinnedPublicKey()}={}){
|
|
71
71
|
if(!m||typeof m!=='object')throw new Error('The update server sent no manifest.');
|
|
72
72
|
if(m.protocol!==PROTOCOL)throw new Error('This CLI is too old to read the update manifest. Reinstall: '+installCommand());
|
|
73
73
|
if(!ID.test(String(m.id))||!SHA.test(String(m.sha256))||!Number.isInteger(m.size)||m.size<=0||!m.version)throw new Error('The update manifest is malformed.');
|
|
74
74
|
if(publicKey){
|
|
75
75
|
if(!m.signature)throw new Error('The update is not signed. Refusing to install it.');
|
|
76
|
-
let ok=false;try{ok=edVerify(null,Buffer.from(canonical(m)),
|
|
76
|
+
let ok=false;try{ok=edVerify(null,Buffer.from(canonical(m)),ed25519PublicKey(publicKey),Buffer.from(m.signature,'base64'))}catch{}
|
|
77
77
|
if(!ok)throw new Error('The update signature does not match. Refusing to install it.');
|
|
78
78
|
}
|
|
79
79
|
return m;
|
|
@@ -204,7 +204,7 @@ async function withLock(dir,fn){
|
|
|
204
204
|
/**
|
|
205
205
|
* How this copy was installed, from where its files are:
|
|
206
206
|
* managed ~/.mlai/cli/versions/<id> (install.sh / install.ps1) -> mlai update replaces it
|
|
207
|
-
* npm .../node_modules/mlai-code
|
|
207
|
+
* npm .../node_modules/mlai-code -> npm install -g mlai-code@latest
|
|
208
208
|
* brew .../Cellar/mlai/... -> brew upgrade mlai
|
|
209
209
|
* app inside the Mac app bundle -> updates with the app
|
|
210
210
|
* source a repository checkout -> git pull
|
package/src/engine-key.mjs
CHANGED
|
@@ -1,4 +1,18 @@
|
|
|
1
|
-
/* The Ed25519 public key that signs harness updates (lib/laptop-engine.ts)
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
1
|
+
/* The Ed25519 public key that signs harness updates (lib/laptop-engine.ts) and CLI release manifests (lib/cli-release.ts),
|
|
2
|
+
base64 of the raw 32 bytes (what publicKeyOf() in lib/laptop-engine.ts prints; key id fc37e74e7423f42f). The server
|
|
3
|
+
signs with MLAI_ENGINE_SIGNING_KEY. A copy with this pin refuses unsigned or badly signed manifests: harness updates
|
|
4
|
+
fall back to the bundled harness, `mlai update` installs nothing. MLAI_ENGINE_PUBLIC_KEY overrides it (tests, CI). */
|
|
5
|
+
import {createPublicKey} from 'node:crypto';
|
|
6
|
+
|
|
7
|
+
export const ENGINE_PUBLIC_KEY='xT81sNCk0xWN5qYJ1C1SFZXk9mFw5Vt53JG9zVLawFA=';
|
|
8
|
+
|
|
9
|
+
const SPKI_PREFIX=Buffer.from('302a300506032b6570032100','hex');
|
|
10
|
+
/** The pinned key as base64: MLAI_ENGINE_PUBLIC_KEY, else ENGINE_PUBLIC_KEY ('' when neither is set). */
|
|
11
|
+
export const pinnedPublicKey=(env=process.env)=>String(env.MLAI_ENGINE_PUBLIC_KEY||ENGINE_PUBLIC_KEY||'').trim();
|
|
12
|
+
/** A KeyObject from base64 of either the raw 32-byte Ed25519 key or its full SPKI DER (44 bytes); throws otherwise. */
|
|
13
|
+
export function ed25519PublicKey(b64){
|
|
14
|
+
const k=Buffer.from(String(b64||'').trim(),'base64');
|
|
15
|
+
if(k.length===32)return createPublicKey({key:Buffer.concat([SPKI_PREFIX,k]),format:'der',type:'spki'});
|
|
16
|
+
if(k.length===44&&k.subarray(0,12).equals(SPKI_PREFIX))return createPublicKey({key:k,format:'der',type:'spki'});
|
|
17
|
+
throw Object.assign(new Error('The pinned update key is not a 32-byte Ed25519 public key'),{code:'engine_key'});
|
|
18
|
+
}
|
package/src/engine.mjs
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import {createHash,
|
|
1
|
+
import {createHash,verify,randomUUID} from 'node:crypto';
|
|
2
2
|
import {readFile,writeFile,mkdir,rename,rm,readdir,copyFile,stat} from 'node:fs/promises';
|
|
3
3
|
import path from 'node:path';
|
|
4
4
|
import {sub,workerDir} from './home.mjs';
|
|
5
|
-
import {
|
|
5
|
+
import {pinnedPublicKey,ed25519PublicKey} from './engine-key.mjs';
|
|
6
6
|
|
|
7
7
|
/* Harness auto-update: runs use the newest worker the server publishes (GET /api/laptop/engine, lib/laptop-engine.ts)
|
|
8
8
|
without an app update, and fall back to the copy bundled with the app on any doubt.
|
|
@@ -14,7 +14,7 @@ import {ENGINE_PUBLIC_KEY} 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','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}$/;
|
|
@@ -32,13 +32,8 @@ export function bundleHash(entries){
|
|
|
32
32
|
export function canonicalManifest(m){
|
|
33
33
|
return JSON.stringify({v:1,protocol:m.protocol,version:m.version,files:[...m.files].sort((a,b)=>a.path<b.path?-1:a.path>b.path?1:0).map(f=>[f.path,f.sha256,f.size])});
|
|
34
34
|
}
|
|
35
|
-
const SPKI=Buffer.from('302a300506032b6570032100','hex');
|
|
36
35
|
/** The pinned Ed25519 public key: MLAI_ENGINE_PUBLIC_KEY, else the one shipped in engine-key.mjs, else none. */
|
|
37
|
-
export function pinnedKey(){
|
|
38
|
-
const raw=String(process.env.MLAI_ENGINE_PUBLIC_KEY||ENGINE_PUBLIC_KEY||'').trim();if(!raw)return null;
|
|
39
|
-
const key=Buffer.from(raw,'base64');if(key.length!==32)throw fail('The pinned engine key is not a 32-byte Ed25519 key','engine_key');
|
|
40
|
-
return createPublicKey({key:Buffer.concat([SPKI,key]),format:'der',type:'spki'});
|
|
41
|
-
}
|
|
36
|
+
export function pinnedKey(){const raw=pinnedPublicKey();return raw?ed25519PublicKey(raw):null}
|
|
42
37
|
/** Shape, limits and (with a pinned key) the signature; returns a clean copy. Throws plain errors with a code. */
|
|
43
38
|
export function checkManifest(m,{key=pinnedKey()}={}){
|
|
44
39
|
if(!m||typeof m!=='object')throw fail('The server sent no engine manifest','engine_manifest');
|
package/src/home.mjs
CHANGED
|
@@ -3,7 +3,7 @@ import path from 'node:path';
|
|
|
3
3
|
import {mkdirSync,chmodSync,statSync} from 'node:fs';
|
|
4
4
|
import {fileURLToPath} from 'node:url';
|
|
5
5
|
|
|
6
|
-
export const VERSION='0.3.
|
|
6
|
+
export const VERSION='0.3.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(' · '+
|
|
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=
|
|
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
|
-
|
|
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});
|
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"}}};
|
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
|
-
|
|
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){
|
|
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
|
-
|
|
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){
|
|
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,
|
|
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=
|
|
27
|
-
export const creditsFor=tokens=>Math.round(Math.max(0,Number(tokens)||0)/TOKENS_PER_CREDIT*
|
|
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||'
|
|
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;
|
|
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;
|
package/src/tui/cmd-core.mjs
CHANGED
|
@@ -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
|
|
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.
|
|
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
|
|
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)+' '+
|
|
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
|
}
|
package/src/tui/commands.mjs
CHANGED
|
@@ -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
|
-
|
|
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. */
|
package/src/tui/statusline.mjs
CHANGED
|
@@ -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(
|
|
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 '';
|