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.
Files changed (182) hide show
  1. package/README.md +12 -2
  2. package/bin/mlai.mjs +3 -0
  3. package/package.json +18 -3
  4. package/src/browser-setup.mjs +77 -0
  5. package/src/cli-ext.mjs +146 -0
  6. package/src/cli.mjs +534 -0
  7. package/src/cloud.mjs +29 -0
  8. package/src/completion.mjs +159 -0
  9. package/src/credentials.mjs +54 -0
  10. package/src/deploy.mjs +134 -0
  11. package/src/distribution.mjs +373 -0
  12. package/src/engine-key.mjs +4 -0
  13. package/src/engine.mjs +167 -0
  14. package/src/headless.mjs +196 -0
  15. package/src/home.mjs +22 -0
  16. package/src/host.mjs +123 -0
  17. package/src/local-models.mjs +64 -0
  18. package/src/modes.mjs +38 -0
  19. package/src/netbox.mjs +97 -0
  20. package/src/netjail.py +59 -0
  21. package/src/offline.mjs +98 -0
  22. package/src/parity.mjs +86 -0
  23. package/src/project.mjs +68 -0
  24. package/src/relay.mjs +140 -0
  25. package/src/render.mjs +73 -0
  26. package/src/restricted.mjs +47 -0
  27. package/src/review.mjs +70 -0
  28. package/src/runner.mjs +127 -0
  29. package/src/runtime.mjs +75 -0
  30. package/src/sandbox.mjs +135 -0
  31. package/src/sdk.mjs +11 -0
  32. package/src/server.mjs +110 -0
  33. package/src/session.mjs +290 -0
  34. package/src/settings.mjs +135 -0
  35. package/src/shared-data.mjs +3 -0
  36. package/src/tui/acp.mjs +145 -0
  37. package/src/tui/agents-cli.mjs +114 -0
  38. package/src/tui/agents-local.mjs +65 -0
  39. package/src/tui/ansi.mjs +123 -0
  40. package/src/tui/app.mjs +710 -0
  41. package/src/tui/approval.mjs +88 -0
  42. package/src/tui/bg.mjs +172 -0
  43. package/src/tui/bgterm.mjs +79 -0
  44. package/src/tui/chat.mjs +230 -0
  45. package/src/tui/clipboard.mjs +74 -0
  46. package/src/tui/cloud-cli.mjs +57 -0
  47. package/src/tui/cloud-run.mjs +123 -0
  48. package/src/tui/cmd-agents.mjs +130 -0
  49. package/src/tui/cmd-auto-review.mjs +94 -0
  50. package/src/tui/cmd-cloud.mjs +17 -0
  51. package/src/tui/cmd-config.mjs +104 -0
  52. package/src/tui/cmd-core.mjs +160 -0
  53. package/src/tui/cmd-distribution.mjs +15 -0
  54. package/src/tui/cmd-ecosystem.mjs +169 -0
  55. package/src/tui/cmd-extensibility.mjs +333 -0
  56. package/src/tui/cmd-remote.mjs +18 -0
  57. package/src/tui/cmd-review.mjs +58 -0
  58. package/src/tui/cmd-session-extra.mjs +152 -0
  59. package/src/tui/cmd-tui.mjs +200 -0
  60. package/src/tui/commands.mjs +160 -0
  61. package/src/tui/custom-commands.mjs +98 -0
  62. package/src/tui/diff.mjs +60 -0
  63. package/src/tui/editor.mjs +190 -0
  64. package/src/tui/ext-state.mjs +16 -0
  65. package/src/tui/extensions-local.mjs +140 -0
  66. package/src/tui/files.mjs +72 -0
  67. package/src/tui/handoff.mjs +110 -0
  68. package/src/tui/import-setups.mjs +151 -0
  69. package/src/tui/init.mjs +104 -0
  70. package/src/tui/keymap.mjs +70 -0
  71. package/src/tui/keys.mjs +101 -0
  72. package/src/tui/loop.mjs +75 -0
  73. package/src/tui/markdown.mjs +118 -0
  74. package/src/tui/mcp-config.mjs +225 -0
  75. package/src/tui/mcp-oauth.mjs +162 -0
  76. package/src/tui/permissions.mjs +189 -0
  77. package/src/tui/plain.mjs +32 -0
  78. package/src/tui/plugins-local.mjs +103 -0
  79. package/src/tui/remote.mjs +125 -0
  80. package/src/tui/review-cli.mjs +332 -0
  81. package/src/tui/review-github.mjs +59 -0
  82. package/src/tui/screen.mjs +60 -0
  83. package/src/tui/session-ops.mjs +104 -0
  84. package/src/tui/skills-local.mjs +92 -0
  85. package/src/tui/snapshots.mjs +87 -0
  86. package/src/tui/statusline.mjs +98 -0
  87. package/src/tui/transcript.mjs +116 -0
  88. package/src/two-words.mjs +36 -0
  89. package/src/wakeups.mjs +53 -0
  90. package/src/winenv.mjs +94 -0
  91. package/src/winsandbox.py +351 -0
  92. package/src/workspace-api.mjs +621 -0
  93. package/src/worktree.mjs +128 -0
  94. package/vendor/client-sdk/controller.cjs +115 -0
  95. package/vendor/client-sdk/files.cjs +38 -0
  96. package/vendor/client-sdk/index.cjs +133 -0
  97. package/vendor/client-sdk/login.cjs +52 -0
  98. package/vendor/client-sdk/updates.cjs +41 -0
  99. package/vendor/cloud-cli/mlai.mjs +394 -0
  100. package/worker/architecture_parse.cjs +23 -0
  101. package/worker/architecture_worker.py +394 -0
  102. package/worker/ask_first.py +96 -0
  103. package/worker/attachment_reader.py +66 -0
  104. package/worker/background_jobs.py +111 -0
  105. package/worker/brief_questions.py +56 -0
  106. package/worker/browser_local.py +49 -0
  107. package/worker/browser_pane.py +89 -0
  108. package/worker/browser_tool.py +101 -0
  109. package/worker/build_planner.py +187 -0
  110. package/worker/chat_fork.py +277 -0
  111. package/worker/checkpoints.py +133 -0
  112. package/worker/cloud_pty.py +351 -0
  113. package/worker/command_policy.py +39 -0
  114. package/worker/command_safety.py +717 -0
  115. package/worker/computer_card.sh +23 -0
  116. package/worker/computer_setup.sh +86 -0
  117. package/worker/computer_use.py +221 -0
  118. package/worker/connector_search.py +43 -0
  119. package/worker/context_manager.py +60 -0
  120. package/worker/conversation.py +144 -0
  121. package/worker/deploy_pack.py +116 -0
  122. package/worker/design_director.py +240 -0
  123. package/worker/dev_jobs.py +166 -0
  124. package/worker/edit_guard.py +99 -0
  125. package/worker/env_setup.py +129 -0
  126. package/worker/evidence.py +109 -0
  127. package/worker/fast_search.py +24 -0
  128. package/worker/git_sync.py +333 -0
  129. package/worker/goals.py +156 -0
  130. package/worker/handover.py +98 -0
  131. package/worker/harness_memory.py +194 -0
  132. package/worker/image_generation.py +173 -0
  133. package/worker/intelligence.py +149 -0
  134. package/worker/intent_model.py +78 -0
  135. package/worker/intent_weights.json +1 -0
  136. package/worker/ios_simulator.py +87 -0
  137. package/worker/kimi_bridge.py +997 -0
  138. package/worker/kimi_compact.py +93 -0
  139. package/worker/kimi_gates.py +304 -0
  140. package/worker/kimi_hook.py +617 -0
  141. package/worker/lifecycle.py +95 -0
  142. package/worker/lsp.py +77 -0
  143. package/worker/mcp_local.py +293 -0
  144. package/worker/memory.py +99 -0
  145. package/worker/mlai_auto_review.py +177 -0
  146. package/worker/mlai_hooks.py +966 -0
  147. package/worker/mlai_mcp.py +441 -0
  148. package/worker/mlai_permissions.py +283 -0
  149. package/worker/model_stream.py +75 -0
  150. package/worker/nested_repos.py +76 -0
  151. package/worker/offline_guard.py +17 -0
  152. package/worker/preview.py +806 -0
  153. package/worker/proc_watch.py +124 -0
  154. package/worker/project_context.py +72 -0
  155. package/worker/project_rules.py +99 -0
  156. package/worker/quality.py +180 -0
  157. package/worker/reply_language.py +56 -0
  158. package/worker/repo_hygiene.py +132 -0
  159. package/worker/repo_memory.py +101 -0
  160. package/worker/repo_policy.py +269 -0
  161. package/worker/roles.json +3173 -0
  162. package/worker/roles.py +303 -0
  163. package/worker/runner.py +1795 -0
  164. package/worker/runtime_control.py +205 -0
  165. package/worker/secret_scan.py +168 -0
  166. package/worker/session_hub.py +80 -0
  167. package/worker/skill_library.py +129 -0
  168. package/worker/skill_pack.py +533 -0
  169. package/worker/subagents.py +91 -0
  170. package/worker/task_controller.py +139 -0
  171. package/worker/task_skills.py +159 -0
  172. package/worker/team_checkpoint.py +33 -0
  173. package/worker/token_count.py +32 -0
  174. package/worker/tool_catalog.py +38 -0
  175. package/worker/upload_storage.py +531 -0
  176. package/worker/verification.py +725 -0
  177. package/worker/vision.py +84 -0
  178. package/worker/wakeups.py +63 -0
  179. package/worker/web_tools.py +203 -0
  180. package/worker/winproc.py +135 -0
  181. package/worker/work_ledger.py +117 -0
  182. package/worker/worktrees.py +79 -0
