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,200 @@
1
+ // Terminal-interface commands (TUI owner): /vim, /theme (and syntax themes), /image, /keys, /statusline, /keymap,
2
+ // /title, /raw, /ps, /stop, /tui. Each works in the plain loop too (settings are saved; the full TUI also applies
3
+ // them right away through its ui extras).
4
+ import {CommandError} from './commands.mjs';
5
+ import {theme as makeTheme,SYNTAX_NAMES} from './ansi.mjs';
6
+ import {render as markdown} from './markdown.mjs';
7
+ import {ITEMS,DEFAULT_ITEMS,statusLine,itemsOf} from './statusline.mjs';
8
+ import {ACTIONS,resolveKeymap,checkBinding,labelOf,normalizeSpec} from './keymap.mjs';
9
+ import {terminals} from './bgterm.mjs';
10
+ const THEMES=['dark','light','auto'];
11
+ const SYNTAX_INFO={default:'The interface theme colors',github:'GitHub-like',monokai:'Monokai',solarized:'Solarized',nord:'Nord',mono:'No highlighting, code stays distinct'};
12
+ const SAMPLE='```js\n// greet the user\nexport async function greet(name){\n const n = 3;\n return `hello ${name}`;\n}\n```';
13
+
14
+ export const KEYS=[
15
+ ['Enter','Send the message'],
16
+ ['Shift+Enter, Alt+Enter, Ctrl+J, \\ at line end','New line'],
17
+ ['Shift+Tab','Switch mode (agent, plan, ask, auto)'],
18
+ ['Esc','Stop the agent; close a popup'],
19
+ ['Esc Esc','Rewind to an earlier message (clears the input when it has text)'],
20
+ ['Ctrl-C','Stop the agent or clear the input; twice to exit'],
21
+ ['Ctrl-D','Exit when the input is empty'],
22
+ ['Up / Down','History (or move in a popup)'],
23
+ ['Ctrl-R','Search history'],
24
+ ['Tab','Complete a command, argument or file'],
25
+ ['/','Commands'],
26
+ ['@','Add a file or folder'],
27
+ ['!','Run a shell command in the project; its output goes with the next message'],
28
+ ['Ctrl-O','Expand or collapse tool output'],
29
+ ['Ctrl-L','Redraw the screen'],
30
+ ['Ctrl-A / Ctrl-E, Ctrl-W, Ctrl-U, Ctrl-K','Line start / end, delete word, delete to start / end'],
31
+ ['Drag an image or paste its path','Attach the image'],
32
+ ['Ctrl-V (Alt-V on Windows)','Paste an image from the clipboard'],
33
+ ['Tab while the agent works','Queue the message for after this turn (Enter steers right away)'],
34
+ ['Alt-Up','Pull the last queued message back into the input'],
35
+ ['!command &','Run a command in a background terminal (/ps, /stop)'],
36
+ ['Alt-R','Raw scrollback on or off'],
37
+ ['Alt-J','List background terminals'],
38
+ ];
39
+ export function keysText(cols=process.stdout.columns||100){
40
+ const w=Math.max(...KEYS.map(k=>k[0].length).filter(n=>n<=28)),ind=' '.repeat(w+4),room=Math.max(20,cols-w-6);
41
+ const wrap=d=>{const out=[];let line='';for(const word of d.split(' ')){if(line&&(line+' '+word).length>room){out.push(line);line=word}else line=line?line+' '+word:word}if(line)out.push(line);return out};
42
+ return KEYS.map(([k,d])=>{const parts=wrap(d);const head=k.length>w?' '+k+'\n'+ind+parts[0]:' '+k.padEnd(w+2)+parts[0];return [head,...parts.slice(1).map(x=>ind+x)].join('\n')}).join('\n')}
43
+
44
+ async function save(ctx,key,value,scope='user'){
45
+ try{const next=await ctx.settings?.save?.(scope,key,value);if(next&&typeof next==='object')try{ctx.settings=next}catch{}return true}
46
+ catch(e){ctx.ui.error?.('Not saved: '+e.message);return false}
47
+ }
48
+ const onOff=(a,cur)=>a==='on'||a==='true'?true:a==='off'||a==='false'?false:a?null:!cur;
49
+ /** A short code sample in a syntax theme (for /theme syntax). */
50
+ export function syntaxPreview(name,{dark=true,color=true,cols=60}={}){
51
+ const t=makeTheme(dark?'dark':'light',{color,syntax:name});
52
+ return markdown(SAMPLE,{t,cols}).map(l=>' '+l).join('\n');
53
+ }
54
+
55
+ export function install(register){
56
+ register({name:'vim',summary:'Toggle vim keys in the input box',args:'[on|off]',complete:async()=>['on','off'],run:async(ctx,a)=>{
57
+ const cur=Boolean(ctx.ui.status?.()?.vim??ctx.settings?.vim);
58
+ const on=a==='on'?true:a==='off'?false:a?null:!cur;
59
+ if(on===null)throw new CommandError('Usage: /vim [on|off]');
60
+ ctx.ui.setVim?.(on);await save(ctx,'vim',on);
61
+ ctx.out(on?'Vim keys on. Esc for normal mode, i to insert.':'Vim keys off.');
62
+ return {vim:on};
63
+ }});
64
+ register({name:'theme',summary:'Switch the color theme, or the code colors with /theme syntax',args:'[dark|light|auto|syntax <name>]',complete:async(ctx,a)=>/^syntax\s/.test(a||'')?SYNTAX_NAMES.map(n=>'syntax '+n):[...THEMES,'syntax'],run:async(ctx,a)=>{
65
+ const sm=/^syntax(?:\s+(\S+))?$/.exec(a||'');
66
+ if(sm){
67
+ let name=sm[1];
68
+ const dark=(ctx.ui.theme||'dark')!=='light';
69
+ if(!name){
70
+ const picked=await ctx.ui.pick?.(SYNTAX_NAMES.map(n=>({label:n,value:n,detail:SYNTAX_INFO[n]})),{title:'Code colors'});
71
+ name=picked?.value||picked;if(!name)return;
72
+ }
73
+ if(!SYNTAX_NAMES.includes(name))throw new CommandError('Syntax themes: '+SYNTAX_NAMES.join(', '));
74
+ ctx.ui.setSyntax?.(name);await save(ctx,'syntaxTheme',name);
75
+ ctx.out('Code colors: '+name+'\n'+syntaxPreview(name,{dark,color:Boolean(ctx.ui.setSyntax)&&!('NO_COLOR' in process.env&&process.env.NO_COLOR!=='')}));
76
+ return {syntaxTheme:name};
77
+ }
78
+ if(!a){
79
+ const picked=await ctx.ui.pick?.(THEMES.map(n=>({label:n,value:n,detail:n==='auto'?'Follow the terminal background':n==='dark'?'Light text on a dark background':'Dark text on a light background'})),{title:'Theme'});
80
+ a=picked?.value||picked;if(!a)return;
81
+ }
82
+ if(!THEMES.includes(a))throw new CommandError('Themes: '+THEMES.join(', '));
83
+ ctx.ui.setTheme?.(a);await save(ctx,'theme',a);ctx.out('Theme: '+a);return {theme:a};
84
+ }});
85
+ register({name:'image',summary:'Attach an image to the next message',args:'<path>',run:async(ctx,a)=>{
86
+ if(!a)throw new CommandError('Usage: /image <path to a png, jpg, webp or gif>');
87
+ if(!ctx.ui.attachImage)throw new CommandError('Use --image <path> with mlai, or the full terminal interface, to attach images.');
88
+ const file=a.replace(/^["']|["']$/g,'');
89
+ try{const r=await ctx.ui.attachImage(file);ctx.out('Attached '+r.path+' as [Image #'+r.index+'].');return r}
90
+ catch(e){throw new CommandError(e.message)}
91
+ }});
92
+ register({name:'keys',aliases:['keybindings'],summary:'Show keyboard shortcuts',run:async ctx=>{ctx.out(keysText())}});
93
+
94
+ register({name:'statusline',summary:'Choose what the status line shows, or run your own command',args:'[items|command <cmd>|on|off|reset]',
95
+ complete:async()=>['items','command ','on','off','reset',...Object.keys(ITEMS).map(k=>'items '+k)],run:async(ctx,a)=>{
96
+ const cur=ctx.settings?.statusLine&&typeof ctx.settings.statusLine==='object'?ctx.settings.statusLine:{enabled:true};
97
+ const write=v=>save(ctx,'statusLine',v);
98
+ a=(a||'').trim();
99
+ if(a==='on'||a==='off'){await write({...cur,enabled:a==='on'});ctx.out('Status line '+a+'.');return}
100
+ if(a==='reset'){await write({enabled:true,command:null});ctx.out('Status line reset to the default items: '+DEFAULT_ITEMS.join(', ')+'.');return}
101
+ const cm=/^command(?:\s+([\s\S]+))?$/.exec(a);
102
+ if(cm){
103
+ const cmd=cm[1]?.trim()||null;
104
+ await write({...cur,enabled:true,command:cmd&&cmd!=='none'?cmd:null});
105
+ ctx.out(cmd&&cmd!=='none'?'Status line command: '+cmd+'\nIt gets the status as JSON on stdin; its first line is shown (1 s limit).':'Status line command removed.');return;
106
+ }
107
+ let items=null;
108
+ const im=/^items?(?:\s+(.+))?$/.exec(a);
109
+ if(im&&im[1])items=im[1].split(/[\s,]+/).filter(Boolean);
110
+ else if(!a||im){
111
+ if(!ctx.ui.pickMany){ctx.out('Status line items: '+itemsOf(ctx.settings).join(', ')+'\nAvailable: '+Object.keys(ITEMS).join(', ')+'\nSet them with /statusline items model,mode,branch');return}
112
+ const st=ctx.ui.status?.()||{};
113
+ const sel=await ctx.ui.pickMany(Object.entries(ITEMS).map(([k,v])=>({label:k,value:k,detail:v.summary})),{title:'Status line',selected:itemsOf(ctx.settings),
114
+ preview:(on,{t,cols,box})=>statusLine({...st,items:on.length?on:['mode'],now:Date.now()},{t,cols,box})});
115
+ if(!sel)return;
116
+ items=sel;
117
+ }else throw new CommandError('Usage: /statusline [items <a,b,...>|command <cmd>|on|off|reset]');
118
+ const bad=items.filter(x=>!ITEMS[x]);if(bad.length)throw new CommandError('Unknown item '+bad.join(', ')+'. Items: '+Object.keys(ITEMS).join(', '));
119
+ if(!items.length)throw new CommandError('Pick at least one item, or /statusline off.');
120
+ await write({...cur,enabled:true,items});ctx.out('Status line: '+items.join(', '));return {items};
121
+ }});
122
+ register({name:'keymap',summary:'Show or change key bindings',args:'[set <action> <key>|reset [action]]',
123
+ complete:async(ctx,a)=>{const p=String(a||'').split(/\s+/);return p[0]==='set'&&p.length<=2?Object.keys(ACTIONS).map(x=>'set '+x+' '):p[0]==='reset'?['reset',...Object.keys(ACTIONS).map(x=>'reset '+x)]:['set ','reset']},run:async(ctx,a)=>{
124
+ const custom={...(ctx.settings?.keymap||{})};
125
+ const map=resolveKeymap(custom);
126
+ const list=()=>{const w=Math.max(...Object.keys(ACTIONS).map(k=>k.length));return Object.entries(ACTIONS).map(([k,v])=>' '+k.padEnd(w+2)+labelOf(map[k]).padEnd(12)+v.summary+(custom[k]!==undefined?' (custom)':'')).join('\n')};
127
+ a=(a||'').trim();
128
+ const bind=async(action,spec)=>{
129
+ const {spec:n,conflict}=checkBinding(action,spec,map);
130
+ custom[action]=n;if(conflict)custom[conflict]=null;
131
+ await save(ctx,'keymap',custom);
132
+ ctx.out('Saved: '+labelOf(n)+' = '+ACTIONS[action].summary.toLowerCase()+(conflict?' ('+conflict+' is now unbound; /keymap set '+conflict+' <key> to give it another key)':'')+'.');
133
+ return {action,key:n,conflict};
134
+ };
135
+ const sm=/^set\s+(\w+)\s+(\S+)$/.exec(a);
136
+ if(sm){try{return await bind(sm[1],sm[2])}catch(e){throw new CommandError(e.message)}}
137
+ const rm=/^reset(?:\s+(\w+))?$/.exec(a);
138
+ if(rm){
139
+ if(rm[1]){if(!ACTIONS[rm[1]])throw new CommandError('Unknown action '+rm[1]);delete custom[rm[1]];await save(ctx,'keymap',custom);ctx.out(rm[1]+' is back on '+labelOf(resolveKeymap(custom)[rm[1]])+'.');return}
140
+ await save(ctx,'keymap',undefined);ctx.out('Key bindings reset to the defaults.');return;
141
+ }
142
+ if(a)throw new CommandError('Usage: /keymap [set <action> <key>|reset [action]]');
143
+ if(!ctx.ui.pick||!ctx.ui.captureKey){ctx.out('Key bindings:\n'+list()+'\nChange one with /keymap set <action> <key> (for example /keymap set toggleTools ctrl+t).');return}
144
+ const picked=await ctx.ui.pick(Object.entries(ACTIONS).map(([k,v])=>({label:k,value:k,detail:labelOf(map[k]).padEnd(11)+v.summary})),{title:'Key bindings: choose one to change'});
145
+ const action=picked?.value||picked;if(!action)return;
146
+ const spec=await ctx.ui.captureKey('New key for '+action+' ('+ACTIONS[action].summary.toLowerCase()+')');
147
+ if(!spec)return;
148
+ if(!normalizeSpec(spec))throw new CommandError(labelOf(spec)+' cannot be bound: use Ctrl, Alt, a function key or Shift+Tab.');
149
+ try{return await bind(action,spec)}catch(e){throw new CommandError(e.message)}
150
+ }});
151
+ register({name:'title',summary:'Set the terminal title, or auto / off',args:'[<text>|auto|off]',complete:async()=>['auto','off'],run:async(ctx,a)=>{
152
+ a=(a||'').trim();
153
+ if(!a){ctx.out('Terminal title: '+(ctx.settings?.terminalTitle||'auto')+'. Use /title <text> for this session, /title auto or /title off.');return}
154
+ if(a==='auto'||a==='off'){ctx.ui.setTitle?.(a);await save(ctx,'terminalTitle',a==='auto'?undefined:'off');ctx.out(a==='off'?'Terminal title updates off.':'Terminal title follows the session again.');return {title:a}}
155
+ if(/[\x00-\x1f]/.test(a))throw new CommandError('The title cannot hold control characters.');
156
+ if(!ctx.ui.setTitle)throw new CommandError('Titles need the full terminal interface.');
157
+ ctx.ui.setTitle(a);ctx.out('Terminal title: '+a+' (this session; /title auto to undo).');return {title:a};
158
+ }});
159
+ register({name:'raw',summary:'Raw scrollback: replies as plain text, easy to copy',args:'[on|off]',complete:async()=>['on','off'],run:async(ctx,a)=>{
160
+ const cur=Boolean(ctx.ui.raw??ctx.settings?.rawScrollback);
161
+ const on=onOff(a,cur);if(on===null)throw new CommandError('Usage: /raw [on|off]');
162
+ ctx.ui.setRaw?.(on);await save(ctx,'rawScrollback',on);
163
+ ctx.out(on?'Raw scrollback on: replies print as written (markdown source, no wrapping) and tool output prints in full.':'Raw scrollback off.');return {raw:on};
164
+ }});
165
+ register({name:'ps',summary:'Background terminals: list, show output, or start one',args:'[<id>|new <command>]',complete:async()=>['new ',...terminals.list().map(j=>String(j.id))],run:async(ctx,a)=>{
166
+ a=(a||'').trim();
167
+ const nm=/^new\s+([\s\S]+)$/.exec(a);
168
+ if(nm){
169
+ const job=terminals.start(nm[1],{cwd:ctx.session?.meta?.root||process.cwd()});
170
+ ctx.out('Background #'+job.id+' running: '+job.command+'\n/ps '+job.id+' shows its output, /stop '+job.id+' ends it.');return {id:job.id};
171
+ }
172
+ if(a){
173
+ const job=terminals.get(a);if(!job)throw new CommandError('No background terminal '+a+'. /ps lists them.');
174
+ const tail=terminals.tail(job,40);
175
+ ctx.out('#'+job.id+' '+job.command+' ('+terminals.status(job)+')\n'+(tail.length?tail.map(l=>' '+l).join('\n'):' (no output yet)'));return {id:job.id};
176
+ }
177
+ const rows=terminals.rows();
178
+ if(!rows.length){ctx.out('No background terminals. Start one with !<command> & or /ps new <command>.');return {rows}}
179
+ ctx.out(rows.map(r=>' #'+r.id+' '+r.status.padEnd(18)+r.command+(r.last?'\n '+r.last.slice(0,100):'')).join('\n'));return {rows};
180
+ }});
181
+ register({name:'stop',summary:'Stop a background terminal, or all of them',args:'[id|all]',complete:async()=>['all',...terminals.running().map(j=>String(j.id))],run:async(ctx,a)=>{
182
+ a=(a||'').trim();
183
+ if(!a){const r=terminals.running();if(r.length===1)a=String(r[0].id);else throw new CommandError(r.length?'Usage: /stop <id|all> ('+r.map(j=>'#'+j.id).join(', ')+' running)':'No background terminals are running.')}
184
+ if(a==='all'){const n=await terminals.stopAll();ctx.out(n?'Stopped '+n+' background terminal'+(n===1?'':'s')+'.':'No background terminals are running.');return {stopped:n}}
185
+ const job=terminals.get(a);if(!job)throw new CommandError('No background terminal '+a+'. /ps lists them.');
186
+ if(job.ended!=null){ctx.out('#'+job.id+' already ended ('+terminals.status(job)+').');return {stopped:0}}
187
+ await terminals.stop(job);ctx.out('Stopped #'+job.id+': '+job.command);return {stopped:1};
188
+ }});
189
+ register({name:'tui',summary:'Choose the full terminal interface or the plain one',args:'[auto|full|plain]',complete:async()=>['auto','full','plain'],run:async(ctx,a)=>{
190
+ a=(a||'').trim();
191
+ const cur=ctx.settings?.tui||'auto';
192
+ if(!a){
193
+ if(ctx.ui.pick){const p=await ctx.ui.pick([{label:'auto',value:'auto',detail:'Full interface in a terminal, plain when piped or TERM=dumb'},{label:'full',value:'full',detail:'Bordered input, popups, live status line'},{label:'plain',value:'plain',detail:'Line by line, works with screen readers and any terminal'}],{title:'Interface (now '+cur+')'});a=p?.value||p;if(!a)return}
194
+ else{ctx.out('Interface: '+cur+'. /tui full, /tui plain or /tui auto; --tui and --no-tui override it per run.');return}
195
+ }
196
+ if(!['auto','full','plain'].includes(a))throw new CommandError('Usage: /tui [auto|full|plain]');
197
+ await save(ctx,'tui',a);
198
+ ctx.out('Interface: '+a+'. It applies the next time you start mlai (mlai -c continues this session).');return {tui:a};
199
+ }});
200
+ }
@@ -0,0 +1,160 @@
1
+ /**
2
+ * Slash-command registry (CLI v1 shared contract). Every command, built in or added by a feature, goes through
3
+ * register(); the TUI popup, Tab completion, /help and the plain readline loop all read from here.
4
+ *
5
+ * register({name, aliases?, args?, summary, run(ctx, args), complete?(ctx, partial), hidden?, when?(ctx)})
6
+ *
7
+ * name lower-case word, no slash ('model'). aliases: other names ('new' for 'clear').
8
+ * args hint shown after the name in the popup ('[filter]', '<agent|plan|ask|auto>').
9
+ * summary one line for the popup and /help. No emojis, no exclamation points, no provider names.
10
+ * run async (ctx, args:string) => any. args is the raw text after the name, trimmed.
11
+ * Return {exit:true} to end the session, {send:text} to send text to the agent as a task.
12
+ * complete async (ctx, partial) => string[] of candidate values for the argument being typed.
13
+ * when (ctx) => boolean; hidden from the popup and refused when false (e.g. /logout when signed out).
14
+ *
15
+ * Where commands live: one module per area, src/tui/cmd-<area>.mjs, exporting install(register). loadCommands()
16
+ * imports every cmd-*.mjs in this folder (sorted), so owners never edit a shared list. install gets a second
17
+ * argument {addRewriter} for input prefixes like '&'; loops call rewrite(line) before dispatch.
18
+ *
19
+ * ctx = {session, settings, ui, out, exec, server}
20
+ * session the current Session (src/session.mjs); commands may replace it via ui.setSession(next).
21
+ * settings the merged settings object from settings.mjs (read-only; write with settings.save()).
22
+ * ui {print(text), error(text), confirm(question, {default}) => bool, pick(items, {title, filter}) => item|null,
23
+ * input(question, {default}) => string|null, setSession(s), setMode(m), status() => object, theme}
24
+ * Plain-terminal fallbacks exist for every method (tui/plain.mjs); the full TUI overrides them.
25
+ * out (text) => void, the same as ui.print; kept as a short name for simple commands.
26
+ * exec (command, {cwd}) => Promise<{code, stdout, stderr}>, a shell in the repository.
27
+ * server the signed-in Cloud client (src/cloud.mjs), or null when signed out.
28
+ */
29
+
30
+ import {readdir} from 'node:fs/promises';
31
+ import path from 'node:path';
32
+ import {fileURLToPath,pathToFileURL} from 'node:url';
33
+
34
+ const NAME=/^[a-z][a-z0-9-]{0,31}$/;
35
+ const commands=new Map(),aliases=new Map();
36
+
37
+ export function register(cmd){
38
+ if(!cmd||!NAME.test(cmd.name||''))throw new Error('Command name must be a lower-case word: '+cmd?.name);
39
+ if(typeof cmd.run!=='function')throw new Error('Command /'+cmd.name+' needs run(ctx, args)');
40
+ if(typeof cmd.summary!=='string'||!cmd.summary.trim())throw new Error('Command /'+cmd.name+' needs a summary');
41
+ if(/[!]|\p{Extended_Pictographic}/u.test(cmd.summary))throw new Error('Command /'+cmd.name+' summary: no emojis or exclamation points');
42
+ unregister(cmd.name);
43
+ const entry={aliases:[],args:'',hidden:false,...cmd,aliases:[...new Set(cmd.aliases||[])]};
44
+ for(const a of entry.aliases){if(!NAME.test(a))throw new Error('Bad alias '+a);if(commands.has(a))throw new Error('Alias /'+a+' is already a command')}
45
+ commands.set(entry.name,entry);
46
+ for(const a of entry.aliases)aliases.set(a,entry.name);
47
+ aliases.delete(entry.name);
48
+ return entry;
49
+ }
50
+ export function unregister(name){
51
+ const c=commands.get(name);if(!c)return false;
52
+ commands.delete(name);for(const a of c.aliases)if(aliases.get(a)===name)aliases.delete(a);
53
+ return true;
54
+ }
55
+ /** For tests: an empty registry. */
56
+ export function reset(){commands.clear();aliases.clear();rewriters.length=0}
57
+ /** Input rewriters run on every submitted line before dispatch ('&task' -> '/cloud task'). fn(line) => new line or null. */
58
+ const rewriters=[];
59
+ export function addRewriter(fn){if(typeof fn!=='function')throw new Error('addRewriter needs a function');rewriters.push(fn)}
60
+ /** The line after the first rewriter that changes it; the input loop (plain and TUI) calls this before dispatch. */
61
+ export function rewrite(line){for(const fn of rewriters){const r=fn(line);if(typeof r==='string'&&r!==line)return r}return line}
62
+ export function find(name){
63
+ const n=String(name||'').replace(/^\//,'').toLowerCase();
64
+ return commands.get(n)||commands.get(aliases.get(n))||null;
65
+ }
66
+ const visible=(c,ctx)=>!c.hidden&&(!c.when||!ctx||safeWhen(c,ctx));
67
+ const safeWhen=(c,ctx)=>{try{return c.when(ctx)!==false}catch{return false}};
68
+ /** Commands for /help and the popup, sorted by name. */
69
+ export function list(ctx){return [...commands.values()].filter(c=>visible(c,ctx)).sort((a,b)=>a.name.localeCompare(b.name))}
70
+
71
+ /** '/model fast' -> {name:'model', args:'fast'}; null for anything that is not a slash command ('/' alone, '//x', paths). */
72
+ export function parse(line){
73
+ const m=/^\/([A-Za-z][\w-]*)(?:\s+([\s\S]*))?$/.exec(String(line||'').trim());
74
+ return m?{name:m[1].toLowerCase(),args:(m[2]||'').trim()}:null;
75
+ }
76
+
77
+ /**
78
+ * Subsequence fuzzy match. Returns a score (higher is better) or null. Prefix and word-start matches rank first,
79
+ * so 'mo' finds model and mode before compact.
80
+ */
81
+ export function fuzzy(query,text){
82
+ const q=String(query||'').toLowerCase(),t=String(text||'').toLowerCase();
83
+ if(!q)return 0;
84
+ if(t.startsWith(q))return 1000-t.length;
85
+ let score=0,ti=0,prev=-2;
86
+ for(const ch of q){
87
+ const i=t.indexOf(ch,ti);if(i<0)return null;
88
+ score+=i===prev+1?8:(i===0||/[\s/_.-]/.test(t[i-1]))?6:1;
89
+ prev=i;ti=i+1;
90
+ }
91
+ return score-t.length*0.01;
92
+ }
93
+ /** Popup rows for what is typed after '/': [{name, args, summary, aliases}], best first. */
94
+ export function suggest(ctx,typed){
95
+ const q=String(typed||'').replace(/^\//,'');
96
+ const rows=[];
97
+ for(const c of list(ctx)){
98
+ const best=Math.max(...[c.name,...c.aliases].map(n=>fuzzy(q,n)??-Infinity));
99
+ if(best>-Infinity)rows.push({c,best});
100
+ }
101
+ return rows.sort((a,b)=>b.best-a.best||a.c.name.localeCompare(b.c.name)).map(({c})=>({name:c.name,args:c.args,summary:c.summary,aliases:c.aliases}));
102
+ }
103
+ /**
104
+ * Tab completion for a whole input line. '/mo' -> ['/model ', '/mode ']; '/model fa' -> the command's own
105
+ * completions, as full lines. Always returns full replacement lines.
106
+ */
107
+ export async function complete(ctx,line){
108
+ const s=String(line||'');
109
+ const m=/^\/([\w-]*)$/.exec(s);
110
+ if(m)return suggest(ctx,m[1]).map(r=>'/'+r.name+' ');
111
+ const p=/^\/([\w-]+)\s+([\s\S]*)$/.exec(s);if(!p)return [];
112
+ const c=find(p[1]);if(!c?.complete||!visible(c,ctx))return [];
113
+ const partial=p[2];
114
+ const vals=await Promise.resolve(c.complete(ctx,partial)).catch(()=>[]);
115
+ return (Array.isArray(vals)?vals:[]).filter(v=>fuzzy(partial,v)!==null).map(v=>'/'+p[1]+' '+v);
116
+ }
117
+
118
+ /** Edit distance with transpositions (optimal string alignment); typos like /mdoe still find /mode. */
119
+ export function distance(a,b){
120
+ const d=Array.from({length:a.length+1},(_,i)=>[i,...Array(b.length).fill(0)]);for(let j=0;j<=b.length;j++)d[0][j]=j;
121
+ for(let i=1;i<=a.length;i++)for(let j=1;j<=b.length;j++){
122
+ d[i][j]=Math.min(d[i-1][j]+1,d[i][j-1]+1,d[i-1][j-1]+(a[i-1]===b[j-1]?0:1));
123
+ if(i>1&&j>1&&a[i-1]===b[j-2]&&a[i-2]===b[j-1])d[i][j]=Math.min(d[i][j],d[i-2][j-2]+1);
124
+ }
125
+ return d[a.length][b.length];
126
+ }
127
+ function nearest(ctx,name){
128
+ const close=list(ctx).map(c=>({c,d:Math.min(...[c.name,...c.aliases].map(n=>distance(name,n)))})).filter(x=>x.d<=2).sort((a,b)=>a.d-b.d).map(x=>'/'+x.c.name);
129
+ return [...new Set([...close,...suggest(ctx,name).map(r=>'/'+r.name)])].slice(0,3);
130
+ }
131
+ export class CommandError extends Error{constructor(m){super(m);this.name='CommandError'}}
132
+ /**
133
+ * Runs a slash line. Returns {handled:false} when the line is not a command (send it to the agent), otherwise
134
+ * {handled:true, result}. Unknown commands and refusals print a short message and are handled.
135
+ */
136
+ export async function dispatch(ctx,line){
137
+ const p=parse(line);if(!p)return {handled:false};
138
+ const c=find(p.name);
139
+ const say=t=>(ctx.ui?.error||ctx.out||(()=>{}))(t);
140
+ if(!c){const near=nearest(ctx,p.name);say('Unknown command /'+p.name+'.'+(near.length?' Did you mean '+near.join(', ')+'?':' /help lists them.'));return {handled:true,result:null}}
141
+ if(c.when&&!safeWhen(c,ctx)){say('/'+c.name+' is not available right now.');return {handled:true,result:null}}
142
+ try{return {handled:true,result:await c.run(ctx,p.args)}}
143
+ catch(e){say(e instanceof CommandError?e.message:'/'+c.name+' failed: '+(e?.message||e));return {handled:true,result:null,error:e}}
144
+ }
145
+ /** /help text from the registry. */
146
+ export function helpText(ctx){
147
+ const rows=list(ctx);const w=Math.min(28,Math.max(...rows.map(r=>(r.name+' '+r.args).length))+2);
148
+ return rows.map(r=>('/'+r.name+(r.args?' '+r.args:'')).padEnd(w+1)+r.summary+(r.aliases.length?' (also /'+r.aliases.join(', /')+')':'')).join('\n');
149
+ }
150
+
151
+ /** Imports src/tui/cmd-*.mjs and calls each install(register). Returns the module names; a broken module is reported, not fatal. */
152
+ export async function loadCommands({dir=path.dirname(fileURLToPath(import.meta.url)),warn=()=>{}}={}){
153
+ const names=(await readdir(dir).catch(()=>[])).filter(n=>/^cmd-[a-z0-9-]+\.mjs$/.test(n)).sort();
154
+ const loaded=[];
155
+ for(const n of names){
156
+ try{const m=await import(pathToFileURL(path.join(dir,n)).href);if(typeof m.install!=='function')throw new Error('no install(register) export');await m.install(register,{addRewriter});loaded.push(n)}
157
+ catch(e){warn('Commands in '+n+' did not load: '+(e?.message||e))}
158
+ }
159
+ return loaded;
160
+ }
@@ -0,0 +1,98 @@
1
+ /**
2
+ * Custom slash commands: Markdown prompt files that become /<name>.
3
+ * project <repo>/.mlai/commands/**\/*.md (also .claude/commands and .cursor/commands, so existing ones work)
4
+ * user ~/.mlai/commands/**\/*.md (also ~/.claude/commands)
5
+ * plugins <plugin>/commands/*.md (--plugin-dir, --plugin-url)
6
+ * The file name is the command (review-pr.md -> /review-pr); a project command wins over a user command with the same
7
+ * name, and built-in commands are never replaced. Optional frontmatter:
8
+ * ---
9
+ * description: Review a pull request
10
+ * argument-hint: <number>
11
+ * ---
12
+ * The body is sent to the agent as the task. $ARGUMENTS is replaced with everything typed after the command, $1..$9
13
+ * with single arguments (quotes group words). When the body has no placeholder, the arguments are appended.
14
+ */
15
+ import {readdirSync,readFileSync,lstatSync} from 'node:fs';
16
+ import path from 'node:path';
17
+ import {home} from '../home.mjs';
18
+ import {extState} from './ext-state.mjs';
19
+
20
+ const MAX_FILES=200,MAX_BYTES=60000;
21
+ export function commandDirs(root,{homeDir=null}={}){
22
+ const h=homeDir||path.dirname(home());
23
+ return [
24
+ ...(root?[{dir:path.join(root,'.mlai','commands'),scope:'project'},{dir:path.join(root,'.claude','commands'),scope:'project'},{dir:path.join(root,'.cursor','commands'),scope:'project'}]:[]),
25
+ ...extState.pluginDirs.map(d=>({dir:path.join(d,'commands'),scope:'plugin'})),
26
+ {dir:path.join(home(),'commands'),scope:'user'},{dir:path.join(h,'.claude','commands'),scope:'user'},
27
+ ];
28
+ }
29
+ function walk(dir,depth=0,out=[]){
30
+ let names=[];try{if(lstatSync(dir).isSymbolicLink())return out;names=readdirSync(dir)}catch{return out}
31
+ for(const n of names.sort()){
32
+ if(out.length>=MAX_FILES)break;if(n.startsWith('.'))continue;
33
+ const p=path.join(dir,n);let st;try{st=lstatSync(p)}catch{continue}
34
+ if(st.isSymbolicLink())continue;
35
+ if(st.isDirectory()&&depth<3)walk(p,depth+1,out);else if(st.isFile()&&n.endsWith('.md')&&st.size<=MAX_BYTES)out.push(p);
36
+ }
37
+ return out;
38
+ }
39
+ export function frontmatter(text){
40
+ const t=String(text).replace(/^\uFEFF/,'');
41
+ if(!t.startsWith('---'))return {meta:{},body:t};
42
+ const end=t.indexOf('\n---',3);if(end<0)return {meta:{},body:t};
43
+ const meta={};for(const line of t.slice(3,end).split(/\r?\n/)){const m=/^([A-Za-z][\w-]*)\s*:\s*(.*)$/.exec(line);if(m)meta[m[1].toLowerCase()]=m[2].trim().replace(/^["']|["']$/g,'')}
44
+ return {meta,body:t.slice(end+4).replace(/^\r?\n/,'')};
45
+ }
46
+ export const commandName=s=>String(s).toLowerCase().replace(/[^a-z0-9]+/g,'-').replace(/^-+|-+$/g,'').replace(/^(\d)/,'c$1').slice(0,32);
47
+ /** [{name, file, scope, description, argumentHint, body}] in precedence order (project first), unique names. */
48
+ export function discover(root,opts={}){
49
+ const seen=new Map();
50
+ for(const {dir,scope} of commandDirs(root,opts)){
51
+ for(const file of walk(dir)){
52
+ const rel=path.relative(dir,file).replace(/\.md$/,'');const parts=rel.split(path.sep);
53
+ let name=commandName(parts[parts.length-1]);if(!name||!/^[a-z]/.test(name))continue;
54
+ if(seen.has(name)&&parts.length>1)name=commandName(parts.join('-'));
55
+ if(seen.has(name))continue;
56
+ let text;try{text=readFileSync(file,'utf8')}catch{continue}
57
+ const {meta,body}=frontmatter(text);if(!body.trim())continue;
58
+ const first=body.trim().split('\n')[0].replace(/^#+\s*/,'').trim();
59
+ const description=(meta.description||first||'Custom command').replace(/[!]/g,'.').replace(/\p{Extended_Pictographic}/gu,'').slice(0,100).trim()||'Custom command';
60
+ seen.set(name,{name,file,scope,description,argumentHint:(meta['argument-hint']||'').slice(0,60),body});
61
+ }
62
+ }
63
+ return [...seen.values()];
64
+ }
65
+ /** Shell-like split: words, "double" and 'single' quoted groups. */
66
+ export function splitArgs(s){
67
+ const out=[];const re=/"((?:[^"\\]|\\.)*)"|'([^']*)'|(\S+)/g;let m;
68
+ while((m=re.exec(String(s||''))))out.push(m[1]!=null?m[1].replace(/\\(.)/g,'$1'):m[2]!=null?m[2]:m[3]);
69
+ return out;
70
+ }
71
+ export function expandBody(body,args=''){
72
+ const a=String(args||'').trim(),pos=splitArgs(a);
73
+ let used=false;
74
+ let text=String(body).replace(/\$ARGUMENTS\b|\$\{ARGUMENTS\}/g,()=>{used=true;return a}).replace(/\$([1-9])\b/g,(_,n)=>{used=true;return pos[Number(n)-1]??''});
75
+ if(!used&&a)text=text.replace(/\s*$/,'')+'\n\nArguments: '+a;
76
+ return text.trim();
77
+ }
78
+
79
+ const installed=new Set();
80
+ /**
81
+ * Registers the custom commands for a project (replacing earlier custom ones). Built-in names are left alone.
82
+ * `find` is the registry's find(); `unregister` removes the previous project's commands. Returns the registered names.
83
+ */
84
+ export function installCustom(register,{root,find,unregister,warn=()=>{}}={}){
85
+ for(const n of installed)unregister?.(n);
86
+ installed.clear();
87
+ const names=[];
88
+ for(const c of discover(root)){
89
+ const existing=find?.(c.name);
90
+ if(existing&&!existing.custom){warn('/'+c.name+' from '+c.file+' is a built-in command name; rename the file to use it.');continue}
91
+ try{
92
+ register({name:c.name,args:c.argumentHint||'[arguments]',summary:c.description+' ('+c.scope+')',custom:true,file:c.file,
93
+ run:async(_ctx,args)=>{let body=c.body;try{body=frontmatter(readFileSync(c.file,'utf8')).body||body}catch{}return {send:expandBody(body,args)}}});
94
+ installed.add(c.name);names.push(c.name);
95
+ }catch(e){warn('Could not add /'+c.name+': '+e.message)}
96
+ }
97
+ return names;
98
+ }
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Unified diffs for approvals: a line diff (Myers-style LCS on lines, bounded) between the text an edit removes and
3
+ * the text it puts in its place, rendered with +/- gutters, colors and changed-word emphasis.
4
+ */
5
+ import {wrap,width} from './ansi.mjs';
6
+
7
+ /** Line operations [{op:' '|'-'|'+', text}] turning a into b. Falls back to remove-all/add-all for huge inputs. */
8
+ export function diffLines(a,b){
9
+ const A=String(a??'').replace(/\n$/,'').split('\n'),B=String(b??'').replace(/\n$/,'').split('\n');
10
+ if(a==='')A.length=0;if(b==='')B.length=0;
11
+ if(A.length*B.length>4_000_000)return [...A.map(text=>({op:'-',text})),...B.map(text=>({op:'+',text}))];
12
+ const n=A.length,m=B.length;const L=Array.from({length:n+1},()=>new Uint32Array(m+1));
13
+ for(let i=n-1;i>=0;i--)for(let j=m-1;j>=0;j--)L[i][j]=A[i]===B[j]?L[i+1][j+1]+1:Math.max(L[i+1][j],L[i][j+1]);
14
+ const out=[];let i=0,j=0;
15
+ while(i<n&&j<m){if(A[i]===B[j]){out.push({op:' ',text:A[i]});i++;j++}else if(L[i+1][j]>=L[i][j+1])out.push({op:'-',text:A[i++]});else out.push({op:'+',text:B[j++]})}
16
+ while(i<n)out.push({op:'-',text:A[i++]});while(j<m)out.push({op:'+',text:B[j++]});
17
+ return out;
18
+ }
19
+ /** Keeps changes with `context` lines around them; long unchanged runs become a "... N unchanged lines" row. */
20
+ export function hunks(ops,context=3){
21
+ const keep=ops.map(()=>false);
22
+ ops.forEach((o,i)=>{if(o.op!==' ')for(let k=Math.max(0,i-context);k<=Math.min(ops.length-1,i+context);k++)keep[k]=true});
23
+ const out=[];let skipped=0;
24
+ ops.forEach((o,i)=>{if(keep[i]){if(skipped)out.push({op:'~',text:skipped+' unchanged line'+(skipped===1?'':'s')});skipped=0;out.push(o)}else skipped++});
25
+ if(skipped&&out.length)out.push({op:'~',text:skipped+' unchanged line'+(skipped===1?'':'s')});
26
+ return out;
27
+ }
28
+ /** Word-level emphasis for a removed/added pair that is mostly the same. */
29
+ function emphasize(oldLine,newLine,t){
30
+ const a=oldLine.split(/(\s+|\b)/),b=newLine.split(/(\s+|\b)/);
31
+ let p=0;while(p<a.length&&p<b.length&&a[p]===b[p])p++;
32
+ let s=0;while(s<a.length-p&&s<b.length-p&&a[a.length-1-s]===b[b.length-1-s])s++;
33
+ const mark=(parts,style)=>parts.slice(0,p).join('')+style(parts.slice(p,parts.length-s).join(''))+parts.slice(parts.length-s).join('');
34
+ return [mark(a,x=>t.bold(t.under(x))),mark(b,x=>t.bold(t.under(x)))];
35
+ }
36
+ /** Diff rows for the terminal, at most maxLines (the rest is summarized). */
37
+ export function renderDiff(oldText,newText,{t,cols=80,maxLines=80,path=null}={}){
38
+ const ops=hunks(diffLines(oldText,newText));
39
+ const adds=ops.filter(o=>o.op==='+').length,dels=ops.filter(o=>o.op==='-').length;
40
+ const rows=[];
41
+ if(path)rows.push(t.bold(path)+' '+t.add('+'+adds)+' '+t.del('-'+dels));
42
+ for(let i=0;i<ops.length;i++){
43
+ const o=ops[i];
44
+ let text=o.text.replace(/\t/g,' ');
45
+ if(o.op==='-'&&ops[i+1]?.op==='+'&&ops[i+2]?.op!=='+'&&(ops[i-1]?.op!=='-')){
46
+ const [x,y]=emphasize(text,ops[i+1].text.replace(/\t/g,' '),t);
47
+ pushRow(rows,'-',x,t,cols);pushRow(rows,'+',y,t,cols);i++;continue;
48
+ }
49
+ if(o.op==='~'){rows.push(t.dim(' ⋯ '+o.text));continue}
50
+ pushRow(rows,o.op,text,t,cols);
51
+ }
52
+ if(rows.length>maxLines){const more=rows.length-maxLines;return [...rows.slice(0,maxLines),t.dim(' ⋯ '+more+' more line'+(more===1?'':'s')+' (Ctrl-O shows all)')]}
53
+ return rows;
54
+ }
55
+ function pushRow(rows,op,text,t,cols){
56
+ const style=op==='+'?t.add:op==='-'?t.del:t.dim;
57
+ const parts=wrap(text,Math.max(10,cols-2));
58
+ parts.forEach((p,i)=>rows.push(style(i?' ':op+' ')+(op===' '?t.dim(p):style(p))));
59
+ }
60
+ export {width};