mlai-code 0.3.2 → 0.3.4

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 (157) hide show
  1. package/README.md +1 -1
  2. package/package.json +1 -1
  3. package/src/checkpoints.mjs +217 -0
  4. package/src/cli.mjs +178 -31
  5. package/src/cloud.mjs +2 -0
  6. package/src/engine.mjs +1 -1
  7. package/src/headless.mjs +25 -9
  8. package/src/home.mjs +3 -2
  9. package/src/host.mjs +141 -13
  10. package/src/ide-quick.mjs +147 -0
  11. package/src/ide.mjs +182 -0
  12. package/src/netbox.mjs +1 -1
  13. package/src/parity.mjs +20 -1
  14. package/src/relay.mjs +1 -1
  15. package/src/render.mjs +12 -3
  16. package/src/runtime.mjs +23 -1
  17. package/src/sandbox.mjs +19 -3
  18. package/src/server.mjs +46 -7
  19. package/src/session.mjs +53 -10
  20. package/src/shared-data.mjs +1 -1
  21. package/src/tui/acp.mjs +121 -19
  22. package/src/tui/app.mjs +24 -5
  23. package/src/tui/chat.mjs +43 -16
  24. package/src/tui/cmd-config.mjs +3 -1
  25. package/src/tui/cmd-core.mjs +11 -7
  26. package/src/tui/cmd-extensibility.mjs +13 -2
  27. package/src/tui/commands.mjs +2 -1
  28. package/src/tui/extensions-local.mjs +2 -0
  29. package/src/tui/mcp-config.mjs +22 -4
  30. package/src/tui/review-cli.mjs +15 -4
  31. package/src/tui/snapshots.mjs +57 -16
  32. package/src/tui/statusline.mjs +2 -1
  33. package/src/two-words.mjs +14 -8
  34. package/src/view-sync.mjs +48 -0
  35. package/src/wakeups.mjs +2 -2
  36. package/src/winenv.mjs +1 -1
  37. package/src/workspace-api.mjs +21 -4
  38. package/vendor/client-sdk/index.cjs +5 -4
  39. package/vendor/cloud-cli/mlai.mjs +184 -28
  40. package/worker/architecture_worker.py +33 -4
  41. package/worker/browser_tool.py +19 -1
  42. package/worker/build_planner.py +75 -7
  43. package/worker/chat_fork.py +4 -1
  44. package/worker/checkpoints.py +71 -8
  45. package/worker/cloud_pty.py +91 -2
  46. package/worker/command_safety.py +80 -3
  47. package/worker/compaction_brief.py +186 -0
  48. package/worker/connected_turn.py +30 -0
  49. package/worker/context_manager.py +6 -0
  50. package/worker/conversation.py +139 -12
  51. package/worker/deck_render.js +11 -0
  52. package/worker/deck_tools.py +825 -0
  53. package/worker/git_sync.py +42 -17
  54. package/worker/goals.py +4 -0
  55. package/worker/image_generation.py +102 -23
  56. package/worker/kimi_bridge.py +580 -52
  57. package/worker/kimi_gates.py +74 -6
  58. package/worker/kimi_hook.py +213 -19
  59. package/worker/media_tools.py +182 -0
  60. package/worker/memory.py +2 -2
  61. package/worker/mlai_hooks.py +314 -5
  62. package/worker/mlai_mcp.py +49 -11
  63. package/worker/mlai_review/README.md +35 -0
  64. package/worker/mlai_review/__init__.py +1 -0
  65. package/worker/mlai_review/__main__.py +261 -0
  66. package/worker/mlai_review/_compat.py +29 -0
  67. package/worker/mlai_review/analysis/__init__.py +3 -0
  68. package/worker/mlai_review/analysis/detect.py +50 -0
  69. package/worker/mlai_review/analysis/main.py +128 -0
  70. package/worker/mlai_review/analysis/messages.py +8 -0
  71. package/worker/mlai_review/analysis/tools.py +194 -0
  72. package/worker/mlai_review/application/__init__.py +1 -0
  73. package/worker/mlai_review/application/asking.py +53 -0
  74. package/worker/mlai_review/application/challengers.py +142 -0
  75. package/worker/mlai_review/application/context_builder.py +194 -0
  76. package/worker/mlai_review/application/errors.py +17 -0
  77. package/worker/mlai_review/application/feedback.py +52 -0
  78. package/worker/mlai_review/application/matching.py +46 -0
  79. package/worker/mlai_review/application/messages.py +41 -0
  80. package/worker/mlai_review/application/ports.py +222 -0
  81. package/worker/mlai_review/application/prompts.py +342 -0
  82. package/worker/mlai_review/application/review_service.py +200 -0
  83. package/worker/mlai_review/application/reviewers.py +438 -0
  84. package/worker/mlai_review/application/streaming.py +91 -0
  85. package/worker/mlai_review/application/tools.py +138 -0
  86. package/worker/mlai_review/application/usage.py +145 -0
  87. package/worker/mlai_review/application/write_check.py +46 -0
  88. package/worker/mlai_review/contracts/__init__.py +5 -0
  89. package/worker/mlai_review/contracts/analysis.py +57 -0
  90. package/worker/mlai_review/contracts/review.py +42 -0
  91. package/worker/mlai_review/domain/__init__.py +4 -0
  92. package/worker/mlai_review/domain/changes.py +77 -0
  93. package/worker/mlai_review/domain/context.py +147 -0
  94. package/worker/mlai_review/domain/diagnostics.py +239 -0
  95. package/worker/mlai_review/domain/feedback.py +216 -0
  96. package/worker/mlai_review/domain/findings.py +505 -0
  97. package/worker/mlai_review/domain/lifecycle.py +85 -0
  98. package/worker/mlai_review/domain/partition.py +42 -0
  99. package/worker/mlai_review/domain/relations.py +166 -0
  100. package/worker/mlai_review/domain/relevance.py +202 -0
  101. package/worker/mlai_review/domain/report.py +99 -0
  102. package/worker/mlai_review/domain/structure.py +56 -0
  103. package/worker/mlai_review/domain/writes.py +86 -0
  104. package/worker/mlai_review/eval.py +221 -0
  105. package/worker/mlai_review/eval_cases/clean-rename.json +11 -0
  106. package/worker/mlai_review/eval_cases/missing-ownership-check.json +22 -0
  107. package/worker/mlai_review/eval_cases/off-by-one.json +22 -0
  108. package/worker/mlai_review/eval_cases/sql-injection.json +20 -0
  109. package/worker/mlai_review/feedback_report.py +60 -0
  110. package/worker/mlai_review/infrastructure/__init__.py +1 -0
  111. package/worker/mlai_review/infrastructure/analysis/__init__.py +1 -0
  112. package/worker/mlai_review/infrastructure/analysis/none.py +12 -0
  113. package/worker/mlai_review/infrastructure/analysis/translate.py +17 -0
  114. package/worker/mlai_review/infrastructure/github/__init__.py +0 -0
  115. package/worker/mlai_review/infrastructure/github/client.py +445 -0
  116. package/worker/mlai_review/infrastructure/github/feedback.py +212 -0
  117. package/worker/mlai_review/infrastructure/github/http.py +31 -0
  118. package/worker/mlai_review/infrastructure/github/rendering.py +398 -0
  119. package/worker/mlai_review/infrastructure/github/token.py +20 -0
  120. package/worker/mlai_review/infrastructure/local/__init__.py +1 -0
  121. package/worker/mlai_review/infrastructure/local/analyzer.py +48 -0
  122. package/worker/mlai_review/infrastructure/local/events.py +100 -0
  123. package/worker/mlai_review/infrastructure/local/git_reader.py +233 -0
  124. package/worker/mlai_review/infrastructure/local/publisher.py +138 -0
  125. package/worker/mlai_review/infrastructure/messages.py +54 -0
  126. package/worker/mlai_review/infrastructure/models/__init__.py +0 -0
  127. package/worker/mlai_review/infrastructure/models/openai_compatible.py +269 -0
  128. package/worker/mlai_review/infrastructure/structure/__init__.py +1 -0
  129. package/worker/mlai_review/infrastructure/structure/heuristic.py +186 -0
  130. package/worker/mlai_review/infrastructure/structure/tree_sitter.py +186 -0
  131. package/worker/mlai_review/infrastructure/workspace/__init__.py +1 -0
  132. package/worker/mlai_review/infrastructure/workspace/local.py +105 -0
  133. package/worker/mlai_review/infrastructure/workspace/memory.py +77 -0
  134. package/worker/mlai_review/infrastructure/workspace/paths.py +17 -0
  135. package/worker/mlai_review/pipeline.py +89 -0
  136. package/worker/mlai_review/runtime.py +194 -0
  137. package/worker/mlai_review/settings.py +139 -0
  138. package/worker/model_stream.py +21 -7
  139. package/worker/offline_guard.py +1 -1
  140. package/worker/preview.py +62 -4
  141. package/worker/product_facts.py +20 -0
  142. package/worker/project_context.py +33 -7
  143. package/worker/reply_language.py +92 -10
  144. package/worker/repo_policy.py +5 -0
  145. package/worker/roles.json +199 -37
  146. package/worker/roles.py +271 -9
  147. package/worker/runner.py +366 -53
  148. package/worker/runtime_control.py +64 -3
  149. package/worker/secret_scan.py +3 -2
  150. package/worker/server_memory.py +122 -0
  151. package/worker/site_check.py +279 -0
  152. package/worker/skill_library.py +15 -3
  153. package/worker/skill_pack.py +170 -16
  154. package/worker/subagents.py +6 -2
  155. package/worker/tool_catalog.py +4 -3
  156. package/worker/verification.py +156 -19
  157. package/worker/wakeups.py +56 -4
