mlai-code 0.0.0-stage → 0.3.0
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 +12 -2
- package/bin/mlai.mjs +3 -0
- package/package.json +18 -3
- package/src/browser-setup.mjs +77 -0
- package/src/cli-ext.mjs +146 -0
- package/src/cli.mjs +534 -0
- package/src/cloud.mjs +29 -0
- package/src/completion.mjs +159 -0
- package/src/credentials.mjs +54 -0
- package/src/deploy.mjs +134 -0
- package/src/distribution.mjs +373 -0
- package/src/engine-key.mjs +4 -0
- package/src/engine.mjs +167 -0
- package/src/headless.mjs +196 -0
- package/src/home.mjs +22 -0
- package/src/host.mjs +123 -0
- package/src/local-models.mjs +64 -0
- package/src/modes.mjs +38 -0
- package/src/netbox.mjs +97 -0
- package/src/netjail.py +59 -0
- package/src/offline.mjs +98 -0
- package/src/parity.mjs +86 -0
- package/src/project.mjs +68 -0
- package/src/relay.mjs +140 -0
- package/src/render.mjs +73 -0
- package/src/restricted.mjs +47 -0
- package/src/review.mjs +70 -0
- package/src/runner.mjs +127 -0
- package/src/runtime.mjs +75 -0
- package/src/sandbox.mjs +135 -0
- package/src/sdk.mjs +11 -0
- package/src/server.mjs +110 -0
- package/src/session.mjs +290 -0
- package/src/settings.mjs +135 -0
- package/src/shared-data.mjs +3 -0
- package/src/tui/acp.mjs +145 -0
- package/src/tui/agents-cli.mjs +114 -0
- package/src/tui/agents-local.mjs +65 -0
- package/src/tui/ansi.mjs +123 -0
- package/src/tui/app.mjs +710 -0
- package/src/tui/approval.mjs +88 -0
- package/src/tui/bg.mjs +172 -0
- package/src/tui/bgterm.mjs +79 -0
- package/src/tui/chat.mjs +230 -0
- package/src/tui/clipboard.mjs +74 -0
- package/src/tui/cloud-cli.mjs +57 -0
- package/src/tui/cloud-run.mjs +123 -0
- package/src/tui/cmd-agents.mjs +130 -0
- package/src/tui/cmd-auto-review.mjs +94 -0
- package/src/tui/cmd-cloud.mjs +17 -0
- package/src/tui/cmd-config.mjs +104 -0
- package/src/tui/cmd-core.mjs +160 -0
- package/src/tui/cmd-distribution.mjs +15 -0
- package/src/tui/cmd-ecosystem.mjs +169 -0
- package/src/tui/cmd-extensibility.mjs +333 -0
- package/src/tui/cmd-remote.mjs +18 -0
- package/src/tui/cmd-review.mjs +58 -0
- package/src/tui/cmd-session-extra.mjs +152 -0
- package/src/tui/cmd-tui.mjs +200 -0
- package/src/tui/commands.mjs +160 -0
- package/src/tui/custom-commands.mjs +98 -0
- package/src/tui/diff.mjs +60 -0
- package/src/tui/editor.mjs +190 -0
- package/src/tui/ext-state.mjs +16 -0
- package/src/tui/extensions-local.mjs +140 -0
- package/src/tui/files.mjs +72 -0
- package/src/tui/handoff.mjs +110 -0
- package/src/tui/import-setups.mjs +151 -0
- package/src/tui/init.mjs +104 -0
- package/src/tui/keymap.mjs +70 -0
- package/src/tui/keys.mjs +101 -0
- package/src/tui/loop.mjs +75 -0
- package/src/tui/markdown.mjs +118 -0
- package/src/tui/mcp-config.mjs +225 -0
- package/src/tui/mcp-oauth.mjs +162 -0
- package/src/tui/permissions.mjs +189 -0
- package/src/tui/plain.mjs +32 -0
- package/src/tui/plugins-local.mjs +103 -0
- package/src/tui/remote.mjs +125 -0
- package/src/tui/review-cli.mjs +332 -0
- package/src/tui/review-github.mjs +59 -0
- package/src/tui/screen.mjs +60 -0
- package/src/tui/session-ops.mjs +104 -0
- package/src/tui/skills-local.mjs +92 -0
- package/src/tui/snapshots.mjs +87 -0
- package/src/tui/statusline.mjs +98 -0
- package/src/tui/transcript.mjs +116 -0
- package/src/two-words.mjs +36 -0
- package/src/wakeups.mjs +53 -0
- package/src/winenv.mjs +94 -0
- package/src/winsandbox.py +351 -0
- package/src/workspace-api.mjs +621 -0
- package/src/worktree.mjs +128 -0
- package/vendor/client-sdk/controller.cjs +115 -0
- package/vendor/client-sdk/files.cjs +38 -0
- package/vendor/client-sdk/index.cjs +133 -0
- package/vendor/client-sdk/login.cjs +52 -0
- package/vendor/client-sdk/updates.cjs +41 -0
- package/vendor/cloud-cli/mlai.mjs +394 -0
- package/worker/architecture_parse.cjs +23 -0
- package/worker/architecture_worker.py +394 -0
- package/worker/ask_first.py +96 -0
- package/worker/attachment_reader.py +66 -0
- package/worker/background_jobs.py +111 -0
- package/worker/brief_questions.py +56 -0
- package/worker/browser_local.py +49 -0
- package/worker/browser_pane.py +89 -0
- package/worker/browser_tool.py +101 -0
- package/worker/build_planner.py +187 -0
- package/worker/chat_fork.py +277 -0
- package/worker/checkpoints.py +133 -0
- package/worker/cloud_pty.py +351 -0
- package/worker/command_policy.py +39 -0
- package/worker/command_safety.py +717 -0
- package/worker/computer_card.sh +23 -0
- package/worker/computer_setup.sh +86 -0
- package/worker/computer_use.py +221 -0
- package/worker/connector_search.py +43 -0
- package/worker/context_manager.py +60 -0
- package/worker/conversation.py +144 -0
- package/worker/deploy_pack.py +116 -0
- package/worker/design_director.py +240 -0
- package/worker/dev_jobs.py +166 -0
- package/worker/edit_guard.py +99 -0
- package/worker/env_setup.py +129 -0
- package/worker/evidence.py +109 -0
- package/worker/fast_search.py +24 -0
- package/worker/git_sync.py +333 -0
- package/worker/goals.py +156 -0
- package/worker/handover.py +98 -0
- package/worker/harness_memory.py +194 -0
- package/worker/image_generation.py +173 -0
- package/worker/intelligence.py +149 -0
- package/worker/intent_model.py +78 -0
- package/worker/intent_weights.json +1 -0
- package/worker/ios_simulator.py +87 -0
- package/worker/kimi_bridge.py +997 -0
- package/worker/kimi_compact.py +93 -0
- package/worker/kimi_gates.py +304 -0
- package/worker/kimi_hook.py +617 -0
- package/worker/lifecycle.py +95 -0
- package/worker/lsp.py +77 -0
- package/worker/mcp_local.py +293 -0
- package/worker/memory.py +99 -0
- package/worker/mlai_auto_review.py +177 -0
- package/worker/mlai_hooks.py +966 -0
- package/worker/mlai_mcp.py +441 -0
- package/worker/mlai_permissions.py +283 -0
- package/worker/model_stream.py +75 -0
- package/worker/nested_repos.py +76 -0
- package/worker/offline_guard.py +17 -0
- package/worker/preview.py +806 -0
- package/worker/proc_watch.py +124 -0
- package/worker/project_context.py +72 -0
- package/worker/project_rules.py +99 -0
- package/worker/quality.py +180 -0
- package/worker/reply_language.py +56 -0
- package/worker/repo_hygiene.py +132 -0
- package/worker/repo_memory.py +101 -0
- package/worker/repo_policy.py +269 -0
- package/worker/roles.json +3173 -0
- package/worker/roles.py +303 -0
- package/worker/runner.py +1795 -0
- package/worker/runtime_control.py +205 -0
- package/worker/secret_scan.py +168 -0
- package/worker/session_hub.py +80 -0
- package/worker/skill_library.py +129 -0
- package/worker/skill_pack.py +533 -0
- package/worker/subagents.py +91 -0
- package/worker/task_controller.py +139 -0
- package/worker/task_skills.py +159 -0
- package/worker/team_checkpoint.py +33 -0
- package/worker/token_count.py +32 -0
- package/worker/tool_catalog.py +38 -0
- package/worker/upload_storage.py +531 -0
- package/worker/verification.py +725 -0
- package/worker/vision.py +84 -0
- package/worker/wakeups.py +63 -0
- package/worker/web_tools.py +203 -0
- package/worker/winproc.py +135 -0
- package/worker/work_ledger.py +117 -0
- package/worker/worktrees.py +79 -0
package/src/session.mjs
ADDED
|
@@ -0,0 +1,290 @@
|
|
|
1
|
+
import {renameBranch} from './worktree.mjs';
|
|
2
|
+
import {EventEmitter} from 'node:events';
|
|
3
|
+
import {spawn} from 'node:child_process';
|
|
4
|
+
import {randomUUID,randomBytes} from 'node:crypto';
|
|
5
|
+
import {open,readFile,writeFile,rename,rm,mkdir,readdir,stat} from 'node:fs/promises';
|
|
6
|
+
import {existsSync} from 'node:fs';
|
|
7
|
+
import path from 'node:path';
|
|
8
|
+
import os from 'node:os';
|
|
9
|
+
import {home,sub} from './home.mjs';
|
|
10
|
+
import {prepareEngine} from './engine.mjs';
|
|
11
|
+
import {projectRoot,projectId,computerCard,gitRemote} from './project.mjs';
|
|
12
|
+
import {ensureRuntime} from './runtime.mjs';
|
|
13
|
+
import {wrap,sandboxKind,SANDBOXES,denyRoots} from './sandbox.mjs';
|
|
14
|
+
import {windowsEnv,killTree,ensureBusybox} from './winenv.mjs';
|
|
15
|
+
import {twoWordTitle,isTwoWords} from './two-words.mjs';
|
|
16
|
+
import {mergeExtensions} from './tui/extensions-local.mjs';
|
|
17
|
+
import {NET_KINDS,startRelay,offlineEnv} from './netbox.mjs';
|
|
18
|
+
|
|
19
|
+
export const MODES={guided:'approve',auto:'auto',plan:'plan'};
|
|
20
|
+
/** Web shell run modes to the session's sandbox mode. Brief mode asks before building, so it runs guided. */
|
|
21
|
+
export const RUN_MODES={approve:'guided',auto:'auto',plan:'plan',brief:'guided'};
|
|
22
|
+
const ENTRIES=['runner.py','kimi_bridge.py'];
|
|
23
|
+
/** Only non-secret settings the server may hand to the harness (gateway URLs, versions, model names). */
|
|
24
|
+
const SERVER_ENV=/^(MINI_IMAGE_GATEWAY|MINI_RESEARCH_GATEWAY|MINI_KIMI_VERSION|OPENROUTER_IMAGE_MODEL|MLAI_HUB_URL)$/;
|
|
25
|
+
export function serverEnv(env){
|
|
26
|
+
const out={};
|
|
27
|
+
for(const [k,v] of Object.entries(env&&typeof env==='object'?env:{}))if(SERVER_ENV.test(k)&&typeof v==='string'&&v.length<2000)out[k]=v;
|
|
28
|
+
return out;
|
|
29
|
+
}
|
|
30
|
+
/** Vault secrets the owner shared with the agent: kept in memory and handed to the harness as MINI_VAULT, like cloud runs. */
|
|
31
|
+
export function vaultEnv(secrets){
|
|
32
|
+
const vault={};
|
|
33
|
+
for(const [k,v] of Object.entries(secrets&&typeof secrets==='object'?secrets:{}))if(/^[A-Za-z_][A-Za-z0-9_]{0,99}$/.test(k)&&typeof v==='string'&&v)vault[k]=v;
|
|
34
|
+
const json=JSON.stringify(vault);
|
|
35
|
+
return Object.keys(vault).length&&json.length<200000?{MINI_VAULT:json}:{};
|
|
36
|
+
}
|
|
37
|
+
export function redact(text,values){let out=String(text||'');for(const v of values)if(typeof v==='string'&&v.length>=4)out=out.split(v).join('[redacted]');return out}
|
|
38
|
+
const FINAL=['completed','limited','error','stopped','interrupted'];
|
|
39
|
+
const RESET=['inference-progress.json','cancel','events.jsonl','pending.json','checks.json','todos.json','completion.json','steering.json','design-review.json','status.json'];
|
|
40
|
+
/** Environment variables that look like credentials stay out of the agent's processes unless allowed. */
|
|
41
|
+
const SECRET_ENV=/(TOKEN|SECRET|PASSWORD|PASSWD|API_?KEY|PRIVATE_?KEY|CREDENTIAL|SESSION_?KEY|AUTH)/i;
|
|
42
|
+
export function agentEnv(base=process.env,allow=(base.MLAI_PASS_ENV||'').split(',').map(s=>s.trim()).filter(Boolean)){
|
|
43
|
+
const out={};
|
|
44
|
+
for(const [k,v] of Object.entries(base)){
|
|
45
|
+
if(v==null||k.startsWith('MLAI_')||k==='MODEL_API_KEY')continue;
|
|
46
|
+
if(SECRET_ENV.test(k)&&!allow.includes(k))continue;
|
|
47
|
+
out[k]=v;
|
|
48
|
+
}
|
|
49
|
+
return out;
|
|
50
|
+
}
|
|
51
|
+
/** The server-built request (same builder as cloud runs) with this machine's run id, task and attachments. */
|
|
52
|
+
export function serverRequest(built,{started,task,images=[]}){
|
|
53
|
+
const {secrets,network,...rest}=built;
|
|
54
|
+
return {...rest,runId:started.runId,task:typeof built.task==='string'&&built.task.trim()?built.task:task,laptop:true,endpoint:built.endpoint||started.gateway,harness:built.harness||started.harness||'mini',
|
|
55
|
+
...(rest.accountTokensLeft===undefined?{accountTokensLeft:started.budget??null}:{}),...(images.length?{images}:{})};
|
|
56
|
+
}
|
|
57
|
+
/** A title the engine made before two-word names (the first task cut at 80) becomes two words; a rename (meta.renamed) never changes. */
|
|
58
|
+
export function legacyTitle(m){const t=String(m?.title||''),first=String(m?.turns?.[0]?.task||'');return t&&!m.renamed&&!isTwoWords(t)&&first&&first.slice(0,80)===t?twoWordTitle(first):null}
|
|
59
|
+
async function writeJson(file,data){const tmp=file+'.tmp';await writeFile(tmp,JSON.stringify(data));await rename(tmp,file)}
|
|
60
|
+
async function readJson(file,fallback){try{return JSON.parse(await readFile(file,'utf8'))}catch{return fallback}}
|
|
61
|
+
/** Images attached to a message (screenshots, mockups). Stored in the session folder; the harness shows them to the model. */
|
|
62
|
+
export const IMAGE_MAX=4,IMAGE_BYTES=5_000_000;
|
|
63
|
+
export const IMAGE_NAME=/^[a-f0-9]{16}\.(png|jpg|webp|gif)$/;
|
|
64
|
+
export function imageKind(bytes){
|
|
65
|
+
const b=Buffer.isBuffer(bytes)?bytes:Buffer.from(bytes||[]);
|
|
66
|
+
if(b.length>=8&&b.subarray(0,8).equals(Buffer.from([0x89,0x50,0x4e,0x47,0x0d,0x0a,0x1a,0x0a])))return 'png';
|
|
67
|
+
if(b.length>=3&&b[0]===0xff&&b[1]===0xd8&&b[2]===0xff)return 'jpg';
|
|
68
|
+
if(b.length>=12&&b.toString('latin1',0,4)==='RIFF'&&b.toString('latin1',8,12)==='WEBP')return 'webp';
|
|
69
|
+
if(b.length>=6&&/^GIF8[79]a$/.test(b.toString('latin1',0,6)))return 'gif';
|
|
70
|
+
return null;
|
|
71
|
+
}
|
|
72
|
+
const MIME={png:'image/png',jpg:'image/jpeg',webp:'image/webp',gif:'image/gif'};
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* One conversation about one project. The session folder is the harness's state root, the project folder is
|
|
76
|
+
* its repository. Each message is one run: the cloud issues a run token for the model gateway, the harness runs
|
|
77
|
+
* here, and the run is closed with the usage the gateway counted.
|
|
78
|
+
*/
|
|
79
|
+
export class Session extends EventEmitter{
|
|
80
|
+
constructor(meta){super();this.meta=meta;this.dir=path.join(sub('sessions'),meta.id);this.child=null;this.offset=0}
|
|
81
|
+
static async create({cwd=process.cwd(),mode='guided',worktree=null,id=null}={}){
|
|
82
|
+
if(!MODES[mode])throw new Error('Mode must be guided, auto or plan');
|
|
83
|
+
// id: a caller-chosen session id (mlai --session-id); it must be a new UUID.
|
|
84
|
+
if(id!==null&&!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(String(id)))throw new Error('Session id must be a UUID');
|
|
85
|
+
const newId=id?String(id).toLowerCase():randomUUID();
|
|
86
|
+
if(worktree){
|
|
87
|
+
// The session works in its own checkout; it still belongs to (and is listed with) the main folder.
|
|
88
|
+
const {root}=await projectRoot(worktree.path);
|
|
89
|
+
const meta={id:newId,root,git:true,parent:worktree.parent,worktree:{path:root,branch:worktree.branch,base:worktree.base,baseBranch:worktree.baseBranch||null,copied:worktree.copied||[],named:!!worktree.named},project:await projectId(worktree.parent),folder:path.basename(worktree.parent),mode,created:new Date().toISOString(),title:'',turns:[]};
|
|
90
|
+
const s=new Session(meta);await mkdir(s.dir,{recursive:true,mode:0o700});await s.save();return s;
|
|
91
|
+
}
|
|
92
|
+
const {root,git}=await projectRoot(cwd);
|
|
93
|
+
const meta={id:newId,root,git,project:await projectId(root),folder:path.basename(root),mode,created:new Date().toISOString(),title:'',turns:[]};
|
|
94
|
+
const s=new Session(meta);await mkdir(s.dir,{recursive:true,mode:0o700});await s.save();return s;
|
|
95
|
+
}
|
|
96
|
+
static async open(id){
|
|
97
|
+
const meta=await readJson(path.join(sub('sessions'),id,'session.json'),null);
|
|
98
|
+
if(!meta)throw new Error('No session '+id);
|
|
99
|
+
return new Session(meta);
|
|
100
|
+
}
|
|
101
|
+
static async list(){
|
|
102
|
+
const dir=sub('sessions');const out=[];
|
|
103
|
+
for(const id of await readdir(dir).catch(()=>[])){const m=await readJson(path.join(dir,id,'session.json'),null);if(!m)continue;
|
|
104
|
+
const t=legacyTitle(m);if(t){m.title=t;await writeJson(path.join(dir,id,'session.json'),m).catch(()=>{})}out.push(m)}
|
|
105
|
+
return out.sort((a,b)=>(b.updated||b.created).localeCompare(a.updated||a.created));
|
|
106
|
+
}
|
|
107
|
+
async save(){this.meta.updated=new Date().toISOString();await writeJson(path.join(this.dir,'session.json'),this.meta)}
|
|
108
|
+
get running(){return Boolean(this.child)}
|
|
109
|
+
|
|
110
|
+
/** Moves the previous turn into history so the harness sees it as conversation context. */
|
|
111
|
+
async archive(){
|
|
112
|
+
const events=path.join(this.dir,'events.jsonl');if(!existsSync(events))return;
|
|
113
|
+
const lines=(await readFile(events,'utf8')).split('\n').flatMap(l=>{try{return [JSON.parse(l)]}catch{return []}});
|
|
114
|
+
const prior=await readJson(path.join(this.dir,'request.json'),{});
|
|
115
|
+
const h=path.join(this.dir,'history');await mkdir(h,{recursive:true});
|
|
116
|
+
const read=n=>readJson(path.join(this.dir,n),n==='completion.json'?null:[]);
|
|
117
|
+
await writeFile(path.join(h,String(process.hrtime.bigint()+BigInt(Date.now())*1000000n)+'.json'),JSON.stringify({task:prior.task||'',...(Array.isArray(prior.images)?{images:prior.images}:{}),status:await readJson(path.join(this.dir,'status.json'),{}),todos:await read('todos.json'),checks:await read('checks.json'),completion:await read('completion.json'),events:lines}));
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** Runs one message to completion. Resolves with the final status. */
|
|
121
|
+
/** Saves one image for the next message. Returns its name. Only PNG, JPEG, WebP and GIF, up to 5 MB. */
|
|
122
|
+
async addImage(bytes){
|
|
123
|
+
const b=Buffer.isBuffer(bytes)?bytes:Buffer.from(bytes||[]);
|
|
124
|
+
if(!b.length)throw new Error('The image is empty.');
|
|
125
|
+
if(b.length>IMAGE_BYTES)throw new Error('Images can be up to 5 MB.');
|
|
126
|
+
const kind=imageKind(b);if(!kind)throw new Error('Use a PNG, JPEG, WebP or GIF image.');
|
|
127
|
+
const d=path.join(this.dir,'attachments');await mkdir(d,{recursive:true,mode:0o700});
|
|
128
|
+
const name=randomBytes(8).toString('hex')+'.'+kind;await writeFile(path.join(d,name),b,{mode:0o600});
|
|
129
|
+
return name;
|
|
130
|
+
}
|
|
131
|
+
/** An attached image as a data URL, for showing it in the conversation. */
|
|
132
|
+
async image(name){
|
|
133
|
+
if(!IMAGE_NAME.test(String(name)))throw new Error('Invalid image');
|
|
134
|
+
const b=await readFile(path.join(this.dir,'attachments',name)).catch(()=>null);if(!b)throw new Error('This image is no longer available.');
|
|
135
|
+
return 'data:'+MIME[name.split('.').pop()]+';base64,'+b.toString('base64');
|
|
136
|
+
}
|
|
137
|
+
async #images(list){
|
|
138
|
+
if(list==null)return [];
|
|
139
|
+
if(!Array.isArray(list)||list.length>IMAGE_MAX)throw new Error('Attach up to '+IMAGE_MAX+' images.');
|
|
140
|
+
const out=[];
|
|
141
|
+
for(const n of list){if(!IMAGE_NAME.test(String(n))||!existsSync(path.join(this.dir,'attachments',n)))throw new Error('An attached image is missing. Attach it again.');if(!out.includes(n))out.push(n)}
|
|
142
|
+
return out;
|
|
143
|
+
}
|
|
144
|
+
/**
|
|
145
|
+
* `run` (optional) is the web shell's run body (task, mode, role, model, effort, planApproval, askFirst, tools...).
|
|
146
|
+
* The server builds the run request from it, exactly as for a cloud run; without it (or with an older server) the
|
|
147
|
+
* engine uses its own reduced request. Resolves with {intake} when the server asks for details instead of starting.
|
|
148
|
+
*/
|
|
149
|
+
async send(task,{cloud,steps=120,effort='medium',onProgress=()=>{},allowUnsandboxed=false,images,run=null,extraEnv=null,extraRead=null,starter=null,finisher=null,extensions=null}={}){
|
|
150
|
+
if(this.child)throw new Error('A task is already running in this session');
|
|
151
|
+
if(typeof task!=='string'||!task.trim()||task.length>30000)throw new Error('Enter a task under 30,000 characters');
|
|
152
|
+
images=await this.#images(images);
|
|
153
|
+
const mode=run?RUN_MODES[run.mode]||'guided':this.meta.mode,kind=sandboxKind();
|
|
154
|
+
// CLI /sandbox off (extensions.sandbox.enabled false) is the user's explicit choice to run without the OS sandbox.
|
|
155
|
+
const sandboxOff=extensions?.sandbox?.enabled===false;
|
|
156
|
+
if(mode==='auto'&&!SANDBOXES.includes(kind)&&!allowUnsandboxed&&!sandboxOff)throw new Error('Auto mode needs an OS sandbox, which is not available here. Use guided mode, or pass --no-sandbox to accept running commands with your full permissions.');
|
|
157
|
+
await this.lock();
|
|
158
|
+
try{return await this.#run(task,{cloud,steps,effort,onProgress,mode,kind,images,run,extraEnv,extraRead,starter,finisher,extensions})}finally{await rm(path.join(this.dir,'running.lock'),{force:true})}
|
|
159
|
+
}
|
|
160
|
+
/** One task at a time per session across processes: the terminal and the Mac app share ~/.mlai. */
|
|
161
|
+
async lock(){
|
|
162
|
+
const file=path.join(this.dir,'running.lock');
|
|
163
|
+
for(let i=0;i<2;i++){
|
|
164
|
+
try{await writeFile(file,String(process.pid),{flag:'wx'});return}
|
|
165
|
+
catch(e){
|
|
166
|
+
if(e.code!=='EEXIST')throw e;
|
|
167
|
+
const pid=Number(await readFile(file,'utf8').catch(()=>''));
|
|
168
|
+
let alive=pid===process.pid;if(pid>0&&!alive){try{process.kill(pid,0);alive=true}catch(err){alive=err.code==='EPERM'}}
|
|
169
|
+
if(alive)throw Object.assign(new Error('This session is already running in another ML AI Code window or terminal.'),{code:'session_busy'});
|
|
170
|
+
await rm(file,{force:true});
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
throw Object.assign(new Error('This session is busy. Try again.'),{code:'session_busy'});
|
|
174
|
+
}
|
|
175
|
+
async #run(task,{cloud,steps,effort,onProgress,mode,kind,images=[],run,extraEnv,extraRead,starter,finisher,extensions=null}){
|
|
176
|
+
const python=await ensureRuntime({onProgress});
|
|
177
|
+
// The newest verified harness from the server, or the bundled one (src/engine.mjs); offline runs never check.
|
|
178
|
+
const engine=await prepareEngine({cloud:starter?null:cloud}),worker=engine.dir,used={version:engine.version,source:engine.source};
|
|
179
|
+
// A worktree branch gets its real name from the first task (mlai/fix-login-redirect), if nothing was pushed yet.
|
|
180
|
+
if(this.meta.worktree&&!this.meta.worktree.named&&!this.meta.worktree.removed){try{const next=await renameBranch({...this.meta.worktree,parent:this.meta.parent},task);this.meta.worktree={...this.meta.worktree,branch:next.branch,named:true};await this.save()}catch{}}
|
|
181
|
+
// folderProject and repo let a chat that is not filed in a sidebar project get the context of the folder it runs in.
|
|
182
|
+
const repo=this.meta.git?await gitRemote(this.meta.parent||this.meta.root):'';
|
|
183
|
+
const startBody={project:this.meta.cloudProject||this.meta.project,folder:this.meta.folder,folderProject:this.meta.project,...(repo?{repo}:{}),title:twoWordTitle(task,'Laptop Task'),...(run?{run:{...run,task,...(images.length?{images}:{})}}:{})};
|
|
184
|
+
const started=starter?await starter(startBody):await cloud.start(startBody);
|
|
185
|
+
// The server answered with intake questions instead of starting: nothing ran and no run token was issued.
|
|
186
|
+
if(started?.intake&&!started.token){this.emit('intake',started.intake);return {intake:started.intake}}
|
|
187
|
+
await this.archive();
|
|
188
|
+
for(const n of RESET)await rm(path.join(this.dir,n),{force:true});
|
|
189
|
+
for(const f of await readdir(this.dir).catch(()=>[]))if(f.startsWith('decision-'))await rm(path.join(this.dir,f),{force:true});
|
|
190
|
+
// Restricted mode (src/restricted.mjs) runs every mode in the OS sandbox and never accepts /sandbox off.
|
|
191
|
+
const restricted=extensions?.restricted?.enabled===true;
|
|
192
|
+
const wantSandbox=restricted?SANDBOXES.includes(kind):(mode==='auto'||mode==='plan')&&extensions?.sandbox?.enabled!==false;
|
|
193
|
+
const busybox=wantSandbox&&kind==='windows'?await ensureBusybox(home(),{onProgress,server:cloud?.server}):undefined;
|
|
194
|
+
const extraDeny=denyRoots(started.request?.extensions?.hardDeny?.paths,{repo:this.meta.root});
|
|
195
|
+
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
|
+
const sandboxed=wantSandbox?wrap('x',[],box):null;
|
|
197
|
+
const secrets=started.secrets&&typeof started.secrets==='object'?started.secrets:{};
|
|
198
|
+
const built=started.request&&typeof started.request==='object'?started.request:null;
|
|
199
|
+
const request=built?serverRequest(built,{started,task,images}):{runId:started.runId,task,laptop:true,conversational:true,streaming:true,focused_tools:true,provider:'isoquant',model:started.model?.id||'mlai-code',endpoint:started.gateway,
|
|
200
|
+
contextWindow:started.model?.contextWindow||131072,responseReserve:started.model?.responseReserve||32768,vision:started.model?.vision!==false,accountTokensLeft:started.budget??null,
|
|
201
|
+
tools:[],mode:MODES[mode],reasoningEffort:effort,planApproval:'off',briefFirst:false,askFirst:'never',go:true,role:'engineer',steps:Math.min(160,Math.max(1,steps)),harness:'mini',...(images.length?{images}:{}),...(run?.goal?{goal:run.goal}:{}),...(run?.wake?{wake:run.wake}:{})};
|
|
202
|
+
// CLI extensions (tui/extensions-local.mjs): permission rules, local hooks, network, MCP servers. Their ${VAR}
|
|
203
|
+
// values travel in the environment like Vault secrets, never in request.json.
|
|
204
|
+
let mcpEnv=null;
|
|
205
|
+
if(extensions){const m=mergeExtensions(request.extensions,extensions);request.extensions=m.extensions;mcpEnv=m.mcpEnv}
|
|
206
|
+
// Network off (src/netbox.mjs): with Seatbelt or bubblewrap the harness gets no network at all, only a relay to
|
|
207
|
+
// the model gateway; elsewhere the engine's hook-level block is all there is (status says which).
|
|
208
|
+
const netOff=request.extensions?.network?.enabled===false;
|
|
209
|
+
const relay=netOff&&NET_KINDS.includes(kind)&&request.endpoint?await startRelay({targets:[request.endpoint,built?serverEnv(started.env).MINI_IMAGE_GATEWAY:null],deny:[built?serverEnv(started.env).MINI_RESEARCH_GATEWAY:null],kind}):null;
|
|
210
|
+
try{
|
|
211
|
+
if(relay)request.endpoint=relay.rewrite(request.endpoint);
|
|
212
|
+
await writeFile(path.join(this.dir,'computer.md'),await computerCard({sandbox:sandboxed?.kind||'none',mode,network:netOff?(relay?'os':'hooks'):'on',restricted}));
|
|
213
|
+
await writeJson(path.join(this.dir,'request.json'),request);
|
|
214
|
+
await writeJson(path.join(this.dir,'status.json'),{state:'starting',started:Date.now()/1000,engine:used});
|
|
215
|
+
const turn={runId:started.runId,task:task.slice(0,2000),...(images.length?{images}:{}),started:new Date().toISOString(),state:'running',engine:used};
|
|
216
|
+
this.meta.turns.push(turn);if(!this.meta.title)this.meta.title=twoWordTitle(task);await this.save();
|
|
217
|
+
let env={...agentEnv(),...(built?serverEnv(started.env):{}),MINI_ROOT:this.dir,MINI_REPO:this.meta.root,MODEL_API_KEY:started.token,PYTHONDONTWRITEBYTECODE:'1',PYTHONUNBUFFERED:'1',MINI_PREVIEW_PROD:'0',MINI_LAPTOP:'1',MINI_ENGINE_VERSION:used.version,...(extraEnv&&typeof extraEnv==='object'?extraEnv:{}),...vaultEnv(secrets),...(mcpEnv?{MINI_MCP_ENV:JSON.stringify(mcpEnv)}:{})};
|
|
218
|
+
const script=path.join(worker,built&&ENTRIES.includes(started.entry)?started.entry:'runner.py');
|
|
219
|
+
if(relay)env=offlineEnv(env,relay);
|
|
220
|
+
const launch=(sandboxed?wrap(python,[script],{...box,network:relay?.box||null}):relay?wrap(python,[script],{...box,netOnly:true,network:relay.box}):null)||{cmd:python,args:[script]};
|
|
221
|
+
env=windowsEnv({...env,PYTHONUTF8:'1',...(launch.env||{})});
|
|
222
|
+
const log=await open(path.join(this.dir,'worker.log'),'a');
|
|
223
|
+
this.offset=0;
|
|
224
|
+
const child=spawn(launch.cmd,launch.args,{cwd:this.meta.root,env,stdio:['ignore',log.fd,log.fd],detached:process.platform!=='win32',windowsHide:true});
|
|
225
|
+
this.child=child;this.emit('started',{runId:started.runId,harness:request.harness||'mini',engine:used,sandbox:sandboxed?.kind||'none',...(netOff?{network:launch.network==='os'?'off (OS)':'off (engine check only)'}:{}),...(restricted?{restricted:true}:{}),tokensLeft:started.accountTokensLeft??started.budget??null});
|
|
226
|
+
const timer=setInterval(()=>this.poll().catch(()=>{}),150);
|
|
227
|
+
const exit=await new Promise(resolve=>{child.on('exit',(code,signal)=>resolve({code,signal}));child.on('error',e=>resolve({code:-1,error:e.message}))});
|
|
228
|
+
clearInterval(timer);await this.poll().catch(()=>{});await log.close().catch(()=>{});this.child=null;
|
|
229
|
+
if(relay)await relay.close().catch(()=>{});
|
|
230
|
+
let status=await readJson(path.join(this.dir,'status.json'),{});
|
|
231
|
+
if(!FINAL.includes(status.state)){
|
|
232
|
+
const tail=(await readFile(path.join(this.dir,'worker.log'),'utf8').catch(()=>'')).split('\n').filter(Boolean).slice(-6).join('\n');
|
|
233
|
+
const clean=redact(tail,[started.token,...Object.values(secrets)]);
|
|
234
|
+
status={state:existsSync(path.join(this.dir,'cancel'))?'stopped':'error',error:exit.error||('The local engine exited unexpectedly.'+(clean?'\n'+clean:''))};
|
|
235
|
+
}
|
|
236
|
+
// Which harness ran is part of the final status (the harness rewrites status.json while it runs).
|
|
237
|
+
status={...status,engine:used};await writeJson(path.join(this.dir,'status.json'),status);
|
|
238
|
+
let usage=null;
|
|
239
|
+
try{usage=finisher?await finisher(started.token,status.state,status.usage):await cloud.finish(started.token,status.state,status.usage)}catch(e){usage={error:e.message}}
|
|
240
|
+
Object.assign(turn,{state:status.state,finished:new Date().toISOString(),tokens:usage?.tokens??status.tokens??0,calls:usage?.calls??status.calls??0});
|
|
241
|
+
await this.save();
|
|
242
|
+
const result={...status,usage,completion:await readJson(path.join(this.dir,'completion.json'),null)};
|
|
243
|
+
// The gateway refuses calls once the plan allowance for this run is used; say so plainly.
|
|
244
|
+
if(status.state!=='completed'&&started.budget!=null&&Number(usage?.tokens)>=started.budget){result.code='billing_limit';result.error='Your plan allowance ran out during this task. Changes so far are kept. Upgrade or wait for the allowance to reset, then continue.'}
|
|
245
|
+
this.emit('done',result);
|
|
246
|
+
return result;
|
|
247
|
+
}finally{if(relay)await relay.close().catch(()=>{})}
|
|
248
|
+
}
|
|
249
|
+
/** Earlier turns plus the current one, for showing a resumed session. */
|
|
250
|
+
async transcript(){
|
|
251
|
+
const h=path.join(this.dir,'history');const turns=[];
|
|
252
|
+
for(const f of (await readdir(h).catch(()=>[])).filter(n=>n.endsWith('.json')).sort((a,b)=>a.length-b.length||a.localeCompare(b)).slice(-20)){
|
|
253
|
+
const t=await readJson(path.join(h,f),null);if(t)turns.push({task:t.task,...(t.images?{images:t.images}:{}),status:t.status,completion:t.completion,events:(t.events||[]).slice(-400)});
|
|
254
|
+
}
|
|
255
|
+
const lines=(await readFile(path.join(this.dir,'events.jsonl'),'utf8').catch(()=>'')).split('\n').flatMap(l=>{try{return l?[JSON.parse(l)]:[]}catch{return []}});
|
|
256
|
+
const req=await readJson(path.join(this.dir,'request.json'),null);
|
|
257
|
+
if(req||lines.length)turns.push({task:req?.task||'',...(req?.images?{images:req.images}:{}),status:await readJson(path.join(this.dir,'status.json'),{}),completion:await readJson(path.join(this.dir,'completion.json'),null),events:lines.slice(-400),current:true});
|
|
258
|
+
return turns;
|
|
259
|
+
}
|
|
260
|
+
/** New events from the harness, read incrementally from events.jsonl. */
|
|
261
|
+
async poll(){
|
|
262
|
+
const file=path.join(this.dir,'events.jsonl');let size;try{size=(await stat(file)).size}catch{return}
|
|
263
|
+
if(size<=this.offset)return;
|
|
264
|
+
const fh=await open(file,'r');
|
|
265
|
+
try{
|
|
266
|
+
const buf=Buffer.alloc(size-this.offset);await fh.read(buf,0,buf.length,this.offset);
|
|
267
|
+
const text=buf.toString('utf8'),end=text.lastIndexOf('\n');if(end<0)return;
|
|
268
|
+
this.offset+=Buffer.byteLength(text.slice(0,end+1));
|
|
269
|
+
for(const line of text.slice(0,end).split('\n')){if(!line.trim())continue;try{this.emit('event',JSON.parse(line))}catch{}}
|
|
270
|
+
}finally{await fh.close()}
|
|
271
|
+
}
|
|
272
|
+
async pending(){return readJson(path.join(this.dir,'pending.json'),null)}
|
|
273
|
+
/** verdict: approve | approve_all | reject */
|
|
274
|
+
async decide(id,verdict){
|
|
275
|
+
if(!/^[a-f0-9]{8,64}$/.test(String(id)))throw new Error('Invalid approval');
|
|
276
|
+
if(!['approve','approve_all','reject'].includes(verdict))throw new Error('Invalid decision');
|
|
277
|
+
await writeFile(path.join(this.dir,'decision-'+id),verdict);
|
|
278
|
+
}
|
|
279
|
+
async steer(message){
|
|
280
|
+
const d=path.join(this.dir,'steering');await mkdir(d,{recursive:true});
|
|
281
|
+
await writeJson(path.join(d,Date.now()+'-'+randomUUID().slice(0,8)+'.json'),{message:String(message).slice(0,5000),created:Date.now()});
|
|
282
|
+
}
|
|
283
|
+
async cancel(){
|
|
284
|
+
await writeFile(path.join(this.dir,'cancel'),'1');
|
|
285
|
+
const c=this.child;if(!c)return;
|
|
286
|
+
setTimeout(()=>{if(this.child===c)killTree(c.pid)},8000).unref();
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
export {sandboxKind};
|
|
290
|
+
export const defaults={os:os.platform()};
|
package/src/settings.mjs
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Layered settings (CLI v1 shared contract), lowest to highest:
|
|
3
|
+
* defaults < ~/.mlai/settings.json (user) < <repo>/.mlai/settings.json (project, committed)
|
|
4
|
+
* < <repo>/.mlai/settings.local.json (local, gitignored) < flags
|
|
5
|
+
* Objects merge by key; permission lists (allow, deny, ask) add up across layers so a project can add rules but a
|
|
6
|
+
* user's deny always stays. Unknown keys are kept (features may add their own) but known keys are type-checked:
|
|
7
|
+
* a bad value in one file is dropped with a warning instead of breaking the CLI.
|
|
8
|
+
*/
|
|
9
|
+
import {readFileSync} from 'node:fs';
|
|
10
|
+
import {mkdir,writeFile,rename,readFile,appendFile} from 'node:fs/promises';
|
|
11
|
+
import path from 'node:path';
|
|
12
|
+
import {home} from './home.mjs';
|
|
13
|
+
|
|
14
|
+
export const SCOPES=['user','project','local'];
|
|
15
|
+
export const DEFAULTS=Object.freeze({
|
|
16
|
+
model:null, // null: the account default; otherwise an id from the server's model list
|
|
17
|
+
mode:'agent', // agent | plan | ask | auto (modes.mjs)
|
|
18
|
+
effort:'medium', // low | medium | high | max (max only where the model takes it)
|
|
19
|
+
fallbackModel:null, // model id or [ids] tried in order when the chosen model is overloaded or unavailable
|
|
20
|
+
permissions:{allow:[],deny:[],ask:[]}, // rules like 'Bash(npm test:*)', 'Edit(src/**)', 'WebFetch(domain:x.com)'
|
|
21
|
+
sandbox:{enabled:true,network:true},
|
|
22
|
+
hooks:{}, // event -> [{matcher, command}] (the existing hooks format)
|
|
23
|
+
mcpServers:{}, // name -> {command, args, env} or {url}
|
|
24
|
+
theme:'auto', // auto | dark | light
|
|
25
|
+
vim:false,
|
|
26
|
+
statusLine:{enabled:true,command:null},
|
|
27
|
+
autoUpdate:true,
|
|
28
|
+
maxSteps:120,
|
|
29
|
+
reviewModel:null, // /review and mlai review (null: the chat's model); auto-review sends it, the cloud gateway keeps the run's model
|
|
30
|
+
autoReview:true, // auto mode: a reviewer pass gates risky actions (mlai_auto_review.py)
|
|
31
|
+
});
|
|
32
|
+
const MODES=['agent','plan','ask','auto'],EFFORTS=['low','medium','high','max'],THEMES=['auto','dark','light'];
|
|
33
|
+
const MODEL_ID=/^[\w.:/-]{1,80}$/;
|
|
34
|
+
export const STATUS_ITEMS=['mode','model','effort','branch','context','credits','cwd','session','time','vim','queue','jobs'];
|
|
35
|
+
export const SYNTAX_THEMES=['default','github','monokai','solarized','nord','mono'];
|
|
36
|
+
const isObj=v=>v!==null&&typeof v==='object'&&!Array.isArray(v);
|
|
37
|
+
const strList=v=>Array.isArray(v)&&v.every(x=>typeof x==='string'&&x.length<=500);
|
|
38
|
+
/** key -> check(value) => true when valid. */
|
|
39
|
+
export const CHECKS={
|
|
40
|
+
model:v=>v===null||(typeof v==='string'&&MODEL_ID.test(v)),
|
|
41
|
+
mode:v=>MODES.includes(v),
|
|
42
|
+
effort:v=>EFFORTS.includes(v),
|
|
43
|
+
fallbackModel:v=>v===null||(typeof v==='string'&&MODEL_ID.test(v))||(Array.isArray(v)&&v.length<=5&&v.every(x=>typeof x==='string'&&MODEL_ID.test(x))),
|
|
44
|
+
permissions:v=>isObj(v)&&['allow','deny','ask'].every(k=>v[k]===undefined||strList(v[k])),
|
|
45
|
+
sandbox:v=>isObj(v)&&(v.enabled===undefined||typeof v.enabled==='boolean')&&(v.network===undefined||typeof v.network==='boolean'),
|
|
46
|
+
hooks:isObj,
|
|
47
|
+
mcpServers:isObj,
|
|
48
|
+
theme:v=>THEMES.includes(v),
|
|
49
|
+
vim:v=>typeof v==='boolean',
|
|
50
|
+
statusLine:v=>typeof v==='boolean'||(isObj(v)&&(v.enabled===undefined||typeof v.enabled==='boolean')&&(v.command==null||typeof v.command==='string')&&(v.items===undefined||(strList(v.items)&&v.items.every(x=>STATUS_ITEMS.includes(x))))),
|
|
51
|
+
// Interface keys (src/tui): key bindings, code colors, window title, interface choice, raw scrollback.
|
|
52
|
+
keymap:v=>isObj(v)&&Object.entries(v).every(([a,k])=>/^[a-zA-Z]{1,40}$/.test(a)&&(k===null||(typeof k==='string'&&k.length<=40))),
|
|
53
|
+
syntaxTheme:v=>SYNTAX_THEMES.includes(v),
|
|
54
|
+
terminalTitle:v=>typeof v==='string'&&v.length<=200,
|
|
55
|
+
tui:v=>['auto','full','plain'].includes(v),
|
|
56
|
+
rawScrollback:v=>typeof v==='boolean',
|
|
57
|
+
autoUpdate:v=>typeof v==='boolean',
|
|
58
|
+
maxSteps:v=>Number.isInteger(v)&&v>=1&&v<=160,
|
|
59
|
+
reviewModel:v=>v===null||(typeof v==='string'&&/^[\w.:/-]{1,80}$/.test(v)),
|
|
60
|
+
autoReview:v=>typeof v==='boolean',
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
export function settingsPaths(root){
|
|
64
|
+
const p={user:path.join(home(),'settings.json')};
|
|
65
|
+
if(root){p.project=path.join(root,'.mlai','settings.json');p.local=path.join(root,'.mlai','settings.local.json')}
|
|
66
|
+
return p;
|
|
67
|
+
}
|
|
68
|
+
function readLayer(file,warn){
|
|
69
|
+
let text;try{text=readFileSync(file,'utf8')}catch{return {}}
|
|
70
|
+
let v;try{v=JSON.parse(text)}catch{warn(file+' is not valid JSON; ignoring it.');return {}}
|
|
71
|
+
if(!isObj(v)){warn(file+' must hold a JSON object; ignoring it.');return {}}
|
|
72
|
+
return clean(v,file,warn);
|
|
73
|
+
}
|
|
74
|
+
/** Drops invalid known keys (with a warning); keeps unknown keys. */
|
|
75
|
+
export function clean(v,where='settings',warn=()=>{}){
|
|
76
|
+
const out={};
|
|
77
|
+
for(const [k,x] of Object.entries(v)){
|
|
78
|
+
if(k==='statusLine'&&typeof x==='boolean'){out[k]={enabled:x};continue}
|
|
79
|
+
if(CHECKS[k]&&!CHECKS[k](x)){warn(where+': ignoring an invalid value for "'+k+'".');continue}
|
|
80
|
+
out[k]=x;
|
|
81
|
+
}
|
|
82
|
+
return out;
|
|
83
|
+
}
|
|
84
|
+
const LISTS=new Set(['permissions.allow','permissions.deny','permissions.ask']);
|
|
85
|
+
function merge(a,b,at=''){
|
|
86
|
+
const out={...a};
|
|
87
|
+
for(const [k,v] of Object.entries(b)){
|
|
88
|
+
const key=at?at+'.'+k:k;
|
|
89
|
+
if(v===undefined)continue;
|
|
90
|
+
if(LISTS.has(key)&&Array.isArray(v))out[k]=[...new Set([...(Array.isArray(a[k])?a[k]:[]),...v])];
|
|
91
|
+
else if(isObj(v)&&isObj(a[k]))out[k]=merge(a[k],v,key);
|
|
92
|
+
else out[k]=isObj(v)?merge({},v,key):Array.isArray(v)?[...v]:v;
|
|
93
|
+
}
|
|
94
|
+
return out;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Loads the merged settings for a repository root (null outside a project). `flags` are the CLI's own overrides
|
|
99
|
+
* ({model, mode, effort, maxSteps, ...}; undefined values are skipped). Returns a frozen-ish object with:
|
|
100
|
+
* .sources key -> scope that last set it ('default' | 'user' | 'project' | 'local' | 'flag')
|
|
101
|
+
* .warnings messages about ignored files or values
|
|
102
|
+
* .save(scope, key, value) writes one key to a scope file and returns the reloaded settings
|
|
103
|
+
*/
|
|
104
|
+
export function loadSettings({root=null,flags={}}={}){
|
|
105
|
+
const warnings=[];const warn=m=>warnings.push(m);
|
|
106
|
+
const paths=settingsPaths(root);
|
|
107
|
+
const layers=[['default',DEFAULTS],...SCOPES.filter(s=>paths[s]).map(s=>[s,readLayer(paths[s],warn)]),['flag',clean(Object.fromEntries(Object.entries(flags||{}).filter(([,v])=>v!==undefined&&v!==null)),'flags',warn)]];
|
|
108
|
+
let merged={};const sources={};
|
|
109
|
+
for(const [scope,layer] of layers){merged=merge(merged,layer);for(const k of Object.keys(layer))sources[k]=scope}
|
|
110
|
+
Object.defineProperties(merged,{
|
|
111
|
+
sources:{value:sources},warnings:{value:warnings},paths:{value:paths},root:{value:root},
|
|
112
|
+
save:{value:async(scope,key,value,opts={})=>{await saveSetting({root,scope,key,value,...opts});return loadSettings({root,flags})}},
|
|
113
|
+
});
|
|
114
|
+
return merged;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** Writes one top-level key (value undefined removes it) to a scope file, atomically. The local file is gitignored. */
|
|
118
|
+
/** permissions adds rules to the file's lists (pass {allow:['Bash(npm test:*)']}); replace:true writes the value as given. */
|
|
119
|
+
export async function saveSetting({root=null,scope='user',key,value,replace=false}){
|
|
120
|
+
if(!SCOPES.includes(scope))throw new Error('Scope must be user, project or local');
|
|
121
|
+
if(typeof key!=='string'||!/^[A-Za-z][\w]{0,40}$/.test(key))throw new Error('Invalid settings key');
|
|
122
|
+
if(value!==undefined&&CHECKS[key]&&!CHECKS[key](value))throw new Error('Invalid value for '+key);
|
|
123
|
+
const file=settingsPaths(root)[scope];if(!file)throw new Error('Project settings need a project folder');
|
|
124
|
+
let cur={};try{const v=JSON.parse(await readFile(file,'utf8'));if(isObj(v))cur=v}catch{}
|
|
125
|
+
if(value===undefined)delete cur[key];else cur[key]=key==='permissions'&&!replace&&isObj(cur[key])?merge(cur[key],value,'permissions'):value;
|
|
126
|
+
await mkdir(path.dirname(file),{recursive:true});
|
|
127
|
+
const tmp=file+'.'+process.pid+'.tmp';
|
|
128
|
+
await writeFile(tmp,JSON.stringify(cur,null,2)+'\n',{mode:scope==='user'?0o600:0o644});await rename(tmp,file);
|
|
129
|
+
if(scope==='local')await ignoreLocal(path.dirname(file));
|
|
130
|
+
return file;
|
|
131
|
+
}
|
|
132
|
+
async function ignoreLocal(dir){
|
|
133
|
+
const gi=path.join(dir,'.gitignore');const text=await readFile(gi,'utf8').catch(()=>'');
|
|
134
|
+
if(!text.split(/\r?\n/).includes('settings.local.json'))await appendFile(gi,(text&&!text.endsWith('\n')?'\n':'')+'settings.local.json\n');
|
|
135
|
+
}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// Generated from lib/skills.ts starterSkills and lib/safety-gates.ts POLICY_TEMPLATES; test/parity.test.mjs checks it.
|
|
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"}}};
|
package/src/tui/acp.mjs
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
// `mlai acp`: the local agent as an Agent Client Protocol server over stdio (JSON-RPC 2.0, one message per line).
|
|
2
|
+
// Editors (Zed, JetBrains, Neovim plugins) start it in a project; the agent works in that folder on this computer,
|
|
3
|
+
// exactly like `mlai` in a terminal. No dependencies: stdout carries protocol messages only, diagnostics go to stderr.
|
|
4
|
+
import readline from 'node:readline';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import {randomUUID} from 'node:crypto';
|
|
7
|
+
import {MODES,MODE_NAMES,modeName,applyMode,taskFor,sessionMode} from '../modes.mjs';
|
|
8
|
+
|
|
9
|
+
export const PROTOCOL_VERSION=1;
|
|
10
|
+
const ERR={parse:-32700,invalid:-32600,method:-32601,params:-32602,internal:-32603,auth:-32000,session:-32002};
|
|
11
|
+
class RpcError extends Error{constructor(code,message){super(message);this.code=code}}
|
|
12
|
+
|
|
13
|
+
/** The editor's tool kind for an engine event. */
|
|
14
|
+
export function toolKind(e){
|
|
15
|
+
if(e.type==='command')return 'execute';
|
|
16
|
+
const n=String(e.name||'').toLowerCase();
|
|
17
|
+
return /edit|write|patch|replace|create_file/.test(n)?'edit':/read|open|view|cat/.test(n)?'read':/search|grep|find|glob|list/.test(n)?'search':/fetch|web|browse/.test(n)?'fetch':/delete|remove/.test(n)?'delete':'other';
|
|
18
|
+
}
|
|
19
|
+
/** Prompt content blocks -> task text. Text, embedded text resources and resource links (by path) are accepted. */
|
|
20
|
+
export function promptText(blocks){
|
|
21
|
+
if(!Array.isArray(blocks))throw new RpcError(ERR.params,'prompt must be a list of content blocks');
|
|
22
|
+
const parts=blocks.map(b=>{
|
|
23
|
+
if(b?.type==='text')return String(b.text||'');
|
|
24
|
+
if(b?.type==='resource'&&typeof b.resource?.text==='string')return 'File '+(b.resource.uri||'')+':\n'+b.resource.text;
|
|
25
|
+
if(b?.type==='resource_link')return '@'+String(b.uri||b.name||'').replace(/^file:\/\//,'');
|
|
26
|
+
throw new RpcError(ERR.params,'Only text, embedded text and file links are supported.');
|
|
27
|
+
});
|
|
28
|
+
const task=parts.join('\n\n').trim();
|
|
29
|
+
if(!task||task.length>30000)throw new RpcError(ERR.params,'Use a text prompt under 30,000 characters');
|
|
30
|
+
return task;
|
|
31
|
+
}
|
|
32
|
+
const planStatus=s=>s==='done'||s==='completed'?'completed':s==='in_progress'?'in_progress':'pending';
|
|
33
|
+
const modesFor=current=>({currentModeId:current,availableModes:MODE_NAMES.map(id=>({id,name:MODES[id].label,description:MODES[id].summary}))});
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* write(obj): sends one protocol message. deps: createSession({cwd,mode}) => Session, cloud() => signed-in Cloud,
|
|
37
|
+
* version, log(text) for stderr. Returns {handle(message), close()}; handle resolves after a request is answered.
|
|
38
|
+
*/
|
|
39
|
+
export function createAcpServer({write,createSession,cloud,version='0',log=()=>{},steps=120}){
|
|
40
|
+
const sessions=new Map(),waiting=new Map();
|
|
41
|
+
const send=m=>write({jsonrpc:'2.0',...m});
|
|
42
|
+
const notify=(sessionId,update)=>send({method:'session/update',params:{sessionId,update}});
|
|
43
|
+
const request=(method,params)=>new Promise((resolve,reject)=>{const id='mlai-'+randomUUID();waiting.set(id,{resolve,reject});send({id,method,params})});
|
|
44
|
+
const need=id=>{const s=sessions.get(id);if(!s)throw new RpcError(ERR.session,'Unknown session');return s};
|
|
45
|
+
|
|
46
|
+
const methods={
|
|
47
|
+
initialize:async p=>({protocolVersion:Math.min(Number(p?.protocolVersion)||PROTOCOL_VERSION,PROTOCOL_VERSION),
|
|
48
|
+
agentInfo:{name:'mlai',title:'ML AI Code',version},
|
|
49
|
+
agentCapabilities:{loadSession:false,promptCapabilities:{image:false,audio:false,embeddedContext:true},mcpCapabilities:{http:false,sse:false}},
|
|
50
|
+
authMethods:[]}),
|
|
51
|
+
authenticate:async()=>({}),
|
|
52
|
+
'session/new':async p=>{
|
|
53
|
+
if(typeof p?.cwd!=='string'||!path.isAbsolute(p.cwd))throw new RpcError(ERR.params,'The working directory must be an absolute path');
|
|
54
|
+
if(sessions.size>=20)throw new RpcError(ERR.internal,'Too many sessions in this connection. Restart the agent.');
|
|
55
|
+
const s=await createSession({cwd:p.cwd,mode:'guided'});
|
|
56
|
+
const id=s.meta.id;sessions.set(id,{s,busy:null});
|
|
57
|
+
return {sessionId:id,modes:modesFor(sessionMode(s.meta))};
|
|
58
|
+
},
|
|
59
|
+
'session/set_mode':async p=>{
|
|
60
|
+
const {s}=need(p?.sessionId);const m=modeName(p?.modeId);if(!m)throw new RpcError(ERR.params,'Modes: '+MODE_NAMES.join(', '));
|
|
61
|
+
await applyMode(s,m);notify(p.sessionId,{sessionUpdate:'current_mode_update',currentModeId:m});return {};
|
|
62
|
+
},
|
|
63
|
+
'session/prompt':async p=>{
|
|
64
|
+
const entry=need(p?.sessionId),{s}=entry,sid=p.sessionId;
|
|
65
|
+
if(entry.busy)throw new RpcError(ERR.internal,'This session is already working on a prompt');
|
|
66
|
+
const task=taskFor(sessionMode(s.meta),promptText(p.prompt));
|
|
67
|
+
let client;try{client=await cloud()}catch(e){throw new RpcError(ERR.auth,e.message||'Sign in first: run mlai login in a terminal.')}
|
|
68
|
+
const tools=[],say=text=>text&¬ify(sid,{sessionUpdate:'agent_message_chunk',content:{type:'text',text}});
|
|
69
|
+
entry.cancelled=false;
|
|
70
|
+
const onEvent=async e=>{
|
|
71
|
+
try{
|
|
72
|
+
if(e.type==='assistant'||e.type==='answer')say(String(e.content||'')+'\n\n');
|
|
73
|
+
else if(e.type==='error')say('Error: '+String(e.content||e.error||'')+'\n\n');
|
|
74
|
+
else if(e.type==='tool'||e.type==='command'){
|
|
75
|
+
const toolCallId=String(e.id||randomUUID());tools.push(toolCallId);
|
|
76
|
+
notify(sid,{sessionUpdate:'tool_call',toolCallId,title:String(e.type==='command'?e.command:(e.name+(e.target?' '+e.target:''))).slice(0,300),kind:toolKind(e),status:'in_progress',
|
|
77
|
+
...(e.type==='tool'&&typeof e.target==='string'&&e.target&&!/\s/.test(e.target)?{locations:[{path:path.resolve(s.meta.root,e.target)}]}:{})});
|
|
78
|
+
}else if(e.type==='output'&&tools.length){
|
|
79
|
+
notify(sid,{sessionUpdate:'tool_call_update',toolCallId:tools.shift(),status:e.returncode===0?'completed':'failed',content:[{type:'content',content:{type:'text',text:String(e.output||'').slice(-4000)||'No output.'}}]});
|
|
80
|
+
}else if(e.type==='todos'){
|
|
81
|
+
notify(sid,{sessionUpdate:'plan',entries:(e.items||[]).slice(0,50).map(t=>({content:String(t.text||t.content||''),priority:'medium',status:planStatus(t.status)}))});
|
|
82
|
+
}else if(e.type==='approval'){
|
|
83
|
+
const edit=/^Edit (.+)\nREMOVE:\n([\s\S]*?)\nREPLACE WITH:\n([\s\S]*)$/.exec(String(e.command||''));
|
|
84
|
+
const toolCall={toolCallId:String(e.id),title:edit?'Edit '+edit[1]:String(e.command||e.description||(e.items||[]).join('\n')||'Approve this step').slice(0,500),kind:edit?'edit':e.kind==='plan'?'think':'execute',status:'pending',
|
|
85
|
+
...(edit?{content:[{type:'diff',path:path.resolve(s.meta.root,edit[1]),oldText:edit[2],newText:edit[3]}]}:{})};
|
|
86
|
+
const r=await request('session/request_permission',{sessionId:sid,toolCall,options:[
|
|
87
|
+
{optionId:'allow-once',name:'Allow',kind:'allow_once'},{optionId:'allow-always',name:'Allow for this task',kind:'allow_always'},{optionId:'reject-once',name:'Reject',kind:'reject_once'}]}).catch(()=>null);
|
|
88
|
+
const o=r?.outcome,verdict=o?.outcome==='selected'?{'allow-once':'approve','allow-always':'approve_all'}[o.optionId]||'reject':'reject';
|
|
89
|
+
await s.decide(e.id,verdict).catch(()=>{});
|
|
90
|
+
}
|
|
91
|
+
}catch(err){log('acp: '+(err?.message||err))}
|
|
92
|
+
};
|
|
93
|
+
s.on('event',onEvent);entry.busy=true;
|
|
94
|
+
try{
|
|
95
|
+
const r=await s.send(task,{cloud:client,steps,onProgress:m=>log(m+'...')});
|
|
96
|
+
for(const id of tools)notify(sid,{sessionUpdate:'tool_call_update',toolCallId:id,status:'completed'});
|
|
97
|
+
if(entry.cancelled||r?.state==='stopped')return {stopReason:'cancelled'};
|
|
98
|
+
if(r?.state!=='completed'&&r?.error)say(String(r.error)+'\n');
|
|
99
|
+
if(r?.code==='billing_limit')return {stopReason:'refusal'};
|
|
100
|
+
return {stopReason:'end_turn'};
|
|
101
|
+
}catch(e){if(entry.cancelled)return {stopReason:'cancelled'};throw new RpcError(ERR.internal,e?.message||String(e))}
|
|
102
|
+
finally{s.off('event',onEvent);entry.busy=null}
|
|
103
|
+
},
|
|
104
|
+
};
|
|
105
|
+
const notifications={
|
|
106
|
+
'session/cancel':async p=>{const e=sessions.get(p?.sessionId);if(e?.busy){e.cancelled=true;await e.s.cancel().catch(()=>{})}},
|
|
107
|
+
};
|
|
108
|
+
|
|
109
|
+
async function handle(m){
|
|
110
|
+
if(!m||typeof m!=='object'||m.jsonrpc!=='2.0'){send({id:m?.id??null,error:{code:ERR.invalid,message:'Invalid request'}});return}
|
|
111
|
+
if(m.method===undefined&&m.id!=null){const w=waiting.get(m.id);if(w){waiting.delete(m.id);m.error?w.reject(new Error(m.error.message)):w.resolve(m.result)}return}
|
|
112
|
+
if(m.id===undefined||m.id===null){await notifications[m.method]?.(m.params).catch(e=>log('acp: '+e.message));return}
|
|
113
|
+
const fn=methods[m.method];
|
|
114
|
+
if(!fn){send({id:m.id,error:{code:ERR.method,message:'Method not found: '+m.method}});return}
|
|
115
|
+
try{send({id:m.id,result:await fn(m.params||{})})}
|
|
116
|
+
catch(e){send({id:m.id,error:{code:e instanceof RpcError?e.code:ERR.internal,message:String(e?.message||e)}})}
|
|
117
|
+
}
|
|
118
|
+
return {handle,sessions,close(){for(const {s,busy} of sessions.values())if(busy)s.cancel().catch(()=>{});for(const w of waiting.values())w.reject(new Error('closed'));waiting.clear()}};
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** Reads newline-delimited JSON-RPC from `input` until it ends. Requests are handled concurrently (prompts are long). */
|
|
122
|
+
export async function serveStdio(server,{input=process.stdin,write}={}){
|
|
123
|
+
const rl=readline.createInterface({input,crlfDelay:Infinity});const inflight=new Set();
|
|
124
|
+
for await(const line of rl){
|
|
125
|
+
if(!line.trim())continue;let m;
|
|
126
|
+
try{m=JSON.parse(line)}catch{write({jsonrpc:'2.0',id:null,error:{code:ERR.parse,message:'Parse error'}});continue}
|
|
127
|
+
const p=server.handle(m).catch(()=>{});inflight.add(p);p.finally(()=>inflight.delete(p));
|
|
128
|
+
}
|
|
129
|
+
await Promise.allSettled([...inflight]);server.close();
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** Entry point for `mlai acp` (cli.mjs). */
|
|
133
|
+
export async function acpMain(o={}){
|
|
134
|
+
const [{Session},{loadLogin},{Cloud},{VERSION,DEFAULT_SERVER}]=await Promise.all([import('../session.mjs'),import('../credentials.mjs'),import('../cloud.mjs'),import('../home.mjs')]);
|
|
135
|
+
const write=m=>process.stdout.write(JSON.stringify(m)+'\n');
|
|
136
|
+
const cloud=async()=>{
|
|
137
|
+
const login=await loadLogin().catch(()=>null);
|
|
138
|
+
if(!login?.token)throw new Error('Not signed in. Run mlai login in a terminal, then try again.');
|
|
139
|
+
return new Cloud({server:(o.server||process.env.MLAI_SERVER||login.server||DEFAULT_SERVER).replace(/\/$/,''),token:login.token});
|
|
140
|
+
};
|
|
141
|
+
const server=createAcpServer({write,version:VERSION,cloud,createSession:a=>Session.create(a),log:t=>process.stderr.write(t+'\n'),steps:o.steps||120});
|
|
142
|
+
process.stderr.write('ML AI Code ACP server ready on stdio.\n');
|
|
143
|
+
await serveStdio(server,{write});
|
|
144
|
+
return 0;
|
|
145
|
+
}
|