@@ -0,0 +1,74 @@
1
+ /**
2
+ * Clipboard image paste for the TUI (Ctrl-V; Alt-V on Windows, where the terminal keeps Ctrl-V for text).
3
+ * Terminals only paste text, so the image is read with the platform's own tools and saved as a PNG:
4
+ * macOS osascript (the clipboard as PNG)
5
+ * Windows PowerShell + System.Windows.Forms.Clipboard
6
+ * Linux wl-paste (Wayland) or xclip (X11)
7
+ * readClipboardImage() resolves to {path} or {error} with a message the user can act on. Dependency-free.
8
+ */
9
+ import {execFile} from 'node:child_process';
10
+ import {mkdir,stat,writeFile,unlink} from 'node:fs/promises';
11
+ import path from 'node:path';
12
+ import os from 'node:os';
13
+
14
+ const run=(file,args,{encoding='utf8',timeout=5000,input}={})=>new Promise(resolve=>{
15
+ const p=execFile(file,args,{encoding,timeout,maxBuffer:20_000_000,windowsHide:true},(e,stdout,stderr)=>resolve({ok:!e,code:e?.code,stdout,stderr:String(stderr||''),missing:e?.code==='ENOENT'}));
16
+ if(input!=null){p.stdin?.end(input)}
17
+ });
18
+ const PNG=Buffer.from([0x89,0x50,0x4e,0x47]);
19
+ const isImage=b=>Buffer.isBuffer(b)&&b.length>8&&(b.subarray(0,4).equals(PNG)||(b[0]===0xff&&b[1]===0xd8));
20
+
21
+ /** Where pasted images go: <tmp>/mlai-paste/paste-<time>.png */
22
+ export async function pasteFile(dir=path.join(os.tmpdir(),'mlai-paste')){
23
+ await mkdir(dir,{recursive:true});
24
+ return path.join(dir,'paste-'+new Date().toISOString().replace(/[:.]/g,'-')+'.png');
25
+ }
26
+
27
+ /** The commands tried per platform, in order. Exported for tests. */
28
+ export function clipboardPlan(platform=process.platform,env=process.env){
29
+ if(platform==='darwin')return ['osascript'];
30
+ if(platform==='win32')return ['powershell'];
31
+ const wayland=Boolean(env.WAYLAND_DISPLAY);
32
+ return wayland?['wl-paste','xclip']:['xclip','wl-paste'];
33
+ }
34
+
35
+ export async function readClipboardImage({platform=process.platform,env=process.env,runImpl=run,file=null}={}){
36
+ const out=file||await pasteFile();
37
+ const tried=[];
38
+ for(const tool of clipboardPlan(platform,env)){
39
+ if(tool==='osascript'){
40
+ const script=['set f to (open for access POSIX file "'+out.replace(/"/g,'\\"')+'" with write permission)','try','write (the clipboard as «class PNGf») to f','close access f','on error m','close access f','error m','end try'];
41
+ const r=await runImpl('osascript',script.flatMap(l=>['-e',l]));
42
+ if(r.ok&&await size(out)>0)return {path:out};
43
+ await unlink(out).catch(()=>{});
44
+ tried.push(r.missing?'osascript not found':'no image on the clipboard');continue;
45
+ }
46
+ if(tool==='powershell'){
47
+ const ps="Add-Type -AssemblyName System.Windows.Forms,System.Drawing; $i=[System.Windows.Forms.Clipboard]::GetImage(); if($i -eq $null){ exit 3 }; $i.Save($env:MLAI_PASTE_OUT,[System.Drawing.Imaging.ImageFormat]::Png); 'ok'";
48
+ const r=await runImpl('powershell.exe',['-NoProfile','-NonInteractive','-STA','-Command',ps.replace('$env:MLAI_PASTE_OUT',"'"+out.replace(/'/g,"''")+"'")]);
49
+ if(r.ok&&await size(out)>0)return {path:out};
50
+ tried.push(r.missing?'PowerShell not found':'no image on the clipboard');continue;
51
+ }
52
+ if(tool==='wl-paste'){
53
+ const types=await runImpl('wl-paste',['--list-types']);
54
+ if(types.missing){tried.push('wl-paste not found');continue}
55
+ const type=String(types.stdout||'').split('\n').map(s=>s.trim()).find(s=>/^image\/(png|jpeg)$/.test(s));
56
+ if(!type){tried.push('no image on the clipboard');continue}
57
+ const r=await runImpl('wl-paste',['--no-newline','--type',type],{encoding:'buffer'});
58
+ if(r.ok&&isImage(r.stdout)){await writeFile(out,r.stdout);return {path:out}}
59
+ tried.push('could not read the clipboard image');continue;
60
+ }
61
+ if(tool==='xclip'){
62
+ const types=await runImpl('xclip',['-selection','clipboard','-t','TARGETS','-o']);
63
+ if(types.missing){tried.push('xclip not found');continue}
64
+ const type=String(types.stdout||'').split('\n').map(s=>s.trim()).find(s=>/^image\/(png|jpeg)$/.test(s));
65
+ if(!type){tried.push('no image on the clipboard');continue}
66
+ const r=await runImpl('xclip',['-selection','clipboard','-t',type,'-o'],{encoding:'buffer'});
67
+ if(r.ok&&isImage(r.stdout)){await writeFile(out,r.stdout);return {path:out}}
68
+ tried.push('could not read the clipboard image');continue;
69
+ }
70
+ }
71
+ const missing=tried.length&&tried.every(x=>/not found/.test(x));
72
+ return {error:missing?(platform==='linux'?'Install wl-clipboard or xclip to paste images, or drag the image file in.':'Could not read the clipboard ('+tried.join(', ')+').'):'No image on the clipboard. Copy an image, or drag the file in.'};
73
+ }
74
+ async function size(f){try{return (await stat(f)).size}catch{return 0}}
@@ -0,0 +1,57 @@
1
+ // `mlai --cloud "task"` and `mlai --teleport [chat]` (cli.mjs calls these; the logic is in cloud-run.mjs).
2
+ import {projectRoot} from '../project.mjs';
3
+ import {startCloudTask,followCloud,cloudAnswer,cloudChats,findChat,teleport,chatRow} from './cloud-run.mjs';
4
+
5
+ const short=n=>String(n||'').replace(/^mini-/,'').slice(0,8);
6
+
7
+ /**
8
+ * Starts a cloud agent on this folder's work (pushed to a new mlai/ branch) and follows it here until it ends.
9
+ * deps: {cloud, out(stdout line), log(stderr line), ask(question)=>string|null, renderEvent, c, json, detach(bool)}.
10
+ */
11
+ export async function cloudMain(task,{cloud,cwd=process.cwd(),out,log,ask,renderEvent,c,json=false,detach=false,signal,intervalMs}){
12
+ const {root,git}=await projectRoot(cwd);
13
+ if(!git)throw new Error('A cloud agent works on a GitHub repository. Run this in a clone with a github.com origin.');
14
+ log(c.dim('Pushing this folder to a new branch for the cloud agent...'));
15
+ const r=await startCloudTask(task,{cloud,root});
16
+ log('Cloud agent started on '+r.branch+' ('+r.repo+').');
17
+ log('Open it on the web: '+r.url);
18
+ const meta={name:r.name,url:r.url,repo:r.repo,branch:r.branch};
19
+ if(detach){if(json)out(JSON.stringify({type:'result',state:'running',exitCode:0,cloud:meta}));else log(c.dim('Bring it here later with: mlai --teleport '+short(r.name)));return 0}
20
+ const f=await followCloud(cloud.device,r.token,{signal,intervalMs,
21
+ render:e=>{if(json)out(JSON.stringify(e));else{const l=renderEvent(e,{c});if(l&&e.type!=='answer')log(l)}},
22
+ ask:ask?async p=>{log(c.yellow(p.kind==='plan'?'Review the plan':'Approval')+(p.command?': '+String(p.command).slice(0,600):(p.items?'\n'+p.items.map(t=>' - '+t).join('\n'):'')));return ask('approve? [y]es / [a]ll / [n]o (Enter leaves it for the web) › ')}:null});
23
+ const text=f.state==='waiting'?'':cloudAnswer(f.snapshot);
24
+ const code=f.state==='completed'||f.detached?0:1;
25
+ if(json)out(JSON.stringify({type:'result',state:f.state,exitCode:code,cloud:meta,text,waiting:f.waiting||null}));
26
+ else{
27
+ if(text)out(text);
28
+ if(f.detached)log(c.dim('Detached. The cloud agent keeps working: '+r.url));
29
+ else if(f.state==='waiting')log(c.yellow('Waiting for an approval. Answer it on the web: ')+r.url);
30
+ else log(c.dim('Cloud run '+f.state+'.'));
31
+ log(c.dim('Bring it here with: mlai --teleport '+short(r.name)));
32
+ }
33
+ return code;
34
+ }
35
+
36
+ /** Picks a cloud chat by reference (name, link, title words) or from a list. pick(rows,{title}) => row|null. */
37
+ export async function chooseChat(cloud,ref,{pick}){
38
+ const chats=cloudChats(await cloud.device.projects());
39
+ if(!chats.length)throw new Error('No cloud chats yet. Start one with mlai --cloud "task" or & in a session.');
40
+ const f=findChat(chats,ref);if(f.chat)return f.chat;
41
+ if(!f.matches.length)throw new Error('No cloud chat matches '+ref+'.');
42
+ if(!pick)throw new Error('More than one cloud chat matches'+(ref?' '+ref:'')+': '+f.matches.slice(0,5).map(x=>short(x.name)+' '+x.title).join('; '));
43
+ const row=await pick(f.matches.slice(0,30).map(x=>chatRow(x,cloud.server)),{title:'Teleport a cloud chat'});
44
+ return row?f.matches.find(x=>x.name===row.value)||null:null;
45
+ }
46
+
47
+ /** Brings a cloud chat into a new local worktree session. Returns the session, or null when nothing was chosen. */
48
+ export async function teleportMain(ref,{cloud,cwd=process.cwd(),log,c,pick,createWorktree,createSession}){
49
+ const chat=await chooseChat(cloud,ref,{pick});if(!chat)return null;
50
+ const {root,git}=await projectRoot(cwd);
51
+ if(!git)throw new Error('Run this in a git clone of the cloud chat\u2019s repository.');
52
+ log(c.dim('Bringing "'+chat.title+'" to this computer...'));
53
+ const r=await teleport(chat,{client:cloud.device,root,createWorktree,createSession,log:t=>log(c.yellow(t))});
54
+ log('Teleported to '+r.tree.path+' on branch '+r.tree.branch+(r.branch?' (from '+r.branch+')':'')+(r.applied===true?', with the cloud\u2019s uncommitted changes':r.applied===false?'; some changes need a look':'')+'.');
55
+ log(c.dim('Your folder and branch did not change. The cloud chat is still there: '+chatRow(chat,cloud.server).url));
56
+ return r.session;
57
+ }
@@ -0,0 +1,123 @@
1
+ // Cloud from the terminal: `mlai --cloud "task"` starts a cloud agent on this project's work and follows it here;
2
+ // `mlai --teleport <chat>` and /teleport bring a cloud chat (its branch, uncommitted changes and conversation) into a
3
+ // local worktree session so you can continue it on this computer.
4
+ import {writeFile,mkdir,rm,mkdtemp} from 'node:fs/promises';
5
+ import os from 'node:os';
6
+ import path from 'node:path';
7
+ import {git,githubRepo,pushForCloud,startCloud,chatUrl,slug} from './handoff.mjs';
8
+
9
+ const RUNNING=new Set(['running','starting','queued','waiting','resuming']);
10
+ const TERMINAL=new Set(['completed','failed','error','stopped','interrupted','limited','lost']);
11
+ const clip=(s,n)=>{const t=String(s||'').replace(/\s+/g,' ').trim();return t.length>n?t.slice(0,n-1)+'\u2026':t};
12
+
13
+ /** Cloud chats from GET /api/account, with their workspace tokens (kept in memory only). */
14
+ export function cloudChats(account){
15
+ const runs=Array.isArray(account?.runs)?account.runs:[];
16
+ return (Array.isArray(account?.workspaces)?account.workspaces:[])
17
+ .filter(w=>w&&typeof w.name==='string'&&typeof w.token==='string'&&w.backend!=='laptop'&&!w.name.startsWith('remote-')&&!String(w.title||'').startsWith('Laptop: '))
18
+ .map(w=>{const last=runs.filter(r=>r?.workspace_name===w.name).sort((a,b)=>String(b.started_at||'').localeCompare(String(a.started_at||'')))[0];
19
+ return {name:w.name,token:w.token,title:String(w.title||last?.title||w.name).slice(0,120),repo:typeof w.repo==='string'?w.repo:'',state:last?String(last.state||''):'idle',updated:last?.started_at||w.created_at||null}})
20
+ .sort((a,b)=>String(b.updated||'').localeCompare(String(a.updated||'')));
21
+ }
22
+ /** A chat by exact name, name or link prefix (6+ characters), or title words. Returns {chat} or {matches}. */
23
+ export function findChat(chats,ref){
24
+ const r=String(ref||'').trim().replace(/^.*[?&]chat=/,'').replace(/&.*$/,'');let q;try{q=decodeURIComponent(r)}catch{q=r}
25
+ if(!q)return {matches:chats};
26
+ const exact=chats.find(c=>c.name===q);if(exact)return {chat:exact};
27
+ const pre=q.length>=6?chats.filter(c=>c.name.startsWith(q)||c.name.replace(/^mini-/,'').startsWith(q)):[];if(pre.length===1)return {chat:pre[0]};
28
+ const words=q.toLowerCase().split(/\s+/);const byTitle=chats.filter(c=>words.every(w=>c.title.toLowerCase().includes(w)));
29
+ const all=pre.length?pre:byTitle;return all.length===1?{chat:all[0]}:{matches:all};
30
+ }
31
+
32
+ /**
33
+ * Follows a cloud run until it ends. Events are rendered with `render(e)`; approvals are answered with
34
+ * ask(text) => 'y'|'a'|'n'|null when given (null leaves it for the web). Ctrl-C (signal) detaches; the run keeps going.
35
+ * Returns {state, snapshot, detached, waiting}.
36
+ */
37
+ export async function followCloud(client,token,{render=()=>{},ask=null,signal,intervalMs=1500,maxPolls=2400,onPending=()=>{}}={}){
38
+ let answered=new Set(),snapshot=null;
39
+ try{
40
+ snapshot=await client.watch(token,{signal,intervalMs,maxPolls,onEvent:e=>{if(e?.type!=='approval')render(e)},onSnapshot:async snap=>{
41
+ const p=snap?.pending;if(!p?.id||answered.has(p.id))return;answered.add(p.id);
42
+ onPending(p);
43
+ if(!ask)throw Object.assign(new Error('waiting'),{waiting:p,snap});
44
+ const a=String(await ask(p)||'').trim().toLowerCase();
45
+ if(a==='y'||a==='yes')await client.workspace(token,'approve',{id:p.id,approved:true});
46
+ else if(a==='a'||a==='all')await client.workspace(token,'approve',{id:p.id,approved:true,all:true});
47
+ else if(a==='n'||a==='no')await client.workspace(token,'approve',{id:p.id,approved:false});
48
+ else throw Object.assign(new Error('waiting'),{waiting:p,snap});
49
+ }});
50
+ }catch(e){
51
+ if(e?.waiting)return {state:'waiting',snapshot:e.snap,waiting:e.waiting};
52
+ if(e?.name==='AbortError'||signal?.aborted)return {state:'running',snapshot,detached:true};
53
+ if(e?.code==='watch_timeout')return {state:'running',snapshot,detached:true};
54
+ throw e;
55
+ }
56
+ return {state:snapshot?.status?.state||'completed',snapshot};
57
+ }
58
+ /** Final answer text from a cloud snapshot. */
59
+ export function cloudAnswer(snapshot){
60
+ const ev=Array.isArray(snapshot?.events)?snapshot.events:[];const a=[...ev].reverse().find(e=>e?.type==='answer'&&e.content);
61
+ return String(a?.content||snapshot?.answer||snapshot?.status?.result?.submission||snapshot?.status?.error||'').trim();
62
+ }
63
+
64
+ /** `mlai --cloud "task"`: push this folder's work to a new branch and start a cloud agent on it with the task. */
65
+ export async function startCloudTask(task,{cloud,root,title,mode='approve'}){
66
+ if(!cloud?.device)throw new Error('Sign in first: run mlai login.');
67
+ const pushed=await pushForCloud(root,{title:title||task});
68
+ return await startCloud({client:cloud.device,server:cloud.server,pushed,task,mode});
69
+ }
70
+
71
+ /** Events worth keeping as conversation context: what was asked and said, not tool output. */
72
+ export function contextEvents(events){
73
+ return (Array.isArray(events)?events:[]).filter(e=>e&&['assistant','answer','steering','imported_user','todos','completion'].includes(e.type)).slice(-300)
74
+ .map(e=>({...e,...(typeof e.content==='string'?{content:e.content.slice(0,8000)}:{})}));
75
+ }
76
+
77
+ /**
78
+ * Brings a cloud chat to this computer. Needs a clone of the chat's GitHub repository at `root`. The cloud branch is
79
+ * fetched into a new worktree (your folder and branch do not change), the cloud's uncommitted changes are applied on
80
+ * top, and a local session gets the conversation as context. `createWorktree` and `createSession` come from
81
+ * src/worktree.mjs and src/session.mjs (injectable for tests). Returns {session, tree, chat, branch, applied, patchFile}.
82
+ */
83
+ export async function teleport(chat,{client,root,createWorktree,createSession,log=()=>{}}){
84
+ const status=await client.status(chat.token);
85
+ const state=status?.status?.state;
86
+ if(RUNNING.has(state))throw new Error('That cloud chat is still working. Wait for it to finish, or stop it, then teleport it.');
87
+ const g=await client.workspace(chat.token,'git_status').catch(()=>null);
88
+ const repo=g?.repository||githubRepo(chat.repo)||(/^[\w.-]+\/[\w.-]+$/.test(chat.repo||'')?chat.repo:null);
89
+ if(!repo)throw new Error('That cloud chat has no GitHub repository, so it cannot come to this computer. Open it on the web instead.');
90
+ const origin=githubRepo((await git(root,['config','--get','remote.origin.url'])).stdout);
91
+ if(!origin||origin.toLowerCase()!==repo.toLowerCase())throw new Error('Run this in a clone of '+repo+' (its origin must be github.com/'+repo+').');
92
+ const branch=g?.branch||null;let base=null;
93
+ if(branch){const f=await git(root,['fetch','--quiet','origin',branch],{timeout:180000});if(!f.code)base=(await git(root,['rev-parse','FETCH_HEAD'])).stdout;else log('Could not fetch '+branch+' from GitHub; starting from your current commit.')}
94
+ if(!base&&g?.remoteHead){const f=await git(root,['fetch','--quiet','origin',g.remoteHead],{timeout:180000});if(!f.code)base=(await git(root,['rev-parse','FETCH_HEAD'])).stdout}
95
+ const tree=await createWorktree(root,{name:'teleport '+(chat.title||chat.name)});
96
+ if(base){const r=await git(tree.path,['reset','--quiet','--hard',base]);if(r.code)throw new Error('Could not check out the cloud branch: '+(r.stderr||r.stdout));tree.base=base}
97
+ const exported=await client.workspace(chat.token,'export').catch(()=>null);
98
+ const patch=typeof exported?.patch==='string'?exported.patch:'';let applied=null,patchFile=null;
99
+ if(patch.trim()){
100
+ const tmp=await mkdtemp(path.join(os.tmpdir(),'mlai-teleport-'));const file=path.join(tmp,'cloud.patch');
101
+ try{
102
+ await writeFile(file,patch.endsWith('\n')?patch:patch+'\n');
103
+ const r=await git(tree.path,['apply','--3way','--whitespace=nowarn',file]);
104
+ applied=!r.code;
105
+ if(!applied){patchFile=path.join(tree.path,'.mlai-cloud.patch');await writeFile(patchFile,patch);log('Some cloud changes did not apply cleanly; the full patch is in '+patchFile+'.')}
106
+ }finally{await rm(tmp,{recursive:true,force:true}).catch(()=>{})}
107
+ }
108
+ const transcript=await client.workspace(chat.token,'session_export').catch(()=>null);
109
+ const s=await createSession({mode:'guided',worktree:tree});
110
+ const messages=(Array.isArray(transcript?.messages)?transcript.messages:[]).filter(m=>m&&typeof m.content==='string'&&m.content.trim()).slice(-40).map(m=>({role:m.role==='user'?'user':'assistant',content:m.content.slice(0,8000)}));
111
+ const events=contextEvents(transcript?.events);
112
+ const h=path.join(s.dir,'history');await mkdir(h,{recursive:true});
113
+ await writeFile(path.join(h,String(BigInt(Date.now())*1000000n)+'.json'),JSON.stringify({task:String(transcript?.title||chat.title||'Cloud chat').slice(0,2000),status:{state:'imported',from:'cloud'},todos:[],checks:[],completion:null,events}));
114
+ if(messages.length)await writeFile(path.join(s.dir,'imported-context.json'),JSON.stringify({title:chat.title,messages,source:'cloud'}));
115
+ s.meta.title=clip(chat.title||'Cloud chat',80);s.meta.cliMode='agent';
116
+ s.meta.teleported={name:chat.name,repo,branch,base,applied,at:new Date().toISOString()};
117
+ s.meta.turns.push({task:String(transcript?.title||chat.title||'Cloud chat').slice(0,2000),state:'imported',started:new Date().toISOString(),finished:new Date().toISOString(),tokens:0,calls:0,imported:true});
118
+ await s.save();
119
+ return {session:s,tree,chat,branch,applied,patchFile,url:null};
120
+ }
121
+ /** One line per chat for pickers. */
122
+ export function chatRow(c,server){return {value:c.name,label:clip(c.title,48),detail:['cloud',c.state||'idle',c.repo?String(c.repo).replace(/^https:\/\/github\.com\//,''):''].filter(Boolean).join(' \u00b7 '),url:chatUrl(server,c.name)}}
123
+ export {RUNNING,TERMINAL,slug};
@@ -0,0 +1,130 @@
1
+ // Agents and handoff commands (owner 5): /goal, /cloud (and the & prefix), /agents, /loop.
2
+ import {readFile,writeFile,rename} from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import {CommandError} from './commands.mjs';
5
+ import {sessionMode} from '../modes.mjs';
6
+ import {sendToCloud,cloudSessions,chatUrl} from './handoff.mjs';
7
+ import {createLoops,parseLoop,loopFile,intervalText} from './loop.mjs';
8
+
9
+ async function readJson(file,fallback){try{return JSON.parse(await readFile(file,'utf8'))}catch{return fallback}}
10
+ async function writeJson(file,data){const tmp=file+'.'+process.pid+'.tmp';await writeFile(tmp,JSON.stringify(data));await rename(tmp,file)}
11
+ const ago=t=>{const s=Math.max(0,(Date.now()-Date.parse(t))/1000);return !Number.isFinite(s)?'':s<90?'just now':s<5400?Math.round(s/60)+'m ago':s<129600?Math.round(s/3600)+'h ago':Math.round(s/86400)+'d ago'};
12
+ const one=s=>String(s||'').replace(/\s+/g,' ').trim();
13
+ const clip=(s,n)=>{const t=one(s);return t.length>n?t.slice(0,n-1)+'\u2026':t};
14
+
15
+ // ---------- /goal ----------
16
+ /** '/goal' arguments -> the task the worker's goals.from_task reads: '/goal <objective>' plus an optional 'Check: <command>' line. */
17
+ export function goalTask(args){
18
+ const text=String(args||'').trim();
19
+ const m=/^([\s\S]*?)(?:\s+|\n)check\s*:\s*(.+)$/i.exec(text);
20
+ const objective=(m?m[1]:text).trim(),check=m?m[2].trim():'';
21
+ if(!objective)return null;
22
+ return '/goal '+objective+(check?'\nCheck: '+check:'');
23
+ }
24
+ export function goalText(g,w){
25
+ if(!g?.condition)return 'No goal in this session. Start one with /goal <objective> [check: <command>].';
26
+ const status={working:'working on it',met:'met',stopped:'stopped',budget:'stopped at its budget'}[g.status]||g.status||'unknown';
27
+ const lines=['Goal: '+clip(g.condition,300),'Status: '+status+(g.attempts!=null?' \u00b7 attempt '+g.attempts+' of '+(g.maxTurns??'?'):'')];
28
+ if(g.check)lines.push('Check: '+clip(g.check,200));
29
+ if(g.reason)lines.push('Last check: '+clip(g.reason,300));
30
+ if(w?.state==='pending'&&w.kind==='goal')lines.push('Continues '+new Date(w.at).toLocaleString()+(w.note?' \u00b7 '+clip(w.note,120):''));
31
+ return lines.join('\n');
32
+ }
33
+ /** Stops the session's goal (the running turn finishes, no further check) and cancels a pending goal wakeup. Same as the app's goal_update stop. */
34
+ export async function stopGoal(dir){
35
+ const gf=path.join(dir,'goal.json'),wf=path.join(dir,'wakeup.json');const g=await readJson(gf,null),w=await readJson(wf,null);let changed=false;
36
+ if(g?.status==='working'){await writeJson(gf,{...g,status:'stopped',reason:'Stopped by you.'});await writeFile(path.join(dir,'goal-stop'),'1');changed=true}
37
+ if(w?.state==='pending'&&w.kind==='goal'){await writeJson(wf,{...w,state:'cancelled',cancelled:new Date().toISOString()});changed=true}
38
+ return changed;
39
+ }
40
+
41
+ // ---------- /agents ----------
42
+ /** Subagents the current run started, from the session's events (subagent rows the harness writes). */
43
+ export async function subagents(session){
44
+ const turns=await session.transcript().catch(()=>[]);const out=[];
45
+ for(const t of turns)for(const e of t.events||[]){
46
+ if(e?.type!=='subagent')continue;
47
+ if(e.state==='running')out.push({task:clip(e.content,120),state:'running',result:''});
48
+ else{const open=[...out].reverse().find(s=>s.state==='running');if(open){open.state=e.state||'completed';open.result=clip(e.content,200)}else out.push({task:'Subagent',state:e.state||'completed',result:clip(e.content,200)})}
49
+ }
50
+ return out.slice(-20);
51
+ }
52
+ /** Rows for /agents: this folder's sessions first, then other local sessions, then cloud chats. */
53
+ export function agentRows({local=[],cloud=[],current=null,root=null,server=''}){
54
+ const rows=[];
55
+ const here=local.filter(m=>m.root===root||m.parent===root),other=local.filter(m=>!here.includes(m));
56
+ for(const m of [...here,...other].slice(0,30))rows.push({kind:'local',id:m.id,label:(m.id===current?'* ':' ')+clip(m.title||m.folder||'New Chat',48),detail:[m.folder,sessionMode(m),(m.turns?.length||0)+' turn'+(m.turns?.length===1?'':'s'),m.updated?ago(m.updated):''].filter(Boolean).join(' \u00b7 ')});
57
+ for(const w of cloud)rows.push({kind:'cloud',id:w.name,label:' '+clip(w.title,48),detail:['cloud',w.state,w.updated?ago(w.updated):''].filter(Boolean).join(' \u00b7 '),url:chatUrl(server,w.name)});
58
+ return rows;
59
+ }
60
+
61
+ // ---------- /loop ----------
62
+ const loopsFor=new WeakMap();
63
+ function loops(ctx){
64
+ const key=ctx.ui||ctx;let l=loopsFor.get(key);
65
+ if(!l){l=createLoops({queue:t=>ctx.ui.queue(t),notify:t=>ctx.ui.print?.(t)});loopsFor.set(key,l)}
66
+ return l;
67
+ }
68
+
69
+ export function install(register,{addRewriter}={}){
70
+ addRewriter?.(line=>/^&(?!&)/.test(String(line||'').trimStart())?'/cloud '+String(line).trimStart().slice(1).trim():null);
71
+
72
+ register({name:'goal',args:'[objective [check: command] | stop]',summary:'Work until a goal is met, show it, or stop it',
73
+ complete:async()=>['stop'],
74
+ run:async(ctx,a)=>{
75
+ const s=ctx.session,dir=s?.dir;
76
+ if(!a||a==='status'){ctx.out(goalText(dir&&await readJson(path.join(dir,'goal.json'),null),dir&&await readJson(path.join(dir,'wakeup.json'),null)));return}
77
+ if(a==='stop'){ctx.out(dir&&await stopGoal(dir)?'Goal stopped. The current step finishes, then the agent stops.':'No goal is running.');return}
78
+ const mode=sessionMode(s?.meta);if(mode==='plan'||mode==='ask')throw new CommandError('Goals change code, so they need agent or auto mode. Switch with /mode agent.');
79
+ const task=goalTask(a);if(!task)throw new CommandError('Say what done looks like: /goal all tests pass check: npm test');
80
+ return {send:task};
81
+ }});
82
+
83
+ register({name:'cloud',args:'[what to do next]',summary:'Hand this conversation to a cloud agent and print its link (or start a line with &)',
84
+ run:async(ctx,a)=>{
85
+ if(!ctx.server)throw new CommandError('Sign in first: run mlai login.');
86
+ const s=ctx.session;if(!s)throw new CommandError('No session yet.');
87
+ const tree=s.meta.worktree&&!s.meta.worktree.removed;
88
+ const ok=await ctx.ui.confirm((tree?'Commit this worktree and push '+s.meta.worktree.branch:'Push a snapshot of this folder, including uncommitted files, to a new branch')+' on GitHub, then continue in a cloud chat? Your files here do not change.',{default:true});
89
+ if(!ok){ctx.out('Not sent.');return}
90
+ ctx.out('Pushing and starting the cloud chat...');
91
+ const {commitAll}=await import('../worktree.mjs');
92
+ const r=await sendToCloud(s,{client:ctx.server.device,server:ctx.server.server,note:a,commitAll:tree?()=>commitAll(s.meta.worktree,s.meta.title||'Work from ML AI Code'):undefined})
93
+ .catch(e=>{throw new CommandError(e.message)});
94
+ ctx.out('Continuing in the cloud on '+r.branch+' ('+r.repo+').\nOpen: '+r.url);
95
+ return r;
96
+ }});
97
+
98
+ register({name:'agents',args:'[filter]',summary:'List sessions, cloud chats and subagents; switch to one',
99
+ run:async(ctx,a)=>{
100
+ const {Session}=await import('../session.mjs');
101
+ const [local,account,subs]=await Promise.all([Session.list().catch(()=>[]),ctx.server?ctx.server.device.projects().catch(()=>null):null,ctx.session?subagents(ctx.session):[]]);
102
+ if(subs.length)ctx.out('Subagents in this session:\n'+subs.map(x=>' '+x.state.padEnd(9)+' '+x.task+(x.result?'\n '+x.result:'')).join('\n'));
103
+ const rows=agentRows({local,cloud:cloudSessions(account),current:ctx.session?.meta?.id,root:ctx.session?.meta?.parent||ctx.session?.meta?.root,server:ctx.server?.server||''});
104
+ if(!rows.length){ctx.out('No other sessions yet.');return}
105
+ const pick=await ctx.ui.pick(rows,{title:'Sessions'+(ctx.server?' and cloud chats':''),filter:a});
106
+ if(!pick)return;
107
+ if(pick.kind==='cloud'){ctx.out('Cloud chat: '+pick.url);return {url:pick.url}}
108
+ if(pick.id===ctx.session?.meta?.id){ctx.out('Already in this session.');return}
109
+ if(ctx.session?.child)throw new CommandError('Wait for the task to finish, or stop it with Esc, before switching.');
110
+ const next=await Session.open(pick.id);ctx.ui.setSession(next);ctx.out('Switched to '+clip(next.meta.title||next.meta.folder,60)+'.');
111
+ return {session:next.meta.id};
112
+ }});
113
+
114
+ register({name:'loop',args:'[interval] <prompt> [until <condition>] | list | stop [id|all]',summary:'Repeat a prompt every interval while this terminal is open',
115
+ complete:async()=>['list','stop','5m','10m','1h'],
116
+ run:async(ctx,a)=>{
117
+ if(typeof ctx.ui?.queue!=='function')throw new CommandError('/loop needs the interactive terminal.');
118
+ const l=loops(ctx);
119
+ if(a==='list'||(!a&&l.list().length)){
120
+ const all=l.list();ctx.out(all.length?all.map(it=>it.id+' every '+intervalText(it.every)+' '+it.runs+' run'+(it.runs===1?'':'s')+' '+clip(it.prompt,60)+(it.until?' until '+clip(it.until,40):'')).join('\n'):'No loops. Start one with /loop 10m check CI.');return}
121
+ const stop=/^stop(?:\s+(\S+))?$/i.exec(a);
122
+ if(stop){const id=stop[1];if(!id||id==='all'){ctx.out(l.stopAll()?'Loops stopped.':'No loops.');return}ctx.out(l.stop(id)?'Loop '+id+' stopped.':'No loop '+id+'.');return}
123
+ let p;try{p=parseLoop(a)}catch(e){throw new CommandError(e.message)}
124
+ if(!p.prompt)p.prompt=await loopFile(ctx.session?.meta?.root||process.cwd());
125
+ if(!p.prompt)throw new CommandError('Say what to repeat: /loop 10m check CI and fix failures. Or write the prompt in .mlai/loop.md.');
126
+ const it=l.add(p);
127
+ ctx.out('Loop '+it.id+': every '+intervalText(it.every)+(p.defaulted?' (the default)':'')+(it.until?', until '+it.until:'')+'. It runs now, then after each interval while this terminal is open. /loop stop '+it.id+' ends it.');
128
+ return {loop:it.id};
129
+ }});
130
+ }
@@ -0,0 +1,94 @@
1
+ // /approve and /feedback (code_review_engineer).
2
+ // /approve: auto mode's reviewer (worker/mlai_auto_review.py) denied an action; this allows that exact action once.
3
+ // The engine reads ROOT/auto-review/approved.json on the retry and consumes the grant.
4
+ // /feedback: the server has no feedback endpoint, so it writes a bundle file (version, settings and recent events,
5
+ // secrets removed) the user can attach to a report, and says so.
6
+ import {readFile,writeFile,mkdir,rename} from 'node:fs/promises';
7
+ import path from 'node:path';
8
+ import os from 'node:os';
9
+ import {CommandError} from './commands.mjs';
10
+
11
+ const arDir=s=>path.join(s.dir,'auto-review');
12
+ const readJson=async(f,d)=>{try{return JSON.parse(await readFile(f,'utf8'))}catch{return d}};
13
+ const writeJson=async(f,v)=>{await mkdir(path.dirname(f),{recursive:true});const t=f+'.'+process.pid+'.tmp';await writeFile(t,JSON.stringify(v,null,1));await rename(t,f)};
14
+ const one=s=>String(s||'').replace(/\s+/g,' ').trim();
15
+
16
+ export async function deniedActions(session){
17
+ const v=await readJson(path.join(arDir(session),'denied.json'),[]);
18
+ return (Array.isArray(v)?v:[]).filter(i=>i&&typeof i.fingerprint==='string').reverse(); // newest first
19
+ }
20
+ /** Grants one retry of a denied action; returns the item. */
21
+ export async function approveOnce(session,item){
22
+ const dir=arDir(session),ap=path.join(dir,'approved.json');
23
+ const grants=await readJson(ap,[]);const list=Array.isArray(grants)?grants:[];
24
+ if(!list.includes(item.fingerprint))list.push(item.fingerprint);
25
+ await writeJson(ap,list.slice(-50));
26
+ const left=(await deniedActions(session)).filter(i=>i.fingerprint!==item.fingerprint).reverse();
27
+ await writeJson(path.join(dir,'denied.json'),left);
28
+ return item;
29
+ }
30
+ export const retryPrompt=item=>'I approved this action once: '+item.action+'\nRetry it now, exactly as before, then continue the task.';
31
+
32
+ /* ---------- /feedback ---------- */
33
+
34
+ const SECRET_KEY=/(token|secret|password|passwd|api[_-]?key|auth|credential|cookie|session[_-]?key|private)/i;
35
+ const R='[redacted]';
36
+ const SECRET_TEXT=[[/\b(sk|pk|rk)-[A-Za-z0-9_-]{16,}/g,R],[/\bgh[pousr]_[A-Za-z0-9]{20,}/g,R],[/\bgithub_pat_[A-Za-z0-9_]{20,}/g,R],[/\bxox[abprs]-[A-Za-z0-9-]{10,}/g,R],
37
+ [/\bAKIA[0-9A-Z]{16}\b/g,R],[/\bAIza[0-9A-Za-z_-]{30,}/g,R],[/\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{5,}/g,R],
38
+ [/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/g,R],[/\b(Bearer|Basic)\s+[A-Za-z0-9._~+/=-]{8,}/gi,'$1 '+R],
39
+ [/\b([A-Za-z0-9_]*(TOKEN|SECRET|PASSWORD|API_KEY|APIKEY)[A-Za-z0-9_]*)=\S+/gi,'$1='+R],[/(\/\/[^:/\s]+:)[^@/\s]+@/g,'$1'+R+'@']];
40
+ export function scrub(text){let out=String(text??'');for(const [rx,to] of SECRET_TEXT)out=out.replace(rx,to);return out}
41
+ /** A deep copy with secret-looking keys, env blocks and secret-looking strings removed. */
42
+ export function scrubValue(v,key=''){
43
+ if(typeof v==='string')return SECRET_KEY.test(key)&&v?'[redacted]':scrub(v).slice(0,4000);
44
+ if(Array.isArray(v))return v.slice(0,500).map(x=>scrubValue(x,key));
45
+ if(v&&typeof v==='object'){
46
+ const out={};
47
+ for(const [k,x] of Object.entries(v))out[k]=(k==='env'||k==='headers')&&x&&typeof x==='object'?Object.fromEntries(Object.keys(x).map(n=>[n,'[redacted]'])):scrubValue(x,k);
48
+ return out;
49
+ }
50
+ return v;
51
+ }
52
+ export async function feedbackBundle({session,settings,message='',version='',events=200}){
53
+ const lines=String(await readFile(path.join(session.dir,'events.jsonl'),'utf8').catch(()=>'')).split('\n').filter(Boolean).slice(-events);
54
+ const recent=lines.flatMap(l=>{try{return [JSON.parse(l)]}catch{return []}});
55
+ const m=session.meta||{};
56
+ const plainSettings=settings?Object.fromEntries(Object.entries(settings).filter(([,x])=>typeof x!=='function')):{};
57
+ return scrubValue({kind:'mlai-feedback',version:1,createdAt:new Date().toISOString(),message:String(message).slice(0,4000),
58
+ cli:{version,node:process.version,platform:process.platform,arch:process.arch,release:os.release(),term:process.env.TERM_PROGRAM||process.env.TERM||''},
59
+ session:{id:m.id,mode:m.mode,cliMode:m.cliMode,model:m.model,turns:Array.isArray(m.turns)?m.turns.length:0,folder:m.folder||(m.root?path.basename(m.root):'')},
60
+ settings:plainSettings,
61
+ autoReview:{denied:(await deniedActions(session)).slice(0,20)},
62
+ events:recent});
63
+ }
64
+
65
+ export function install(register,deps={}){
66
+ register({name:'approve',args:'[n|list]',summary:'Allow an action auto-review denied, once, and retry it',
67
+ complete:async ctx=>ctx.session?['list',...(await deniedActions(ctx.session)).map((_,i)=>String(i+1))]:[],
68
+ run:async(ctx,args)=>{
69
+ const s=ctx.session;if(!s?.dir)throw new CommandError('Open a project folder first.');
70
+ const items=await deniedActions(s);const a=String(args||'').trim();
71
+ if(!items.length){ctx.out('Nothing to approve: auto-review has not denied anything in this session.');return {approved:null}}
72
+ if(a==='list'){ctx.out(items.map((i,n)=>' '+String(n+1).padStart(2)+'. '+one(i.action).slice(0,120)+'\n '+one(i.reason).slice(0,160)).join('\n')+'\n/approve <n> allows one of them once.');return {denied:items}}
73
+ const n=a?Number(a):1;const item=items[n-1];
74
+ if(!Number.isInteger(n)||!item)throw new CommandError('Choose an action from 1 to '+items.length+' (/approve list shows them).');
75
+ await approveOnce(s,item);
76
+ ctx.out('Approved once: '+one(item.action).slice(0,160));
77
+ if(ctx.chat?.running){ctx.out('The agent can retry it now.');return {approved:item}}
78
+ return {approved:item,send:retryPrompt(item)};
79
+ }});
80
+ register({name:'feedback',aliases:['bug'],args:'[message]',summary:'Save a feedback bundle (logs and settings, secrets removed)',
81
+ run:async(ctx,args)=>{
82
+ const s=ctx.session;if(!s?.dir)throw new CommandError('Open a project folder first.');
83
+ let message=String(args||'').trim();
84
+ if(!message&&ctx.ui?.input)message=String(await ctx.ui.input('What happened? (optional)')||'').trim();
85
+ const {VERSION,sub}=await import('../home.mjs');
86
+ const bundle=await feedbackBundle({session:s,settings:ctx.settings,message,version:VERSION});
87
+ const dir=deps.dir||sub('feedback');
88
+ const file=path.join(dir,new Date().toISOString().replace(/[:.]/g,'-').slice(0,19)+'-'+String(s.meta?.id||'session').replace(/[^\w-]/g,'').slice(0,40)+'.json');
89
+ await mkdir(dir,{recursive:true});await writeFile(file,JSON.stringify(bundle,null,1),{mode:0o600});
90
+ const n=bundle.events.length;
91
+ ctx.out('There is no feedback endpoint on the server yet, so nothing was sent.\nSaved a feedback bundle (CLI version, settings'+(n?' and the last '+n+' session event'+(n===1?'':'s'):'')+', secrets removed):\n '+file+'\nAttach it to your report.');
92
+ return {file};
93
+ }});
94
+ }
@@ -0,0 +1,17 @@
1
+ // /teleport: bring a cloud chat into this terminal (src/tui/cloud-run.mjs). The CLI flag is mlai --teleport [chat].
2
+ import {CommandError} from './commands.mjs';
3
+
4
+ export function install(register){
5
+ register({name:'teleport',args:'[chat]',summary:'Continue a cloud chat here: its branch and changes in a new worktree, its conversation as context',
6
+ run:async(ctx,a)=>{
7
+ if(!ctx.server)throw new CommandError('Sign in first: run mlai login.');
8
+ if(ctx.session?.child)throw new CommandError('Wait for the task to finish, or stop it with Esc, before teleporting.');
9
+ const [{teleportMain},{createWorktree},{Session}]=await Promise.all([import('./cloud-cli.mjs'),import('../worktree.mjs'),import('../session.mjs')]);
10
+ const plain={dim:t=>t,yellow:t=>t};
11
+ const s=await teleportMain(a,{cloud:ctx.server,cwd:ctx.session?.meta?.parent||ctx.session?.meta?.root||process.cwd(),log:t=>ctx.out(t),c:plain,
12
+ pick:(rows,o)=>ctx.ui.pick(rows,o),createWorktree,createSession:x=>Session.create(x)}).catch(e=>{throw new CommandError(e.message)});
13
+ if(!s)return null;
14
+ ctx.ui.setSession(s);ctx.out('Switched to the teleported session. Type to continue where the cloud left off.');
15
+ return {session:s.meta.id};
16
+ }});
17
+ }
@@ -0,0 +1,104 @@
1
+ // /config (search, show and edit settings) and /debug-config (where every value comes from). Settings: settings.mjs.
2
+ import {readFileSync,existsSync} from 'node:fs';
3
+ import {DEFAULTS,CHECKS,SCOPES} from '../settings.mjs';
4
+ import {CommandError} from './commands.mjs';
5
+
6
+ /** What each key does and the values it takes; keys other owners add show up too, without a description. */
7
+ export const KEYS={
8
+ model:{about:'Model for new sessions (null: the account default)',hint:'model id'},
9
+ mode:{about:'Mode for new sessions',choices:['agent','plan','ask','auto']},
10
+ effort:{about:'Reasoning effort, where the model takes it',choices:['low','medium','high','max']},
11
+ fallbackModel:{about:'Models tried in order when the chosen one is overloaded or unavailable',hint:'"id" or ["id","id"]'},
12
+ permissions:{about:'Rules for what runs without asking (/permissions edits them)',hint:'{"allow":[],"deny":[],"ask":[]}'},
13
+ sandbox:{about:'OS sandbox and network for auto mode (/sandbox)',hint:'{"enabled":true,"network":true}'},
14
+ hooks:{about:'Commands run on agent events (/hooks)',hint:'{"event":[{"matcher":"","command":""}]}'},
15
+ mcpServers:{about:'MCP servers (/mcp)',hint:'{"name":{"command":"","args":[]}}'},
16
+ theme:{about:'Terminal colors',choices:['auto','dark','light']},
17
+ vim:{about:'Vim keys in the input',choices:[true,false]},
18
+ statusLine:{about:'The status line under the input',hint:'{"enabled":true,"command":null}'},
19
+ autoUpdate:{about:'Install CLI updates in the background',choices:[true,false]},
20
+ maxSteps:{about:'Agent steps per turn, 1 to 160',hint:'number'},
21
+ reviewModel:{about:'Model for /review and mlai review (null: the chat model)',hint:'model id or null'},
22
+ autoReview:{about:'In auto mode, a reviewer checks risky actions first',choices:[true,false]},
23
+ memories:{about:'Send .mlai/MEMORY.md with each turn (/memories; opt-in)',choices:[true,false]},
24
+ presets:{about:'Saved mode, model and effort combinations (/presets, mlai --preset)',hint:'{"name":{"mode":"plan","effort":"high"}}'},
25
+ skills:{about:'Local skills turned off on this computer (/skills disable)',hint:'{"disabled":["id"]}'},
26
+ };
27
+ const SECRETISH=/token|secret|password|passwd|api.?key|authorization|cookie|credential/i;
28
+ /** A copy with values under secret-looking keys replaced, so /config never prints a credential. */
29
+ export function masked(v,key=''){
30
+ if(SECRETISH.test(key)&&v!=null&&typeof v!=='boolean')return '(hidden)';
31
+ if(Array.isArray(v))return v.map(x=>masked(x));
32
+ if(v&&typeof v==='object')return Object.fromEntries(Object.entries(v).map(([k,x])=>[k,masked(x,k)]));
33
+ if(typeof v==='string'&&/^(sk|pk|ghp|gho|xox[abp]|mlaid)[-_][\w-]{8,}/.test(v))return '(hidden)';
34
+ return v;
35
+ }
36
+ const show=v=>{const t=JSON.stringify(masked(v));return t===undefined?'unset':t.length>70?t.slice(0,67)+'...':t};
37
+ export function allKeys(settings){return [...new Set([...Object.keys(DEFAULTS),...Object.keys(CHECKS),...Object.keys(settings||{})])]}
38
+ /** '4' -> 4, 'true' -> true, '["a"]' -> ['a'], 'null' -> null, otherwise the text itself. */
39
+ export function parseValue(text){const t=String(text).trim();try{return JSON.parse(t)}catch{return t}}
40
+ function rows(settings,query=''){
41
+ const q=String(query).toLowerCase();
42
+ return allKeys(settings).filter(k=>!q||k.toLowerCase().includes(q)||(KEYS[k]?.about||'').toLowerCase().includes(q))
43
+ .map(k=>({key:k,value:settings?.[k],source:settings?.sources?.[k]||'default',about:KEYS[k]?.about||''}));
44
+ }
45
+ const scopeArg=words=>{const i=words.findIndex(w=>/^--?(user|project|local)$/.test(w));if(i<0)return null;const s=words[i].replace(/^-+/,'');words.splice(i,1);return s};
46
+ async function save(ctx,scope,key,value){
47
+ if(!ctx.settings?.save)throw new CommandError('Settings cannot be saved here.');
48
+ if(scope!=='user'&&!ctx.settings.paths?.[scope])throw new CommandError('Project and local settings need a project folder; use --user.');
49
+ try{ctx.settings=await ctx.settings.save(scope,key,value,key==='permissions'?{replace:true}:{})}catch(e){throw new CommandError(e.message)}
50
+ const live={model:'/model',mode:'/mode',effort:'/effort'}[key];
51
+ ctx.out((value===undefined?'Removed ':'Set ')+key+(value===undefined?'':' = '+show(value))+' in '+scope+' settings ('+ctx.settings.paths[scope]+').'+(live?' New sessions use it; '+live+' changes this one.':''));
52
+ }
53
+
54
+ export function install(register){
55
+ register({name:'config',args:'[search] | set <key> <value> [--user|--project|--local] | unset <key> [scope] | get <key>',summary:'Search, show and change settings',
56
+ complete:async ctx=>['set','unset','get',...allKeys(ctx.settings)],run:async(ctx,a)=>{
57
+ const words=String(a||'').trim().split(/\s+/).filter(Boolean),verb=words[0];
58
+ if(verb==='get'){const k=words[1];if(!k)throw new CommandError('Usage: /config get <key>');ctx.out(k+' = '+JSON.stringify(masked(ctx.settings?.[k]),null,2)+' ('+(ctx.settings?.sources?.[k]||'default')+')');return {key:k}}
59
+ if(verb==='set'||verb==='unset'){
60
+ const scope=scopeArg(words)||'user';const key=words[1];
61
+ if(!key)throw new CommandError('Usage: /config '+verb+' <key>'+(verb==='set'?' <value>':'')+' [--user|--project|--local]');
62
+ if(verb==='unset'){await save(ctx,scope,key,undefined);return {key,scope}}
63
+ const raw=words.slice(2).join(' ');if(!raw)throw new CommandError('Give a value: /config set '+key+' <value>');
64
+ const value=parseValue(raw);
65
+ if(CHECKS[key]&&!CHECKS[key](value))throw new CommandError('Invalid value for '+key+(KEYS[key]?.choices?': use '+KEYS[key].choices.join(', '):KEYS[key]?.hint?': '+KEYS[key].hint:''));
66
+ await save(ctx,scope,key,value);return {key,scope,value};
67
+ }
68
+ const list=rows(ctx.settings,words.join(' '));
69
+ if(!list.length){ctx.ui.error('No setting matches '+words.join(' ')+'.');return}
70
+ if(!ctx.ui.pick||!process.stdin.isTTY&&!ctx.ui.interactive){
71
+ ctx.out(list.map(r=>r.key.padEnd(15)+' '+show(r.value).padEnd(28)+' '+r.source.padEnd(8)+' '+r.about).join('\n'));
72
+ ctx.out('Change one: /config set <key> <value> [--user|--project|--local]');return {keys:list.map(r=>r.key)};
73
+ }
74
+ const pick=await ctx.ui.pick(list.map(r=>({label:r.key,detail:show(r.value)+' · '+r.source+(r.about?' · '+r.about:''),value:r.key})),{title:'Settings'+(words.length?' matching '+words.join(' '):'')});
75
+ if(!pick)return;
76
+ const key=pick.value,info=KEYS[key]||{};
77
+ let value;
78
+ if(info.choices){const c=await ctx.ui.pick(info.choices.map(x=>({label:String(x)+(JSON.stringify(x)===JSON.stringify(ctx.settings?.[key])?' (now)':''),value:x})),{title:key});if(!c)return;value=c.value}
79
+ else{const t=await ctx.ui.input(key+' ('+(info.hint||'JSON or text')+'):',{default:ctx.settings?.[key]===undefined?null:JSON.stringify(ctx.settings[key])});if(t==null)return;value=parseValue(t)}
80
+ if(CHECKS[key]&&!CHECKS[key](value))throw new CommandError('Invalid value for '+key);
81
+ const sc=await ctx.ui.pick(SCOPES.filter(s=>s==='user'||ctx.settings?.paths?.[s]).map(s=>({label:s,detail:ctx.settings.paths[s],value:s})),{title:'Save to'});if(!sc)return;
82
+ await save(ctx,sc.value,key,value);return {key,scope:sc.value,value};
83
+ }});
84
+
85
+ register({name:'debug-config',summary:'Show every settings layer, where each value comes from, and problems',run:async ctx=>{
86
+ const st=ctx.settings||{},paths=st.paths||{},chat=ctx.chat;
87
+ const lines=['Layers (lowest first; later layers win, permission lists add up):',' default built in'];
88
+ for(const s of SCOPES){
89
+ const p=paths[s];if(!p){lines.push(' '+s.padEnd(9)+' (no project folder)');continue}
90
+ let state='not found';
91
+ if(existsSync(p)){try{const v=JSON.parse(readFileSync(p,'utf8'));state=v&&typeof v==='object'&&!Array.isArray(v)?'ok, keys: '+(Object.keys(v).join(', ')||'none'):'not a JSON object (ignored)'}catch{state='invalid JSON (ignored)'}}
92
+ lines.push(' '+s.padEnd(9)+' '+p+' '+state);
93
+ }
94
+ const flags=Object.entries(st.sources||{}).filter(([,v])=>v==='flag').map(([k])=>k);
95
+ lines.push(' flag '+(flags.length?flags.join(', '):'none'),'','Effective values:');
96
+ for(const r of rows(st))lines.push(' '+r.key.padEnd(15)+' '+show(r.value).padEnd(40)+' from '+r.source);
97
+ lines.push('','Warnings: '+((st.warnings||[]).join('; ')||'none'));
98
+ const env=['MLAI_HOME','MLAI_SERVER','MLAI_TOKEN','MLAI_SANDBOX','MLAI_NO_TUI','MLAI_AUTO_UPDATE','MLAI_ENGINE_UPDATES','MLAI_KEYCHAIN','MLAI_PYTHON','NO_COLOR'].filter(k=>process.env[k]!=null);
99
+ lines.push('Environment: '+(env.map(k=>k+'='+(SECRETISH.test(k)||k==='MLAI_TOKEN'?'(set)':process.env[k])).join(' ')||'none of the MLAI_* overrides'));
100
+ if(chat)lines.push('This session: model '+(chat.model||'account default')+', mode '+chat.mode+', effort '+chat.effort+', max steps '+chat.steps+(chat.fallbacks?.length?', fallback '+chat.fallbacks.join(' > '):'')+
101
+ (chat.toolRules?', tool rules allow ['+(chat.toolRules.allow||[]).join(', ')+'] deny ['+(chat.toolRules.deny||[]).join(', ')+']':''));
102
+ ctx.out(lines.join('\n'));return {layers:SCOPES.map(s=>paths[s]||null)};
103
+ }});
104
+ }