@@ -14,14 +14,35 @@ import readline from 'node:readline';
14
14
  import process from 'node:process';
15
15
 
16
16
  export const VERSION='0.1.0';
17
- const DEFAULT_URL=process.env.MLAI_URL||'https://mlai-mini-code.vercel.app';
17
+ export const DEFAULT_URL=process.env.MLAI_URL||'https://code.ml.ai';
18
18
  const CONFIG_DIR=process.env.MLAI_CONFIG_DIR||join(process.env.XDG_CONFIG_HOME||join(homedir(),'.config'),'mlai');
19
19
  const CONFIG=join(CONFIG_DIR,'config.json');
20
20
  const LINKS=join(CONFIG_DIR,'projects.json');
21
- const TTY=process.stdout.isTTY&&!process.env.NO_COLOR&&process.env.TERM!=='dumb';
22
- const c={dim:s=>TTY?`\x1b[2m${s}\x1b[0m`:s,bold:s=>TTY?`\x1b[1m${s}\x1b[0m`:s,teal:s=>TTY?`\x1b[36m${s}\x1b[0m`:s,green:s=>TTY?`\x1b[32m${s}\x1b[0m`:s,yellow:s=>TTY?`\x1b[33m${s}\x1b[0m`:s,red:s=>TTY?`\x1b[31m${s}\x1b[0m`:s,gray:s=>TTY?`\x1b[90m${s}\x1b[0m`:s};
21
+ // TTY: a person is at the terminal (prompts, inline approvals). Colour is separate: NO_COLOR and TERM=dumb turn it off,
22
+ // FORCE_COLOR turns it on (or off with 0) even when piped; stderr gets colour only when stderr itself is a terminal.
23
+ const TTY=Boolean(process.stdout.isTTY);
24
+ export function colorOn(stream,env=process.env){
25
+ const f=env.FORCE_COLOR;if(f!==undefined&&f!=='')return !['0','false'].includes(String(f).toLowerCase());
26
+ return Boolean(stream?.isTTY)&&!env.NO_COLOR&&env.TERM!=='dumb';
27
+ }
28
+ const palette=on=>{const k=(code,s)=>on?`\x1b[${code}m${s}\x1b[0m`:s;return {dim:s=>k(2,s),bold:s=>k(1,s),teal:s=>k(36,s),green:s=>k(32,s),yellow:s=>k(33,s),red:s=>k(31,s),gray:s=>k(90,s)}};
29
+ const c=palette(colorOn(process.stdout)),ce=palette(colorOn(process.stderr));
30
+ /** Exit codes scripts can rely on: 0 done, 1 failed, 2 usage (bad command or flag, nothing linked), 130 stopped or interrupted. */
31
+ export const EXIT={ok:0,failed:1,usage:2,stopped:130,auth:4,billing:5};
32
+ /**
33
+ * Run as `mlai cloud ...` from the mlai CLI (MLAI_CLOUD_PARENT is its version): help shows that version and the
34
+ * commands with the `cloud` prefix, and sign-in and plan-limit failures use the same exit codes as mlai (4 and 5).
35
+ * BUG-0470, BUG-0472.
36
+ */
37
+ export const PARENT=process.env.MLAI_CLOUD_PARENT||'';
38
+ export function cloudPrefix(text,parent=PARENT,{keepLogin=false}={}){
39
+ if(!parent)return String(text);
40
+ return String(text).replace(/(^|[\s`'"(])mlai (?!cloud\b)(?=[a-z<])/gm,(m,pre,off,all)=>keepLogin&&/^(login|logout|whoami)\b/.test(all.slice(off+m.length))?m:pre+'mlai cloud ');
41
+ }
23
42
  const MODES={plan:'plan',brief:'brief',guided:'approve',approve:'approve',auto:'auto'};
24
43
  let JSON_OUT=false;
44
+ // `mlai completion bash | head` closes the pipe early; that is not an error.
45
+ process.stdout.on('error',e=>{if(e?.code==='EPIPE')process.exit(0);throw e});
25
46
 
26
47
  // ---------- config ----------
27
48
  function readJson(p,d){try{return JSON.parse(readFileSync(p,'utf8'))}catch{return d}}
@@ -31,12 +52,20 @@ function saveConfig(v){writeJson(CONFIG,v)}
31
52
  function links(){return readJson(LINKS,{})}
32
53
  function linkedProject(dir=process.cwd()){const all=links();let d=resolve(dir);for(;;){if(all[d])return all[d];const up=resolve(d,'..');if(up===d)return null;d=up}}
33
54
  function saveLink(project,dir=process.cwd()){const all=links();all[resolve(dir)]=project;writeJson(LINKS,all)}
34
- function baseUrl(){return (config().url||DEFAULT_URL).replace(/\/$/,'')}
55
+ /**
56
+ * The sign-in to use. MLAI_TOKEN (set by `mlai cloud`, from the `mlai login` sign-in, together with MLAI_URL) wins over
57
+ * the saved config, so both commands use the same account and server; otherwise the token saved by this CLI's login.
58
+ */
59
+ export function signIn(cfg=config(),env=process.env){
60
+ if(env.MLAI_TOKEN)return {url:(env.MLAI_URL||cfg.url||DEFAULT_URL).replace(/\/$/,''),token:String(env.MLAI_TOKEN),label:cfg.token===env.MLAI_TOKEN?cfg.label||'':'mlai login',env:true};
61
+ return {url:(cfg.url||DEFAULT_URL).replace(/\/$/,''),token:cfg.token||'',label:cfg.label||'',env:false};
62
+ }
63
+ function baseUrl(){return signIn().url}
35
64
 
36
65
  // ---------- http ----------
37
66
  class ApiError extends Error{constructor(message,status,code){super(message);this.status=status;this.code=code}}
38
67
  async function api(path,body,{auth=true,method='POST'}={}){
39
- const cfg=config();const headers={'Content-Type':'application/json','User-Agent':'mlai-cli/'+VERSION};
68
+ const cfg=signIn();const headers={'Content-Type':'application/json','User-Agent':'mlai-cli/'+VERSION};
40
69
  if(auth){if(!cfg.token)throw new ApiError('Not signed in. Run `mlai login` first.',401,'no_token');headers.Authorization='Bearer '+cfg.token}
41
70
  const r=await fetch(baseUrl()+path,{method,headers,body:body?JSON.stringify(body):undefined});
42
71
  const text=await r.text();let data;try{data=JSON.parse(text)}catch{data={error:text.slice(0,200)||r.statusText}}
@@ -48,9 +77,18 @@ const ws=(token,action,extra={})=>api('/api/workspace',{action,token,...extra});
48
77
  // ---------- output helpers ----------
49
78
  function out(s=''){process.stdout.write(s+'\n')}
50
79
  function emit(obj){if(JSON_OUT)out(JSON.stringify(obj))}
51
- function fail(msg,code=1){process.stderr.write(c.red('error: ')+msg+'\n');process.exit(code)}
80
+ function fail(msg,code=1){closeInput();process.stderr.write(ce.red('error: ')+cloudPrefix(msg,PARENT,{keepLogin:true})+'\n');process.exit(code)}
52
81
  function wrap(text,indent=' ',width=Math.min(process.stdout.columns||100,110)){const lines=[];for(const para of String(text).split('\n')){let line='';for(const word of para.split(/\s+/)){if((line+' '+word).trim().length>width-indent.length){lines.push(indent+line.trim());line=word}else line+=' '+word}lines.push(indent+line.trim())}return lines.join('\n')}
53
- function ask(question){return new Promise(res=>{const rl=readline.createInterface({input:process.stdin,output:process.stdout});rl.question(question,a=>{rl.close();res(a.trim())})})}
82
+ // One readline for the whole process, so the up arrow brings back earlier tasks and answers in the interactive session.
83
+ let rl=null;
84
+ function input(){
85
+ if(rl)return rl;
86
+ rl=readline.createInterface({input:process.stdin,output:process.stdout,terminal:Boolean(process.stdin.isTTY&&process.stdout.isTTY),historySize:200,removeHistoryDuplicates:true});
87
+ rl.on('SIGINT',()=>process.emit('SIGINT'));rl.on('close',()=>{rl=null});
88
+ return rl;
89
+ }
90
+ function closeInput(){try{rl?.close()}catch{}rl=null}
91
+ function ask(question){return new Promise(res=>{const r=input();let done=false;const end=()=>{if(!done){done=true;res('')}};r.once('close',end);r.question(question,a=>{done=true;r.off('close',end);res(a.trim())})})}
54
92
  function openBrowser(url){const cmd=platform()==='darwin'?'open':platform()==='win32'?'cmd':'xdg-open';const args=platform()==='win32'?['/c','start','',url]:[url];try{const p=spawn(cmd,args,{stdio:'ignore',detached:true});p.on('error',()=>{});p.unref();return true}catch{return false}}
55
93
  function requireProject(opts){const token=opts.project||process.env.MLAI_PROJECT||linkedProject()?.token;if(!token)fail('No project linked to this folder. Run `mlai projects` then `mlai link <name>` or `mlai new`.',2);return token}
56
94
  function timeAgo(ms){const s=Math.max(0,(Date.now()-ms)/1000);if(s<60)return 'just now';if(s<3600)return Math.floor(s/60)+'m ago';if(s<86400)return Math.floor(s/3600)+'h ago';return Math.floor(s/86400)+'d ago'}
@@ -102,7 +140,7 @@ async function login(opts){
102
140
 
103
141
  // ---------- commands ----------
104
142
  const commands={};
105
- const help=`${c.bold('mlai')} ${VERSION} — ML AI Code from your terminal
143
+ const help=(PARENT?`${c.bold('mlai cloud')} — cloud workspaces (ML AI Code ${PARENT})`:`${c.bold('mlai')} ${VERSION} — ML AI Code from your terminal`)+`
106
144
 
107
145
  ${c.bold('Account')}
108
146
  mlai login [--manual] [--url URL] approve this computer in your browser
@@ -116,7 +154,7 @@ ${c.bold('Projects')} (a project is a cloud workspace; link one to a folder)
116
154
  mlai open open the linked project in the web app
117
155
 
118
156
  ${c.bold('Tasks')}
119
- mlai run "<task>" [-m plan|brief|guided|auto] [-r role] [-e low|medium|high] [-s steps] [--no-watch] [--build-brief answers.json]
157
+ mlai run "<task>" [--mode plan|brief|guided|auto] [--role role] [--effort low|medium|high] [--steps n] [--no-watch] [--build-brief answers.json]
120
158
  mlai interactive session: type tasks, answer approvals inline
121
159
  mlai watch | status | stop | resume follow the current run / snapshot / stop / continue
122
160
  mlai steer "<message>" add an instruction while the agent is working
@@ -140,12 +178,24 @@ ${c.bold('Deploys')} (connect a host once in the web app: Deploys)
140
178
  ${c.bold('Catalog')}
141
179
  mlai roles [query] | skills [query] | modes
142
180
 
143
- Global: --json (machine output), -p <project-token>, MLAI_URL, MLAI_PROJECT, NO_COLOR`;
144
- commands.help=async()=>out(help);
145
- commands.version=async()=>out(VERSION);
181
+ ${c.bold('More')}
182
+ mlai doctor check the server, sign-in and linked project
183
+ mlai completion bash|zsh|fish print a shell completion script
184
+ mlai help <command> help for one command (or mlai <command> --help)
185
+
186
+ Global: --json (machine output), --project <token>, MLAI_URL, MLAI_PROJECT, NO_COLOR, FORCE_COLOR
187
+ Exit codes: ${PARENT?'0 done, 1 failed, 2 usage, 4 sign-in needed, 5 plan limit reached, 130 stopped':'0 done, 1 failed, 2 usage error, 130 stopped or interrupted'}`;
188
+ // Prefixed help keeps its columns: the padding after a command shrinks by the length of "cloud ".
189
+ const alignedHelp=()=>PARENT?help.split('\n').map(l=>{const m=/^( \S.*?)( {2,})(\S.*)$/.exec(l);if(!m)return cloudPrefix(l.replace(/^ mlai$/,' mlai cloud'));const a=cloudPrefix(m[1].replace(/^ mlai$/,' mlai cloud'));return a+' '.repeat(Math.max(2,m[1].length+m[2].length-a.length))+cloudPrefix(m[3])}).join('\n'):help;
190
+ commands.help=async opts=>{const name=opts?._?.[0];if(!name)return out(alignedHelp());const h=commandHelp(name);if(!h)fail(unknownCommand(name),EXIT.usage);out(h)};
191
+ commands.version=async()=>out(PARENT||VERSION);
146
192
  commands.login=login;
147
- commands.logout=async()=>{const cfg=config();delete cfg.token;delete cfg.owner;delete cfg.label;saveConfig(cfg);out('Signed out. The token on this computer was forgotten.')};
148
- commands.whoami=async()=>{const me=await api('/api/cli',{action:'whoami'});emit(me);if(!JSON_OUT){out(c.bold('Signed in')+' as '+me.label+c.dim(' · owner '+me.owner.slice(0,8)+'… · '+me.server));out(c.dim('Token expires '+new Date(me.expires).toLocaleString()))}};
193
+ // The server has no token revocation endpoint (CLI tokens are signed and expire on their own), so logout removes it here.
194
+ commands.logout=async()=>{const cfg=config();const had=Boolean(cfg.token);delete cfg.token;delete cfg.owner;delete cfg.label;saveConfig(cfg);out(had?'Signed out. The token was removed from this computer. It cannot be used from here again and expires on its own.':'Already signed out on this computer.')};
195
+ commands.whoami=async()=>{
196
+ // The device sign-in from `mlai login` is checked by `mlai whoami`; this CLI's whoami route takes only its own tokens.
197
+ const si=signIn();if(si.env&&si.token.startsWith('mlaid_')){emit({server:si.url,signIn:'mlai login'});if(!JSON_OUT)out(c.bold('Signed in')+' with mlai login'+c.dim(' · '+si.url+' · run mlai whoami for the account'));return}
198
+ const me=await api('/api/cli',{action:'whoami'});emit(me);if(!JSON_OUT){out(c.bold('Signed in')+' as '+me.label+c.dim(' · owner '+me.owner.slice(0,8)+'… · '+me.server));out(c.dim('Token expires '+new Date(me.expires).toLocaleString()))}};
149
199
 
150
200
  async function listProjects(){const acct=await api('/api/account',null,{method:'GET'});if(!acct.configured)throw new ApiError('This server has no account database; projects cannot be listed.',503);return (acct.workspaces||[]).sort((a,b)=>(b.created||0)-(a.created||0))}
151
201
  commands.projects=async()=>{
@@ -169,7 +219,7 @@ commands.new=async opts=>{
169
219
  saveLink({token:w.token,name:w.name,label:opts.name||w.label||repo.split('/').slice(-2).join('/')||w.name});
170
220
  if(!JSON_OUT)out(c.green('Project ready ')+(repo||'(empty)')+c.dim(' · linked to '+process.cwd()));
171
221
  };
172
- commands.open=async()=>{const url=baseUrl()+'/';out(url);openBrowser(url)};
222
+ commands.open=async opts=>{const name=opts.project?'':linkedProject()?.name;const url=baseUrl()+'/'+(name?'?chat='+encodeURIComponent(name):'');out(url);openBrowser(url)};
173
223
 
174
224
  // ----- run / watch -----
175
225
  function renderEvent(e,state){
@@ -211,7 +261,18 @@ async function answerPending(token,pending,interactive){
211
261
  if(/^n/i.test(a)){await ws(token,'approve',{id:pending.id,approved:false});return true}
212
262
  return false;
213
263
  }
214
- async function watch(token,{interactive=TTY,since=0,quiet=false}={}){
264
+ /** While a run is followed, Ctrl+C leaves it running in the cloud and says how to get back to it. */
265
+ let following=null;
266
+ process.on('SIGINT',()=>{
267
+ closeInput();
268
+ if(following)process.stderr.write('\n'+ce.yellow('Still running.')+' The task keeps going in the cloud. Follow it again with `mlai watch`, or stop it with `mlai stop`.\n');
269
+ else process.stderr.write('\n');
270
+ process.exit(EXIT.stopped);
271
+ });
272
+ /** How a finished run maps to the exit code: completed 0, stopped 130, anything else 1. */
273
+ export function exitFor(state){return state==='completed'||state==='done'||state==='idle'?EXIT.ok:state==='stopped'||state==='cancelled'?EXIT.stopped:EXIT.failed}
274
+ async function watch(token,opts={}){following=token;try{return await follow(token,opts)}finally{following=null}}
275
+ async function follow(token,{interactive=TTY,since=0,quiet=false}={}){
215
276
  const state={finished:null};let lastTime=since;let lastPendingId=null;let idlePolls=0;
216
277
  for(;;){
217
278
  const snap=await ws(token,'status');
@@ -221,7 +282,8 @@ async function watch(token,{interactive=TTY,since=0,quiet=false}={}){
221
282
  if(snap.pending&&snap.pending.id!==lastPendingId){lastPendingId=snap.pending.id;if(!JSON_OUT){const answered=await answerPending(token,snap.pending,interactive);if(!answered&&!interactive)return snap}else out(JSON.stringify({type:'pending',...snap.pending}))}
222
283
  if(!running){
223
284
  const st=snap.status?.state||state.finished||'idle';
224
- if(!JSON_OUT&&!quiet){const comp=snap.completion;out('');out((st==='completed'?c.green('✓ '):st==='stopped'?c.yellow('■ '):c.red('✕ '))+c.bold(st)+(snap.status?.tokens?c.dim(` · ${snap.status.tokens.toLocaleString()} tokens · ${snap.status.calls||0} calls`):'')+(comp?c.dim(` · checks ${comp.checksPassed||0} passed, ${comp.checksFailed||0} failed`):''))}
285
+ process.exitCode=exitFor(st);
286
+ if(!JSON_OUT&&!quiet){const comp=snap.completion;out('');out((st==='completed'?c.green('✓ '):st==='stopped'?c.yellow('■ '):c.red('✕ '))+c.bold(st)+(snap.status?.tokens?c.dim(` · ${(()=>{const v=snap.status.tokens/1e6;return v<0.01?'under 0.01':String(Math.round(v*100)/100)})()} credits · ${snap.status.calls||0} calls`):'')+(comp?c.dim(` · checks ${comp.checksPassed||0} passed, ${comp.checksFailed||0} failed`):''))}
225
287
  return snap;
226
288
  }
227
289
  idlePolls=events.length?0:idlePolls+1;
@@ -229,7 +291,7 @@ async function watch(token,{interactive=TTY,since=0,quiet=false}={}){
229
291
  }
230
292
  }
231
293
  async function startRun(token,task,opts){
232
- const mode=MODES[String(opts.mode||'guided').toLowerCase()];if(!mode)fail('Mode must be plan, brief, guided or auto');
294
+ const mode=MODES[String(opts.mode||'guided').toLowerCase()];if(!mode)fail('Mode must be plan, brief, guided or auto.',EXIT.usage);
233
295
  const body={action:'run',token,task,buildIntake:true,requestId:randomUUID(),mode,effort:['low','medium','high'].includes(opts.effort)?opts.effort:'medium',steps:Math.min(160,Math.max(1,Number(opts.steps)||120)),role:opts.role||'auto',planApproval:mode==='auto'?'off':'guided',tools:[]};
234
296
  if(opts['build-brief'])body.buildAnswers=JSON.parse(readFileSync(String(opts['build-brief']),'utf8'));
235
297
  let r=await api('/api/workspace',body);
@@ -267,6 +329,7 @@ commands.status=async opts=>{
267
329
  if(snap.history?.length){out(c.bold('Recent'));for(const h of snap.history.slice(0,5))out(c.dim(' '+h.state.padEnd(9))+' '+h.task.slice(0,90))}
268
330
  };
269
331
  commands.stop=async opts=>{await ws(requireProject(opts),'stop');out('Stop requested.')};
332
+ commands.completion=async opts=>{const sh=String(opts._[0]||'');const script=completionScript(sh);if(!script)fail('Usage: mlai completion bash|zsh|fish',EXIT.usage);process.stdout.write(script)};
270
333
  commands.resume=async opts=>{const t=requireProject(opts);await ws(t,'resume',{requestId:randomUUID()});out(c.dim('Continuing the previous task…'));await watch(t)};
271
334
  commands.steer=async opts=>{const msg=opts._.join(' ');if(!msg)fail('Usage: mlai steer "<message>"');await ws(requireProject(opts),'steer',{message:msg});out('Instruction delivered.')};
272
335
  async function pendingOrFail(token){const snap=await ws(token,'status');if(!snap.pending)fail('Nothing is waiting for approval.');return snap.pending}
@@ -290,7 +353,7 @@ commands.pull=async opts=>{
290
353
  const stat=spawnSync('git',['diff','--stat'],{encoding:'utf8'}).stdout;out(c.green('Applied workspace changes to this repo.')+'\n'+stat);
291
354
  };
292
355
  commands.sh=async opts=>{const cmd=opts._.join(' ');if(!cmd)fail('Usage: mlai sh "<command>"');const r=await ws(requireProject(opts),'terminal',{command:cmd});process.stdout.write(r.output||'');process.exitCode=r.exitCode||0};
293
- commands.push=async opts=>{const m=opts.m||opts.message;if(!m)fail('Usage: mlai push -m "commit message"');const r=await ws(requireProject(opts),'git_push',{confirm:true,message:m});emit(r);if(!JSON_OUT)out(c.green('Pushed')+(r.branch?' to '+r.branch:'')+(r.url?' · '+r.url:''))};
356
+ commands.push=async opts=>{const m=opts.message||opts.mode;if(!m)fail('Usage: mlai push -m "commit message"');const r=await ws(requireProject(opts),'git_push',{confirm:true,message:m});emit(r);if(!JSON_OUT)out(c.green('Pushed')+(r.branch?' to '+r.branch:'')+(r.url?' · '+r.url:''))};
294
357
  commands.pr=async opts=>{const t=requireProject(opts);const title=opts.title;if(!title)fail('Usage: mlai pr -t "title" [-b "body"]');const plan=await ws(t,'pr_plan');if(!opts.yes&&TTY){out(c.bold('Files in this PR'));for(const f of plan.files||plan.changes||[])out(' '+(f.path||f));const a=await ask('Open a draft PR? [Y/n] ');if(/^n/i.test(a))return}const r=await ws(t,'pr_publish',{confirm:true,title,body:opts.body||'',planHash:plan.planHash});emit(r);if(!JSON_OUT)out(c.green('Draft PR ')+(r.url||JSON.stringify(r)))};
295
358
 
296
359
  // ----- deploys -----
@@ -359,7 +422,7 @@ commands.roles=async opts=>{const q=opts._.join(' ').toLowerCase();const cat=awa
359
422
  let group='';for(const r of roles){if(r.group!==group){group=r.group;out(c.bold('\n'+group))}out(' '+c.teal(r.id.padEnd(12))+r.label.padEnd(20)+c.dim(r.tagline.slice(0,70)))}
360
423
  out(c.dim('\n'+roles.length+' roles · `mlai roles <id>` for tools and decisions · `mlai run -r <id> "…"`'))};
361
424
  commands.skills=async opts=>{const q=opts._.join(' ').toLowerCase();const cat=await catalog();const skills=cat.skills.filter(s=>!q||(s.id+' '+s.name+' '+s.description).toLowerCase().includes(q));emit(skills);if(JSON_OUT)return;for(const s of skills)out(' '+c.teal(s.id.padEnd(28))+c.dim(s.description.slice(0,80)));out(c.dim('\n'+skills.length+' skills'))};
362
- commands.doctor=async()=>{const cfg=config();out('server '+baseUrl());out('token '+(cfg.token?'present ('+(cfg.label||'')+')':'missing — run mlai login'));out('project '+(linkedProject()?.label||'none linked here'));out('node '+process.version);try{const h=await fetch(baseUrl()+'/api/health').then(r=>r.status);out('health HTTP '+h)}catch(e){out(c.red('health unreachable: '+e.message))}};
425
+ commands.doctor=async()=>{const cfg=signIn();out('version '+VERSION);out('server '+cfg.url);out('token '+(cfg.token?'present ('+(cfg.label||'')+')':'missing — run mlai login'));out('project '+(linkedProject()?.label||'none linked here'));out('node '+process.version);try{const h=await fetch(baseUrl()+'/api/health').then(r=>r.status);out('health HTTP '+h)}catch(e){out(c.red('health '+(networkMessage(e,baseUrl())||'unreachable: '+e.message)));process.exitCode=EXIT.failed}};
363
426
 
364
427
  // ----- interactive session -----
365
428
  async function session(opts){
@@ -369,7 +432,7 @@ async function session(opts){
369
432
  const snap=await ws(token,'status');if(snap.status?.state==='running'){out(c.dim('A task is already running; attaching…'));await watch(token)}
370
433
  for(;;){
371
434
  const line=await ask(c.teal('› '));if(!line)continue;
372
- if(line==='/quit'||line==='/exit'||line==='/q')return;
435
+ if(line==='/quit'||line==='/exit'||line==='/q'){process.exitCode=0;return}
373
436
  if(line.startsWith('/mode ')){const m=line.slice(6).trim();if(!MODES[m]){out(c.red('Modes: plan, brief, guided, auto'));continue}mode=m;out(c.dim('mode '+mode));continue}
374
437
  if(line.startsWith('/role ')){role=line.slice(6).trim()||'auto';out(c.dim('role '+role));continue}
375
438
  if(line==='/status'){await commands.status({_:[],project:token});continue}
@@ -381,14 +444,107 @@ async function session(opts){
381
444
  }
382
445
  }
383
446
 
447
+ // ---------- per-command help, typos, flags, completions ----------
448
+ /** usage, what it does, and the flags it takes (besides the global --json, -p/--project, --help). */
449
+ export const COMMANDS={
450
+ login:{usage:'mlai login [--manual] [--url URL] [--token TOKEN]',about:'Approve this computer in your browser. --manual prints a link and asks for the token; --url signs in to another server.',flags:['manual','url','token','browser']},
451
+ logout:{usage:'mlai logout',about:'Remove the token from this computer.'},
452
+ whoami:{usage:'mlai whoami',about:'Show the account this computer is signed in to.'},
453
+ projects:{usage:'mlai projects',about:'List your projects. The one linked to this folder is marked.'},
454
+ new:{usage:'mlai new [github-url] [-n name] [--profile small|medium|large] [-y]',about:'Create a project, empty or from a GitHub repository, and link this folder to it.',flags:['name','backend','profile','yes']},
455
+ link:{usage:'mlai link <name|#n>',about:'Link this folder to an existing project (see mlai projects).'},
456
+ open:{usage:'mlai open',about:'Open the linked chat in the web app.'},
457
+ run:{usage:'mlai run "<task>" [--mode plan|brief|guided|auto] [--role role] [--effort low|medium|high] [--steps n] [--no-watch] [--build-brief answers.json]',about:'Start a task in the linked project and follow it. Ctrl+C stops following; the task keeps running. Exits 0 when it completes, 1 when it fails, 130 when it was stopped.',flags:['mode','role','effort','steps','watch','build-brief']},
458
+ watch:{usage:'mlai watch',about:'Follow the current run and answer approvals inline.'},
459
+ status:{usage:'mlai status',about:'Show the current state, task list, approval and recent runs.'},
460
+ stop:{usage:'mlai stop',about:'Stop the current run.'},
461
+ resume:{usage:'mlai resume',about:'Continue the previous task.'},
462
+ steer:{usage:'mlai steer "<message>"',about:'Add an instruction while the agent is working.'},
463
+ approve:{usage:'mlai approve [--all]',about:'Approve what is waiting. --all approves the rest of this run.',flags:['all']},
464
+ reject:{usage:'mlai reject',about:'Reject what is waiting.'},
465
+ reply:{usage:'mlai reply "<feedback>"',about:'Brief mode: send feedback on the task list.'},
466
+ ls:{usage:'mlai ls',about:'List the files in the workspace.'},
467
+ cat:{usage:'mlai cat <file>',about:'Print a file from the workspace.'},
468
+ diff:{usage:'mlai diff',about:'Show the uncommitted changes.'},
469
+ patch:{usage:'mlai patch',about:'Print the uncommitted changes as a patch.'},
470
+ pull:{usage:'mlai pull [-y]',about:'Apply the workspace changes to this git repository (git apply --3way).',flags:['yes']},
471
+ sh:{usage:'mlai sh "<command>"',about:'Run a shell command in the workspace (90 second limit). Exits with the command\'s exit code.'},
472
+ push:{usage:'mlai push -m "message"',about:'Commit and push to the linked GitHub repository.',flags:['message','mode']},
473
+ pr:{usage:'mlai pr -t "title" [-b body] [-y]',about:'Open a draft pull request.',flags:['title','body','yes']},
474
+ deploys:{usage:'mlai deploys',about:'Production, the latest preview and recent deployments.'},
475
+ preview:{usage:'mlai preview [--no-wait] [-y]',about:'Deploy the workspace as a preview and print the URL.',flags:['wait','yes']},
476
+ promote:{usage:'mlai promote [deployment] [-y]',about:'Review checks and promote a preview to production.',flags:['yes']},
477
+ rollback:{usage:'mlai rollback [deployment] [-y]',about:'Roll production back (default: the build before the last change).',flags:['yes']},
478
+ roles:{usage:'mlai roles [query]',about:'List agent roles, or show one.'},
479
+ skills:{usage:'mlai skills [query]',about:'List skills.'},
480
+ modes:{usage:'mlai modes',about:'List run modes.'},
481
+ doctor:{usage:'mlai doctor',about:'Check the server address, sign-in, linked project, Node version and that the server answers.'},
482
+ completion:{usage:'mlai completion bash|zsh|fish',about:'Print a completion script. Add `source <(mlai completion bash)` to ~/.bashrc, `source <(mlai completion zsh)` to ~/.zshrc, or run `mlai completion fish > ~/.config/fish/completions/mlai.fish`.'},
483
+ help:{usage:'mlai help [command]',about:'Show help.'},
484
+ version:{usage:'mlai version',about:'Print the version.'},
485
+ };
486
+ const GLOBAL_FLAGS=['json','project','help','version'];
487
+ const SESSION_FLAGS=['mode','role'];
488
+ export function commandHelp(name){const h=COMMANDS[name];if(!h)return '';const f=(h.flags||[]).map(x=>'--'+x);return cloudPrefix(`${c.bold('Usage')} ${h.usage}\n\n${wrap(h.about,' ')}${f.length?'\n\n'+c.bold('Options')+' '+f.join(' '):''}\n${c.dim('Global: --json, --project <token>, --help')}`)}
489
+ /** Edit distance, for "did you mean". */
490
+ function distance(a,b){const d=Array.from({length:a.length+1},(_,i)=>[i]);for(let j=1;j<=b.length;j++)d[0][j]=j;for(let i=1;i<=a.length;i++)for(let j=1;j<=b.length;j++)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),i>1&&j>1&&a[i-1]===b[j-2]&&a[i-2]===b[j-1]?d[i-2][j-2]+1:Infinity);return d[a.length][b.length]}
491
+ export function didYouMean(word,options){
492
+ const w=String(word||'').toLowerCase();let best='',score=Infinity;
493
+ for(const o of options){const d=o.startsWith(w)&&w.length>=2?0.5:distance(w,o);if(d<score){score=d;best=o}}
494
+ return score<=Math.max(1,Math.floor(w.length/3))?best:'';
495
+ }
496
+ function unknownCommand(name){const m=didYouMean(name,Object.keys(COMMANDS));return `Unknown command "${name}".`+(m?` Did you mean \`mlai ${m}\`?`:'')+' Run `mlai help` for the list.'}
497
+ /** Flags a command does not take, and values that cannot work. Returns an error message or ''. */
498
+ export function checkFlags(name,opts){
499
+ const allowed=new Set([...GLOBAL_FLAGS,...(name?COMMANDS[name]?.flags||[]:SESSION_FLAGS)]);
500
+ for(const k of Object.keys(opts)){
501
+ if(k==='_'||allowed.has(k))continue;
502
+ const flag=k.length===1?'-'+k:'--'+k;const m=didYouMean(k,[...allowed]);
503
+ return `Unknown option ${flag}${name?' for mlai '+name:''}.`+(m?` Did you mean --${m}?`:'')+` See \`mlai help${name?' '+name:''}\`.`;
504
+ }
505
+ if(name!=='push'&&opts.mode!==undefined&&!MODES[String(opts.mode).toLowerCase()])return 'Mode must be plan, brief, guided or auto.';
506
+ if(opts.effort!==undefined&&!['low','medium','high'].includes(opts.effort))return 'Effort must be low, medium or high.';
507
+ if(opts.steps!==undefined&&!(/^\d+$/.test(String(opts.steps))&&Number(opts.steps)>=1&&Number(opts.steps)<=160))return 'Steps must be a whole number from 1 to 160.';
508
+ if(opts.profile!==undefined&&!['small','medium','large'].includes(opts.profile))return 'Profile must be small, medium or large.';
509
+ for(const k of ['project','role','title','body','name','message','url','token','build-brief'])if(opts[k]===true&&allowed.has(k)&&!(name==='login'&&k==='token'))return `--${k} needs a value.`;
510
+ return '';
511
+ }
512
+ export function completionScript(sh){
513
+ const cmds=Object.keys(COMMANDS).join(' ');
514
+ if(sh==='bash')return `# mlai completion for bash\n_mlai(){ local cur=\${COMP_WORDS[COMP_CWORD]}; if [ \$COMP_CWORD -eq 1 ]; then COMPREPLY=( \$(compgen -W "${cmds}" -- "\$cur") ); elif [[ "\$cur" == -* ]]; then COMPREPLY=( \$(compgen -W "--json --project --help --mode --role --effort --steps --no-watch --all --yes" -- "\$cur") ); fi; }\ncomplete -F _mlai mlai\n`;
515
+ if(sh==='zsh')return `#compdef mlai\n# mlai completion for zsh\n_mlai(){ local -a cmds; cmds=(${Object.entries(COMMANDS).map(([k,v])=>`'${k}:${v.about.split('.')[0].replace(/['\:]/g,'')}'`).join(' ')}); if (( CURRENT == 2 )); then _describe 'command' cmds; else _arguments '--json[machine output]' '--project[project token]:token' '--help[help]' '--mode[run mode]:mode:(plan brief guided auto)' '--effort[effort]:effort:(low medium high)' '--all' '--yes'; fi }\ncompdef _mlai mlai\n`;
516
+ if(sh==='fish')return `# mlai completion for fish\ncomplete -c mlai -f\n${Object.entries(COMMANDS).map(([k,v])=>`complete -c mlai -n '__fish_use_subcommand' -a ${k} -d '${v.about.split('.')[0].replace(/'/g,'')}'`).join('\n')}\ncomplete -c mlai -l json -d 'Machine output'\ncomplete -c mlai -s p -l project -r -d 'Project token'\ncomplete -c mlai -s m -l mode -xa 'plan brief guided auto'\ncomplete -c mlai -s e -l effort -xa 'low medium high'\n`;
517
+ return '';
518
+ }
519
+ /** fetch failures as plain sentences instead of "fetch failed". */
520
+ export function networkMessage(e,url){
521
+ const code=e?.cause?.code||e?.cause?.errors?.[0]?.code||e?.code||'';const host=(()=>{try{return new URL(url).host}catch{return url}})();
522
+ if(!code&&!(e instanceof TypeError&&/fetch failed/i.test(e.message)))return '';
523
+ if(['ENOTFOUND','EAI_AGAIN'].includes(code))return `Could not find ${host}. Check your internet connection, or the server address (mlai login --url, MLAI_URL).`;
524
+ if(code==='ECONNREFUSED')return `${host} refused the connection. The server may be down or the address wrong (mlai login --url, MLAI_URL).`;
525
+ if(['ETIMEDOUT','UND_ERR_CONNECT_TIMEOUT','UND_ERR_HEADERS_TIMEOUT'].includes(code))return `${host} did not answer in time. Check your connection and try again.`;
526
+ if(['ECONNRESET','UND_ERR_SOCKET','EPIPE'].includes(code))return `The connection to ${host} dropped. Try again.`;
527
+ if(/CERT|SSL|TLS/i.test(code))return `Could not make a secure connection to ${host} (${code}). A proxy or firewall may be in the way.`;
528
+ if(['ENETUNREACH','EHOSTUNREACH'].includes(code))return `No network route to ${host}. Check your internet connection.`;
529
+ return `Could not reach ${host}${code?' ('+code+')':''}. Check your internet connection.`;
530
+ }
531
+
384
532
  // ---------- main ----------
