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.
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,333 @@
1
+ // Extensibility commands (CLI v1 owner 3): /init /permissions /sandbox /mcp /hooks /plugin /commands, plus the
2
+ // project's custom slash commands (.mlai/commands/*.md, ~/.mlai/commands/*.md). The engine enforces what these
3
+ // write: rules in worker/mlai_permissions.py, hooks in worker/mlai_hooks.py, MCP servers in worker/mcp_local.py.
4
+ import {execFileSync,spawn} from 'node:child_process';
5
+ import {existsSync,readFileSync} from 'node:fs';
6
+ import {writeFile} from 'node:fs/promises';
7
+ import path from 'node:path';
8
+ import {CommandError,find,unregister} from './commands.mjs';
9
+ import {KINDS,parseRule,normalizeRule,explainRule,decide,scopedRules,setTrusted,readLayer} from './permissions.mjs';
10
+ import {listServers,addServer,removeServer,listTools,engineServers,trustRepoServers,repoServers,NAME} from './mcp-config.mjs';
11
+ import {installCustom,discover} from './custom-commands.mjs';
12
+ import {scan,render,REFINE_TASK} from './init.mjs';
13
+ import {HOOK_EVENTS,hooksFromSettings,scopedHooks,repoHooksText} from './extensions-local.mjs';
14
+ import {sandboxKind,SANDBOXES} from '../sandbox.mjs';
15
+ import {osNetwork} from '../netbox.mjs';
16
+
17
+ const isObj=v=>v!==null&&typeof v==='object'&&!Array.isArray(v);
18
+ const SCOPE_NAMES=['user','project','local'];
19
+ export function gitRoot(cwd=process.cwd()){
20
+ try{return execFileSync('git',['rev-parse','--show-toplevel'],{cwd,encoding:'utf8',stdio:['ignore','pipe','ignore']}).trim()||cwd}catch{return cwd}
21
+ }
22
+ const rootOf=ctx=>ctx.session?.meta?.root||ctx.settings?.root||gitRoot();
23
+ /** Splits '--scope user rest' style flags out of an argument string. */
24
+ function flags(text,names){
25
+ const out={rest:[]};const words=String(text||'').match(/"[^"]*"|'[^']*'|\S+/g)||[];
26
+ for(let i=0;i<words.length;i++){
27
+ const m=/^--([a-z-]+)(?:=(.*))?$/.exec(words[i]);
28
+ if(m&&names.includes(m[1])){const v=m[2]??words[++i];if(v==null)throw new CommandError('--'+m[1]+' needs a value.');(out[m[1]]??=[]).push(unquote(v))}
29
+ else out.rest.push(words[i]);
30
+ }
31
+ return out;
32
+ }
33
+ const unquote=s=>/^(["']).*\1$/.test(s)?s.slice(1,-1):s;
34
+ function scopeOf(f,dflt='local'){
35
+ const s=(f.scope||[dflt]).at(-1);if(!SCOPE_NAMES.includes(s))throw new CommandError('Scope must be user, project or local.');return s;
36
+ }
37
+ async function save(ctx,scope,key,value,opts){
38
+ if(!ctx.settings?.save)throw new CommandError('Settings cannot be saved here.');
39
+ if(scope!=='user'&&!ctx.settings.root)throw new CommandError('Project and local settings need a project folder; use --scope user.');
40
+ ctx.settings=await ctx.settings.save(scope,key,value,opts);return ctx.settings;
41
+ }
42
+ const fileFor=(ctx,scope)=>ctx.settings?.paths?.[scope]||scope;
43
+
44
+ // ------------------------------------------------------------------ /init
45
+ async function initCmd(ctx,args){
46
+ const root=rootOf(ctx);const a=String(args||'').trim();
47
+ if(a==='--refine'||a==='refine')return {send:REFINE_TASK};
48
+ const file=path.join(root,'AGENTS.md');
49
+ const text=render(scan(root));
50
+ if(existsSync(file)&&a!=='--force'){
51
+ const choice=await ctx.ui.pick([
52
+ {label:'Ask the agent to improve it',value:'refine',detail:'reviews the file against the code'},
53
+ {label:'Replace it with a fresh scan',value:'replace'},
54
+ {label:'Cancel',value:'cancel'},
55
+ ],{title:'AGENTS.md already exists'});
56
+ if(!choice||choice.value==='cancel'){ctx.out('AGENTS.md left as it is.');return null}
57
+ if(choice.value==='refine')return {send:REFINE_TASK};
58
+ }
59
+ await writeFile(file,text);
60
+ const lines=text.split('\n').length;
61
+ ctx.out('Wrote AGENTS.md ('+lines+' lines). The agent reads it on every run.');
62
+ if(await ctx.ui.confirm('Ask the agent to check it against the code and fill in the gaps?',{default:false}))return {send:REFINE_TASK};
63
+ ctx.out('Run /init --refine any time to have the agent improve it.');
64
+ return {written:file};
65
+ }
66
+
67
+ // ------------------------------------------------------------------ /permissions
68
+ function permissionsList(ctx){
69
+ const root=rootOf(ctx);const s=scopedRules(root);const L=[];
70
+ for(const scope of SCOPE_NAMES){
71
+ const r=s.by[scope];const n=KINDS.reduce((t,k)=>t+r[k].length,0);
72
+ L.push(scope+' ('+fileFor(ctx,scope)+')'+(scope==='project'&&r.allow.length&&!s.projectTrusted?' allow rules not trusted yet: /permissions trust':''));
73
+ if(!n){L.push(' no rules');continue}
74
+ for(const k of KINDS)for(const rule of r[k])L.push(' '+k.padEnd(5)+' '+rule.padEnd(28)+' '+explainRule(rule));
75
+ }
76
+ L.push('','Rules: Bash(npm test:*) Edit(src/**) Read(.env*) WebFetch(domain:example.com) WebSearch mcp__server Agent');
77
+ L.push('Deny wins over ask, ask over allow. /permissions allow|deny|ask <rule> [--scope user|project|local], /permissions remove <rule>.');
78
+ return L.join('\n');
79
+ }
80
+ async function permissionsCmd(ctx,args){
81
+ const f=flags(args,['scope']);const [sub,...rest]=f.rest;const ruleText=rest.join(' ');
82
+ const root=rootOf(ctx);
83
+ if(!sub||sub==='list'){ctx.out(permissionsList(ctx));return null}
84
+ if(KINDS.includes(sub)){
85
+ const rule=normalizeRule(ruleText);if(!rule)throw new CommandError('Not a valid rule: '+(ruleText||'(empty)')+'. Example: Bash(npm test:*)');
86
+ const scope=scopeOf(f);
87
+ // The user adding a project allow rule reviews that rule, not the others in the file: keep trust only if it was there.
88
+ const wasTrusted=scope==='project'&&sub==='allow'&&scopedRules(root).projectTrusted;
89
+ await save(ctx,scope,'permissions',{[sub]:[rule]});
90
+ if(wasTrusted)await setTrusted(root,'permissions',(readLayer(root,'project').permissions?.allow||[]).filter(x=>parseRule(x)));
91
+ ctx.out(sub[0].toUpperCase()+sub.slice(1)+' '+rule+' ('+explainRule(rule)+') in '+scope+' settings.');return {rule,kind:sub,scope};
92
+ }
93
+ if(sub==='remove'||sub==='rm'){
94
+ const rule=normalizeRule(ruleText)||ruleText.trim();if(!rule)throw new CommandError('Usage: /permissions remove <rule>');
95
+ const scopes=f.scope?[scopeOf(f)]:SCOPE_NAMES;const from=[];
96
+ for(const scope of scopes){
97
+ const cur=readLayer(root,scope).permissions;if(!isObj(cur))continue;
98
+ const next={};let hit=false;
99
+ for(const k of KINDS){const l=Array.isArray(cur[k])?cur[k]:[];next[k]=l.filter(x=>(normalizeRule(x)||x)!==rule);hit||=next[k].length!==l.length}
100
+ if(hit){await save(ctx,scope,'permissions',{...cur,...next},{replace:true});from.push(scope)}
101
+ }
102
+ ctx.out(from.length?'Removed '+rule+' from '+from.join(', ')+' settings.':'No rule '+rule+' found.');return {removed:from};
103
+ }
104
+ if(sub==='trust'){
105
+ const allow=(readLayer(root,'project').permissions?.allow||[]).filter(x=>parseRule(x));
106
+ if(!allow.length){ctx.out('The project settings have no allow rules to trust.');return null}
107
+ ctx.out('The project settings (.mlai/settings.json) allow:\n'+allow.map(r=>' '+r.padEnd(28)+' '+explainRule(r)).join('\n'));
108
+ if(!await ctx.ui.confirm('Let these rules run without asking on this computer?',{default:false})){ctx.out('Not trusted.');return null}
109
+ await setTrusted(root,'permissions',allow);ctx.out('Trusted. If the file changes, you will be asked again.');return {trusted:true};
110
+ }
111
+ if(sub==='check'||sub==='test'){
112
+ if(!ruleText)throw new CommandError('Usage: /permissions check <shell command>');
113
+ const r=decide(scopedRules(root).effective,[{kind:'Bash',value:ruleText}],{root});
114
+ ctx.out(r.decision==='deny'?'Denied by '+r.rule+'.':r.decision==='ask'?'Asks first ('+r.rule+').':r.decision==='allow'?'Allowed by '+r.rule+'.':'No rule matches; the mode decides (Agent and Plan ask, Auto runs it in the sandbox).');
115
+ return r;
116
+ }
117
+ throw new CommandError('Usage: /permissions [list | allow|deny|ask <rule> | remove <rule> | trust | check <command>]');
118
+ }
119
+
120
+ // ------------------------------------------------------------------ /sandbox
121
+ function sandboxStatus(ctx){
122
+ const s=isObj(ctx.settings?.sandbox)?ctx.settings.sandbox:{};const kind=sandboxKind();
123
+ const on=s.enabled!==false,net=s.network!==false;
124
+ const how=SANDBOXES.includes(kind)?{seatbelt:'macOS Seatbelt',bwrap:'bubblewrap',windows:'a restricted Windows token'}[kind]:null;
125
+ const netHow=osNetwork(kind)==='os'?'; enforced by the OS, only the model gateway is reachable':'; enforced by the engine check, not the OS, on this computer';
126
+ return [...(ctx.chat?.restricted?['Restricted mode: shell commands are off, file tools stay in this project, and the sandbox stays on.']:[]),'Sandbox: '+(on?'on':'off')+(on?how?' ('+how+'; Auto and Plan runs can only write in the repository and caches)':' (not available on this computer; Auto mode cannot start)':' (Auto mode runs commands without the OS sandbox)'),
127
+ 'Network: '+(net?'on':'off'+' (web tools, remote hosts and package installs are refused'+netHow+')')].join('\n');
128
+ }
129
+ async function sandboxCmd(ctx,args){
130
+ const words=String(args||'').trim().toLowerCase().split(/\s+/).filter(Boolean);
131
+ const cur=isObj(ctx.settings?.sandbox)?ctx.settings.sandbox:{};
132
+ const scope=ctx.settings?.root?'local':'user';
133
+ const set=async v=>{await save(ctx,scope,'sandbox',{enabled:cur.enabled!==false,network:cur.network!==false,...v});ctx.out(sandboxStatus(ctx))};
134
+ if(!words.length||words[0]==='status'){ctx.out(sandboxStatus(ctx));return null}
135
+ if(words[0]==='on'){await set({enabled:true});return {enabled:true}}
136
+ if(words[0]==='off'){
137
+ if(ctx.chat?.restricted)throw new CommandError('Restricted mode keeps the sandbox on.');
138
+ if(!await ctx.ui.confirm('Turn the sandbox off? Auto mode would then run commands with full access to this computer.',{default:false})){ctx.out('Sandbox stays on.');return null}
139
+ await set({enabled:false});return {enabled:false};
140
+ }
141
+ if(words[0]==='network'&&(words[1]==='on'||words[1]==='off')){await set({network:words[1]==='on'});return {network:words[1]==='on'}}
142
+ throw new CommandError('Usage: /sandbox [on | off | network on|off]');
143
+ }
144
+
145
+ // ------------------------------------------------------------------ /mcp
146
+ function mcpList(root){
147
+ const rows=listServers(root);
148
+ if(!rows.length)return 'No MCP servers. Add one: /mcp add <name> <command> [args...] or /mcp add <name> --url <https://...>';
149
+ const L=rows.map(s=>' '+s.name.padEnd(18)+' '+s.transport.padEnd(5)+' '+(s.spec.url||[s.spec.command,...(s.spec.args||[])].join(' ')).slice(0,60).padEnd(60)+' '+s.source
150
+ +(!s.enabled?' disabled':s.problem?' '+s.problem:!s.trusted?' not trusted (/mcp trust)':s.auth?' '+s.auth:''));
151
+ return 'MCP servers (the agent can call their tools; each call asks first in Agent mode):\n'+L.join('\n');
152
+ }
153
+ function parseKV(list,sep,what){
154
+ const o={};for(const x of list||[]){const i=x.indexOf(sep);if(i<1)throw new CommandError(what+' must look like KEY'+sep+'value.');o[x.slice(0,i).trim()]=x.slice(i+1).trim()}return o;
155
+ }
156
+ async function mcpCmd(ctx,args){
157
+ const root=rootOf(ctx);
158
+ const f=flags(args,['scope','url','header','env','transport','client-id']);const [sub,name,...rest]=f.rest;
159
+ if(!sub||sub==='list'){ctx.out(mcpList(root));return null}
160
+ if(sub==='add'){
161
+ if(!name||!NAME.test(name))throw new CommandError('Usage: /mcp add <name> <command> [args...] or /mcp add <name> --url <url> [--header K:V] [--env K=V] [--scope user|project|local]');
162
+ const url=f.url?.at(-1);
163
+ if(!url&&!rest.length)throw new CommandError('Give a command to start the server, or --url for a remote server.');
164
+ if(url&&!/^https?:\/\//.test(url))throw new CommandError('The URL must start with https:// (or http:// for localhost).');
165
+ const spec=url?{url,...(f.header?{headers:parseKV(f.header,':','--header')}:{}),...(f.transport?.at(-1)==='sse'?{transport:'sse'}:{})}:{command:rest[0],args:rest.slice(1).map(unquote),...(f.env?{env:parseKV(f.env,'=','--env')}:{})};
166
+ const scope=scopeOf(f);const where=await addServer({root,settings:{save:async(...a)=>{await save(ctx,...a)}},scope,name,spec});
167
+ ctx.out('Added MCP server '+name+' ('+scope+', '+where+'). Use ${VAR} in values to read secrets from your environment. /mcp tools '+name+' checks it.');
168
+ return {name,scope};
169
+ }
170
+ if(sub==='remove'||sub==='rm'){
171
+ if(!name)throw new CommandError('Usage: /mcp remove <name>');
172
+ const r=await removeServer({root,settings:{save:async(...a)=>{await save(ctx,...a)}},name});
173
+ ctx.out((r.removed.length?'Removed '+name+' from '+r.removed.join(', ')+'.':'No server '+name+' in the files this CLI manages.')+(r.remains.length?' It is still defined in '+r.remains.join(', ')+'; edit that file or /mcp disable '+name+'.':''));
174
+ return r;
175
+ }
176
+ if(sub==='enable'||sub==='disable'){
177
+ if(!name)throw new CommandError('Usage: /mcp '+sub+' <name>');
178
+ if(!listServers(root).some(s=>s.name===name))throw new CommandError('No MCP server '+name+'.');
179
+ const cur=readLayer(root,'local').mcpServers;const next={...(isObj(cur)?cur:{})};
180
+ next[name]={...(isObj(next[name])?next[name]:{}),disabled:sub==='disable'};
181
+ await save(ctx,'local','mcpServers',next);ctx.out('MCP server '+name+' '+sub+'d on this computer.');return {name,enabled:sub==='enable'};
182
+ }
183
+ if(sub==='trust'){
184
+ const repo=repoServers(root);const names=Object.keys(repo);
185
+ if(!names.length){ctx.out('The repository defines no MCP servers.');return null}
186
+ ctx.out('The repository defines these servers (they start programs or contact URLs on this computer):\n'+names.map(n=>' '+n.padEnd(18)+' '+(repo[n].url||[repo[n].command,...(repo[n].args||[])].join(' '))).join('\n'));
187
+ if(!await ctx.ui.confirm('Trust them on this computer?',{default:false})){ctx.out('Not trusted.');return null}
188
+ await trustRepoServers(root);ctx.out('Trusted. If the files change, you will be asked again.');return {trusted:names};
189
+ }
190
+ if(sub==='tools'){
191
+ if(!name)throw new CommandError('Usage: /mcp tools <name>');
192
+ const s=listServers(root).find(x=>x.name===name);if(!s)throw new CommandError('No MCP server '+name+'.');
193
+ if(!s.trusted)throw new CommandError(name+' comes from the repository and is not trusted yet; /mcp trust first.');
194
+ const e=engineServers(root,{env:process.env});const spec=e.mcpServers[name];
195
+ if(!spec)throw new CommandError(name+' cannot start: '+(e.skipped.find(x=>x.name===name)?.reason||'disabled')+'.');
196
+ ctx.out('Starting '+name+'...');
197
+ const tools=await listTools(spec,{root,secretEnv:e.mcpEnv[name]||{},name}).catch(err=>{throw new CommandError(name+' did not answer: '+(err?.message||err))});
198
+ ctx.out(tools.length?tools.map(t=>' mcp__'+name+'__'+t.name+(t.description?' '+String(t.description).split('\n')[0].slice(0,90):'')).join('\n'):name+' has no tools.');
199
+ return {tools:tools.map(t=>t.name)};
200
+ }
201
+ if(sub==='login'||sub==='logout'){
202
+ if(!name)throw new CommandError('Usage: /mcp '+sub+' <name>'+(sub==='login'?' [--no-browser] [--client-id <id>]':''));
203
+ const oauth=await import('./mcp-oauth.mjs');
204
+ if(sub==='logout'){ctx.out((await oauth.logout(name))?'Signed out of '+name+'.':'Not signed in to '+name+'.');return {name}}
205
+ const s=listServers(root).find(x=>x.name===name);if(!s)throw new CommandError('No MCP server '+name+'.');
206
+ if(!s.trusted)throw new CommandError(name+' comes from the repository and is not trusted yet; /mcp trust first.');
207
+ const url=engineServers(root).mcpServers[name]?.url;if(!url)throw new CommandError(name+' is not a remote (URL) server; only those use sign-in.');
208
+ const noBrowser=rest.includes('--no-browser');
209
+ const open=u=>{if(process.env.MLAI_NO_BROWSER)return;const cmd=process.platform==='darwin'?'open':process.platform==='win32'?'cmd':'xdg-open';try{const p=spawn(cmd,process.platform==='win32'?['/c','start','',u]:[u],{stdio:'ignore',detached:true});p.on('error',()=>{});p.unref()}catch{}};
210
+ const rec=await oauth.login(name,{...s.spec,url},{open,noBrowser,print:t=>ctx.out(t.trimEnd()),prompt:q=>ctx.ui.input(q),clientId:f['client-id']?.at(-1)||null}).catch(e=>{throw new CommandError(e.message)});
211
+ ctx.out('Signed in to '+name+'. The next turn uses it.');return {name,expires:rec.expires_at||null};
212
+ }
213
+ throw new CommandError('Usage: /mcp [list | add | remove <name> | tools <name> | enable|disable <name> | trust | login|logout <name>]');
214
+ }
215
+
216
+ // ------------------------------------------------------------------ /hooks
217
+ function repoHooks(root){
218
+ const text=repoHooksText(root);if(text==null)return {exists:false,hooks:[],errors:[]};
219
+ let v;try{v=JSON.parse(text||'{}')}catch(e){return {exists:true,hooks:[],errors:['.mlai/hooks.json is not valid JSON: '+e.message]}}
220
+ const errors=[];const hooks=Array.isArray(v?.hooks)?v.hooks:[];
221
+ hooks.forEach((h,i)=>{const label=h?.name||'Hook '+(i+1);if(!HOOK_EVENTS.includes(h?.event))errors.push(label+': event must be one of '+HOOK_EVENTS.join(', '));else if(!h.url&&!(typeof h.command==='string'&&h.command.trim()))errors.push(label+': add a command')});
222
+ return {exists:true,hooks,errors,deny:v?.deny};
223
+ }
224
+ function hooksList(ctx){
225
+ const root=rootOf(ctx);const sh=scopedHooks(root);const L=[];
226
+ for(const scope of SCOPE_NAMES){
227
+ const r=hooksFromSettings(sh.by[scope]);
228
+ L.push(scope+' settings'+(scope==='project'&&r.hooks.length&&!sh.projectTrusted?' not trusted yet: /hooks trust':''));
229
+ L.push(...(r.hooks.length?r.hooks.map(h=>' '+h.event.padEnd(14)+' '+(h.matcher||'*').padEnd(12)+' '+(h.command||h.url)):[' none']),...r.warnings.map(w=>' '+w));
230
+ }
231
+ const rh=repoHooks(root);
232
+ L.push('.mlai/hooks.json'+(!rh.exists?'':sh.fileTrusted?' trusted':' not trusted yet: /hooks trust'));
233
+ L.push(...(rh.exists?rh.hooks.map(h=>' '+String(h.event).padEnd(14)+' '+String(h.matcher||'*').padEnd(12)+' '+(h.command||h.url)):[' none']),...rh.errors.map(e=>' '+e));
234
+ L.push('','Account and project hooks from the web app (Settings, Hooks and rules) also run. Events: '+HOOK_EVENTS.join(', ')+'.');
235
+ L.push('A hook gets the event as JSON on stdin; exit code 2 blocks the step and its stderr goes back to the agent.');
236
+ return L.join('\n');
237
+ }
238
+ async function hooksCmd(ctx,args){
239
+ const root=rootOf(ctx);const f=flags(args,['scope','matcher']);const [sub,...rest]=f.rest;
240
+ if(!sub||sub==='list'){ctx.out(hooksList(ctx));return null}
241
+ if(sub==='trust'){
242
+ const sh=scopedHooks(root);const proj=sh.by.project&&Object.keys(sh.by.project).length?sh.by.project:null;
243
+ if(!proj&&sh.file==null){ctx.out('This repository defines no hooks.');return null}
244
+ ctx.out('Hooks defined by the repository run commands on this computer:\n'+hooksList(ctx).split('\n').filter(l=>/^ {2}\S/.test(l)).join('\n'));
245
+ if(!await ctx.ui.confirm('Trust the repository hooks on this computer?',{default:false})){ctx.out('Not trusted.');return null}
246
+ if(proj)await setTrusted(root,'hooks',proj);
247
+ if(sh.file!=null)await setTrusted(root,'hooksFile',sh.file);
248
+ ctx.out('Trusted. If the files change, you will be asked again.');return {trusted:true};
249
+ }
250
+ if(sub==='validate'){
251
+ const rh=repoHooks(root);const sh=scopedHooks(root);const warn=SCOPE_NAMES.flatMap(s=>hooksFromSettings(sh.by[s]).warnings);
252
+ const all=[...rh.errors,...warn];ctx.out(all.length?all.join('\n'):'Hooks look valid.');return {ok:!all.length,errors:all};
253
+ }
254
+ if(sub==='add'){
255
+ let [event,...cmd]=rest;
256
+ if(!event){const p=await ctx.ui.pick(HOOK_EVENTS.map(e=>({label:e,value:e})),{title:'When should the hook run?'});if(!p)return null;event=p.value}
257
+ if(!HOOK_EVENTS.includes(event))throw new CommandError('Events: '+HOOK_EVENTS.join(', '));
258
+ let command=cmd.join(' ');
259
+ if(!command)command=(await ctx.ui.input('Command to run (gets the event as JSON on stdin; exit 2 blocks):'))||'';
260
+ if(!command.trim()){ctx.out('No hook added.');return null}
261
+ const matcher=f.matcher?.at(-1)??(event.endsWith('_tool')||event==='approval'?(await ctx.ui.input('Which tools (shell, edit, read, web; | separates; empty for all):',{default:''}))||'':'');
262
+ const scope=scopeOf(f);const cur=readLayer(root,scope).hooks;const next={...(isObj(cur)?cur:{})};
263
+ const wasTrusted=scope==='project'&&scopedHooks(root).projectTrusted;
264
+ next[event]=[...(Array.isArray(next[event])?next[event]:[]),{...(matcher?{matcher}:{}),command:command.trim()}];
265
+ await save(ctx,scope,'hooks',next);
266
+ if(wasTrusted)await setTrusted(root,'hooks',readLayer(root,'project').hooks);
267
+ ctx.out('Added a '+event+' hook to '+scope+' settings.');return {event,scope};
268
+ }
269
+ if(sub==='remove'||sub==='rm'){
270
+ const [event,idx]=rest;const scope=scopeOf(f);const cur=readLayer(root,scope).hooks;
271
+ const list=isObj(cur)&&Array.isArray(cur[event])?cur[event]:[];const n=Number(idx||1)-1;
272
+ if(!list[n])throw new CommandError('Usage: /hooks remove <event> [number] [--scope user|project|local]; /hooks lists them.');
273
+ const next={...cur,[event]:list.filter((_,i)=>i!==n)};if(!next[event].length)delete next[event];
274
+ await save(ctx,scope,'hooks',next);ctx.out('Removed the hook.');return {removed:true};
275
+ }
276
+ throw new CommandError('Usage: /hooks [list | add [event] [command] | remove <event> [n] | trust | validate]');
277
+ }
278
+
279
+ // ------------------------------------------------------------------ /plugin
280
+ async function pluginCmd(ctx,args){
281
+ const [sub]=String(args||'').trim().split(/\s+/);
282
+ const web='Settings, Plugins in the web app';
283
+ if(sub&&sub!=='list'){ctx.out('Installing, enabling and removing plugins needs approval in the web app ('+web+'). They apply to CLI runs on the next turn.');return null}
284
+ if(!ctx.server?.device?.request){ctx.out('Sign in (mlai login) to see your plugins. Plugins are managed in '+web+'.');return null}
285
+ let r;try{r=await ctx.server.device.request('/api/extensions',undefined,{method:'GET',readOnly:true})}catch(e){throw new CommandError('Could not load plugins: '+(e?.message||e))}
286
+ const x=r?.extensions||{};const installed=Array.isArray(x.plugins)?x.plugins:[];
287
+ const L=[installed.length?'Installed plugins:':'No plugins installed.'];
288
+ for(const p of installed){const m=p.manifest||{};L.push(' '+String(m.name||m.id).padEnd(24)+' '+String(m.version||'').padEnd(8)+' '+(p.enabled?.all?'on everywhere':p.enabled?.projects?.length?'on in '+p.enabled.projects.length+' project(s)':'off'))}
289
+ const cat=(Array.isArray(x.catalog)?x.catalog:[]).filter(m=>!installed.some(p=>p.manifest?.id===m.id));
290
+ if(cat.length)L.push('','Available:',...cat.map(m=>' '+String(m.name||m.id).padEnd(24)+' '+String(m.description||'').slice(0,70)));
291
+ L.push('','Manage plugins in '+web+'.');
292
+ ctx.out(L.join('\n'));return {plugins:installed.map(p=>p.manifest?.id)};
293
+ }
294
+
295
+ // ------------------------------------------------------------------ custom commands
296
+ let registerRef=null;
297
+ /** Re-reads .mlai/commands and ~/.mlai/commands (and the .claude/.cursor equivalents). Returns the names. */
298
+ export function reloadCustomCommands(root=gitRoot(),{warn=()=>{}}={}){
299
+ if(!registerRef)return [];
300
+ return installCustom(registerRef,{root,find,unregister,warn});
301
+ }
302
+ async function commandsCmd(ctx,args){
303
+ const root=rootOf(ctx);
304
+ const names=reloadCustomCommands(root,{warn:m=>ctx.ui.error(m)});
305
+ const all=discover(root);
306
+ if(String(args||'').trim()==='reload'){ctx.out('Loaded '+names.length+' custom command'+(names.length===1?'':'s')+'.');return {names}}
307
+ ctx.out(all.length?'Custom commands:\n'+all.map(c=>' /'+c.name.padEnd(20)+' '+c.description.slice(0,60)+' '+path.relative(root,c.file).replace(/^(\.\.\/)+/,'~/')).join('\n')
308
+ :'No custom commands. Add a Markdown file to .mlai/commands/ (this project) or ~/.mlai/commands/ (everywhere); its name is the command, $ARGUMENTS is replaced with what you type after it.');
309
+ return {names};
310
+ }
311
+
312
+ // ------------------------------------------------------------------ --dangerously-skip-permissions
313
+ /** true when the user confirmed running without any approvals. Refuses without a terminal unless yes is set. */
314
+ export async function confirmSkipPermissions(ui,{yes=false,tty=process.stdin.isTTY&&process.stdout.isTTY}={}){
315
+ if(yes)return true;
316
+ if(!tty){ui?.error?.('--dangerously-skip-permissions needs a terminal to confirm, or --yes as well.');return false}
317
+ ui?.error?.('Every command and edit will run without asking. Deny rules and blocking hooks still apply. Use this only in a disposable environment, such as a container or a throwaway checkout.');
318
+ return !!(await ui?.confirm?.('Run without approvals?',{default:false}));
319
+ }
320
+
321
+ export function install(register){
322
+ registerRef=register;
323
+ register({name:'init',args:'[--refine]',summary:'Write AGENTS.md project instructions from the repository',run:initCmd});
324
+ register({name:'permissions',aliases:['perms','allowed-tools'],args:'[allow|deny|ask <rule> | remove <rule> | trust | check]',summary:'Show or change what runs without asking',
325
+ complete:async()=>['list','allow','deny','ask','remove','trust','check'],run:permissionsCmd});
326
+ register({name:'sandbox',args:'[on|off|network on|off]',summary:'Show or change the sandbox and network access',complete:async()=>['on','off','network on','network off','status'],run:sandboxCmd});
327
+ register({name:'mcp',args:'[list|add|remove|tools|enable|disable|trust|login|logout]',summary:'Manage MCP servers',
328
+ complete:async(ctx,p)=>/^\S+\s/.test(p||'')?listServers(rootOf(ctx)).map(s=>s.name):['list','add','remove','tools','enable','disable','trust','login','logout'],run:mcpCmd});
329
+ register({name:'hooks',args:'[list|add|remove|trust|validate]',summary:'Show or add hooks that run on agent events',complete:async()=>['list','add','remove','trust','validate'],run:hooksCmd});
330
+ register({name:'plugin',aliases:['plugins'],args:'[list]',summary:'Show installed and available plugins',run:pluginCmd});
331
+ register({name:'commands',args:'[reload]',summary:'List or reload custom slash commands',run:commandsCmd});
332
+ reloadCustomCommands(gitRoot());
333
+ }
@@ -0,0 +1,18 @@
1
+ // Remote control (tui/remote.mjs): /remote-control [on|off|status], alias /rc. Same as `mlai --rc` mid-session.
2
+ import {CommandError} from './commands.mjs';
3
+ import {startRemote,stopRemote,remoteBanner} from './remote.mjs';
4
+
5
+ export function install(register){
6
+ register({name:'remote-control',aliases:['rc'],summary:'Continue this session from the web or your phone',args:'[on|off|status]',
7
+ complete:async()=>['on','off','status'],run:async(ctx,a)=>{
8
+ const chat=ctx.chat;if(!chat)throw new CommandError('Remote control needs an interactive session.');
9
+ const arg=String(a||'').trim().toLowerCase()||(chat.remote?'status':'on');
10
+ if(arg==='off'){if(!chat.remote){ctx.out('Remote control is off.');return {remote:false}}await stopRemote(chat);ctx.out('Remote control is off. Other devices can still read this chat, but not drive it.');return {remote:false}}
11
+ if(arg==='status'){ctx.out(chat.remote?'Remote control is on: '+chat.remote.url:'Remote control is off. Turn it on with /remote-control.');return {remote:Boolean(chat.remote)}}
12
+ if(arg!=='on')throw new CommandError('Usage: /remote-control [on|off|status]');
13
+ if(chat.remote){ctx.out(remoteBanner(chat.remote));return {remote:true,url:chat.remote.url}}
14
+ let r;try{r=await startRemote({chat,ctx,cloud:ctx.server})}catch(e){throw new CommandError(e.message)}
15
+ ctx.out(remoteBanner(r));
16
+ return {remote:true,url:r.url};
17
+ }});
18
+ }
@@ -0,0 +1,58 @@
1
+ // /review (code_review_engineer): ML AI Review of this session's project, findings inline with file:line.
2
+ // /review [deep|security] [uncommitted|branch|repo|#123|--base <ref>] [focus words], then /review fix <n> sends a
3
+ // finding to the agent and /review dismiss <n> keeps the next review quiet about it.
4
+ import path from 'node:path';
5
+ import {CommandError} from './commands.mjs';
6
+ import {parseReviewArgs,resolveTarget,runReview,renderReview,fixPrompt,dismissFinding,gitRunner,ghRunner,engineDeps,ReviewUsage} from './review-cli.mjs';
7
+
8
+ const last=new Map();
9
+ const WORDS=['deep','security','uncommitted','branch','repo','--base ','#','fix ','dismiss ','last'];
10
+ const dirOf=s=>path.join(s.dir,'reviews');
11
+
12
+ export function install(register,deps={}){
13
+ register({name:'review',args:'[deep|security] [uncommitted|branch|#PR|repo|--base <ref>] [focus]',
14
+ summary:'Review changes, the branch or a pull request, findings with file:line',
15
+ complete:async(ctx,partial)=>{
16
+ if(/^--base\s+\S*$/.test(partial)||/^base\s+\S*$/.test(partial)){
17
+ const git=(deps.git||gitRunner)(ctx.session?.meta?.root||process.cwd());
18
+ const refs=String(await git(['for-each-ref','--format=%(refname:short)','refs/heads','refs/remotes'],{allowFail:true})||'').split('\n').filter(Boolean).slice(0,50);
19
+ const head=partial.replace(/\S*$/,'');return refs.map(r=>head+r);
20
+ }
21
+ const s=last.get(ctx.session?.dir);
22
+ if(/^(fix|dismiss)\s+\S*$/.test(partial)&&s)return s.state.findings.map((_,i)=>partial.split(/\s+/)[0]+' '+(i+1));
23
+ return WORDS;
24
+ },
25
+ run:async(ctx,args)=>{
26
+ const session=ctx.session;const root=session?.meta?.root;
27
+ if(!root)throw new CommandError('Open a project folder first.');
28
+ const c=ctx.ui?.color||deps.color||undefined;
29
+ const [verb,...rest]=String(args||'').trim().split(/\s+/);
30
+ if(verb==='fix'||verb==='dismiss'||verb==='last'){
31
+ const prev=last.get(session.dir);if(!prev)throw new CommandError('Run /review first.');
32
+ if(verb==='last'){ctx.out(renderReview(prev.state,{label:prev.target.label,c}));return {review:prev.state}}
33
+ const n=Number(rest[0]);const f=prev.state.findings[n-1];
34
+ if(!f)throw new CommandError('Choose a finding from 1 to '+prev.state.findings.length+', for example /review '+verb+' 1.');
35
+ if(verb==='fix')return {send:fixPrompt(f)};
36
+ await dismissFinding(dirOf(session),f,rest.slice(1).join(' ')||'marked as not useful');
37
+ ctx.out('Dismissed '+n+'. The next review will not raise it again.');return {dismissed:f.fingerprint};
38
+ }
39
+ let o;try{o=parseReviewArgs(args)}catch(e){throw new CommandError(e.message)}
40
+ if(o.help){ctx.out('Usage: /review '+'[deep|security] [uncommitted|branch|#PR|repo|--base <ref>] [focus]\nThen /review fix <n>, /review dismiss <n> [reason], /review last.');return}
41
+ if(!ctx.server)throw new CommandError('Sign in with mlai login to review code.');
42
+ const git=(deps.git||gitRunner)(root),gh=(deps.gh||ghRunner)(root);
43
+ let target;try{target=await resolveTarget(o,{git,gh})}catch(e){throw new CommandError(e instanceof ReviewUsage?e.message:'Could not prepare the review: '+(e?.message||e))}
44
+ if(target.empty){ctx.out('Nothing to review: no '+target.label+'.');return {empty:true}}
45
+ ctx.out('Reviewing '+target.label+'...');
46
+ const engine=deps.engine||await engineDeps();let shown='';
47
+ const r=await runReview({root,dir:dirOf(session),target,mode:o.mode,focus:o.focus,analysis:o.analysis,
48
+ model:o.model||ctx.settings?.reviewModel||(ctx.chat?.model??ctx.settings?.model)||session.meta.model||null,cloud:ctx.server,
49
+ project:session.meta.cloudProject||session.meta.project,folder:session.meta.folder||path.basename(root),
50
+ ...engine,spawnImpl:deps.spawnImpl,every:deps.every,signal:ctx.signal,
51
+ onEvent:e=>{if(e?.type==='progress'&&e.message&&e.message!==shown){shown=e.message;ctx.out(' '+String(e.message).replace(/\s+/g,' ').slice(0,160))}}})
52
+ .catch(async e=>{throw new CommandError((await import('../cloud.mjs')).friendly(e))});
53
+ last.set(session.dir,r);
54
+ ctx.out(renderReview(r.state,{label:target.label,failOn:o.failOn,c}));
55
+ if(r.state.findings.length)ctx.out('/review fix <n> asks the agent to fix one; /review dismiss <n> hides it next time.');
56
+ return {review:r.state};
57
+ }});
58
+ }
@@ -0,0 +1,152 @@
1
+ // Session extras (CLI wave 2, section 3): /side (/btw), /archive, /unarchive, /delete, /worktree, /cd, /pwd, /recap.
2
+ // /new is the lead's alias of /clear (cmd-core.mjs). Folder moves for archive live in session-ops.mjs.
3
+ import {existsSync,statSync} from 'node:fs';
4
+ import {rm} from 'node:fs/promises';
5
+ import {execFileSync} from 'node:child_process';
6
+ import path from 'node:path';
7
+ import os from 'node:os';
8
+ import {CommandError} from './commands.mjs';
9
+ import {Session} from '../session.mjs';
10
+ import {Chat,answerOf,creditsFor,formatCredits} from './chat.mjs';
11
+ import {findSessions,sessionRow} from './cmd-core.mjs';
12
+ import {archiveSession,unarchiveSession,removeSession,listArchived,worktreeFromArg} from './session-ops.mjs';
13
+ import {loadSettings} from '../settings.mjs';
14
+
15
+ const need=ctx=>{if(!ctx.chat)throw new CommandError('This command needs an interactive session.');return ctx.chat};
16
+ const short=(t,n=80)=>{const s=String(t||'').replace(/\s+/g,' ').trim();return s.length>n?s.slice(0,n-1)+'…':s};
17
+ const git=(cwd,args)=>{try{return execFileSync('git',args,{cwd,encoding:'utf8',stdio:['ignore','pipe','ignore']}).trim()}catch{return ''}};
18
+ const userTask=t=>String(t||'').replace(/^Answer the question from the code[^\n]*\n\nQuestion: /,'').replace(/^Side question[\s\S]*?\nQuestion: /,'');
19
+
20
+ /** A fresh session like the current one (same folder or worktree, mode and model); used after archive/delete. */
21
+ async function freshLike(chat){
22
+ const m=chat.session.meta;
23
+ const next=m.worktree&&!m.worktree.removed?await Session.create({mode:m.mode,worktree:{path:m.worktree.path,parent:m.parent,branch:m.worktree.branch,base:m.worktree.base,baseBranch:m.worktree.baseBranch,copied:[],named:true}}):await Session.create({cwd:m.root,mode:m.mode});
24
+ if(chat.model)next.meta.model=chat.model;next.meta.cliMode=chat.mode;await next.save();return next;
25
+ }
26
+ async function pickSession(ctx,q,title){
27
+ const cur=ctx.session?.meta.id;
28
+ const found=(await findSessions(q)).filter(m=>m.id!==cur);
29
+ if(!found.length)throw new CommandError(q?'No other session matches '+q+'.':'No other sessions.');
30
+ if(found.length===1&&q)return found[0];
31
+ const pick=await ctx.ui.pick(found.slice(0,40).map(sessionRow),{title});return pick?found.find(m=>m.id===pick.value):null;
32
+ }
33
+
34
+ /** The context a side question gets: the last few turns of this conversation, shortened. */
35
+ export async function sideContext(chat,{turns=3,each=1500}={}){
36
+ const t=(await chat.transcript().catch(()=>[])).slice(-turns);
37
+ return t.map(x=>'User: '+short(userTask(x.task),each)+'\nAssistant: '+short(answerOf(x),each)).join('\n\n');
38
+ }
39
+ export const SIDE_TASK='Side question. The main conversation continues separately and will not see this exchange. Answer briefly from the code and the context below; do not change files or run commands that change anything.';
40
+
41
+ /** /side <question>: one read-only turn in a throwaway session; the answer is printed and the session deleted. */
42
+ export async function side(ctx,question,{ChatClass=Chat}={}){
43
+ const chat=need(ctx);const q=String(question||'').trim();
44
+ if(!q)throw new CommandError('Usage: /side <question> (also /btw). Asks without adding to this conversation.');
45
+ const m=chat.session.meta;
46
+ const s=await Session.create({cwd:m.root,mode:'plan'});s.meta.side=true;s.meta.title='Side: '+short(q,60);s.meta.cliMode='ask';await s.save();
47
+ const helper=new ChatClass({session:s,settings:chat.settings,cloud:chat.cloud,models:chat.models,flags:{mode:'ask',model:chat.model,effort:chat.effort,addDirs:chat.addDirs,maxSteps:Math.min(chat.steps||40,40)}});
48
+ ctx.out('Asking on the side (not added to this conversation)...');
49
+ try{
50
+ const context=await sideContext(chat);
51
+ const r=await helper.send(SIDE_TASK+(context?'\n\nContext from the main conversation:\n'+context:'')+'\n\nQuestion: '+q);
52
+ chat.usage.tokens+=r?.usage?.tokens||0;chat.usage.calls+=r?.usage?.calls||0;chat.emit?.('change');
53
+ const answer=await helper.lastAnswer();
54
+ ctx.out(answer?'Side answer:\n'+answer:'No answer'+(r?.state&&r.state!=='completed'?' ('+r.state+')':'')+'.');
55
+ return {answer,state:r?.state,tokens:r?.usage?.tokens||0};
56
+ }finally{await rm(s.dir,{recursive:true,force:true}).catch(()=>{})}
57
+ }
58
+
59
+ async function archive(ctx,a){
60
+ if(a==='list'){const all=await listArchived();ctx.out(all.length?'Archived sessions (/unarchive <id> brings one back):\n'+all.map(m=>' '+m.id.slice(0,8)+' '+short(m.title||'Untitled',40).padEnd(40)+' '+(m.folder||'')).join('\n'):'No archived sessions.');return {archived:all.map(m=>m.id)}}
61
+ if(!a){
62
+ const chat=need(ctx);if(chat.running)throw new CommandError('Stop the agent first (Esc or Ctrl-C).');
63
+ const old=chat.session.meta;const next=await freshLike(chat);await ctx.ui.setSession(next);
64
+ await archiveSession(old.id);
65
+ ctx.out('Archived '+(old.title||'this session')+' ('+old.id.slice(0,8)+'). New session '+next.meta.id.slice(0,8)+'. Bring it back with /unarchive '+old.id.slice(0,8)+' or mlai unarchive.');
66
+ return {archived:old.id,session:next.meta.id};
67
+ }
68
+ const m=await pickSession(ctx,a,'Archive a session');if(!m)return;
69
+ await archiveSession(m.id).catch(e=>{throw new CommandError(e.message)});
70
+ ctx.out('Archived '+(m.title||'the session')+' ('+m.id.slice(0,8)+').');return {archived:m.id};
71
+ }
72
+ async function unarchive(ctx,a){
73
+ if(!a){
74
+ const all=await listArchived();if(!all.length){ctx.out('No archived sessions.');return}
75
+ const pick=await ctx.ui.pick(all.slice(0,40).map(sessionRow),{title:'Bring back a session'});if(!pick)return;a=pick.value;
76
+ }
77
+ const m=await unarchiveSession(a).catch(e=>{throw new CommandError(e.message)});
78
+ ctx.out('Restored '+(m?.title||'the session')+' ('+String(m?.id).slice(0,8)+'). /resume '+String(m?.id).slice(0,8)+' switches to it.');return {restored:m?.id};
79
+ }
80
+ async function del(ctx,a){
81
+ const chat=ctx.chat,current=!a;
82
+ const m=current?need(ctx).session.meta:await pickSession(ctx,a,'Delete a session');if(!m)return;
83
+ if(current&&chat.running)throw new CommandError('Stop the agent first (Esc or Ctrl-C).');
84
+ const what=(m.title||'Untitled')+' ('+m.id.slice(0,8)+', '+m.turns.length+' turn'+(m.turns.length===1?'':'s')+')';
85
+ if(!await ctx.ui.confirm('Delete '+what+'? This cannot be undone.',{default:false})){ctx.out('Not deleted.');return}
86
+ let next=null;
87
+ if(current){next=await freshLike(chat);await ctx.ui.setSession(next)}
88
+ await removeSession(m.id).catch(e=>{throw new CommandError(e.message)});
89
+ ctx.out('Deleted '+what+'.'+(m.worktree&&!m.worktree.removed?' Its worktree is still at '+m.worktree.path+' (git worktree remove deletes it).':'')+(next?' New session '+next.meta.id.slice(0,8)+'.':''));
90
+ return {deleted:m.id,...(next?{session:next.meta.id}:{})};
91
+ }
92
+ async function worktree(ctx,a){
93
+ const chat=need(ctx),m=chat.session.meta;const root=m.parent||m.root;
94
+ if(!m.git&&!m.parent)throw new CommandError('/worktree needs a git repository.');
95
+ if(a==='info'||a==='status'){ctx.out(m.worktree?'Worktree '+m.worktree.path+' on '+m.worktree.branch+(m.worktree.baseBranch?' (from '+m.worktree.baseBranch+')':''):'This session works in '+m.root+' (no worktree). /worktree [name|#PR|url] starts one.');return}
96
+ ctx.out(/^(#?\d+|https?:)/.test(a||'')?'Fetching the pull request...':'Creating a worktree...');
97
+ let tree;try{tree=await worktreeFromArg(root,a||undefined)}catch(e){throw new CommandError(e.message)}
98
+ const next=await Session.create({mode:m.mode,worktree:tree});
99
+ if(chat.model)next.meta.model=chat.model;next.meta.cliMode=chat.mode;if(tree.pr){next.meta.title='PR #'+tree.pr.number;next.meta.pr=tree.pr}await next.save();
100
+ await ctx.ui.setSession(next);
101
+ ctx.out('Worktree '+tree.path+' on branch '+tree.branch+(tree.pr?' (pull request #'+tree.pr.number+')':'')+(tree.copied.length?'; copied '+tree.copied.join(', '):'')+'. New session '+next.meta.id.slice(0,8)+'; your working copy is untouched.');
102
+ return {session:next.meta.id,path:tree.path,branch:tree.branch};
103
+ }
104
+ const expandHome=p=>p==='~'?os.homedir():p.startsWith('~/')?path.join(os.homedir(),p.slice(2)):p;
105
+ async function cd(ctx,a){
106
+ const chat=need(ctx);if(!a)throw new CommandError('Usage: /cd <folder>. Starts a new session there; /pwd shows where you are.');
107
+ if(chat.running)throw new CommandError('Stop the agent first (Esc or Ctrl-C).');
108
+ const dir=path.resolve(chat.session.meta.root,expandHome(a.replace(/^["']|["']$/g,'')));
109
+ if(!existsSync(dir)||!statSync(dir).isDirectory())throw new CommandError('No folder '+dir+'.');
110
+ const next=await Session.create({cwd:dir,mode:chat.session.meta.mode});
111
+ if(chat.model)next.meta.model=chat.model;next.meta.cliMode=chat.mode;await next.save();
112
+ try{process.chdir(dir)}catch{}
113
+ try{ctx.settings=loadSettings({root:next.meta.root})}catch{}
114
+ try{(await import('./cmd-extensibility.mjs')).reloadCustomCommands(next.meta.root)}catch{}
115
+ await ctx.ui.setSession(next);
116
+ ctx.out('Now in '+next.meta.root+(next.meta.git?' ('+(git(next.meta.root,['branch','--show-current'])||'detached')+')':' (not a git repository)')+'. New session '+next.meta.id.slice(0,8)+'.');
117
+ return {session:next.meta.id,root:next.meta.root};
118
+ }
119
+ function pwd(ctx){
120
+ const m=ctx.session?.meta;const L=[];
121
+ if(m){L.push(m.root);if(m.worktree)L.push('worktree of '+m.parent+' on branch '+m.worktree.branch);else if(m.git){const b=git(m.root,['branch','--show-current']);if(b)L.push('branch '+b)}}
122
+ if(!m||path.resolve(process.cwd())!==path.resolve(m.root))L.push('terminal folder: '+process.cwd());
123
+ ctx.out(L.join('\n'));return {root:m?.root||process.cwd()};
124
+ }
125
+
126
+ /** /recap: what happened in this session, from local records only (no credits used). */
127
+ export async function recapText(chat,{gitStatus=true}={}){
128
+ const s=chat.session,m=s.meta,turns=await chat.transcript().catch(()=>[]);
129
+ const L=[(m.title||'Untitled session')+' ('+m.id.slice(0,8)+') '+m.turns.length+' turn'+(m.turns.length===1?'':'s')+' '+formatCredits(creditsFor(chat.usage?.tokens||0))+' credits'];
130
+ if(!turns.length){L.push('Nothing done yet.');return L.join('\n')}
131
+ L.push('','Asked:');
132
+ turns.slice(-8).forEach((t,i,arr)=>{const n=turns.length-arr.length+i+1;const st=t.status?.state||m.turns[n-1]?.state||'';L.push(' '+String(n).padStart(2)+'. '+short(userTask(t.task),90)+(st&&st!=='completed'?' ['+st+']':''))});
133
+ const files=new Set();for(const t of turns)for(const f of t.completion?.changedFiles||[])files.add(typeof f==='string'?f:f.path);
134
+ if(files.size)L.push('','Files changed ('+files.size+'): '+[...files].slice(0,20).join(', ')+(files.size>20?', …':''));
135
+ const todos=[...turns].reverse().map(t=>t.events?.findLast?.(e=>e.type==='todo'&&Array.isArray(e.items))).find(Boolean);
136
+ if(todos){const open=todos.items.filter(x=>x&&x.status!=='completed'&&x.status!=='done');if(open.length)L.push('','Open items:',...open.slice(0,8).map(x=>' - '+short(x.content||x.text||x.title,90)))}
137
+ const last=answerOf(turns.at(-1));
138
+ if(last)L.push('','Last answer:',...String(last).trim().split('\n').slice(0,8).map(l=>' '+l),...(String(last).trim().split('\n').length>8?[' …']:[]));
139
+ if(gitStatus&&m.git!==false){const st=git(m.root,['status','--short']);if(st){const rows=st.split('\n');L.push('','Uncommitted ('+rows.length+'):',...rows.slice(0,10).map(r=>' '+r),...(rows.length>10?[' …']:[]))}}
140
+ return L.join('\n');
141
+ }
142
+
143
+ export function install(register){
144
+ register({name:'side',aliases:['btw'],args:'<question>',summary:'Ask a quick side question without adding it to this conversation',run:async(ctx,a)=>side(ctx,a)});
145
+ register({name:'archive',args:'[id|name|list]',summary:'Archive this session (or another) out of the lists',run:archive,complete:async()=>['list']});
146
+ register({name:'unarchive',args:'[id]',summary:'Bring back an archived session',run:unarchive});
147
+ register({name:'delete',args:'[id|name]',summary:'Delete this session (or another) after confirming',run:del});
148
+ register({name:'worktree',args:'[name|#PR|url|info]',summary:'Continue in a new git worktree, optionally checking out a pull request',run:worktree});
149
+ register({name:'cd',args:'<folder>',summary:'Start a new session in another folder',run:cd});
150
+ register({name:'pwd',summary:'Show the folder and branch this session works in',run:async ctx=>pwd(ctx)});
151
+ register({name:'recap',summary:'Summarize this session so far (no credits used)',run:async ctx=>{const t=await recapText(need(ctx));ctx.out(t);return {text:t}}});
152
+ }