mlai-code 0.0.0-stage → 0.3.1
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
|
@@ -0,0 +1,394 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* mlai — the ML AI Code command line.
|
|
4
|
+
* Zero dependencies, Node 18+. Talks to the hosted workspace API with a personal token from `mlai login`.
|
|
5
|
+
* Every cloud task runs in your ML AI Code sandbox; `mlai pull` brings the resulting patch into the current git repo.
|
|
6
|
+
*/
|
|
7
|
+
import {createServer} from 'node:http';
|
|
8
|
+
import {randomBytes,randomUUID} from 'node:crypto';
|
|
9
|
+
import {readFileSync,writeFileSync,mkdirSync,existsSync,chmodSync} from 'node:fs';
|
|
10
|
+
import {homedir,hostname,platform} from 'node:os';
|
|
11
|
+
import {join,resolve} from 'node:path';
|
|
12
|
+
import {spawn,spawnSync} from 'node:child_process';
|
|
13
|
+
import readline from 'node:readline';
|
|
14
|
+
import process from 'node:process';
|
|
15
|
+
|
|
16
|
+
export const VERSION='0.1.0';
|
|
17
|
+
const DEFAULT_URL=process.env.MLAI_URL||'https://mlai-mini-code.vercel.app';
|
|
18
|
+
const CONFIG_DIR=process.env.MLAI_CONFIG_DIR||join(process.env.XDG_CONFIG_HOME||join(homedir(),'.config'),'mlai');
|
|
19
|
+
const CONFIG=join(CONFIG_DIR,'config.json');
|
|
20
|
+
const LINKS=join(CONFIG_DIR,'projects.json');
|
|
21
|
+
const TTY=process.stdout.isTTY&&!process.env.NO_COLOR&&process.env.TERM!=='dumb';
|
|
22
|
+
const c={dim:s=>TTY?`\x1b[2m${s}\x1b[0m`:s,bold:s=>TTY?`\x1b[1m${s}\x1b[0m`:s,teal:s=>TTY?`\x1b[36m${s}\x1b[0m`:s,green:s=>TTY?`\x1b[32m${s}\x1b[0m`:s,yellow:s=>TTY?`\x1b[33m${s}\x1b[0m`:s,red:s=>TTY?`\x1b[31m${s}\x1b[0m`:s,gray:s=>TTY?`\x1b[90m${s}\x1b[0m`:s};
|
|
23
|
+
const MODES={plan:'plan',brief:'brief',guided:'approve',approve:'approve',auto:'auto'};
|
|
24
|
+
let JSON_OUT=false;
|
|
25
|
+
|
|
26
|
+
// ---------- config ----------
|
|
27
|
+
function readJson(p,d){try{return JSON.parse(readFileSync(p,'utf8'))}catch{return d}}
|
|
28
|
+
function writeJson(p,v){mkdirSync(CONFIG_DIR,{recursive:true});writeFileSync(p,JSON.stringify(v,null,1));try{chmodSync(p,0o600)}catch{}}
|
|
29
|
+
export function config(){return readJson(CONFIG,{})}
|
|
30
|
+
function saveConfig(v){writeJson(CONFIG,v)}
|
|
31
|
+
function links(){return readJson(LINKS,{})}
|
|
32
|
+
function linkedProject(dir=process.cwd()){const all=links();let d=resolve(dir);for(;;){if(all[d])return all[d];const up=resolve(d,'..');if(up===d)return null;d=up}}
|
|
33
|
+
function saveLink(project,dir=process.cwd()){const all=links();all[resolve(dir)]=project;writeJson(LINKS,all)}
|
|
34
|
+
function baseUrl(){return (config().url||DEFAULT_URL).replace(/\/$/,'')}
|
|
35
|
+
|
|
36
|
+
// ---------- http ----------
|
|
37
|
+
class ApiError extends Error{constructor(message,status,code){super(message);this.status=status;this.code=code}}
|
|
38
|
+
async function api(path,body,{auth=true,method='POST'}={}){
|
|
39
|
+
const cfg=config();const headers={'Content-Type':'application/json','User-Agent':'mlai-cli/'+VERSION};
|
|
40
|
+
if(auth){if(!cfg.token)throw new ApiError('Not signed in. Run `mlai login` first.',401,'no_token');headers.Authorization='Bearer '+cfg.token}
|
|
41
|
+
const r=await fetch(baseUrl()+path,{method,headers,body:body?JSON.stringify(body):undefined});
|
|
42
|
+
const text=await r.text();let data;try{data=JSON.parse(text)}catch{data={error:text.slice(0,200)||r.statusText}}
|
|
43
|
+
if(!r.ok||data.error){if(data.code==='cli_token_invalid')throw new ApiError('Your CLI token expired or was rejected. Run `mlai login` again.',401,data.code);throw new ApiError(data.error||('HTTP '+r.status),r.status,data.code)}
|
|
44
|
+
return data;
|
|
45
|
+
}
|
|
46
|
+
const ws=(token,action,extra={})=>api('/api/workspace',{action,token,...extra});
|
|
47
|
+
|
|
48
|
+
// ---------- output helpers ----------
|
|
49
|
+
function out(s=''){process.stdout.write(s+'\n')}
|
|
50
|
+
function emit(obj){if(JSON_OUT)out(JSON.stringify(obj))}
|
|
51
|
+
function fail(msg,code=1){process.stderr.write(c.red('error: ')+msg+'\n');process.exit(code)}
|
|
52
|
+
function wrap(text,indent=' ',width=Math.min(process.stdout.columns||100,110)){const lines=[];for(const para of String(text).split('\n')){let line='';for(const word of para.split(/\s+/)){if((line+' '+word).trim().length>width-indent.length){lines.push(indent+line.trim());line=word}else line+=' '+word}lines.push(indent+line.trim())}return lines.join('\n')}
|
|
53
|
+
function ask(question){return new Promise(res=>{const rl=readline.createInterface({input:process.stdin,output:process.stdout});rl.question(question,a=>{rl.close();res(a.trim())})})}
|
|
54
|
+
function openBrowser(url){const cmd=platform()==='darwin'?'open':platform()==='win32'?'cmd':'xdg-open';const args=platform()==='win32'?['/c','start','',url]:[url];try{const p=spawn(cmd,args,{stdio:'ignore',detached:true});p.on('error',()=>{});p.unref();return true}catch{return false}}
|
|
55
|
+
function requireProject(opts){const token=opts.project||process.env.MLAI_PROJECT||linkedProject()?.token;if(!token)fail('No project linked to this folder. Run `mlai projects` then `mlai link <name>` or `mlai new`.',2);return token}
|
|
56
|
+
function timeAgo(ms){const s=Math.max(0,(Date.now()-ms)/1000);if(s<60)return 'just now';if(s<3600)return Math.floor(s/60)+'m ago';if(s<86400)return Math.floor(s/3600)+'h ago';return Math.floor(s/86400)+'d ago'}
|
|
57
|
+
|
|
58
|
+
// ---------- arg parsing ----------
|
|
59
|
+
export function parseArgs(argv){
|
|
60
|
+
const opts={_:[]};
|
|
61
|
+
for(let i=0;i<argv.length;i++){const a=argv[i];
|
|
62
|
+
if(a==='--')
|
|
63
|
+
{opts._.push(...argv.slice(i+1));break}
|
|
64
|
+
const long=/^--([^=]+)(?:=(.*))?$/.exec(a);
|
|
65
|
+
if(long){const [,k,v]=long;if(v!==undefined)opts[k]=v;else if(k.startsWith('no-'))opts[k.slice(3)]=false;else if(argv[i+1]!==undefined&&!argv[i+1].startsWith('-')&&!['json','watch','all','manual','link','yes','help','version','confirm'].includes(k))opts[k]=argv[++i];else opts[k]=true;continue}
|
|
66
|
+
const short=/^-([a-zA-Z])$/.exec(a);
|
|
67
|
+
if(short){const map={m:'mode',r:'role',e:'effort',s:'steps',p:'project',t:'title',b:'body',n:'name',y:'yes',h:'help',v:'version',j:'json'};const k=map[short[1]]||short[1];if(['yes','help','version','json'].includes(k))opts[k]=true;else opts[k]=argv[++i];continue}
|
|
68
|
+
opts._.push(a);
|
|
69
|
+
}
|
|
70
|
+
return opts;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// ---------- login ----------
|
|
74
|
+
async function login(opts){
|
|
75
|
+
const url=(opts.url||baseUrl()).replace(/\/$/,'');
|
|
76
|
+
if(opts.token){const cfg={...config(),url,token:String(opts.token)};saveConfig(cfg);const me=await api('/api/cli',{action:'whoami'});saveConfig({...cfg,owner:me.owner,label:me.label});out(c.green('Signed in.')+' Token for '+me.label+' valid until '+new Date(me.expires).toLocaleDateString());return}
|
|
77
|
+
const label=encodeURIComponent((hostname()||'computer').split('.')[0].slice(0,40));
|
|
78
|
+
if(opts.manual||!TTY&&!opts.browser){
|
|
79
|
+
out('Open this page in a browser where you are signed in to ML AI Code:');out(' '+c.teal(url+'/cli/auth?label='+label));
|
|
80
|
+
const token=await ask('Paste the token here: ');if(!token.startsWith('mlai_'))fail('That does not look like an mlai token.');return login({...opts,manual:false,token});
|
|
81
|
+
}
|
|
82
|
+
const state=randomBytes(18).toString('base64url');
|
|
83
|
+
const got=await new Promise((resolveToken,reject)=>{
|
|
84
|
+
const server=createServer((req,res)=>{
|
|
85
|
+
const u=new URL(req.url,'http://127.0.0.1');
|
|
86
|
+
if(u.pathname!=='/callback'){res.writeHead(404);res.end();return}
|
|
87
|
+
const ok=u.searchParams.get('state')===state&&String(u.searchParams.get('token')||'').startsWith('mlai_');
|
|
88
|
+
res.writeHead(ok?200:400,{'Content-Type':'text/html; charset=utf-8'});
|
|
89
|
+
res.end(`<!doctype html><meta name=viewport content="width=device-width"><body style="font-family:system-ui;background:#141414;color:#eee;display:grid;place-items:center;height:100vh;margin:0"><div style="text-align:center"><div style="font-size:40px">${ok?'✓':'✕'}</div><h2 style="font-weight:600">${ok?'mlai is signed in':'Sign-in did not match'}</h2><p style="color:#aaa">${ok?'You can close this tab and go back to the terminal.':'Run mlai login again.'}</p></div>`);
|
|
90
|
+
if(ok){server.close();resolveToken(u.searchParams.get('token'))}
|
|
91
|
+
});
|
|
92
|
+
server.on('error',reject);
|
|
93
|
+
server.listen(0,'127.0.0.1',()=>{
|
|
94
|
+
const port=server.address().port;const target=`${url}/cli/auth?port=${port}&state=${state}&label=${label}`;
|
|
95
|
+
out('Opening your browser to approve this computer…');out(c.dim('If it does not open, visit: ')+c.teal(target));
|
|
96
|
+
openBrowser(target);
|
|
97
|
+
setTimeout(()=>{server.close();reject(new Error('Timed out waiting for approval (5 minutes). Try `mlai login --manual`.'))},5*60000).unref();
|
|
98
|
+
});
|
|
99
|
+
});
|
|
100
|
+
await login({...opts,token:got,url});
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// ---------- commands ----------
|
|
104
|
+
const commands={};
|
|
105
|
+
const help=`${c.bold('mlai')} ${VERSION} — ML AI Code from your terminal
|
|
106
|
+
|
|
107
|
+
${c.bold('Account')}
|
|
108
|
+
mlai login [--manual] [--url URL] approve this computer in your browser
|
|
109
|
+
mlai logout | whoami forget the token / show who you are
|
|
110
|
+
|
|
111
|
+
${c.bold('Projects')} (a project is a cloud workspace; link one to a folder)
|
|
112
|
+
mlai projects list your projects
|
|
113
|
+
mlai new [github-url] [-n name] create a project (empty or from a GitHub repo) and link this folder
|
|
114
|
+
--profile small|medium|large picks the computer (default: best your plan includes)
|
|
115
|
+
mlai link <name|#n> link this folder to an existing project
|
|
116
|
+
mlai open open the linked project in the web app
|
|
117
|
+
|
|
118
|
+
${c.bold('Tasks')}
|
|
119
|
+
mlai run "<task>" [-m plan|brief|guided|auto] [-r role] [-e low|medium|high] [-s steps] [--no-watch] [--build-brief answers.json]
|
|
120
|
+
mlai interactive session: type tasks, answer approvals inline
|
|
121
|
+
mlai watch | status | stop | resume follow the current run / snapshot / stop / continue
|
|
122
|
+
mlai steer "<message>" add an instruction while the agent is working
|
|
123
|
+
mlai approve [--all] | reject answer a pending approval
|
|
124
|
+
mlai reply "<text>" Brief mode: send feedback on the task list
|
|
125
|
+
|
|
126
|
+
${c.bold('Code')}
|
|
127
|
+
mlai ls | cat <file> | diff browse the workspace
|
|
128
|
+
mlai patch print the uncommitted patch
|
|
129
|
+
mlai pull apply that patch to this git repo (git apply --3way)
|
|
130
|
+
mlai sh "<command>" run a shell command in the workspace (90s limit)
|
|
131
|
+
mlai push -m "message" commit and push to the linked GitHub repo
|
|
132
|
+
mlai pr -t "title" [-b body] open a draft pull request
|
|
133
|
+
|
|
134
|
+
${c.bold('Deploys')} (connect a host once in the web app: Deploys)
|
|
135
|
+
mlai deploys production, latest preview and recent deployments
|
|
136
|
+
mlai preview [--no-wait] deploy the workspace as a preview and print the URL
|
|
137
|
+
mlai promote [deployment] [-y] review checks and promote a preview to production
|
|
138
|
+
mlai rollback [deployment] [-y] roll production back (default: the build before the last change)
|
|
139
|
+
|
|
140
|
+
${c.bold('Catalog')}
|
|
141
|
+
mlai roles [query] | skills [query] | modes
|
|
142
|
+
|
|
143
|
+
Global: --json (machine output), -p <project-token>, MLAI_URL, MLAI_PROJECT, NO_COLOR`;
|
|
144
|
+
commands.help=async()=>out(help);
|
|
145
|
+
commands.version=async()=>out(VERSION);
|
|
146
|
+
commands.login=login;
|
|
147
|
+
commands.logout=async()=>{const cfg=config();delete cfg.token;delete cfg.owner;delete cfg.label;saveConfig(cfg);out('Signed out. The token on this computer was forgotten.')};
|
|
148
|
+
commands.whoami=async()=>{const me=await api('/api/cli',{action:'whoami'});emit(me);if(!JSON_OUT){out(c.bold('Signed in')+' as '+me.label+c.dim(' · owner '+me.owner.slice(0,8)+'… · '+me.server));out(c.dim('Token expires '+new Date(me.expires).toLocaleString()))}};
|
|
149
|
+
|
|
150
|
+
async function listProjects(){const acct=await api('/api/account',null,{method:'GET'});if(!acct.configured)throw new ApiError('This server has no account database; projects cannot be listed.',503);return (acct.workspaces||[]).sort((a,b)=>(b.created||0)-(a.created||0))}
|
|
151
|
+
commands.projects=async()=>{
|
|
152
|
+
const list=await listProjects();emit(list);if(JSON_OUT)return;
|
|
153
|
+
if(!list.length){out('No projects yet. Create one with `mlai new` or `mlai new https://github.com/org/repo`.');return}
|
|
154
|
+
const linked=linkedProject()?.token;
|
|
155
|
+
list.forEach((w,i)=>out(`${c.dim('#'+(i+1))} ${w.token===linked?c.teal('● '):' '}${c.bold(w.label||w.repo||w.name)} ${c.dim((w.repo?w.repo+' · ':'')+'created '+timeAgo(w.created))}`));
|
|
156
|
+
out(c.dim('\n● linked to this folder. `mlai link #n` to change.'));
|
|
157
|
+
};
|
|
158
|
+
commands.link=async opts=>{
|
|
159
|
+
const want=String(opts._[0]||'');if(!want)fail('Usage: mlai link <name|#n>');
|
|
160
|
+
const list=await listProjects();const w=want.startsWith('#')?list[Number(want.slice(1))-1]:list.find(x=>x.name===want||x.label===want||x.repo===want||x.token===want);
|
|
161
|
+
if(!w)fail('No project matched '+want);saveLink({token:w.token,name:w.name,label:w.label||w.repo||w.name});out(c.green('Linked ')+process.cwd()+' → '+(w.label||w.name));
|
|
162
|
+
};
|
|
163
|
+
commands.new=async opts=>{
|
|
164
|
+
const repo=String(opts._[0]||'');if(repo&&!/^https:\/\/github\.com\/[\w.-]+\/[\w.-]+/.test(repo))fail('Pass a GitHub repository URL, e.g. https://github.com/org/repo');
|
|
165
|
+
if(!repo&&!opts.yes&&TTY){const a=await ask('Create an empty project? [Y/n] ');if(/^n/i.test(a))return}
|
|
166
|
+
process.stdout.write(c.dim('Creating workspace…'));
|
|
167
|
+
const w=await api('/api/workspace',{action:'create',repo,backend:opts.backend,profile:opts.profile||'large',fit:!opts.profile});
|
|
168
|
+
process.stdout.write('\r');emit(w);
|
|
169
|
+
saveLink({token:w.token,name:w.name,label:opts.name||w.label||repo.split('/').slice(-2).join('/')||w.name});
|
|
170
|
+
if(!JSON_OUT)out(c.green('Project ready ')+(repo||'(empty)')+c.dim(' · linked to '+process.cwd()));
|
|
171
|
+
};
|
|
172
|
+
commands.open=async()=>{const url=baseUrl()+'/';out(url);openBrowser(url)};
|
|
173
|
+
|
|
174
|
+
// ----- run / watch -----
|
|
175
|
+
function renderEvent(e,state){
|
|
176
|
+
switch(e.type){
|
|
177
|
+
case 'assistant':if(e.content?.trim())out(wrap(e.content.trim(),' '));break;
|
|
178
|
+
case 'answer':out('\n'+c.bold('Answer')+'\n'+wrap(e.content||'',' '));break;
|
|
179
|
+
case 'tool':out(c.gray(' ▸ '+e.name+(e.target?' '+e.target:'')));break;
|
|
180
|
+
case 'command':out(c.gray(' $ '+String(e.command||'').split('\n')[0].slice(0,140)));break;
|
|
181
|
+
case 'output':if(e.returncode&&e.returncode!==0)out(c.yellow(' ↳ exit '+e.returncode)+c.gray(' '+String(e.output||'').trim().split('\n').slice(-1)[0].slice(0,140)));break;
|
|
182
|
+
case 'todos':out(c.bold(' Tasks'));for(const t of e.items||[])out(' '+(t.status==='done'?c.green('✓'):t.status==='in_progress'?c.teal('▶'):c.gray('○'))+' '+t.text);break;
|
|
183
|
+
case 'note':out(c.gray(' · '+e.content));break;
|
|
184
|
+
case 'error':out(c.red(' ✕ '+e.content));break;
|
|
185
|
+
case 'steering':out(c.teal(' » you: ')+e.content);break;
|
|
186
|
+
case 'mode':case 'intent':case 'role_check':case 'skills':case 'harness':if(e.content)out(c.gray(' · '+e.content));break;
|
|
187
|
+
case 'finished':state.finished=e.state||'completed';break;
|
|
188
|
+
case 'approval':break; // handled from pending.json so answers are never stale
|
|
189
|
+
default:break;
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
async function answerPending(token,pending,interactive){
|
|
193
|
+
if(!pending)return false;
|
|
194
|
+
out('');
|
|
195
|
+
if(pending.kind==='plan'){
|
|
196
|
+
out(c.yellow(' Review the task list'));(pending.items||[]).forEach((t,i)=>out(' '+c.dim(String(i+1).padStart(2))+' '+t));
|
|
197
|
+
if(pending.questions?.length){out(c.yellow(' Open questions'));pending.questions.forEach(q=>out(' ? '+q))}
|
|
198
|
+
if(!interactive){out(c.dim(' mlai approve · mlai reply "<feedback>" · mlai reject'));return false}
|
|
199
|
+
const a=await ask(c.bold(' [a]pprove, [r]eply with changes, re[j]ect: '));
|
|
200
|
+
if(/^a/i.test(a)){await ws(token,'approve',{id:pending.id,approved:true});out(c.green(' Approved'));return true}
|
|
201
|
+
if(/^r/i.test(a)){const text=await ask(' Your feedback: ');if(text){await ws(token,'approve',{id:pending.id,revise:text});out(c.teal(' Sent'))}return true}
|
|
202
|
+
if(/^j/i.test(a)){await ws(token,'approve',{id:pending.id,approved:false});out(c.red(' Rejected'));return true}
|
|
203
|
+
return false;
|
|
204
|
+
}
|
|
205
|
+
const title=pending.kind==='deploy'?(pending.action==='promote'?'Promote to production':pending.action==='preview'?'Deploy a preview':'Deploy check'):{command:'Command approval',scope:'Edit outside the agreed scope',network:'Network access',integration:'Connector action'}[pending.kind]||'Approval';
|
|
206
|
+
out(c.yellow(' '+title)+(pending.reason?c.dim(' · '+pending.reason):''));if(pending.domain)out(' '+pending.domain);if(pending.command)out(wrap(String(pending.command).slice(0,600),' $ '));
|
|
207
|
+
if(!interactive){out(c.dim(' mlai approve [--all] · mlai reject'));return false}
|
|
208
|
+
const a=await ask(c.bold(' [y]es, [a]ll for this run, [n]o: '));
|
|
209
|
+
if(/^y/i.test(a)){await ws(token,'approve',{id:pending.id,approved:true});return true}
|
|
210
|
+
if(/^a/i.test(a)){await ws(token,'approve',{id:pending.id,approved:true,all:true});return true}
|
|
211
|
+
if(/^n/i.test(a)){await ws(token,'approve',{id:pending.id,approved:false});return true}
|
|
212
|
+
return false;
|
|
213
|
+
}
|
|
214
|
+
async function watch(token,{interactive=TTY,since=0,quiet=false}={}){
|
|
215
|
+
const state={finished:null};let lastTime=since;let lastPendingId=null;let idlePolls=0;
|
|
216
|
+
for(;;){
|
|
217
|
+
const snap=await ws(token,'status');
|
|
218
|
+
const events=(snap.events||[]).filter(e=>(e.time||0)>lastTime).sort((a,b)=>(a.time||0)-(b.time||0));
|
|
219
|
+
for(const e of events){lastTime=Math.max(lastTime,e.time||0);if(JSON_OUT)out(JSON.stringify(e));else renderEvent(e,state)}
|
|
220
|
+
const running=snap.status?.state==='running';
|
|
221
|
+
if(snap.pending&&snap.pending.id!==lastPendingId){lastPendingId=snap.pending.id;if(!JSON_OUT){const answered=await answerPending(token,snap.pending,interactive);if(!answered&&!interactive)return snap}else out(JSON.stringify({type:'pending',...snap.pending}))}
|
|
222
|
+
if(!running){
|
|
223
|
+
const st=snap.status?.state||state.finished||'idle';
|
|
224
|
+
if(!JSON_OUT&&!quiet){const comp=snap.completion;out('');out((st==='completed'?c.green('✓ '):st==='stopped'?c.yellow('■ '):c.red('✕ '))+c.bold(st)+(snap.status?.tokens?c.dim(` · ${snap.status.tokens.toLocaleString()} tokens · ${snap.status.calls||0} calls`):'')+(comp?c.dim(` · checks ${comp.checksPassed||0} passed, ${comp.checksFailed||0} failed`):''))}
|
|
225
|
+
return snap;
|
|
226
|
+
}
|
|
227
|
+
idlePolls=events.length?0:idlePolls+1;
|
|
228
|
+
await new Promise(r=>setTimeout(r,Math.min(6000,1500+idlePolls*300)));
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
async function startRun(token,task,opts){
|
|
232
|
+
const mode=MODES[String(opts.mode||'guided').toLowerCase()];if(!mode)fail('Mode must be plan, brief, guided or auto');
|
|
233
|
+
const body={action:'run',token,task,buildIntake:true,requestId:randomUUID(),mode,effort:['low','medium','high'].includes(opts.effort)?opts.effort:'medium',steps:Math.min(160,Math.max(1,Number(opts.steps)||120)),role:opts.role||'auto',planApproval:mode==='auto'?'off':'guided',tools:[]};
|
|
234
|
+
if(opts['build-brief'])body.buildAnswers=JSON.parse(readFileSync(String(opts['build-brief']),'utf8'));
|
|
235
|
+
let r=await api('/api/workspace',body);
|
|
236
|
+
if(r.status==='needs_details'&&process.stdin.isTTY&&!JSON_OUT){
|
|
237
|
+
out(c.bold('Before I build'));
|
|
238
|
+
const answers={};
|
|
239
|
+
for(const q of r.questions){
|
|
240
|
+
out(q.label);out(c.dim('Suggested: '+q.fallback));
|
|
241
|
+
answers[q.id]=(await ask('Your answer (Enter uses the suggestion): '))||q.fallback;
|
|
242
|
+
}
|
|
243
|
+
if(!/^y(?:es)?$/i.test(await ask('Start building with these answers? [y/N] ')))return {status:'cancelled'};
|
|
244
|
+
r=await api('/api/workspace',{...body,buildAnswers:answers});
|
|
245
|
+
}
|
|
246
|
+
emit(r);return r;
|
|
247
|
+
}
|
|
248
|
+
commands.run=async opts=>{
|
|
249
|
+
const token=requireProject(opts);const task=opts._.join(' ').trim()||(process.stdin.isTTY?'':readFileSync(0,'utf8').trim());if(!task)fail('Usage: mlai run "<task>"');
|
|
250
|
+
const started=Date.now()/1000-1;const r=await startRun(token,task,opts);
|
|
251
|
+
if(r.status==='needs_details'){
|
|
252
|
+
if(!JSON_OUT){out('Nothing started. This build needs a brief:');for(const q of r.questions)out(' '+q.id+': '+q.label);out('Pass --build-brief answers.json with audience, scope and constraints strings, or use an interactive terminal.')}
|
|
253
|
+
process.exitCode=2;return;
|
|
254
|
+
}
|
|
255
|
+
if(r.status==='cancelled')return;
|
|
256
|
+
if(!JSON_OUT)out(c.dim(`Started in ${String(opts.mode||'guided')} mode${opts.role?' as '+opts.role:''}${r.duplicate?' (already running)':''}.`));
|
|
257
|
+
if(opts.watch===false)return;
|
|
258
|
+
const snap=await watch(token,{since:started});
|
|
259
|
+
if(!JSON_OUT&&snap.status?.state==='completed')out(c.dim('Bring the changes here with `mlai pull`, or publish with `mlai push -m "…"`.'));
|
|
260
|
+
};
|
|
261
|
+
commands.watch=async opts=>{await watch(requireProject(opts))};
|
|
262
|
+
commands.status=async opts=>{
|
|
263
|
+
const snap=await ws(requireProject(opts),'status');emit(snap);if(JSON_OUT)return;
|
|
264
|
+
out(c.bold('State ')+(snap.status?.state||'idle')+(snap.task?c.dim('\nTask ')+snap.task.slice(0,200):''));
|
|
265
|
+
if(snap.todos?.length){out(c.bold('Tasks'));for(const t of snap.todos)out(' '+(t.status==='done'?c.green('✓'):t.status==='in_progress'?c.teal('▶'):c.gray('○'))+' '+t.text)}
|
|
266
|
+
if(snap.pending)await answerPending(requireProject(opts),snap.pending,false);
|
|
267
|
+
if(snap.history?.length){out(c.bold('Recent'));for(const h of snap.history.slice(0,5))out(c.dim(' '+h.state.padEnd(9))+' '+h.task.slice(0,90))}
|
|
268
|
+
};
|
|
269
|
+
commands.stop=async opts=>{await ws(requireProject(opts),'stop');out('Stop requested.')};
|
|
270
|
+
commands.resume=async opts=>{const t=requireProject(opts);await ws(t,'resume',{requestId:randomUUID()});out(c.dim('Continuing the previous task…'));await watch(t)};
|
|
271
|
+
commands.steer=async opts=>{const msg=opts._.join(' ');if(!msg)fail('Usage: mlai steer "<message>"');await ws(requireProject(opts),'steer',{message:msg});out('Instruction delivered.')};
|
|
272
|
+
async function pendingOrFail(token){const snap=await ws(token,'status');if(!snap.pending)fail('Nothing is waiting for approval.');return snap.pending}
|
|
273
|
+
commands.approve=async opts=>{const t=requireProject(opts);const p=await pendingOrFail(t);await ws(t,'approve',{id:p.id,approved:true,all:opts.all===true});out(c.green('Approved')+(opts.all?' (all for this run)':''))};
|
|
274
|
+
commands.reject=async opts=>{const t=requireProject(opts);const p=await pendingOrFail(t);await ws(t,'approve',{id:p.id,approved:false});out(c.red('Rejected'))};
|
|
275
|
+
commands.reply=async opts=>{const t=requireProject(opts);const text=opts._.join(' ');if(!text)fail('Usage: mlai reply "<feedback on the task list>"');const p=await pendingOrFail(t);if(p.kind!=='plan')fail('The pending approval is not a task list; use approve/reject.');await ws(t,'approve',{id:p.id,revise:text});out(c.teal('Feedback sent; the agent will redraft the list.'))};
|
|
276
|
+
|
|
277
|
+
// ----- code -----
|
|
278
|
+
commands.ls=async opts=>{const snap=await ws(requireProject(opts),'status');emit(snap.files);if(!JSON_OUT)out((snap.files||[]).join('\n'))};
|
|
279
|
+
commands.cat=async opts=>{const f=opts._[0];if(!f)fail('Usage: mlai cat <path>');const r=await ws(requireProject(opts),'read',{path:f});process.stdout.write(r.content||'')};
|
|
280
|
+
commands.diff=async opts=>{const r=await ws(requireProject(opts),'diff');emit(r);if(JSON_OUT)return;if(!String(r.diff||'').trim()){out(c.dim('No changes.'));return}
|
|
281
|
+
if(TTY)for(const line of String(r.diff).split('\n'))out(line.startsWith('+')&&!line.startsWith('+++')?c.green(line):line.startsWith('-')&&!line.startsWith('---')?c.red(line):line.startsWith('@@')?c.teal(line):line.startsWith('diff ')?c.bold(line):line);else out(r.diff);
|
|
282
|
+
if(r.skipped?.length)out(c.dim('Skipped large/untracked files: '+r.skipped.join(', ')))};
|
|
283
|
+
commands.patch=async opts=>{const r=await ws(requireProject(opts),'export');process.stdout.write(r.patch||'')};
|
|
284
|
+
commands.pull=async opts=>{
|
|
285
|
+
const r=await ws(requireProject(opts),'export');const patch=r.patch||'';if(!patch.trim()){out(c.dim('Nothing to pull: the workspace has no uncommitted changes.'));return}
|
|
286
|
+
const git=spawnSync('git',['rev-parse','--show-toplevel'],{encoding:'utf8'});if(git.status!==0)fail('Run this inside a git repository.');
|
|
287
|
+
const check=spawnSync('git',['apply','--check','--3way'],{input:patch,encoding:'utf8'});
|
|
288
|
+
if(check.status!==0){process.stderr.write(check.stderr);if(!opts.yes){const a=await ask('The patch does not apply cleanly. Save it to mlai.patch instead? [Y/n] ');if(/^n/i.test(a))return}writeFileSync('mlai.patch',patch);out('Saved mlai.patch');return}
|
|
289
|
+
const apply=spawnSync('git',['apply','--3way'],{input:patch,encoding:'utf8'});if(apply.status!==0){process.stderr.write(apply.stderr);fail('git apply failed')}
|
|
290
|
+
const stat=spawnSync('git',['diff','--stat'],{encoding:'utf8'}).stdout;out(c.green('Applied workspace changes to this repo.')+'\n'+stat);
|
|
291
|
+
};
|
|
292
|
+
commands.sh=async opts=>{const cmd=opts._.join(' ');if(!cmd)fail('Usage: mlai sh "<command>"');const r=await ws(requireProject(opts),'terminal',{command:cmd});process.stdout.write(r.output||'');process.exitCode=r.exitCode||0};
|
|
293
|
+
commands.push=async opts=>{const m=opts.m||opts.message;if(!m)fail('Usage: mlai push -m "commit message"');const r=await ws(requireProject(opts),'git_push',{confirm:true,message:m});emit(r);if(!JSON_OUT)out(c.green('Pushed')+(r.branch?' to '+r.branch:'')+(r.url?' · '+r.url:''))};
|
|
294
|
+
commands.pr=async opts=>{const t=requireProject(opts);const title=opts.title;if(!title)fail('Usage: mlai pr -t "title" [-b "body"]');const plan=await ws(t,'pr_plan');if(!opts.yes&&TTY){out(c.bold('Files in this PR'));for(const f of plan.files||plan.changes||[])out(' '+(f.path||f));const a=await ask('Open a draft PR? [Y/n] ');if(/^n/i.test(a))return}const r=await ws(t,'pr_publish',{confirm:true,title,body:opts.body||'',planHash:plan.planHash});emit(r);if(!JSON_OUT)out(c.green('Draft PR ')+(r.url||JSON.stringify(r)))};
|
|
295
|
+
|
|
296
|
+
// ----- deploys -----
|
|
297
|
+
const depState=s=>({READY:c.green('ready'),ERROR:c.red('failed'),CANCELED:c.red('canceled'),BUILDING:c.yellow('building'),QUEUED:c.yellow('queued'),INITIALIZING:c.yellow('starting')}[s]||c.gray(String(s||'unknown').toLowerCase()));
|
|
298
|
+
const depId=id=>String(id||'').replace(/^dpl_/,'').slice(0,7);
|
|
299
|
+
async function waitDeployment(token,id,label){
|
|
300
|
+
for(let i=0;i<60;i++){const r=await ws(token,'deploy_status',{id,wait:i?20000:0});const d=r.deployment;if(!['QUEUED','BUILDING','INITIALIZING','UNKNOWN'].includes(d.state))return d;if(!JSON_OUT&&i%3===0)out(c.dim(' '+label+'… '+String(d.state).toLowerCase()))}
|
|
301
|
+
return null;
|
|
302
|
+
}
|
|
303
|
+
commands.deploys=async opts=>{
|
|
304
|
+
const t=requireProject(opts);const o=await ws(t,'deploy_overview');emit(o);if(JSON_OUT)return;
|
|
305
|
+
const target=o.targets?.[0];if(!target){out('No deploy target yet. Open the project in the web app, tap Deploys and connect a host (Vercel, Netlify, Cloudflare Pages or your own commands).');return}
|
|
306
|
+
out(c.bold(target.projectName)+c.dim((target.teamName?' · '+target.teamName:'')+' · production branch '+target.productionBranch));
|
|
307
|
+
const h=o.history;if(o.error)out(c.red(' '+o.error));if(!h)return;
|
|
308
|
+
const cur=h.current;out(' Production '+(cur?depState(cur.state)+' '+(h.domains?.[0]||cur.url.replace('https://',''))+c.dim(' '+depId(cur.id)+' · '+timeAgo(cur.created)):c.gray('not deployed')));
|
|
309
|
+
const p=h.previews?.[0];if(p)out(' Preview '+p.url.replace('https://','')+c.dim(' '+depId(p.id)+' · '+timeAgo(p.at)+(p.dirty?' · uncommitted':'')));
|
|
310
|
+
out(c.bold('\nRecent'));for(const d of (h.deployments||[]).slice(0,8))out(' '+(d.current?c.green('●'):' ')+' '+depId(d.id)+' '+(d.target==='production'?'prod ':'preview')+' '+depState(d.state).padEnd(TTY?17:8)+' '+c.dim(timeAgo(d.created))+' '+String(d.message||'').slice(0,60));
|
|
311
|
+
};
|
|
312
|
+
commands.preview=async opts=>{
|
|
313
|
+
const t=requireProject(opts);if(!JSON_OUT)out(c.dim('Packing the workspace and uploading changed files…'));
|
|
314
|
+
let r;try{r=await ws(t,'deploy_preview',{confirm:true})}
|
|
315
|
+
catch(e){if(e.code!=='deploy_first_production')throw e;out(c.yellow(e.message));
|
|
316
|
+
if(!opts.yes){if(!TTY)fail('Add -y to ship the first release without a prompt.');const a=await ask(c.bold('Ship it as the first production release? [y/N] '));if(!/^y/i.test(a)){out('Nothing deployed.');return}}
|
|
317
|
+
r=await ws(t,'deploy_preview',{confirm:true,firstProduction:true})}
|
|
318
|
+
const d=r.deployment;
|
|
319
|
+
if(!JSON_OUT){out(' '+r.pack.files+' files'+(r.pack.skipped?.length?c.dim(' · left out '+r.pack.skipped.map(x=>x.file).join(', ')):'')+(r.env?.synced?.length?c.dim(' · synced '+r.env.synced.join(', ')):''));out(' '+c.teal(d.url))}
|
|
320
|
+
if(opts.wait===false){emit(r);return}
|
|
321
|
+
const fin=await waitDeployment(t,d.id,'Building');emit({...r,deployment:fin||d});if(JSON_OUT)return;
|
|
322
|
+
if(fin?.state==='READY'&&r.firstProduction)out(c.green('✓ First release is live ')+fin.url+c.dim('\n From now on `mlai preview` creates previews; promote with `mlai promote`.'));
|
|
323
|
+
else if(fin?.state==='READY')out(c.green('✓ Preview ready ')+fin.url+c.dim('\n Promote with `mlai promote '+depId(fin.id)+'`'));
|
|
324
|
+
else if(fin?.state==='ERROR'){out(c.red('✕ Build failed')+(fin.error?c.dim(' · '+fin.error):''));const l=await ws(t,'deploy_logs',{id:d.id,limit:30});for(const line of l.lines.slice(-20))out(c.gray(' '+line));process.exitCode=1}
|
|
325
|
+
else out(c.dim('Still building. Check with `mlai deploys`.'));
|
|
326
|
+
};
|
|
327
|
+
async function resolveDeployment(t,ref,kind){
|
|
328
|
+
if(!ref)return undefined;const o=await ws(t,'deploy_overview');const all=o.history?.deployments||[];const m=all.find(d=>d.id===ref||d.id==='dpl_'+ref||d.id.replace(/^dpl_/,'').startsWith(ref));
|
|
329
|
+
if(!m)fail('No recent '+kind+' deployment matches "'+ref+'". See `mlai deploys`.');return m.id;
|
|
330
|
+
}
|
|
331
|
+
commands.promote=async opts=>{
|
|
332
|
+
const t=requireProject(opts);const id=await resolveDeployment(t,opts._[0],'preview');
|
|
333
|
+
const r=await ws(t,'deploy_review',id?{previewId:id}:{});emit(r);
|
|
334
|
+
if(!JSON_OUT){
|
|
335
|
+
out(c.bold('What changes'));out(' '+r.preview.url+c.dim(' '+depId(r.preview.id)+(r.preview.commit?' · '+r.preview.commit.slice(0,7):''))+(r.preview.dirty?c.yellow(' includes uncommitted changes'):''));
|
|
336
|
+
out(' Serves on '+(r.domains?.length?r.domains.join(', '):'the production URL'));
|
|
337
|
+
out(c.bold('Evidence'));for(const ch of r.checks)out(' '+(ch.state==='pass'?c.green('✓'):ch.state==='fail'?c.red('✕'):c.gray('○'))+' '+ch.label.padEnd(14)+c.dim(ch.detail||''));
|
|
338
|
+
out(c.bold('If it goes wrong'));out(' '+(r.rollbackTo?'`mlai rollback` returns to '+depId(r.rollbackTo.id)+' instantly':'First production build: nothing to roll back to'));
|
|
339
|
+
}
|
|
340
|
+
if(!opts.yes){if(!TTY)fail('Add -y to promote without a prompt.');const a=await ask(c.bold('Promote to production? [y/N] '));if(!/^y/i.test(a)){out('Not promoted.');return}}
|
|
341
|
+
const p=await ws(t,'deploy_promote',{previewId:r.preview.id,confirm:true});if(!JSON_OUT)out(c.dim('Rebuilding with production settings. The current build stays live until it is ready…'));
|
|
342
|
+
const fin=await waitDeployment(t,p.deployment.id,'Production build');emit({...p,deployment:fin||p.deployment});if(JSON_OUT)return;
|
|
343
|
+
if(fin?.state==='READY')out(c.green('✓ Live ')+(p.domains?.[0]||fin.url)+c.dim(' · undo with `mlai rollback`'));
|
|
344
|
+
else if(fin)fail('The production build failed, so production did not change.');else out(c.dim('Still building. Check with `mlai deploys`.'));
|
|
345
|
+
};
|
|
346
|
+
commands.rollback=async opts=>{
|
|
347
|
+
const t=requireProject(opts);const id=await resolveDeployment(t,opts._[0],'production');
|
|
348
|
+
if(!opts.yes){if(!TTY)fail('Add -y to roll back without a prompt.');const a=await ask(c.bold('Roll production back'+(id?' to '+depId(id):' to the previous build')+'? [y/N] '));if(!/^y/i.test(a)){out('Nothing changed.');return}}
|
|
349
|
+
const r=await ws(t,'deploy_rollback',{to:id,confirm:true});emit(r);if(JSON_OUT)return;
|
|
350
|
+
out(c.green('✓ Production is on ')+depId(r.to.id)+' '+c.dim(r.to.url));
|
|
351
|
+
out(c.dim("Ask the agent to investigate:"));out(wrap(r.investigate.split('\n')[0],' '));
|
|
352
|
+
};
|
|
353
|
+
|
|
354
|
+
// ----- catalog -----
|
|
355
|
+
async function catalog(){return api('/api/cli',{action:'catalog'},{auth:false})}
|
|
356
|
+
commands.modes=async()=>{const cat=await catalog();emit(cat.modes);if(!JSON_OUT)for(const m of cat.modes)out(c.bold(m.label.padEnd(8))+c.dim(m.hint))};
|
|
357
|
+
commands.roles=async opts=>{const q=opts._.join(' ').toLowerCase();const cat=await catalog();const exact=cat.roles.find(r=>r.id===q);const roles=exact?[exact]:cat.roles.filter(r=>!q||[r.id,r.label,r.title,r.tagline,...(r.tools||[]),...(r.decides||[]),...(r.skills||[])].join(' ').toLowerCase().includes(q)).sort((a,b)=>a.group.localeCompare(b.group));emit(roles);if(JSON_OUT)return;
|
|
358
|
+
if(q&&roles.length===1){const r=roles[0];out(c.bold(r.label)+' · '+r.title+'\n'+wrap(r.tagline,' '));out(c.bold('\n Tools'));out(wrap(r.tools.join(', '),' '));out(c.bold(' Decides'));for(const d of r.decides)out(' - '+d);out(c.bold(' Skills'));out(wrap(r.skills.join(', '),' '));return}
|
|
359
|
+
let group='';for(const r of roles){if(r.group!==group){group=r.group;out(c.bold('\n'+group))}out(' '+c.teal(r.id.padEnd(12))+r.label.padEnd(20)+c.dim(r.tagline.slice(0,70)))}
|
|
360
|
+
out(c.dim('\n'+roles.length+' roles · `mlai roles <id>` for tools and decisions · `mlai run -r <id> "…"`'))};
|
|
361
|
+
commands.skills=async opts=>{const q=opts._.join(' ').toLowerCase();const cat=await catalog();const skills=cat.skills.filter(s=>!q||(s.id+' '+s.name+' '+s.description).toLowerCase().includes(q));emit(skills);if(JSON_OUT)return;for(const s of skills)out(' '+c.teal(s.id.padEnd(28))+c.dim(s.description.slice(0,80)));out(c.dim('\n'+skills.length+' skills'))};
|
|
362
|
+
commands.doctor=async()=>{const cfg=config();out('server '+baseUrl());out('token '+(cfg.token?'present ('+(cfg.label||'')+')':'missing — run mlai login'));out('project '+(linkedProject()?.label||'none linked here'));out('node '+process.version);try{const h=await fetch(baseUrl()+'/api/health').then(r=>r.status);out('health HTTP '+h)}catch(e){out(c.red('health unreachable: '+e.message))}};
|
|
363
|
+
|
|
364
|
+
// ----- interactive session -----
|
|
365
|
+
async function session(opts){
|
|
366
|
+
const token=requireProject(opts);const name=linkedProject()?.label||'project';
|
|
367
|
+
let mode=opts.mode||'guided';let role=opts.role||'auto';
|
|
368
|
+
out(c.bold('ML AI Code')+c.dim(` · ${name} · mode ${mode} · role ${role}`));out(c.dim('Type a task and press Enter. /mode <m>, /role <r>, /status, /pull, /stop, /quit'));
|
|
369
|
+
const snap=await ws(token,'status');if(snap.status?.state==='running'){out(c.dim('A task is already running; attaching…'));await watch(token)}
|
|
370
|
+
for(;;){
|
|
371
|
+
const line=await ask(c.teal('› '));if(!line)continue;
|
|
372
|
+
if(line==='/quit'||line==='/exit'||line==='/q')return;
|
|
373
|
+
if(line.startsWith('/mode ')){const m=line.slice(6).trim();if(!MODES[m]){out(c.red('Modes: plan, brief, guided, auto'));continue}mode=m;out(c.dim('mode '+mode));continue}
|
|
374
|
+
if(line.startsWith('/role ')){role=line.slice(6).trim()||'auto';out(c.dim('role '+role));continue}
|
|
375
|
+
if(line==='/status'){await commands.status({_:[],project:token});continue}
|
|
376
|
+
if(line==='/pull'){await commands.pull({_:[],project:token});continue}
|
|
377
|
+
if(line==='/stop'){await ws(token,'stop');out('Stop requested.');continue}
|
|
378
|
+
if(line==='/help'){out(c.dim('/mode plan|brief|guided|auto · /role <id> · /status · /pull · /stop · /quit'));continue}
|
|
379
|
+
const started=Date.now()/1000-1;
|
|
380
|
+
try{const r=await startRun(token,line,{mode,role});if(r.status!=='cancelled'&&r.status!=='needs_details')await watch(token,{since:started,quiet:false})}catch(e){out(c.red(' '+e.message))}
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
// ---------- main ----------
|
|
385
|
+
export async function main(argv=process.argv.slice(2)){
|
|
386
|
+
const opts=parseArgs(argv);JSON_OUT=opts.json===true;
|
|
387
|
+
if(opts.version)return commands.version();
|
|
388
|
+
const name=opts._.shift();
|
|
389
|
+
if(opts.help||name==='help')return commands.help();
|
|
390
|
+
if(!name)return session(opts);
|
|
391
|
+
const fn=commands[name];if(!fn)fail(`Unknown command "${name}". Run \`mlai help\`.`,2);
|
|
392
|
+
try{await fn(opts)}catch(e){if(e instanceof ApiError){if(e.code==='workspace_missing')fail('This project no longer exists. `mlai projects` to pick another.');fail(e.message)}if(e?.code==='ECONNREFUSED'||e?.cause?.code)fail('Could not reach '+baseUrl()+' ('+(e.cause?.code||e.code)+')');throw e}
|
|
393
|
+
}
|
|
394
|
+
if(import.meta.url===`file://${process.argv[1]}`||process.argv[1]?.endsWith('/mlai')||process.argv[1]?.endsWith('mlai.mjs'))main();
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/* Trusted, isolated syntax adapter. Never loads project config JS, plugins or code. */
|
|
2
|
+
const fs=require('node:fs');
|
|
3
|
+
const ts=require(process.argv[2]);
|
|
4
|
+
const input=JSON.parse(fs.readFileSync(0,'utf8'));
|
|
5
|
+
const result=input.map(({path,text})=>{
|
|
6
|
+
if(path.endsWith('.json')){
|
|
7
|
+
const p=ts.parseConfigFileTextToJson(path,text);
|
|
8
|
+
return {config:p.error?null:p.config,error:!!p.error};
|
|
9
|
+
}
|
|
10
|
+
const source=ts.createSourceFile(path,text,ts.ScriptTarget.Latest,true);
|
|
11
|
+
const imports=[],symbols=[];
|
|
12
|
+
function visit(n){
|
|
13
|
+
if((ts.isImportDeclaration(n)||ts.isExportDeclaration(n))&&n.moduleSpecifier&&ts.isStringLiteral(n.moduleSpecifier))
|
|
14
|
+
imports.push({spec:n.moduleSpecifier.text,line:source.getLineAndCharacterOfPosition(n.getStart(source)).line+1});
|
|
15
|
+
if(ts.isFunctionDeclaration(n)||ts.isClassDeclaration(n)||ts.isInterfaceDeclaration(n)||ts.isTypeAliasDeclaration(n)){
|
|
16
|
+
if(n.name&&symbols.length<200)symbols.push({name:n.name.text,line:source.getLineAndCharacterOfPosition(n.getStart(source)).line+1});
|
|
17
|
+
}
|
|
18
|
+
ts.forEachChild(n,visit);
|
|
19
|
+
}
|
|
20
|
+
visit(source);
|
|
21
|
+
return {imports,symbols,error:source.parseDiagnostics.length>0};
|
|
22
|
+
});
|
|
23
|
+
process.stdout.write(JSON.stringify(result));
|