385
533
  export async function main(argv=process.argv.slice(2)){
386
- const opts=parseArgs(argv);JSON_OUT=opts.json===true;
387
- if(opts.version)return commands.version();
388
- const name=opts._.shift();
389
- if(opts.help||name==='help')return commands.help();
390
- if(!name)return session(opts);
391
- const fn=commands[name];if(!fn)fail(`Unknown command "${name}". Run \`mlai help\`.`,2);
392
- try{await fn(opts)}catch(e){if(e instanceof ApiError){if(e.code==='workspace_missing')fail('This project no longer exists. `mlai projects` to pick another.');fail(e.message)}if(e?.code==='ECONNREFUSED'||e?.cause?.code)fail('Could not reach '+baseUrl()+' ('+(e.cause?.code||e.code)+')');throw e}
534
+ try{
535
+ const opts=parseArgs(argv);JSON_OUT=opts.json===true;
536
+ if(opts.version&&!opts._.length)return await commands.version();
537
+ const name=opts._.shift();
538
+ if(name==='help')return await commands.help(opts);
539
+ if(name&&!commands[name])fail(unknownCommand(name),EXIT.usage);
540
+ if(opts.help){if(name)return out(commandHelp(name));return await commands.help({_:[]})}
541
+ const bad=checkFlags(name,opts);if(bad)fail(bad,EXIT.usage);
542
+ if(!name)return await session(opts);
543
+ await commands[name](opts);
544
+ }catch(e){
545
+ if(e instanceof ApiError){if(e.code==='workspace_missing')fail('This project no longer exists. `mlai projects` to pick another.');fail(e.message,PARENT&&e.status===401?EXIT.auth:PARENT&&(e.status===402||e.code==='billing_limit')?EXIT.billing:EXIT.failed)}
546
+ const net=networkMessage(e,baseUrl());if(net)fail(net);
547
+ fail(e?.message||String(e));
548
+ }finally{closeInput()}
393
549
  }
