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,189 @@
1
+ /**
2
+ * Permission rules on the CLI side (/permissions, "always allow" in approvals). The engine enforces them in
3
+ * worker/mlai_permissions.py; this module validates, explains, suggests and matches rules with the same syntax:
4
+ *
5
+ * Bash | Bash(npm test) | Bash(npm test:*) | Bash(git * main)
6
+ * Edit(src/**) (Write, MultiEdit are aliases) Read(.env*) (Grep, Glob, LS are aliases)
7
+ * WebFetch(domain:example.com) WebSearch mcp__server | mcp__server__tool Connector(name) Agent
8
+ *
9
+ * deny > ask > allow. Allow rules and hooks from the committed project settings (.mlai/settings.json) only count
10
+ * once the user trusted that file (/permissions trust): a cloned repository must not approve its own commands.
11
+ * Deny and ask rules from any scope always count (they only make things safer).
12
+ */
13
+ import {createHash} from 'node:crypto';
14
+ import {readFileSync} from 'node:fs';
15
+ import {mkdir,readFile,writeFile,rename} from 'node:fs/promises';
16
+ import path from 'node:path';
17
+ import {home} from '../home.mjs';
18
+ import {settingsPaths} from '../settings.mjs';
19
+
20
+ export const KINDS=['allow','deny','ask'];
21
+ const ALIASES={bash:'Bash',shell:'Bash',edit:'Edit',write:'Edit',multiedit:'Edit',notebookedit:'Edit',read:'Read',grep:'Read',glob:'Read',ls:'Read',
22
+ webfetch:'WebFetch',fetch:'WebFetch',websearch:'WebSearch',connector:'Connector',agent:'Agent',task:'Agent'};
23
+ const RULE=/^\s*([A-Za-z][A-Za-z0-9_-]*)\s*(?:\(([\s\S]*)\))?\s*$/;
24
+
25
+ /** 'Bash(npm test:*)' -> {tool:'Bash', spec:'npm test:*'}; null when invalid. */
26
+ export function parseRule(rule){
27
+ if(typeof rule!=='string'||!rule.trim()||rule.length>500)return null;
28
+ const m=RULE.exec(rule);if(!m)return null;
29
+ const [,name,raw]=m;
30
+ if(/^mcp__/i.test(name)){const rest=name.slice(5);if(!/^[A-Za-z0-9][\w-]*(?:__[\w*.-]+)?$/.test(rest))return null;return {tool:'mcp',spec:rest+(raw?'__'+raw:'')}}
31
+ const tool=ALIASES[name.toLowerCase()];if(!tool)return null;
32
+ let spec=typeof raw==='string'?raw.trim():null;if(spec===''||spec==='*'||spec==='**')spec=null;
33
+ if(tool==='WebFetch'&&spec&&!spec.startsWith('domain:')){try{spec='domain:'+new URL(spec.includes('//')?spec:'https://'+spec).hostname}catch{return null}}
34
+ if((tool==='WebSearch'||tool==='Agent')&&spec)return null;
35
+ return {tool,spec};
36
+ }
37
+ /** Canonical spelling: 'write(src/**)' -> 'Edit(src/**)'. */
38
+ export function normalizeRule(rule){
39
+ const p=parseRule(rule);if(!p)return null;
40
+ if(p.tool==='mcp')return 'mcp__'+p.spec;
41
+ return p.spec==null?p.tool:p.tool+'('+p.spec+')';
42
+ }
43
+ /** Plain-English meaning, for /permissions. */
44
+ export function explainRule(rule){
45
+ const p=parseRule(rule);if(!p)return 'not a valid rule';
46
+ const s=p.spec;
47
+ switch(p.tool){
48
+ case 'Bash':return s==null?'every shell command':s.endsWith(':*')?'shell commands starting with "'+s.slice(0,-2).trim()+'"':/[*?[]/.test(s)?'shell commands matching "'+s+'"':'the shell command "'+s+'"';
49
+ case 'Edit':return s==null?'every file edit':'edits to '+s;
50
+ case 'Read':return s==null?'every file read':'reads of '+s;
51
+ case 'WebFetch':return s==null?'every web fetch':'web fetches from '+s.slice(7)+' and its subdomains';
52
+ case 'WebSearch':return 'web searches';
53
+ case 'Agent':return 'starting helper agents';
54
+ case 'Connector':return s==null?'every connected-app tool':'the connected-app tool '+s;
55
+ case 'mcp':{const [srv,tool]=s.split('__');return tool?'the MCP tool '+tool+' of '+srv:'every tool of the MCP server '+srv}
56
+ }
57
+ return rule;
58
+ }
59
+
60
+ const norm=s=>String(s).trim().split(/\s+/).join(' ');
61
+ const glob=(pat)=>new RegExp('^'+pat.split(/(\*\*\/?|\*|\?)/).map(t=>t==='**/'?'(?:.*/)?':t==='**'?'.*':t==='*'?'[^/]*':t==='?'?'[^/]':t.replace(/[.+^${}()|[\]\\]/g,'\\$&')).join('')+'$');
62
+ /** Shell segments (&&, ||, ;, |, newlines), leading sudo/env assignments removed. Mirrors mlai_hooks.segments roughly. */
63
+ export function segments(command){
64
+ const text=String(command||'');const inner=[...text.matchAll(/\$\(([^()]*)\)/g)].map(m=>m[1]).concat([...text.matchAll(/`([^`]*)`/g)].map(m=>m[1]));
65
+ const out=[];
66
+ for(const chunk of [text,...inner])for(let s of chunk.split(/&&|\|\||;|\n|\|/)){
67
+ s=s.trim().replace(/^\(+/,'').replace(/\)+$/,'').trim().replace(/^(?:sudo|command|exec|nohup|time|xargs)\s+/,'').replace(/^(?:[A-Za-z_]\w*=\S*\s+)+/,'');
68
+ if(s)out.push(s);
69
+ }
70
+ return out;
71
+ }
72
+ export function commandMatch(command,spec){
73
+ const c=norm(command);if(spec==null)return true;const s=norm(spec);
74
+ if(s.endsWith(':*')){const p=s.slice(0,-2).trimEnd();return c===p||c.startsWith(p+' ')}
75
+ if(/[*?[]/.test(s))return glob(s.replace(/\//g,'\u0000')).test(c.replace(/\//g,'\u0000'));
76
+ return c===s;
77
+ }
78
+ function pathGlobs(spec){
79
+ let s=String(spec||'').trim();if(!s)return [];
80
+ let base;
81
+ if(s.startsWith('//'))base=[s.slice(1)];else if(s.startsWith('~'))base=[s];else if(s.startsWith('/'))base=[s.slice(1)];else if(s.startsWith('./'))base=[s.slice(2)];
82
+ else if(!s.replace(/\/$/,'').includes('/'))base=[s.replace(/\/$/,''),'**/'+s.replace(/\/$/,'')];else base=[s.replace(/\/$/,'')];
83
+ return base.flatMap(b=>b.endsWith('**')?[b]:[b,b+'/**']);
84
+ }
85
+ export function pathMatch(file,spec,{root='',homeDir=process.env.HOME||''}={}){
86
+ let f=String(file||'');if(f.startsWith('~'))f=homeDir+f.slice(1);
87
+ // Globs use '/', so Windows paths are compared with their separators turned around.
88
+ const R=root?path.resolve(root):'',slash=p=>p.split(path.sep).join('/');
89
+ const abs=path.isAbsolute(f)?path.resolve(f):path.resolve(R||'/',f);
90
+ const rel=R&&(abs===R||abs.startsWith(R.endsWith(path.sep)?R:R+path.sep))?slash(path.relative(R,abs)):null;
91
+ return pathGlobs(spec).some(g=>{const q=g.startsWith('~')?homeDir+g.slice(1):g;return path.isAbsolute(q)?glob(slash(path.resolve(q))).test(slash(abs)):rel!=null&&glob(q).test(rel)});
92
+ }
93
+ function hostMatch(url,spec){
94
+ if(!spec)return true;let want=spec.replace(/^domain:/,'').toLowerCase().replace(/^\*?\./,'');let host='';
95
+ try{host=new URL(String(url).includes('//')?url:'https://'+url).hostname.toLowerCase()}catch{return false}
96
+ return !!host&&(host===want||host.endsWith('.'+want));
97
+ }
98
+ /** subjects: [{kind:'Bash'|'Edit'|'Read'|'WebFetch'|'WebSearch'|'mcp'|'Connector'|'Agent', value}] */
99
+ export function ruleHits(rule,subject,opts){
100
+ const p=typeof rule==='string'?parseRule(rule):rule;if(!p)return false;
101
+ const {kind,value}=subject;
102
+ if(p.tool==='mcp'){if(kind!=='mcp')return false;const s=p.spec.replace(/__\*$/,'');return value===s||String(value).startsWith(s+'__')||glob(s).test(value)}
103
+ if(p.tool!==kind)return false;
104
+ if(kind==='Bash')return commandMatch(value,p.spec);
105
+ if(kind==='Edit'||kind==='Read')return p.spec==null||pathMatch(value,p.spec,opts);
106
+ if(kind==='WebFetch')return hostMatch(value,p.spec);
107
+ if(kind==='Connector')return p.spec==null||glob(p.spec).test(value);
108
+ return p.spec==null;
109
+ }
110
+ const HARMLESS=/\s*(?:\d*>&\d+|&>\s*\/dev\/null|\d*>>?\s*\/dev\/null)/g;
111
+ /** {decision:'deny'|'ask'|'allow'|null, rule}. Same order as the engine: deny, then ask, then allow (every segment). */
112
+ export function decide(rules,subjects,opts={}){
113
+ const any=(list,s)=>{
114
+ for(const r of list||[]){
115
+ if(s.kind==='Bash'){if(ruleHits(r,s,opts)||segments(s.value).some(seg=>ruleHits(r,{kind:'Bash',value:seg},opts)))return r}
116
+ else if(ruleHits(r,s,opts))return r;
117
+ }
118
+ return null;
119
+ };
120
+ for(const s of subjects){const r=any(rules.deny,s);if(r)return {decision:'deny',rule:r}}
121
+ for(const s of subjects){const r=any(rules.ask,s);if(r)return {decision:'ask',rule:r}}
122
+ if(rules.allow?.length&&subjects.length){
123
+ const hits=subjects.map(s=>{
124
+ if(s.kind!=='Bash')return (rules.allow||[]).find(r=>ruleHits(r,s,opts))||null;
125
+ const every=(rules.allow||[]).find(r=>normalizeRule(r)==='Bash');if(every)return every;
126
+ const v=String(s.value).replace(HARMLESS,'');if(/>|\btee\b/.test(v))return null;
127
+ const segs=segments(v);let first=null;
128
+ for(const seg of segs.length?segs:[v]){const r=(rules.allow||[]).find(x=>ruleHits(x,{kind:'Bash',value:seg},opts));if(!r)return null;first??=r}
129
+ return first;
130
+ });
131
+ if(hits.every(Boolean))return {decision:'allow',rule:hits[0]};
132
+ }
133
+ return {decision:null,rule:null};
134
+ }
135
+
136
+ const RUNNERS=new Set(['npm','pnpm','yarn','npx','bun','git','cargo','go','uv','poetry','docker','kubectl','make','gh']);
137
+ /**
138
+ * An "always allow" rule for an approval: {kind, command, path, url, name} -> 'Bash(npm test:*)' | 'Edit(src/**)' | ...
139
+ * Returns null when no narrow rule fits (then the TUI offers only "approve once").
140
+ */
141
+ export function suggestRule({kind,command,path:file,url,name}={}){
142
+ const cmd=typeof command==='string'?command:'';
143
+ const edit=/^(Edit|Write)\s+(\S+)/.exec(cmd);
144
+ if(kind==='edit'||kind==='scope'||file||edit){
145
+ const f=String(file||edit?.[2]||'').replace(/^\.\//,'');if(!f||f.startsWith('/')||f.startsWith('..'))return null;
146
+ const dir=path.posix.dirname(f.split(path.sep).join('/'));return dir&&dir!=='.'?'Edit('+dir+'/**)':'Edit('+f+')';
147
+ }
148
+ if(url){try{return 'WebFetch(domain:'+new URL(url).hostname+')'}catch{return null}}
149
+ if(kind==='integration'&&name)return 'Connector('+name+')';
150
+ if(/^mcp__/.test(String(name||'')))return String(name).split('__').slice(0,3).join('__');
151
+ if(!cmd.trim()||cmd.includes('\n'))return null;
152
+ const segs=segments(cmd);if(segs.length!==1)return null;
153
+ const words=segs[0].split(/\s+/);const w0=words[0];
154
+ if(!/^[\w.@/+-]+$/.test(w0)||/^(rm|sudo|dd|mkfs|chmod|chown|curl|wget|ssh|scp|bash|sh|zsh|eval|env)$/.test(w0))return null;
155
+ if(w0==='python'||w0==='python3'){return words[1]==='-m'&&words[2]?'Bash('+words.slice(0,3).join(' ')+':*)':null}
156
+ if(RUNNERS.has(w0)&&words[1]&&/^[\w:.-]+$/.test(words[1])){
157
+ if(w0==='npm'&&words[1]==='run'&&words[2])return 'Bash(npm run '+words[2]+':*)';
158
+ return 'Bash('+w0+' '+words[1]+':*)';
159
+ }
160
+ return 'Bash('+w0+':*)';
161
+ }
162
+
163
+ // ------------------------------------------------------------------ scopes and trust
164
+ export function digest(v){return createHash('sha256').update(JSON.stringify(v??null)).digest('hex').slice(0,24)}
165
+ const trustFile=()=>path.join(home(),'trust.json');
166
+ function readTrust(){try{const v=JSON.parse(readFileSync(trustFile(),'utf8'));return v&&typeof v==='object'?v:{}}catch{return {}}}
167
+ /** Has the user trusted this part ('permissions' | 'hooks') of a project, with exactly this content? */
168
+ export function isTrusted(root,part,value){const t=readTrust();return !!root&&t.projects?.[root]?.[part]===digest(value)}
169
+ export async function setTrusted(root,part,value){
170
+ const t=readTrust();t.projects={...(t.projects||{})};t.projects[root]={...(t.projects[root]||{}),[part]:value===undefined?undefined:digest(value)};
171
+ await mkdir(home(),{recursive:true});const f=trustFile(),tmp=f+'.'+process.pid+'.tmp';
172
+ await writeFile(tmp,JSON.stringify(t,null,2)+'\n',{mode:0o600});await rename(tmp,f);
173
+ }
174
+ /** One settings layer as written on disk (no merging), {} when missing or invalid. */
175
+ export function readLayer(root,scope){
176
+ const f=settingsPaths(root)[scope];if(!f)return {};
177
+ try{const v=JSON.parse(readFileSync(f,'utf8'));return v&&typeof v==='object'&&!Array.isArray(v)?v:{}}catch{return {}}
178
+ }
179
+ const list=(v)=>Array.isArray(v)?v.filter(x=>typeof x==='string'&&parseRule(x)):[];
180
+ /** Rules by scope: {user:{allow,deny,ask}, project:{...}, local:{...}}, plus which ones the engine gets. */
181
+ export function scopedRules(root,{flags=null}={}){
182
+ const by={};
183
+ for(const s of ['user','project','local']){const p=readLayer(root,s).permissions||{};by[s]={allow:list(p.allow),deny:list(p.deny),ask:list(p.ask)}}
184
+ if(flags)by.flag={allow:list(flags.allow),deny:list(flags.deny),ask:list(flags.ask)};
185
+ const projectTrusted=!by.project.allow.length||isTrusted(root,'permissions',by.project.allow);
186
+ const uniq=a=>[...new Set(a.map(normalizeRule).filter(Boolean))];
187
+ const all=k=>uniq(Object.entries(by).flatMap(([s,r])=>k==='allow'&&s==='project'&&!projectTrusted?[]:r[k]));
188
+ return {by,projectTrusted,effective:{allow:all('allow'),deny:all('deny'),ask:all('ask')}};
189
+ }
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Plain-terminal UI for commands (CLI v1 shared contract): the ctx.ui methods over a line reader, used when there is
3
+ * no TTY, with TERM=dumb, in tests, and as the fallback for anything the full TUI does not override.
4
+ * `ask(question)` reads one line (null at end of input); `write(text)` prints.
5
+ */
6
+ export function plainUi({write=t=>process.stdout.write(t),writeErr=t=>process.stderr.write(t),ask=async()=>null,theme='dark',color=null}={}){
7
+ const c=color||{dim:s=>s,bold:s=>s,red:s=>s,yellow:s=>s,cyan:s=>s};
8
+ const ui={
9
+ theme,
10
+ print:t=>write(String(t)+'\n'),
11
+ error:t=>writeErr(c.yellow(String(t))+'\n'),
12
+ async input(question,{default:d=null}={}){const a=await ask(question+(d!=null?' ['+d+']':'')+' ');return a==null?null:(a.trim()||d)},
13
+ async confirm(question,{default:d=false}={}){
14
+ const a=await ask(question+(d?' [Y/n] ':' [y/N] '));if(a==null)return d;
15
+ const v=a.trim().toLowerCase();return v?v==='y'||v==='yes':d;
16
+ },
17
+ /** items: strings or {label, detail?, value?}. Numbered list; type a number or a filter word. */
18
+ async pick(items,{title='Choose',filter=''}={}){
19
+ const rows=items.map(i=>typeof i==='string'?{label:i,value:i}:i);
20
+ let shown=rows;const q=String(filter||'').toLowerCase();
21
+ if(q)shown=rows.filter(r=>(r.label+' '+(r.detail||'')).toLowerCase().includes(q));
22
+ if(!shown.length){ui.error('Nothing matches '+filter+'.');return null}
23
+ write(c.bold(title)+'\n');
24
+ shown.slice(0,50).forEach((r,i)=>write(' '+String(i+1).padStart(2)+'. '+r.label+(r.detail?' '+c.dim(r.detail):'')+'\n'));
25
+ const a=await ask('Number (Enter to cancel): ');if(a==null||!a.trim())return null;
26
+ const n=Number(a.trim());if(Number.isInteger(n)&&n>=1&&n<=shown.length)return shown[n-1];
27
+ const m=shown.filter(r=>r.label.toLowerCase().includes(a.trim().toLowerCase()));return m.length===1?m[0]:null;
28
+ },
29
+ setSession(){},setMode(){},status:()=>({}),
30
+ };
31
+ return ui;
32
+ }
@@ -0,0 +1,103 @@
1
+ /**
2
+ * Plugins loaded for one run from the command line, without installing them in the account:
3
+ * --plugin-dir <folder> a plugin folder on this computer (repeatable)
4
+ * --plugin-url <git url> a plugin repository, checked out once into ~/.mlai/plugin-cache (repeatable;
5
+ * https://host/repo(.git)[#subfolder], git@host:repo or file:// for local repositories)
6
+ * A plugin folder uses the same layout as installed plugins (lib/plugins.ts) and other coding agents:
7
+ * mlai-plugin.json | .claude-plugin/plugin.json | plugin.json name, description, version, and optional hooks/mcpServers
8
+ * skills/<name>/SKILL.md agents/<name>.md commands/<name>.md hooks/hooks.json .mcp.json
9
+ * Skills, agents and commands are read by skills-local, agents-local and custom-commands. This module adds the hooks
10
+ * and MCP servers. The user passed the folder explicitly, so its hooks and servers run like their own settings;
11
+ * ${CLAUDE_PLUGIN_ROOT} and ${MLAI_PLUGIN_ROOT} in commands become the folder's path.
12
+ */
13
+ import {readFileSync,existsSync,lstatSync} from 'node:fs';
14
+ import {mkdir,rm} from 'node:fs/promises';
15
+ import {execFile} from 'node:child_process';
16
+ import {promisify} from 'node:util';
17
+ import {createHash} from 'node:crypto';
18
+ import path from 'node:path';
19
+ import {home} from '../home.mjs';
20
+ import {hooksFromSettings} from './extensions-local.mjs';
21
+ import {extState} from './ext-state.mjs';
22
+
23
+ const run=promisify(execFile);
24
+ const isObj=v=>v!==null&&typeof v==='object'&&!Array.isArray(v);
25
+ const readJson=f=>{try{return JSON.parse(readFileSync(f,'utf8'))}catch{return null}};
26
+
27
+ /** {id, name, version, description, dir, manifest} for a plugin folder; throws when the folder is not a plugin. */
28
+ export function readPlugin(dir){
29
+ const abs=path.resolve(dir);
30
+ let st;try{st=lstatSync(abs)}catch{throw new Error('--plugin-dir: no folder '+abs)}
31
+ if(!st.isDirectory())throw new Error('--plugin-dir: '+abs+' is not a folder');
32
+ const file=['mlai-plugin.json',path.join('.claude-plugin','plugin.json'),'plugin.json'].map(f=>path.join(abs,f)).find(f=>existsSync(f));
33
+ const manifest=file?readJson(file):{};
34
+ if(file&&!isObj(manifest))throw new Error(path.relative(abs,file)+' in '+abs+' is not valid JSON');
35
+ const has=p=>existsSync(path.join(abs,p));
36
+ if(!file&&!has('skills')&&!has('agents')&&!has('commands')&&!has('hooks')&&!has('.mcp.json'))throw new Error(abs+' has no plugin manifest (mlai-plugin.json or .claude-plugin/plugin.json) and no skills, agents, commands or hooks folder');
37
+ const name=String(manifest.name||manifest.id||path.basename(abs)).slice(0,80);
38
+ const id=name.toLowerCase().replace(/[^a-z0-9]+/g,'-').replace(/^-+|-+$/g,'').slice(0,60)||'plugin';
39
+ return {id,name,version:String(manifest.version||'0.0.0').slice(0,40),description:String(manifest.description||'').slice(0,300),dir:abs,manifest};
40
+ }
41
+ const rootRef=/\$\{?(CLAUDE_PLUGIN_ROOT|MLAI_PLUGIN_ROOT)\}?/g;
42
+ // Hooks run in sh, or cmd/PowerShell on Windows, where single quotes do not quote and C:\ paths are plain words.
43
+ const quote=s=>process.platform==='win32'?(/^[\w.:\\~/-]+$/.test(s)?s:'"'+s+'"'):/^[\w./-]+$/.test(s)?s:"'"+s.replace(/'/g,"'\\''")+"'";
44
+ const withRoot=(v,dir)=>typeof v==='string'?v.replace(rootRef,quote(dir)):v;
45
+
46
+ /** Hooks and MCP servers a plugin folder adds: {hooks, mcpServers, warnings}. */
47
+ export function pluginParts(p){
48
+ const warnings=[],hooks=[],mcpServers={};
49
+ const hookSrc=p.manifest.hooks&&typeof p.manifest.hooks==='object'?p.manifest.hooks:readJson(path.join(p.dir,'hooks','hooks.json'));
50
+ if(hookSrc){
51
+ const map=Array.isArray(hookSrc)?null:isObj(hookSrc.hooks)?hookSrc.hooks:hookSrc;
52
+ const fixed=map?Object.fromEntries(Object.entries(map).map(([ev,groups])=>[ev,(Array.isArray(groups)?groups:[]).map(g=>isObj(g)?{...g,...(g.command?{command:withRoot(g.command,p.dir)}:{}),...(Array.isArray(g.hooks)?{hooks:g.hooks.map(h=>isObj(h)?{...h,command:withRoot(h.command,p.dir)}:h)}:{})}:g)])):{};
53
+ const r=hooksFromSettings(fixed,{source:'local'});
54
+ hooks.push(...r.hooks.map(h=>({...h,name:(p.name+': '+h.name).slice(0,80)})));warnings.push(...r.warnings.map(w=>p.name+': '+w));
55
+ }
56
+ const mcpSrc=isObj(p.manifest.mcpServers)?p.manifest.mcpServers:readJson(path.join(p.dir,'.mcp.json'));
57
+ const servers=isObj(mcpSrc?.mcpServers)?mcpSrc.mcpServers:isObj(mcpSrc)?mcpSrc:{};
58
+ for(const [name,spec] of Object.entries(servers)){
59
+ if(!isObj(spec))continue;
60
+ mcpServers[name]={...spec,...(spec.command?{command:withRoot(spec.command,p.dir)}:{}),...(Array.isArray(spec.args)?{args:spec.args.map(a=>withRoot(a,p.dir))}:{}),...(spec.command&&!spec.cwd?{cwd:p.dir}:{})};
61
+ }
62
+ return {hooks,mcpServers,warnings};
63
+ }
64
+
65
+ /** Where a --plugin-url repository is checked out. */
66
+ export function cacheDir(url){return path.join(home(),'plugin-cache',createHash('sha256').update(url).digest('hex').slice(0,16))}
67
+ export function parsePluginUrl(input){
68
+ const [url,sub='']=String(input||'').split('#');
69
+ if(!/^(https:\/\/|file:\/\/|git@[\w.-]+:)/.test(url)||/\s/.test(url))throw new Error('--plugin-url takes a git repository: https://host/owner/repo[#subfolder] (or git@host:owner/repo, file:///path)');
70
+ if(sub&&(sub.split('/').includes('..')||path.isAbsolute(sub)))throw new Error('--plugin-url: the #subfolder must stay inside the repository');
71
+ return {url,sub};
72
+ }
73
+ /** Checks out (or updates) a plugin repository and returns the plugin folder. */
74
+ export async function fetchPluginUrl(input,{timeout=120000}={}){
75
+ const {url,sub}=parsePluginUrl(input);
76
+ const dir=cacheDir(url),env={...process.env,GIT_TERMINAL_PROMPT:'0'};
77
+ await mkdir(path.dirname(dir),{recursive:true,mode:0o700});
78
+ if(existsSync(path.join(dir,'.git'))){
79
+ try{await run('git',['-C',dir,'pull','--ff-only','--quiet'],{timeout,env})}catch{/* offline: keep the copy we have */}
80
+ }else{
81
+ await rm(dir,{recursive:true,force:true});
82
+ try{await run('git',['clone','--depth','1','--quiet',url,dir],{timeout,env})}
83
+ catch(e){throw new Error('Could not fetch the plugin '+url+': '+String(e.stderr||e.message).trim().split('\n').pop())}
84
+ }
85
+ const target=sub?path.join(dir,sub):dir;
86
+ readPlugin(target);
87
+ return target;
88
+ }
89
+
90
+ /** Fetches --plugin-url repositories and reads every plugin folder into extState (once, at startup). */
91
+ export async function loadPlugins({warn=()=>{}}={}){
92
+ for(const u of extState.pluginUrls){
93
+ const dir=await fetchPluginUrl(u);if(!extState.pluginDirs.includes(dir))extState.pluginDirs.push(dir);
94
+ }
95
+ extState.plugins=[];extState.pluginServers=[];
96
+ for(const d of extState.pluginDirs){
97
+ const p=readPlugin(d),parts=pluginParts(p);
98
+ for(const w of parts.warnings)warn(w);
99
+ extState.plugins.push({id:p.id,name:p.name,version:p.version,description:p.description,dir:p.dir,hooks:parts.hooks});
100
+ if(Object.keys(parts.mcpServers).length)extState.pluginServers.push({id:p.id,servers:parts.mcpServers});
101
+ }
102
+ return extState.plugins;
103
+ }
@@ -0,0 +1,125 @@
1
+ /**
2
+ * Remote control for a terminal session (`mlai remote-control`, `mlai --rc`, `/remote-control`): the live session
3
+ * becomes a chat in the web app and on the phone ("On <this computer>"), driven through the same laptop relay as the
4
+ * Mac app (src/relay.mjs on this side, /api/laptop/relay on the server). The work stays in this terminal.
5
+ *
6
+ * Only the signed-in account can reach it: the relay checks this computer's device credential and the browser's
7
+ * account session, and the chat is only listed for that account. Messages from another device run as turns here
8
+ * (they show in the terminal like typed ones); approvals can be answered here or there, whichever comes first;
9
+ * stop and steer work from both. Everything else (status, diff, files, history, checkpoints, git) is answered by
10
+ * the local workspace API from the session folder, so the web shows the same view as for a Mac app chat.
11
+ */
12
+ import {EventEmitter} from 'node:events';
13
+
14
+ /** Engine run modes from the web (lib/run-request.ts) to the terminal's modes. */
15
+ const WEB_MODE={approve:'agent',auto:'auto',plan:'plan',brief:'agent'};
16
+ const UUID=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;
17
+
18
+ /** The chat's relay identity: the local token and the account workspace name the server knows it by. */
19
+ export function remoteIdentity(session){
20
+ const m=session?.meta||{};const project=m.cloudProject||m.project;
21
+ if(!UUID.test(String(m.id||''))||!UUID.test(String(project||'')))return null;
22
+ return {token:'local-'+m.id,name:'mini-'+project,title:m.title||m.folder||'Terminal session',root:m.root,folder:m.folder};
23
+ }
24
+ /** Where the chat opens on the web (and on a phone, which uses the same address). */
25
+ export function remoteUrl(server,name){return String(server||'').replace(/\/$/,'')+'/?chat='+encodeURIComponent(name)}
26
+
27
+ /**
28
+ * The workspace interface src/relay.mjs drives ({list, call, on}), for the one live terminal session.
29
+ * chat: tui/chat.mjs Chat. ctx: its command context (ui.queue runs a turn the way the terminal shows it).
30
+ * ws: the local workspace API (src/workspace-api.mjs) for read-only views and approvals.
31
+ */
32
+ export function remoteWorkspaces({chat,ctx,ws,note=()=>{}}){
33
+ const events=new EventEmitter();
34
+ const id=()=>remoteIdentity(chat.session);
35
+ const changed=()=>{const i=id();if(i)events.emit('change',{token:i.token})};
36
+ let bound=null;
37
+ const bind=s=>{if(bound)bound.off('event',changed);bound=s;s?.on?.('event',changed)};
38
+ bind(chat.session);
39
+ const onSession=s=>{bind(s);changed()};
40
+ chat.on('change',changed);chat.on('session',onSession);chat.on('turn',changed);
41
+ const mine=token=>{const i=id();if(!i||token!==i.token)throw Object.assign(new Error('This chat is not open in the terminal anymore.'),{status:404,code:'workspace_missing'});return i};
42
+
43
+ async function run(b,{resume=false}={}){
44
+ let task=resume?'Continue where you left off.':b.task;
45
+ if(typeof task!=='string'||!task.trim())throw Object.assign(new Error('Enter a task'),{status:400});
46
+ task=task.trim();if(task.length>30000)throw Object.assign(new Error('Enter a task under 30,000 characters'),{status:400});
47
+ // The web's choices for this turn apply here too (between turns only; a running turn keeps its own).
48
+ if(!chat.running){
49
+ const m=WEB_MODE[b.mode];if(m&&m!==chat.mode)await ctx.ui.setMode(m);
50
+ if(typeof b.model==='string'&&b.model&&b.model!==chat.model)await chat.setModel(b.model).catch(()=>{});
51
+ if(['low','medium','high'].includes(b.effort)&&b.effort!==chat.effort)await chat.setEffort(b.effort).catch(()=>{});
52
+ }
53
+ const busy=chat.running;
54
+ note((busy?'Queued from another device: ':'From another device: ')+task.split('\n')[0].slice(0,200));
55
+ // ui.queue waits for the current turn, then runs this one exactly like a typed message.
56
+ Promise.resolve(ctx.ui.queue(task)).catch(e=>note('That message from another device did not run: '+(e?.message||e)));
57
+ return {ok:true,queued:busy};
58
+ }
59
+
60
+ return {
61
+ async list(){const i=id();return i?[{...i,state:chat.running?'running':'idle'}]:[]},
62
+ async call(token,action,body={}){
63
+ const b=body&&typeof body==='object'?body:{};
64
+ const i=mine(token);
65
+ if(action==='run')return run(b);
66
+ if(action==='resume')return run(b,{resume:true});
67
+ if(action==='steer'){
68
+ const msg=String(b.message||'').trim();if(!msg)throw Object.assign(new Error('Enter an instruction'),{status:400});
69
+ if(!chat.running)throw Object.assign(new Error('Wait for the task to start before sending an instruction.'),{status:409});
70
+ await chat.session.steer(msg.slice(0,4000));note('Instruction from another device: '+msg.split('\n')[0].slice(0,200));return {ok:true};
71
+ }
72
+ if(action==='stop'){await chat.session.cancel();note('Stopped from another device.');return {ok:true}}
73
+ if(action==='approve'){
74
+ const r=await ws.call(i.token,'approve',b);
75
+ // The card in the terminal closes; the run continues with the answer from the other device.
76
+ ctx.ui.dismissApproval?.(String(b.id));
77
+ note(b.approved?'Approved from another device.':'Declined from another device.');
78
+ return r;
79
+ }
80
+ return ws.call(i.token,action,b);
81
+ },
82
+ on(ev,fn){events.on(ev,fn);return ()=>events.off(ev,fn)},
83
+ close(){chat.off('change',changed);chat.off('session',onSession);chat.off('turn',changed);bind(null);events.removeAllListeners()},
84
+ };
85
+ }
86
+
87
+ /**
88
+ * Turns remote control on for a chat. Returns {stop, url, name}. One per chat (chat.remote); calling again returns
89
+ * the running one. deps (tests): createWorkspaces, startRelay.
90
+ */
91
+ export async function startRemote(o){
92
+ const chat=o.chat;if(chat.remote)return chat.remote;
93
+ // Two starts at once (the --rc banner and a quick /remote-control) share one relay.
94
+ if(!chat.remoteStarting)chat.remoteStarting=begin(o).finally(()=>{chat.remoteStarting=null});
95
+ return chat.remoteStarting;
96
+ }
97
+ async function begin({chat,ctx,cloud,server,device,deps={}}){
98
+ if(!cloud?.device?.request)throw new Error('Sign in first: run `mlai login`, then try again.');
99
+ const i=remoteIdentity(chat.session);if(!i)throw new Error('This session cannot be shared yet. Send a first message, then try again.');
100
+ const createWorkspaces=deps.createWorkspaces||(await import('../workspace-api.mjs')).createLocalWorkspaces;
101
+ const startRelay=deps.startRelay||(await import('../relay.mjs')).startRelay;
102
+ const ws=createWorkspaces({cloud,wakeups:false,...(device?{device}:{})});
103
+ const note=t=>{try{ctx.out(t)}catch{}};
104
+ const adapter=remoteWorkspaces({chat,ctx,ws,note});
105
+ // The account learns about the chat (it shows in the web list as "On <this computer>"), then after every turn.
106
+ const sync=()=>{const n=remoteIdentity(chat.session);if(n)Promise.resolve(ws.syncView?.(n.token)).catch(()=>{})};
107
+ sync();
108
+ chat.on('turn',sync);chat.on('session',sync);
109
+ const relay=startRelay({workspaces:adapter,getCloud:async()=>cloud});
110
+ const remote={
111
+ name:i.name,url:remoteUrl(server||cloud.server,i.name),
112
+ async stop(){chat.off('turn',sync);chat.off('session',sync);await relay.stop();adapter.close();await ws.close?.();if(chat.remote===remote)chat.remote=null},
113
+ };
114
+ chat.remote=remote;
115
+ return remote;
116
+ }
117
+ export async function stopRemote(chat){if(chat?.remote)await chat.remote.stop()}
118
+
119
+ /** What the terminal prints when remote control turns on. */
120
+ export function remoteBanner(r){
121
+ return ['Remote control is on. Continue this session from the web or your phone:',' '+r.url,
122
+ 'Only your account can see it. Messages, approvals, stop and steer work from there.',
123
+ 'The work stays on this computer.',
124
+ 'Turn it off with /remote-control off.'].join('\n');
125
+ }