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,151 @@
1
+ /**
2
+ * /import: brings an existing Claude Code or Cursor setup into ML AI Code settings, so the same rules, MCP servers,
3
+ * hooks, commands and agents apply here. Nothing is removed from the other tool's files.
4
+ * Claude Code ~/.claude/settings.json -> user, .claude/settings.json -> project, .claude/settings.local.json -> local
5
+ * (permissions allow/deny/ask, hooks); ~/.claude.json mcpServers -> ~/.mlai/mcp.json, and its entry for
6
+ * this folder -> local settings
7
+ * Cursor ~/.cursor/cli-config.json -> user, .cursor/cli.json -> project (permissions: Shell(x) -> Bash(x:*),
8
+ * Write(x) -> Edit(x), MCP(server:tool) -> mcp__server__tool); ~/.cursor/mcp.json -> ~/.mlai/mcp.json
9
+ * Already used as they are (reported, not copied): CLAUDE.md, .cursor/rules and .cursorrules (project rules),
10
+ * .mcp.json and .cursor/mcp.json, .claude/commands and .cursor/commands, .claude/agents, .claude/skills.
11
+ */
12
+ import {readFileSync,existsSync} from 'node:fs';
13
+ import {readFile,writeFile,mkdir,rename} from 'node:fs/promises';
14
+ import path from 'node:path';
15
+ import {home} from '../home.mjs';
16
+ import {saveSetting} from '../settings.mjs';
17
+ import {normalizeRule,readLayer,isTrusted,setTrusted} from './permissions.mjs';
18
+ import {hooksFromSettings} from './extensions-local.mjs';
19
+ import {NAME} from './mcp-config.mjs';
20
+
21
+ const isObj=v=>v!==null&&typeof v==='object'&&!Array.isArray(v);
22
+ const readJson=f=>{try{return JSON.parse(readFileSync(f,'utf8'))}catch{return null}};
23
+ const KINDS=['allow','deny','ask'];
24
+
25
+ /** Cursor CLI rule -> our rule (null when it has no equivalent). */
26
+ export function cursorRule(r){
27
+ const m=/^\s*(\w+)\s*\(([\s\S]*)\)\s*$/.exec(String(r||''));
28
+ if(!m)return normalizeRule(r);
29
+ const [,tool,spec]=m;const s=spec.trim();
30
+ switch(tool.toLowerCase()){
31
+ case 'shell':return s===''||s==='*'?'Bash':normalizeRule('Bash('+(s.endsWith(':*')||/[*?]/.test(s)?s:s+':*')+')');
32
+ case 'read':return normalizeRule('Read('+s+')');
33
+ case 'write':return normalizeRule('Edit('+s+')');
34
+ case 'webfetch':return normalizeRule('WebFetch('+s+')');
35
+ case 'mcp':{const [srv,t]=s.split(':');if(!srv||!/^[\w-]+$/.test(srv))return null;return t&&t!=='*'?normalizeRule('mcp__'+srv+'__'+t):normalizeRule('mcp__'+srv)}
36
+ }
37
+ return normalizeRule(r);
38
+ }
39
+
40
+ function rulesFrom(perm,convert,from){
41
+ const out={allow:[],deny:[],ask:[]},skipped=[];
42
+ if(!isObj(perm))return {rules:out,skipped};
43
+ for(const k of KINDS)for(const r of Array.isArray(perm[k])?perm[k]:[]){const n=convert(r);if(n)out[k].push(n);else skipped.push(from+': '+r)}
44
+ return {rules:out,skipped};
45
+ }
46
+ const newRules=(have,add)=>{const o={};for(const k of KINDS){const h=new Set((have?.[k]||[]).map(normalizeRule));const n=[...new Set(add[k])].filter(r=>!h.has(r));if(n.length)o[k]=n}return o};
47
+ const count=r=>KINDS.reduce((a,k)=>a+(r[k]?.length||0),0);
48
+
49
+ /**
50
+ * What /import would do: {items:[{kind, scope, from, to, summary, apply()}], used:[text], skipped:[text]}.
51
+ * which: 'claude' | 'cursor' | 'all'. homeDir: the user's home folder (tests).
52
+ */
53
+ export function planImport(root,{which='all',homeDir=null}={}){
54
+ const h=homeDir||path.dirname(home());const items=[],used=[],skipped=[];
55
+ const want=w=>which==='all'||which===w;
56
+ const rel=f=>f.startsWith(h+path.sep)?'~/'+path.relative(h,f):root&&f.startsWith(root+path.sep)?path.relative(root,f):f;
57
+ const addPerms=(scope,file,perm,convert,tool)=>{
58
+ if(scope!=='user'&&!root)return;
59
+ const {rules,skipped:sk}=rulesFrom(perm,convert,rel(file));skipped.push(...sk);
60
+ const cur=readLayer(root,scope).permissions||{};const add=newRules(cur,rules);
61
+ if(!count(add))return;
62
+ items.push({kind:'permissions',scope,from:rel(file),summary:count(add)+' permission rule'+(count(add)===1?'':'s')+' ('+KINDS.filter(k=>add[k]).map(k=>add[k].length+' '+k).join(', ')+')',rules:add,
63
+ apply:async()=>{
64
+ const before=readLayer(root,'project').permissions?.allow||[];const wasTrusted=scope==='project'&&(!before.length||isTrusted(root,'permissions',before));
65
+ await saveSetting({root,scope,key:'permissions',value:add});
66
+ // The user just reviewed these rules, so keep the project's trust if it had it (as /mcp add does).
67
+ if(wasTrusted)await setTrusted(root,'permissions',readLayer(root,'project').permissions?.allow||[]);
68
+ }});
69
+ };
70
+ const addHooks=(scope,file,hooks)=>{
71
+ if(!isObj(hooks)||!Object.keys(hooks).length||(scope!=='user'&&!root))return;
72
+ const r=hooksFromSettings(hooks);skipped.push(...r.warnings.map(w=>rel(file)+': '+w));
73
+ if(!r.hooks.length)return;
74
+ const cur=readLayer(root,scope).hooks;
75
+ const curText=JSON.stringify(cur||{});
76
+ const fresh=Object.fromEntries(Object.entries(hooks).filter(([ev,list])=>!curText.includes(JSON.stringify(list))));
77
+ if(!Object.keys(fresh).length)return;
78
+ items.push({kind:'hooks',scope,from:rel(file),summary:r.hooks.length+' hook'+(r.hooks.length===1?'':'s')+' ('+[...new Set(r.hooks.map(x=>x.event))].join(', ')+')',
79
+ apply:async()=>{
80
+ const now=readLayer(root,scope).hooks;const merged={...(isObj(now)?now:{})};
81
+ for(const [ev,list] of Object.entries(fresh))merged[ev]=[...(Array.isArray(merged[ev])?merged[ev]:[]),...(Array.isArray(list)?list:[])];
82
+ const before=readLayer(root,'project').hooks;const wasTrusted=scope==='project'&&(!before||!Object.keys(before).length||isTrusted(root,'hooks',before));
83
+ await saveSetting({root,scope,key:'hooks',value:merged});
84
+ if(wasTrusted)await setTrusted(root,'hooks',readLayer(root,'project').hooks);
85
+ }});
86
+ };
87
+ const userMcp=()=>{const v=readJson(path.join(home(),'mcp.json'));return isObj(v?.mcpServers)?v.mcpServers:{}};
88
+ const addMcp=(scope,file,servers)=>{
89
+ if(!isObj(servers))return;
90
+ const have=scope==='user'?userMcp():(readLayer(root,'local').mcpServers||{});
91
+ const add={};
92
+ for(const [n,s] of Object.entries(servers)){
93
+ if(!isObj(s))continue;
94
+ if(!NAME.test(n)||n==='mlai'){skipped.push(rel(file)+': MCP server '+n+' (the name must use letters, digits, - and _)');continue}
95
+ if(have[n])continue;
96
+ const {type,...spec}=s;add[n]={...spec,...(type==='sse'?{transport:'sse'}:{})};
97
+ }
98
+ if(!Object.keys(add).length||(scope!=='user'&&!root))return;
99
+ items.push({kind:'mcp',scope,from:rel(file),summary:'MCP server'+(Object.keys(add).length===1?' ':'s ')+Object.keys(add).join(', '),
100
+ apply:async()=>{
101
+ if(scope==='user'){
102
+ const f=path.join(home(),'mcp.json');let cur={};try{cur=JSON.parse(await readFile(f,'utf8'))}catch{}
103
+ const next={...(isObj(cur)?cur:{}),mcpServers:{...(isObj(cur?.mcpServers)?cur.mcpServers:{}),...add}};
104
+ await mkdir(path.dirname(f),{recursive:true});const tmp=f+'.'+process.pid+'.tmp';await writeFile(tmp,JSON.stringify(next,null,2)+'\n',{mode:0o600});await rename(tmp,f);
105
+ }else{const cur=readLayer(root,'local').mcpServers;await saveSetting({root,scope:'local',key:'mcpServers',value:{...(isObj(cur)?cur:{}),...add}})}
106
+ }});
107
+ };
108
+
109
+ if(want('claude')){
110
+ const files={user:path.join(h,'.claude','settings.json'),...(root?{project:path.join(root,'.claude','settings.json'),local:path.join(root,'.claude','settings.local.json')}:{})};
111
+ for(const [scope,f] of Object.entries(files)){
112
+ const v=readJson(f);if(!isObj(v))continue;
113
+ addPerms(scope,f,v.permissions,normalizeRule,'claude');addHooks(scope,f,v.hooks);
114
+ if(isObj(v.mcpServers))addMcp(scope==='user'?'user':'local',f,v.mcpServers);
115
+ }
116
+ const cj=path.join(h,'.claude.json'),c=readJson(cj);
117
+ if(isObj(c)){
118
+ addMcp('user',cj,c.mcpServers);
119
+ const proj=root&&isObj(c.projects)?c.projects[root]:null;
120
+ if(isObj(proj)){addMcp('local',cj,proj.mcpServers);if(Array.isArray(proj.allowedTools)&&proj.allowedTools.length)addPerms('local',cj,{allow:proj.allowedTools},normalizeRule,'claude')}
121
+ }
122
+ if(root){
123
+ for(const [p,what] of [['CLAUDE.md','project rules'],['.mcp.json','MCP servers'],[path.join('.claude','commands'),'custom commands'],[path.join('.claude','agents'),'subagents'],[path.join('.claude','skills'),'skills']])
124
+ if(existsSync(path.join(root,p)))used.push(p+' ('+what+')');
125
+ }
126
+ for(const [p,what] of [[path.join('.claude','commands'),'custom commands'],[path.join('.claude','agents'),'subagents'],[path.join('.claude','skills'),'skills']])
127
+ if(existsSync(path.join(h,p)))used.push('~/'+p+' ('+what+')');
128
+ }
129
+ if(want('cursor')){
130
+ const uc=path.join(h,'.cursor','cli-config.json'),u=readJson(uc);if(isObj(u))addPerms('user',uc,u.permissions,cursorRule,'cursor');
131
+ if(root){const pc=path.join(root,'.cursor','cli.json'),p=readJson(pc);if(isObj(p))addPerms('project',pc,p.permissions,cursorRule,'cursor')}
132
+ const um=path.join(h,'.cursor','mcp.json'),m=readJson(um);if(isObj(m))addMcp('user',um,m.mcpServers);
133
+ if(root){
134
+ for(const [p,what] of [[path.join('.cursor','rules'),'project rules'],['.cursorrules','project rules'],[path.join('.cursor','mcp.json'),'MCP servers'],[path.join('.cursor','commands'),'custom commands']])
135
+ if(existsSync(path.join(root,p)))used.push(p+' ('+what+')');
136
+ }
137
+ }
138
+ return {items,used,skipped};
139
+ }
140
+
141
+ /** Text for the user: what will be imported and from where. */
142
+ export function describePlan(plan){
143
+ const L=[];
144
+ if(plan.items.length){L.push('Will import:');for(const i of plan.items)L.push(' '+i.summary.padEnd(44)+' '+i.from+' -> '+i.scope+' settings')}
145
+ else L.push('Nothing new to import.');
146
+ if(plan.used.length)L.push('','Already used as they are:',...plan.used.map(u=>' '+u));
147
+ if(plan.skipped.length)L.push('','Not imported (no equivalent here):',...plan.skipped.slice(0,20).map(s=>' '+s));
148
+ return L.join('\n');
149
+ }
150
+ export async function applyPlan(plan){for(const i of plan.items)await i.apply();return plan.items.length}
151
+ export const hasSetup=(root,homeDir=null)=>{const h=homeDir||path.dirname(home());return ['.claude','.cursor','.claude.json'].some(p=>existsSync(path.join(h,p))||(root&&existsSync(path.join(root,p))))};
@@ -0,0 +1,104 @@
1
+ /**
2
+ * /init: scans the repository and writes AGENTS.md, the project instructions every run loads (worker/project_rules.py).
3
+ * Only facts found in the repository go in: manifests, scripts, lockfiles, languages, layout, lint and test setup.
4
+ * The scan is local and fast (no model call); `/init` can then hand the file to the agent to refine.
5
+ */
6
+ import {execFileSync} from 'node:child_process';
7
+ import {existsSync,readFileSync,readdirSync,lstatSync} from 'node:fs';
8
+ import path from 'node:path';
9
+
10
+ const SKIP=new Set(['node_modules','.git','.next','dist','build','out','coverage','.venv','venv','__pycache__','target','.turbo','.cache','vendor','.mlai','.idea','.vscode']);
11
+ const LANGS={'.ts':'TypeScript','.tsx':'TypeScript','.js':'JavaScript','.jsx':'JavaScript','.mjs':'JavaScript','.cjs':'JavaScript','.py':'Python','.go':'Go','.rs':'Rust',
12
+ '.java':'Java','.kt':'Kotlin','.swift':'Swift','.rb':'Ruby','.php':'PHP','.cs':'C#','.cpp':'C++','.cc':'C++','.c':'C','.h':'C/C++ headers','.m':'Objective-C','.scala':'Scala',
13
+ '.ex':'Elixir','.exs':'Elixir','.dart':'Dart','.lua':'Lua','.sh':'Shell','.sql':'SQL','.vue':'Vue','.svelte':'Svelte','.css':'CSS','.scss':'SCSS','.html':'HTML'};
14
+ const FRAMEWORKS=[['next','Next.js'],['react','React'],['vue','Vue'],['svelte','Svelte'],['@angular/core','Angular'],['vite','Vite'],['express','Express'],['fastify','Fastify'],
15
+ ['@nestjs/core','NestJS'],['electron','Electron'],['react-native','React Native'],['expo','Expo'],['tailwindcss','Tailwind CSS'],['prisma','Prisma'],['drizzle-orm','Drizzle'],
16
+ ['vitest','Vitest'],['jest','Jest'],['@playwright/test','Playwright'],['mocha','Mocha'],['typescript','TypeScript'],['eslint','ESLint'],['prettier','Prettier'],['@biomejs/biome','Biome']];
17
+ const PY=[['django','Django'],['flask','Flask'],['fastapi','FastAPI'],['pytest','pytest'],['ruff','Ruff'],['black','Black'],['mypy','mypy'],['pydantic','Pydantic'],['torch','PyTorch'],['numpy','NumPy']];
18
+ const read=(f,n=200000)=>{try{const s=lstatSync(f);if(!s.isFile()||s.isSymbolicLink())return null;return readFileSync(f,'utf8').slice(0,n)}catch{return null}};
19
+ const json=f=>{const t=read(f);if(t==null)return null;try{return JSON.parse(t)}catch{return null}};
20
+
21
+ export function listFiles(root,limit=20000){
22
+ try{
23
+ const out=execFileSync('git',['ls-files','-co','--exclude-standard'],{cwd:root,encoding:'utf8',maxBuffer:64*1024*1024,stdio:['ignore','pipe','ignore']});
24
+ const files=out.split('\n').filter(Boolean);if(files.length)return files.slice(0,limit);
25
+ }catch{}
26
+ const files=[];
27
+ const walk=(dir,depth)=>{if(files.length>=limit||depth>6)return;let names=[];try{names=readdirSync(path.join(root,dir))}catch{return}
28
+ for(const n of names.sort()){if(SKIP.has(n)||n.startsWith('.')&&n!=='.github')continue;const rel=dir?dir+'/'+n:n;let st;try{st=lstatSync(path.join(root,rel))}catch{continue}
29
+ if(st.isSymbolicLink())continue;if(st.isDirectory())walk(rel,depth+1);else files.push(rel);if(files.length>=limit)return}};
30
+ walk('',0);return files;
31
+ }
32
+ function packageManager(root){
33
+ if(existsSync(path.join(root,'pnpm-lock.yaml')))return 'pnpm';if(existsSync(path.join(root,'yarn.lock')))return 'yarn';
34
+ if(existsSync(path.join(root,'bun.lockb'))||existsSync(path.join(root,'bun.lock')))return 'bun';return existsSync(path.join(root,'package.json'))?'npm':null;
35
+ }
36
+ const runCmd=(pm,script)=>pm==='npm'?(script==='test'||script==='start'?'npm '+script:'npm run '+script):pm+' '+script;
37
+ /** Everything /init found: {name, description, languages, frameworks, commands:[{cmd, what}], layout, workspaces, notes, rules}. */
38
+ export function scan(root){
39
+ const files=listFiles(root);const r={root,name:path.basename(root),description:'',languages:[],frameworks:[],commands:[],layout:[],workspaces:[],notes:[],rules:[],files:files.length};
40
+ const counts={};for(const f of files){const l=LANGS[path.extname(f).toLowerCase()];if(l)counts[l]=(counts[l]||0)+1}
41
+ r.languages=Object.entries(counts).sort((a,b)=>b[1]-a[1]).slice(0,6).map(([l,n])=>l+' ('+n+' files)');
42
+ const pkg=json(path.join(root,'package.json'));const pm=packageManager(root);
43
+ if(pkg){
44
+ if(pkg.name)r.name=pkg.name;if(pkg.description)r.description=String(pkg.description);
45
+ const deps={...pkg.dependencies,...pkg.devDependencies};for(const [k,v] of FRAMEWORKS)if(deps[k])r.frameworks.push(v);
46
+ r.commands.push({cmd:pm==='npm'?(existsSync(path.join(root,'package-lock.json'))?'npm ci':'npm install'):pm+' install',what:'install dependencies ('+pm+')'});
47
+ const order=['dev','start','build','test','lint','typecheck','type-check','format','e2e'];
48
+ const scripts=Object.keys(pkg.scripts||{});
49
+ for(const s of [...order.filter(s=>scripts.includes(s)),...scripts.filter(s=>!order.includes(s))].slice(0,14))r.commands.push({cmd:runCmd(pm,s),what:String(pkg.scripts[s]).slice(0,90)});
50
+ const ws=Array.isArray(pkg.workspaces)?pkg.workspaces:pkg.workspaces?.packages;if(Array.isArray(ws))r.workspaces.push(...ws.map(String));
51
+ if(pkg.engines?.node)r.notes.push('Node '+pkg.engines.node+' (package.json engines).');
52
+ if(pkg.type==='module')r.notes.push('ES modules ("type": "module").');
53
+ }
54
+ const pnpmWs=read(path.join(root,'pnpm-workspace.yaml'));if(pnpmWs)for(const m of pnpmWs.matchAll(/^\s*-\s*['"]?([^'"\n]+)['"]?/gm))r.workspaces.push(m[1].trim());
55
+ const py=read(path.join(root,'pyproject.toml'))||'';const req=read(path.join(root,'requirements.txt'))||'';
56
+ if(py||req){
57
+ const text=(py+'\n'+req).toLowerCase();for(const [k,v] of PY)if(new RegExp('(^|[\\s"\'\\[,])'+k+'\\b','m').test(text))r.frameworks.push(v);
58
+ if(existsSync(path.join(root,'uv.lock')))r.commands.push({cmd:'uv sync',what:'install Python dependencies (uv)'});
59
+ else if(/\[tool\.poetry\]/.test(py))r.commands.push({cmd:'poetry install',what:'install Python dependencies (Poetry)'});
60
+ else if(req)r.commands.push({cmd:'pip install -r requirements.txt',what:'install Python dependencies'});
61
+ if(/pytest/.test(text)||files.some(f=>/(^|\/)(tests?\/.*\.py|test_[^/]*\.py)$/.test(f)))r.commands.push({cmd:'python -m pytest',what:'run the Python tests'});
62
+ if(/ruff/.test(text))r.commands.push({cmd:'ruff check .',what:'lint Python'});
63
+ }else if(files.some(f=>/(^|\/)test_[^/]*\.py$/.test(f)))r.commands.push({cmd:'python -m pytest',what:'run the Python tests'});
64
+ if(existsSync(path.join(root,'Cargo.toml')))r.commands.push({cmd:'cargo build',what:'build (Rust)'},{cmd:'cargo test',what:'run the Rust tests'});
65
+ if(existsSync(path.join(root,'go.mod'))){r.commands.push({cmd:'go build ./...',what:'build (Go)'},{cmd:'go test ./...',what:'run the Go tests'});const m=/^module\s+(\S+)/m.exec(read(path.join(root,'go.mod'))||'');if(m&&!pkg)r.name=m[1]}
66
+ const mk=read(path.join(root,'Makefile'));if(mk){const targets=[...mk.matchAll(/^([a-zA-Z][\w-]*):(?!=)/gm)].map(m=>m[1]).filter((t,i,a)=>a.indexOf(t)===i).slice(0,8);for(const t of targets)r.commands.push({cmd:'make '+t,what:'Makefile target'})}
67
+ if(existsSync(path.join(root,'Package.swift')))r.commands.push({cmd:'swift build',what:'build (Swift package)'},{cmd:'swift test',what:'run the Swift tests'});
68
+ if(existsSync(path.join(root,'Gemfile')))r.commands.push({cmd:'bundle install',what:'install Ruby gems'});
69
+ const top={};for(const f of files){const p=f.split('/');if(p.length>1&&!SKIP.has(p[0]))top[p[0]]=(top[p[0]]||0)+1}
70
+ r.layout=Object.entries(top).sort((a,b)=>b[1]-a[1]).slice(0,14).map(([d,n])=>({dir:d,files:n,hint:dirHint(root,d)}));
71
+ if(files.includes('tsconfig.json')){const t=json(path.join(root,'tsconfig.json'));if(t?.compilerOptions?.strict)r.notes.push('TypeScript strict mode is on.')}
72
+ for(const f of ['.eslintrc','.eslintrc.json','.eslintrc.js','eslint.config.js','eslint.config.mjs','.prettierrc','biome.json','.editorconfig','ruff.toml'])if(files.includes(f))r.notes.push('Style config: '+f+'.');
73
+ if(files.some(f=>f.startsWith('.github/workflows/')))r.notes.push('CI: .github/workflows ('+files.filter(f=>f.startsWith('.github/workflows/')).map(f=>path.basename(f)).slice(0,5).join(', ')+').');
74
+ if(files.includes('.env.example'))r.notes.push('Environment variables are listed in .env.example; never commit real values.');
75
+ for(const f of ['MLAI.md','CLAUDE.md','.cursorrules','.github/copilot-instructions.md'])if(files.includes(f))r.rules.push(f);
76
+ if(files.some(f=>f.startsWith('.cursor/rules/')))r.rules.push('.cursor/rules');
77
+ const readme=read(path.join(root,'README.md'),6000);
78
+ if(readme&&!r.description){const para=readme.split(/\n\s*\n/).map(s=>s.trim()).find(s=>s&&!s.startsWith('#')&&!s.startsWith('![')&&!s.startsWith('[!')&&!s.startsWith('<'));if(para)r.description=para.replace(/\s+/g,' ').slice(0,300)}
79
+ r.frameworks=[...new Set(r.frameworks)];
80
+ return r;
81
+ }
82
+ function dirHint(root,d){
83
+ const p=json(path.join(root,d,'package.json'));if(p?.description)return String(p.description).slice(0,80);
84
+ return {src:'source',app:'app routes',apps:'applications',packages:'shared packages',lib:'library code',test:'tests',tests:'tests',docs:'documentation',scripts:'scripts',
85
+ components:'UI components',public:'static assets',worker:'worker code',server:'server code',api:'API',cmd:'entry points',internal:'internal packages',examples:'examples'}[d]||'';
86
+ }
87
+ /** AGENTS.md text from a scan. */
88
+ export function render(s){
89
+ const L=[];
90
+ L.push('# AGENTS.md','',(s.description?s.description:'Project instructions for coding agents working in '+s.name+'.'),'');
91
+ if(s.languages.length||s.frameworks.length){L.push('## Stack','');if(s.languages.length)L.push('- Languages: '+s.languages.join(', '));if(s.frameworks.length)L.push('- Frameworks and tools: '+s.frameworks.join(', '));L.push('')}
92
+ if(s.commands.length){L.push('## Commands','','Run these from the repository root.','');for(const c of s.commands)L.push('- `'+c.cmd+'`'+(c.what?': '+c.what.replace(/`/g,"'"):''));L.push('')}
93
+ if(s.layout.length||s.workspaces.length){L.push('## Layout','');for(const d of s.layout)L.push('- `'+d.dir+'/`'+(d.hint?': '+d.hint:'')+' ('+d.files+' files)');if(s.workspaces.length)L.push('- Workspaces: '+[...new Set(s.workspaces)].join(', '));L.push('')}
94
+ L.push('## Working here','');
95
+ for(const n of s.notes)L.push('- '+n);
96
+ const test=s.commands.find(c=>/\btest\b/.test(c.cmd)),lint=s.commands.find(c=>/\b(lint|typecheck|type-check|ruff|tsc)\b/.test(c.cmd));
97
+ L.push('- Before finishing a change, run '+(test?'`'+test.cmd+'`':'the relevant tests')+(lint?' and `'+lint.cmd+'`':'')+', and fix what fails.');
98
+ L.push('- Keep changes small and focused; follow the style of the surrounding code.','- Never commit secrets or edit lockfiles by hand.');
99
+ if(s.rules.length)L.push('- Also follow: '+s.rules.join(', ')+' (loaded with this file).');
100
+ L.push('');
101
+ return L.join('\n');
102
+ }
103
+ /** The task /init sends when the agent should refine the file. */
104
+ export const REFINE_TASK='Review AGENTS.md at the repository root against the actual code: verify every command (run the quick ones), fix anything wrong, and add what an engineer new to this repository needs: architecture in a few lines, how to run and test one part, conventions you can see in the code, and pitfalls. Keep it under 150 lines, facts only, no secrets. Do not change other files.';
@@ -0,0 +1,70 @@
1
+ /**
2
+ * Remappable key bindings (/keymap, settings.keymap = {action: "ctrl+t"}). Only interface actions can move; Enter,
3
+ * Esc, Ctrl-C and Ctrl-D keep their meaning so a bad binding can never lock you out. A spec is modifiers and a key
4
+ * joined by '+': ctrl+o, alt+v, shift+tab, f2, ctrl+shift+p.
5
+ */
6
+ export const ACTIONS={
7
+ toggleTools:{key:'ctrl+o',summary:'Expand or collapse tool output'},
8
+ redraw:{key:'ctrl+l',summary:'Redraw the screen'},
9
+ historySearch:{key:'ctrl+r',summary:'Search message history'},
10
+ cycleMode:{key:'shift+tab',summary:'Switch mode (agent, plan, ask, auto)'},
11
+ queueMessage:{key:'tab',summary:'While the agent works: queue the message for after this turn'},
12
+ pasteImage:{key:'ctrl+v',win:'alt+v',summary:'Paste an image from the clipboard'},
13
+ toggleRaw:{key:'alt+r',summary:'Raw scrollback on or off (plain text for copying)'},
14
+ showJobs:{key:'alt+j',summary:'List background terminals (/ps)'},
15
+ editQueued:{key:'alt+up',summary:'Pull the last queued message back into the input'},
16
+ };
17
+ export const RESERVED=new Set(['enter','escape','ctrl+c','ctrl+d','backspace','up','down','left','right']);
18
+ const MODS=['ctrl','alt','shift'];
19
+ const NAMES=new Set(['tab','enter','escape','space','backspace','delete','insert','home','end','pageup','pagedown','up','down','left','right',...Array.from({length:12},(_,i)=>'f'+(i+1))]);
20
+
21
+ /** 'Ctrl+Shift+P' -> 'ctrl+shift+p' (canonical order), or null when it is not a key. */
22
+ export function normalizeSpec(spec){
23
+ const parts=String(spec||'').toLowerCase().replace(/\s+/g,'').replace(/^-|-$/g,'').split(/[+-](?=.)/).filter(Boolean);
24
+ if(!parts.length)return null;
25
+ const key=parts.pop().replace(/^esc$/,'escape').replace(/^return$/,'enter').replace(/^(meta|option|opt)$/,'alt');
26
+ const mods=new Set(parts.map(p=>p.replace(/^(control|ctl)$/,'ctrl').replace(/^(meta|option|opt|cmd)$/,'alt')));
27
+ if([...mods].some(m=>!MODS.includes(m)))return null;
28
+ if(!(NAMES.has(key)||/^[a-z0-9`\-=[\];',./\\]$/.test(key)))return null;
29
+ if(/^[a-z0-9]$/.test(key)&&!mods.has('ctrl')&&!mods.has('alt'))return null; // plain letters are for typing
30
+ return [...MODS.filter(m=>mods.has(m)),key].join('+');
31
+ }
32
+ /** A key event (keys.mjs) -> its spec. */
33
+ export function specOf(k){
34
+ if(!k)return '';
35
+ let name=k.name==='char'?(k.ch===' '?'space':String(k.ch||'').toLowerCase()):k.name;
36
+ return [k.ctrl&&'ctrl',k.alt&&'alt',k.shift&&'shift',name].filter(Boolean).join('+');
37
+ }
38
+ /** Display form: ctrl+o -> Ctrl-O, shift+tab -> Shift+Tab. */
39
+ export function labelOf(spec){
40
+ if(!spec)return 'unbound';
41
+ const p=spec.split('+');const key=p.pop();
42
+ const k=key.length===1?key.toUpperCase():key[0].toUpperCase()+key.slice(1).replace('up','Up').replace('down','Down');
43
+ const mods=p.map(m=>m[0].toUpperCase()+m.slice(1));
44
+ return mods.length===1&&mods[0]==='Ctrl'&&key.length===1?'Ctrl-'+k:[...mods,k].join('+');
45
+ }
46
+ /** The effective bindings: defaults (per platform) with settings.keymap applied. A null value unbinds. */
47
+ export function resolveKeymap(custom={},platform=process.platform){
48
+ const out={};
49
+ for(const [a,d] of Object.entries(ACTIONS))out[a]=(platform==='win32'&&d.win)||d.key;
50
+ for(const [a,v] of Object.entries(custom&&typeof custom==='object'?custom:{})){
51
+ if(!ACTIONS[a])continue;
52
+ if(v===null||v===''||v==='none'){out[a]=null;continue}
53
+ const n=normalizeSpec(v);if(n&&!RESERVED.has(n))out[a]=n;
54
+ }
55
+ return out;
56
+ }
57
+ /** Which action a key triggers, or null. */
58
+ export function actionFor(k,map){const s=specOf(k);for(const [a,v] of Object.entries(map))if(v&&v===s)return a;return null}
59
+ /**
60
+ * Validates a new binding. Returns {spec, conflict} or throws with a message. conflict is the action that held the
61
+ * key before (the caller unbinds it or swaps).
62
+ */
63
+ export function checkBinding(action,spec,map){
64
+ if(!ACTIONS[action])throw new Error('Unknown action '+action+'. Actions: '+Object.keys(ACTIONS).join(', '));
65
+ const n=normalizeSpec(spec);
66
+ if(!n)throw new Error('Not a key: '+spec+'. Use forms like ctrl+t, alt+v, shift+tab or f2.');
67
+ if(RESERVED.has(n))throw new Error(labelOf(n)+' is reserved (Enter, Esc, Ctrl-C, Ctrl-D and arrows keep their meaning).');
68
+ const conflict=Object.entries(map).find(([a,v])=>a!==action&&v===n)?.[0]||null;
69
+ return {spec:n,conflict};
70
+ }
@@ -0,0 +1,101 @@
1
+ /**
2
+ * Raw terminal input -> key events. Handles CSI/SS3 sequences from xterm, iTerm2, Terminal.app, Windows Terminal,
3
+ * the kitty keyboard protocol (CSI <code>;<mods>u, so Shift+Enter is distinct), modifyOtherKeys (CSI 27;<mods>;<code>~),
4
+ * bracketed paste (ESC[200~ ... ESC[201~) and a lone Esc after a short pause.
5
+ *
6
+ * Key: {name, ch?, ctrl, alt, shift, text?(paste), seq}
7
+ * names: char enter tab backspace delete escape up down left right home end pageup pagedown insert paste
8
+ * f1..f12 and letters for ctrl combos (name 'c' with ctrl:true).
9
+ */
10
+ const CSI_FINAL={A:'up',B:'down',C:'right',D:'left',H:'home',F:'end',P:'f1',Q:'f2',R:'f3',S:'f4',Z:'tab'};
11
+ const TILDE={1:'home',2:'insert',3:'delete',4:'end',5:'pageup',6:'pagedown',7:'home',8:'end',11:'f1',12:'f2',13:'f3',14:'f4',15:'f5',17:'f6',18:'f7',19:'f8',20:'f9',21:'f10',23:'f11',24:'f12'};
12
+ const mods=m=>{const n=Math.max(0,(Number(m)||1)-1);return {shift:Boolean(n&1),alt:Boolean(n&2),ctrl:Boolean(n&4),meta:Boolean(n&8)}};
13
+ const key=(name,extra={})=>({name,ctrl:false,alt:false,shift:false,...extra});
14
+ function codeKey(code,m,seq){
15
+ const md=mods(m);
16
+ if(code===13)return key('enter',{...md,seq});
17
+ if(code===9)return key('tab',{...md,seq});
18
+ if(code===27)return key('escape',{...md,seq});
19
+ if(code===127||code===8)return key('backspace',{...md,seq});
20
+ if(code===32&&!md.ctrl&&!md.alt)return key('char',{ch:' ',...md,seq});
21
+ const ch=String.fromCodePoint(code);
22
+ if(md.ctrl||md.alt)return key(ch.toLowerCase(),{...md,ch,seq});
23
+ return key('char',{ch:md.shift?ch.toUpperCase():ch,...md,shift:false,seq});
24
+ }
25
+
26
+ /** Parses one chunk. Returns {keys, rest}: rest is an incomplete sequence to prepend to the next chunk. */
27
+ export function parseKeys(input,{pasting=null}={}){
28
+ const s=String(input);const keys=[];let i=0;let paste=pasting;
29
+ while(i<s.length){
30
+ if(paste!==null){
31
+ const end=s.indexOf('\x1b[201~',i);
32
+ if(end<0){paste+=s.slice(i);return {keys,rest:'',pasting:paste}}
33
+ paste+=s.slice(i,end);keys.push(key('paste',{text:paste.replace(/\r\n?/g,'\n')}));paste=null;i=end+6;continue;
34
+ }
35
+ const c=s[i];
36
+ if(c==='\x1b'){
37
+ if(s.startsWith('\x1b[200~',i)){paste='';i+=6;continue}
38
+ if(i+1>=s.length){keys.push(key('escape',{seq:c,lone:true}));i++;continue}
39
+ const n=s[i+1];
40
+ if(n==='['){
41
+ const m=/^\x1b\[([0-9;:<=>?]*)([ -\/]*)([@-~])/.exec(s.slice(i));
42
+ if(!m){return {keys,rest:s.slice(i),pasting:null}}
43
+ const seq=m[0],params=m[1].split(';'),final=m[3];i+=seq.length;
44
+ if(final==='u'){const [code,mm]=params;keys.push(codeKey(Number(String(code).split(':')[0]),String(mm||'1').split(':')[0],seq));continue}
45
+ if(final==='~'&&params[0]==='27'){keys.push(codeKey(Number(params[2]),params[1],seq));continue}
46
+ if(final==='~'){const name=TILDE[Number(params[0])];if(name)keys.push(key(name,{...mods(params[1]),seq}));continue}
47
+ if(final==='Z'){keys.push(key('tab',{shift:true,seq}));continue}
48
+ if(final==='I'||final==='O'){keys.push(key(final==='I'?'focus':'blur',{seq}));continue}
49
+ const name=CSI_FINAL[final];if(name)keys.push(key(name,{...mods(params[1]),seq}));
50
+ continue;
51
+ }
52
+ if(n==='O'){
53
+ if(i+2>=s.length)return {keys,rest:s.slice(i),pasting:null};
54
+ const f=s[i+2];const name=CSI_FINAL[f]||(f==='M'?'enter':null);i+=3;if(name)keys.push(key(name,{seq:'\x1bO'+f}));continue;
55
+ }
56
+ // Alt+key: ESC then the key (Alt+Enter is ESC CR in most terminals).
57
+ if(n==='\r'||n==='\n'){keys.push(key('enter',{alt:true,seq:c+n}));i+=2;continue}
58
+ if(n==='\x7f'||n==='\b'){keys.push(key('backspace',{alt:true,seq:c+n}));i+=2;continue}
59
+ if(n==='\x1b'){keys.push(key('escape',{seq:c}));i++;continue}
60
+ const cp=s.codePointAt(i+1),ch=String.fromCodePoint(cp);
61
+ keys.push(cp<32?key(String.fromCharCode(cp+96),{ctrl:true,alt:true,seq:c+ch}):key(ch.toLowerCase(),{alt:true,ch,shift:ch!==ch.toLowerCase(),seq:c+ch}));
62
+ i+=1+ch.length;continue;
63
+ }
64
+ if(c==='\r'){keys.push(key('enter',{seq:c}));i+=s[i+1]==='\n'?2:1;continue}
65
+ if(c==='\n'){keys.push(key('j',{ctrl:true,seq:c,newline:true}));i++;continue}
66
+ if(c==='\t'){keys.push(key('tab',{seq:c}));i++;continue}
67
+ if(c==='\x7f'||c==='\b'){keys.push(key('backspace',{seq:c}));i++;continue}
68
+ const cp=s.codePointAt(i);
69
+ if(cp<32){keys.push(key(String.fromCharCode(cp+96),{ctrl:true,seq:c}));i++;continue}
70
+ const ch=String.fromCodePoint(cp);keys.push(key('char',{ch,seq:ch}));i+=ch.length;
71
+ }
72
+ return {keys,rest:'',pasting:paste};
73
+ }
74
+
75
+ /**
76
+ * A stateful reader: feed() raw chunks, get keys via onKey. A trailing lone ESC waits `escDelay` ms before it
77
+ * counts as Escape, so Alt+key and arrow sequences split across reads still parse.
78
+ */
79
+ export function keyReader(onKey,{escDelay=40}={}){
80
+ let rest='',pasting=null,timer=null;
81
+ const flush=()=>{timer=null;if(rest==='\x1b'){rest='';onKey(key('escape',{seq:'\x1b',lone:true}))}else if(rest){const r=rest;rest='';for(const k of parseKeys(r).keys)onKey(k)}};
82
+ return {
83
+ feed(chunk){
84
+ if(timer){clearTimeout(timer);timer=null}
85
+ const data=rest+String(chunk);rest='';
86
+ if(data==='\x1b'&&pasting===null){rest=data;timer=setTimeout(flush,escDelay);return}
87
+ const r=parseKeys(data,{pasting});pasting=r.pasting;
88
+ if(r.rest){rest=r.rest;timer=setTimeout(flush,escDelay)}
89
+ // A chunk ending in a lone ESC: hold it briefly in case the rest of a sequence follows.
90
+ const last=r.keys.at(-1);
91
+ if(last?.lone&&data.endsWith('\x1b')&&pasting===null){r.keys.pop();rest='\x1b';timer=setTimeout(flush,escDelay)}
92
+ for(const k of r.keys)onKey(k);
93
+ },
94
+ close(){if(timer)clearTimeout(timer)},
95
+ };
96
+ }
97
+ /** Short label for a key, for tests and the keybinding table. */
98
+ export function label(k){
99
+ const p=[k.ctrl&&'Ctrl',k.alt&&'Alt',k.shift&&'Shift'].filter(Boolean);
100
+ return [...p,k.name==='char'?k.ch:k.name].join('+');
101
+ }
@@ -0,0 +1,75 @@
1
+ // /loop for the CLI: repeat a prompt in the open session every interval while the terminal stays open.
2
+ // Same parsing and limits as the Mac app's /loop (apps/desktop/src/scheduler.cjs).
3
+ import {readFile} from 'node:fs/promises';
4
+ import path from 'node:path';
5
+ import {randomBytes} from 'node:crypto';
6
+
7
+ const MIN=60e3,HOUR=60*MIN,DAY=24*HOUR;
8
+ export const LIMITS={loopMin:MIN,loopDays:7,loops:10,failures:3,prompt:8000};
9
+ export const DONE_MARK='LOOP_DONE';
10
+
11
+ /** "10m", "90 min", "2h", "1d", "30s" to milliseconds, or null. */
12
+ export function parseDuration(s){
13
+ const m=/^(\d{1,4})\s*(s|secs?|seconds?|m|mins?|minutes?|h|hrs?|hours?|d|days?)$/i.exec(String(s||'').trim());if(!m)return null;
14
+ const n=Number(m[1]),u=m[2][0].toLowerCase();if(!n)return null;
15
+ return n*(u==='s'?1e3:u==='m'?MIN:u==='h'?HOUR:DAY);
16
+ }
17
+ export function intervalText(ms){
18
+ const f=(n,u)=>n+' '+u+(n===1?'':'s');
19
+ return ms%DAY===0?f(ms/DAY,'day'):ms%HOUR===0?f(ms/HOUR,'hour'):ms%MIN===0?f(ms/MIN,'minute'):f(Math.round(ms/1e3),'second');
20
+ }
21
+ /** "[every] 10m <task> [until <condition>]". No interval: every 10 minutes. No task: .mlai/loop.md in the project. */
22
+ export function parseLoop(args){
23
+ let rest=String(args||'').trim(),every=null;
24
+ const m=/^(?:every\s+)?(\d{1,4}\s*[a-z]+)\b\s*/i.exec(rest);
25
+ if(m){const d=parseDuration(m[1]);if(d!=null){every=d;rest=rest.slice(m[0].length)}}
26
+ const defaulted=every==null;if(defaulted)every=10*MIN;
27
+ if(every<LIMITS.loopMin)throw new Error('Loops run at most once a minute. Try /loop 1m or longer.');
28
+ if(every>LIMITS.loopDays*DAY)throw new Error('Loops end after 7 days, so the interval must be shorter than that.');
29
+ const u=/^([\s\S]*?)\s+until\s+([\s\S]+)$/i.exec(rest);
30
+ const [prompt,until]=u&&u[1].trim()?[u[1].trim(),u[2].trim().slice(0,300)]:[rest.trim(),null];
31
+ return {every,prompt:prompt.slice(0,LIMITS.prompt),until,defaulted};
32
+ }
33
+ export function loopPrompt(item){
34
+ let note='This repeats every '+intervalText(item.every)+' from /loop. Keep each run short: check, act only if something needs it, and say what changed since the last run.';
35
+ if(item.until)note+=' Stop condition: '+item.until+'. When it is met, end your final answer with a line that says exactly '+DONE_MARK+'.';
36
+ return item.prompt+'\n\n('+note+')';
37
+ }
38
+ export const isDone=answer=>new RegExp('(^|\\n)\\s*'+DONE_MARK+'\\s*$').test(String(answer||'').trim());
39
+ /** The prompt from .mlai/loop.md when /loop has no task. */
40
+ export async function loopFile(root){try{return (await readFile(path.join(root,'.mlai','loop.md'),'utf8')).trim().slice(0,LIMITS.prompt)}catch{return ''}}
41
+
42
+ /**
43
+ * Loops for one terminal. queue(text) => Promise<{state,answer}> runs a turn when the agent is idle.
44
+ * The next run is timed from the end of the previous one, so runs never overlap. notify(text) reports stops.
45
+ */
46
+ export function createLoops({queue,notify=()=>{},now=()=>Date.now(),setTimer=(f,ms)=>{const t=setTimeout(f,ms);t.unref?.();return t},clearTimer=t=>clearTimeout(t)}){
47
+ const items=new Map();
48
+ const stop=(id,why)=>{const it=items.get(id);if(!it)return false;clearTimer(it.timer);items.delete(id);if(why)notify('Loop '+id+' stopped: '+why);return true};
49
+ const arm=it=>{it.next=now()+it.every;it.timer=setTimer(()=>fire(it.id),it.every)};
50
+ async function fire(id){
51
+ const it=items.get(id);if(!it)return null;
52
+ if(now()>=it.ends){stop(id,'it ran for 7 days.');return null}
53
+ it.running=true;let r;
54
+ try{r=await queue(loopPrompt(it));it.runs++;it.failures=r?.state==='error'||r?.state==='failed'?it.failures+1:0}
55
+ catch(e){it.failures++;r={state:'error',error:e?.message||String(e)}}
56
+ finally{it.running=false}
57
+ if(!items.has(id))return r;
58
+ if(isDone(r?.answer)){stop(id,'the stop condition was met.');return r}
59
+ if(it.failures>=LIMITS.failures){stop(id,'it failed '+LIMITS.failures+' times in a row.');return r}
60
+ arm(it);return r;
61
+ }
62
+ return {
63
+ /** Starts a loop and runs it once now. Returns the item. */
64
+ add({every,prompt,until=null}){
65
+ if(items.size>=LIMITS.loops)throw new Error('At most '+LIMITS.loops+' loops at once. Stop one with /loop stop <id>.');
66
+ if(!String(prompt||'').trim())throw new Error('Say what to repeat: /loop 10m check CI and fix failures.');
67
+ const id=randomBytes(3).toString('hex');
68
+ const it={id,every,prompt:String(prompt),until,runs:0,failures:0,started:now(),ends:now()+LIMITS.loopDays*DAY,next:now(),timer:null,running:false};
69
+ items.set(id,it);it.timer=setTimer(()=>fire(id),0);return it;
70
+ },
71
+ list:()=>[...items.values()].map(({timer,...it})=>it),
72
+ stop,stopAll(){const n=items.size;for(const id of [...items.keys()])stop(id);return n},
73
+ fire,
74
+ };
75
+ }