394
550
  if(import.meta.url===`file://${process.argv[1]}`||process.argv[1]?.endsWith('/mlai')||process.argv[1]?.endsWith('mlai.mjs'))main();
@@ -21,12 +21,14 @@ import uuid
21
21
  VERSION = 'architecture-v1.1-ts6.0.2'
22
22
  MAX_FILES, MAX_BYTES, MAX_FILE = 10000, 64 * 1024 * 1024, 512 * 1024
23
23
  MAX_SNAPSHOTS, MAX_DECISIONS = 120, 2000
24
- EXT = {'.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs', '.mts', '.cts', '.py'}
24
+ # BUG-0240: HTML pages and CSS files are on the map too (script, stylesheet and @import links).
25
+ MARKUP = {'.html', '.htm', '.css'}
26
+ EXT = {'.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs', '.mts', '.cts', '.py'} | MARKUP
25
27
  SKIP = {'.git', 'node_modules', '.next', 'dist', 'build', '.venv', 'venv', '__pycache__', 'vendor', 'coverage', '.turbo'}
26
28
  LIMITATIONS = [
27
29
  'Syntax imports only; not a call graph or runtime evidence.',
28
30
  'Dynamic imports, require(), reflection and generated dependencies are not resolved.',
29
- 'Only local TS/JS and Python modules; no dependency installation or type checking.',
31
+ 'Only local TS/JS and Python modules, plus HTML script/stylesheet links and CSS @import; no dependency installation or type checking.',
30
32
  'Root tsconfig/jsconfig paths only; inherited and nested configs are not resolved.',
31
33
  'Renames appear as added and removed files. No inferred identity.',
32
34
  'Workspace-local history is retained with the computer; deletion removes it.',
@@ -120,6 +122,31 @@ def parse_python(path, text):
120
122
  imports.append({'spec':n.module or '', 'line':n.lineno, 'level':n.level})
121
123
  return {'imports':imports, 'symbols':symbols, 'error':False}
122
124
 
125
+ HTML_LINK = re.compile(r'<script\b[^>]*?\bsrc\s*=\s*["\']([^"\']+)["\']|<link\b(?=[^>]*\brel\s*=\s*["\']?(?:stylesheet|modulepreload)\b)[^>]*?\bhref\s*=\s*["\']([^"\']+)["\']', re.I)
126
+ CSS_IMPORT = re.compile(r'@import\s+(?:url\(\s*)?["\']?([^"\')\s;]+)', re.I)
127
+
128
+ def parse_markup(path, text):
129
+ """Local files an HTML page loads (scripts, stylesheets) or a CSS file @imports. Syntax only."""
130
+ imports, symbols = [], []
131
+ pattern = CSS_IMPORT if path.lower().endswith('.css') else HTML_LINK
132
+ for m in pattern.finditer(text):
133
+ spec = next(g for g in m.groups() if g)
134
+ if len(imports) < 500: imports.append({'spec':spec, 'line':text.count('\n', 0, m.start()) + 1, 'markup':True})
135
+ if not path.lower().endswith('.css'):
136
+ title = re.search(r'<title[^>]*>([^<]{1,120})</title>', text, re.I)
137
+ if title and title.group(1).strip(): symbols.append({'name':title.group(1).strip(), 'line':text.count('\n', 0, title.start()) + 1})
138
+ return {'imports':imports, 'symbols':symbols, 'error':False}
139
+
140
+ def resolve_markup(path, spec, paths):
141
+ """A page or stylesheet link to a file in this repository; URLs and CDNs are not files here."""
142
+ spec = spec.split('#', 1)[0].split('?', 1)[0].strip()
143
+ if not spec or re.match(r'^(?:[a-z][a-z0-9+.-]*:|//)', spec, re.I): return None, 'unresolved'
144
+ parent = str(PurePosixPath(path).parent)
145
+ options = [normalize(spec.lstrip('/')), normalize('public/' + spec.lstrip('/'))] if spec.startswith('/') else [normalize(parent + '/' + spec)]
146
+ for option in options:
147
+ if option and option in paths: return option, 'relative'
148
+ return None, 'unresolved'
149
+
123
150
  def parse_batch(items, parser, compiler):
124
151
  if not items: return []
125
152
  r = subprocess.run(['node', '--max-old-space-size=256', str(parser), str(compiler)],
@@ -246,6 +273,7 @@ def capture(repo, home, ref='working', parser=None, compiler=None):
246
273
  row = db.execute('SELECT data FROM facts WHERE id=?', (key,)).fetchone()
247
274
  if row: facts[path] = json.loads(row[0]); cov['cached'] += 1
248
275
  elif path.endswith('.py'): facts[path] = parse_python(path,content[path]); cov['parsed'] += 1
276
+ elif PurePosixPath(path).suffix.lower() in MARKUP: facts[path] = parse_markup(path,content[path]); cov['parsed'] += 1
249
277
  else: missing.append({'path':path,'text':content[path]})
250
278
  for i in range(0,len(missing),100):
251
279
  batch = missing[i:i+100]
@@ -260,12 +288,13 @@ def capture(repo, home, ref='working', parser=None, compiler=None):
260
288
  f = facts[path]
261
289
  cov['errors'] += int(bool(f.get('error')))
262
290
  if path.endswith('.json'): continue
263
- kind = 'test' if re.search(r'(^|/)(tests?|__tests__)/|\.(test|spec)\.', path) else 'route' if re.search(r'(^|/)(src/)?app/(.*/)?(page|route)\.[tj]sx?$',path) else 'component' if path.endswith(('.tsx','.jsx')) else 'module'
291
+ markup = PurePosixPath(path).suffix.lower() in MARKUP
292
+ kind = 'route' if markup and not path.lower().endswith('.css') else 'module' if markup else 'test' if re.search(r'(^|/)(tests?|__tests__)/|\.(test|spec)\.', path) else 'route' if re.search(r'(^|/)(src/)?app/(.*/)?(page|route)\.[tj]sx?$',path) else 'component' if path.endswith(('.tsx','.jsx')) else 'module'
264
293
  nodes.append(dict(id=path,path=path,kind=kind,hash=manifest[path],symbols=f.get('symbols',[])[:200]))
265
294
  # Syntax errors never produce authoritative edges from recovered parser nodes.
266
295
  if f.get('error'): continue
267
296
  for imp in f.get('imports',[])[:500]:
268
- target,basis = resolve_python(path,imp['spec'],imp.get('level',0),source_paths) if path.endswith('.py') else resolve_js(path,imp['spec'],source_paths,config)
297
+ target,basis = resolve_markup(path,imp['spec'],source_paths) if markup else resolve_python(path,imp['spec'],imp.get('level',0),source_paths) if path.endswith('.py') else resolve_js(path,imp['spec'],source_paths,config)
269
298
  if not target: cov['unresolved'] += 1; continue
270
299
  if target.startswith('pkg:'): external.add(target)
271
300
  evidence = dict(path=path,line=imp['line'],basis='syntax',resolution=basis)
@@ -11,6 +11,24 @@ PREVIEW_HOST='preview-check.vercel.run'
11
11
  # Laptop runs ship the whole worker folder; cloud computers may not have browser_local.py (lib/worker-files.ts).
12
12
  try:import browser_local
13
13
  except ImportError:browser_local=None
14
+ CONTROL_ROLES=('button','link','menuitem','tab','checkbox','radio','switch','option','textbox','combobox','searchbox')
15
+ def step_locator(page,step):
16
+ """The element a click/fill/press step means. CLI bug list (0.3.3): a click with only a name ("Start a conversation",
17
+ a link) ran page.locator('') and failed with 'Unexpected token "" while parsing css selector'. A name alone now
18
+ finds the control by its accessible name, then by its label or visible text."""
19
+ role,name,selector=step.get('role'),step.get('name'),str(step.get('selector') or '').strip()
20
+ if role:return page.get_by_role(role,name=name,exact=True) if name else page.get_by_role(role)
21
+ if selector:return page.locator(selector)
22
+ if name:
23
+ name=str(name)
24
+ found=None
25
+ for r in CONTROL_ROLES:
26
+ loc=page.get_by_role(r,name=name,exact=True)
27
+ found=loc if found is None else found.or_(loc)
28
+ found=found.or_(page.get_by_label(name,exact=True)).or_(page.get_by_text(name,exact=True))
29
+ return found.first
30
+ raise ValueError('This step needs a selector, a role or a name to find the element.')
31
+
14
32
  def on_laptop():return bool(browser_local) and browser_local.laptop()
15
33
 
16
34
  def local_url(value):
@@ -80,7 +98,7 @@ def scenario(args,output):
80
98
  page.goto(as_preview(step['url']),wait_until='domcontentloaded');timeline[-1]['state']='passed';continue
81
99
  if action not in ('click','fill','press','assert_text'):raise ValueError('Unknown browser action')
82
100
  if action=='assert_text':page.get_by_text(str(step.get('text','')),exact=False).first.wait_for(state='visible');timeline[-1]['state']='passed';continue
83
- locator=page.get_by_role(step['role'],name=step.get('name'),exact=True) if step.get('role') else page.locator(str(step.get('selector','')))
101
+ locator=step_locator(page,step)
84
102
  if action=='click':locator.click()
85
103
  elif action=='fill':locator.fill(str(step.get('value',''))[:5000])
86
104
  else:locator.press(str(step.get('key','Enter'))[:50])
@@ -75,17 +75,33 @@ def read_plan(repo):
75
75
  _PHASE = re.compile(r'^#{2,3}\s*Phase\s+(\d+)\s*(?:[:.\u2014\u2013-]\s*)?(.*)$', re.I | re.M)
76
76
  _ITEM = re.compile(r'^\s*[-*]\s*\[( |x|X)\]\s*(.+)$', re.M)
77
77
 
78
+ # "(done)", "[complete]", "- delivered", a bare "delivered" or a check mark after the phase number mark the phase finished.
79
+ _DONE_MARK = re.compile(r'(?:^|\(|\[|\s[\u2014\u2013-]\s)\s*(?:delivered|done|complete|completed|shipped|finished)\s*[)\]]?\s*$|[\u2705\u2714\u2611]', re.I)
80
+ _STATUS_SUFFIX = re.compile(r'\s*(?:[(\[](?:done|complete|completed|delivered|shipped|finished|in progress|next|current)[)\]]|\s[\u2014\u2013-]\s*(?:done|complete|completed|delivered|shipped|finished)|[\u2705\u2714\u2611])\s*$', re.I)
81
+
78
82
  def parse_phases(plan):
79
- """Phases from PLAN.md headings (## Phase N: title) with their checkbox deliverables."""
80
- phases = []
83
+ """Phases from PLAN.md headings (## Phase N: title) with their checkbox deliverables.
84
+ A second heading with the same number ("### Phase 4 delivered", a summary the agent writes after finishing) belongs to
85
+ that phase; it used to become a new, unfinished Phase 4 with no items, so Start Phase 4 kept reappearing and each press
86
+ started a paid run that had nothing to do."""
87
+ phases, by_number = [], {}
81
88
  matches = list(_PHASE.finditer(plan or ''))
82
89
  for i, m in enumerate(matches):
83
90
  body = plan[m.end():matches[i + 1].start() if i + 1 < len(matches) else len(plan)]
84
91
  items = [{'text': t.strip()[:200], 'done': c.lower() == 'x'} for c, t in _ITEM.findall(body)][:30]
85
- title = re.sub(r'\s*\((?:done|complete|in progress|next|current)\)\s*$', '', m.group(2).strip(), flags=re.I)[:120]
86
- marker = m.group(2).lower()
87
- done = bool(items) and all(x['done'] for x in items) or '(done)' in marker or '(complete)' in marker
88
- phases.append({'number': int(m.group(1)), 'title': title or 'Phase ' + m.group(1), 'items': items, 'done': done})
92
+ number, raw = int(m.group(1)), m.group(2).strip()
93
+ marked = bool(_DONE_MARK.search(raw))
94
+ if number in by_number:
95
+ p = by_number[number]
96
+ p['items'] = (p['items'] + items)[:30]; p['_marked'] = p['_marked'] or marked
97
+ continue
98
+ title = _STATUS_SUFFIX.sub('', raw)[:120]
99
+ if _DONE_MARK.fullmatch(title.strip() or 'x'): title = ''
100
+ p = {'number': number, 'title': title or 'Phase ' + m.group(1), 'items': items, '_marked': marked}
101
+ phases.append(p); by_number[number] = p
102
+ for p in phases:
103
+ p['done'] = bool(p['items']) and all(x['done'] for x in p['items']) or p.pop('_marked')
104
+ p.pop('_marked', None)
89
105
  current = next((p for p in phases if not p['done']), None)
90
106
  for p in phases:
91
107
  p['status'] = 'done' if p['done'] else ('current' if p is current else 'planned')
@@ -106,6 +122,8 @@ ARCHITECT_GUIDANCE = '''Build planning (this is a request to build a product): w
106
122
  3. Create the task plan from Phase 1 deliverables only, each item prefixed "Phase 1:". Implement only Phase 1 in this run.
107
123
  4. Verify Phase 1 actually works (build, tests, and the running preview where possible), then tick its boxes in PLAN.md.
108
124
  5. Finish with a short summary: what Phase 1 delivered, how to open it, and what Phase 2 will add. Do not start Phase 2 until the user asks.
125
+ 6. Never link to a page that does not exist. Navigation, buttons and footer links may only point at routes built in this run; add links to later pages when their phase builds them.
126
+ 7. If anything is still broken at the end (a page that errors, a failing check), fix it before finishing. If you cannot, say plainly that it is still open; never call broken work complete or verified.
109
127
  '''
110
128
 
111
129
  _PREFIX = re.compile(r'^\s*phase\s*(\d+)\s*[:.\u2014\u2013-]\s*', re.I)
@@ -163,8 +181,37 @@ def continuation_guidance(phase):
163
181
  'Keep earlier phases working. Update PLAN.md if the architecture changes, verify the phase works end to end, tick its boxes, and finish with what it delivered and what the next phase adds.\n'
164
182
  'Remaining deliverables:\n' + (items or '- (see PLAN.md)') + '\n\n')
165
183
 
184
+ # Resume wraps the person's request (lib/resume-task.ts): "Continue the previous task: <request>" plus notes for the agent.
185
+ _RESUME_PREFIX = 'Continue the previous task:'
186
+ _RESUME_NOTES = ('The previous attempt stopped. Inspect the current files', 'The person saw your last reply only up to here:')
187
+
188
+ def original_task(task):
189
+ """The person's own request inside any number of Resume wrappers. Resume says "continue", which is not a request to
190
+ continue the plan: a resumed edit must stay that edit, not restart the first unticked phase of PLAN.md."""
191
+ t = str(task or '').strip()
192
+ for _ in range(50):
193
+ if not t.startswith(_RESUME_PREFIX): break
194
+ t = t[len(_RESUME_PREFIX):].strip()
195
+ cut = [i for i in (t.find(n) for n in _RESUME_NOTES) if i >= 0]
196
+ return (t[:min(cut)] if cut else t).strip()
197
+
166
198
  def planning_guidance(task, repo, mode='approve', phase1=None):
167
- """Prompt prefix for build requests and phase continuations; empty for everything else."""
199
+ """Prompt prefix for build requests and phase continuations; empty for everything else. A resumed task is judged by
200
+ the request it resumes, so Resume never turns an ordinary follow-up into "start the next unfinished phase".
201
+ An explicit size ("a marketing website with 10 pages") binds this run: all of it is built now, never split into
202
+ phases on the agent's own initiative (bug report Nov 16 2026: 2 of 10 pages built, 7 nav links left 404ing)."""
203
+ task = original_task(task)
204
+ guidance = _planning_guidance(task, repo, mode, phase1)
205
+ try:
206
+ from site_check import requested_scope, scope_rule
207
+ rule = scope_rule(requested_scope(task)) if (guidance or is_build_request(task, source_files(repo)) or re.search(_BUILD_VERB, (task or '').lower())) else ''
208
+ except Exception:
209
+ rule = ''
210
+ if not rule: return guidance
211
+ if mode == 'plan': return guidance + rule + '\n\n'
212
+ return (guidance.rstrip('\n') + '\n' if guidance else '') + rule + '\n\n'
213
+
214
+ def _planning_guidance(task, repo, mode='approve', phase1=None):
168
215
  plan = read_plan(repo)
169
216
  phases = parse_phases(plan) if plan else []
170
217
  current = next((p for p in phases if p['status'] == 'current'), None)
@@ -185,3 +232,24 @@ def planning_guidance(task, repo, mode='approve', phase1=None):
185
232
  + (phase1.strip() + ' ' if phase1 else 'Phase 1 must be a thin working slice the user can open; ') + 'Each phase lists deliverables and an acceptance check.\n\n')
186
233
  rule = (phase1.strip() + ' Every later phase also ends with something working. Order phases by user value and risk.') if phase1 else DEFAULT_PHASE1
187
234
  return ARCHITECT_GUIDANCE.replace('{phase1}', rule) + '\n'
235
+
236
+
237
+ PHASE_CHIP = re.compile(r'^\s*Continue with Phase (\d+):.*from PLAN\.md\.?\s*$', re.I | re.S)
238
+
239
+ def finished_phase_reply(repo, task):
240
+ """The Start Phase button sends "Continue with Phase N: ... from PLAN.md.". When PLAN.md already shows that phase as
241
+ finished, the run answers at once without calling the model, so a repeated press costs nothing (one user ran
242
+ the same finished phase six times). Returns '' when the run should go ahead."""
243
+ m = PHASE_CHIP.match(str(task or ''))
244
+ if not m: return ''
245
+ try: plan = (Path(repo) / 'PLAN.md').read_text(errors='replace')
246
+ except OSError: return ''
247
+ phases = parse_phases(plan)
248
+ number = int(m.group(1))
249
+ phase = next((p for p in phases if p['number'] == number), None)
250
+ if not phase or not phase['done']: return ''
251
+ upcoming = next((p for p in phases if not p['done']), None)
252
+ head = 'Phase %d (%s) is already finished in PLAN.md, so there was nothing new to build and no credits were used.' % (number, phase['title'])
253
+ if upcoming:
254
+ return head + ' The next one is Phase %d: %s. Start it when you are ready, or tell me what to change first.' % (upcoming['number'], upcoming['title'])
255
+ return head + ' All phases in the plan are complete. Tell me what you would like to add or improve next.'
@@ -270,7 +270,10 @@ if __name__ == '__main__':
270
270
  import sys
271
271
  try:
272
272
  action, root, argument = sys.argv[1:4]
273
- result = export_chat(root, argument, sys.argv[4] == 'true') if action == 'export' else import_chat(root, argument)
273
+ if action == 'turns': # BUG-0465: the whole conversation for Export current conversation
274
+ result = chat_turns(Path(root), argument)
275
+ else:
276
+ result = export_chat(root, argument, sys.argv[4] == 'true') if action == 'export' else import_chat(root, argument)
274
277
  print(json.dumps(result))
275
278
  except Exception as error:
276
279
  print(json.dumps({'code': 'fork_refused', 'error': str(error)[:500]}))