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
@@ -20,19 +20,21 @@ TOOLS = [
20
20
  'inputSchema': {'type': 'object', 'properties': {'budget': {'type': 'integer', 'description': 'Approximate characters, 1000-16000'}}}},
21
21
  {'name': 'symbols', 'description': 'Find Python declarations (AST) and JS/TS declaration candidates by name or within a path. Faster than reading files to locate a definition.',
22
22
  'inputSchema': {'type': 'object', 'properties': {'query': {'type': 'string'}, 'path': {'type': 'string'}}}},
23
- {'name': 'memory', 'description': 'Project memory that persists across tasks on this computer. save {name, type: project|user|feedback|reference, description, content} stores one durable fact (how to run or test this project, a convention, a stated preference, a correction, where something lives); saving an existing name replaces it. read {name} returns a fact listed in the memory index; list shows all; forget {name} removes one. Never store secrets.',
23
+ {'name': 'memory', 'description': 'Computer memory that persists across tasks on this chat\'s computer only (not the sidebar project Memory card). save {name, type: project|user|feedback|reference, description, content} stores one durable fact (how to run or test this project, a convention, a stated preference, a correction, where something lives); saving an existing name replaces it. read {name} returns a fact listed in the memory index; list shows all; forget {name} removes one. Never store secrets.',
24
24
  'inputSchema': {'type': 'object', 'properties': {'action': {'type': 'string', 'enum': ['save', 'read', 'list', 'forget']}, 'name': {'type': 'string'}, 'type': {'type': 'string', 'enum': ['project', 'user', 'feedback', 'reference']}, 'description': {'type': 'string'}, 'content': {'type': 'string'}}, 'required': ['action']}},
25
25
  ]
26
26
 
27
27
  TOOLS.append({'name': 'schedule_wakeup', 'description': 'Resume this session later instead of waiting or polling: when the work depends on something outside your control (a deploy, CI, a review, a time of day). Give in_minutes or at (ISO 8601 with time zone), plus a note saying what to check then. Between 5 minutes and 30 days; a new wakeup replaces the pending one; cancel: true removes it. After scheduling, finish the turn with a short summary of what is pending.',
28
28
  'inputSchema': {'type': 'object', 'properties': {'in_minutes': {'type': 'number', 'minimum': 5}, 'at': {'type': 'string'}, 'note': {'type': 'string'}, 'cancel': {'type': 'boolean'}}}})
29
29
 
30
- from image_generation import TOOL as IMAGE_TOOL
30
+ from image_generation import TOOL as IMAGE_TOOL, IMAGE_REJECTED, image_tokens
31
+ from media_tools import STOCK_TOOL, BRAND_TOOL
32
+ import deck_tools
31
33
  from repo_memory import TOOL as MEMORY_PROPOSE_TOOL
32
34
  import computer_use
33
35
 
34
- WRITE_TOOLS = [IMAGE_TOOL, MEMORY_PROPOSE_TOOL,
35
- {'name': 'browser', 'description': 'Open the local app (http://127.0.0.1:3000 by default, start it with preview first; it is browsed under a preview-style *.vercel.run host, the way the user reaches it, so dev-server host and origin blocks show up here) in headless Chromium at a given viewport, run up to 12 steps and take a screenshot. Reports page errors, console errors, failed requests, horizontal overflow, visible text and whether the page became interactive (hydrated). For UI work check a phone width (<=480) and a desktop width (>=1024) with at least one click/fill/press and an assert_text. Each call starts a fresh browser profile: localStorage, cookies and sessions from an earlier call are gone, so do every step that depends on saved state (sign in, add items, then a goto step to the same URL to reload, then assert_text) inside one call.',
36
+ WRITE_TOOLS = [IMAGE_TOOL, STOCK_TOOL, BRAND_TOOL, *deck_tools.TOOLS, MEMORY_PROPOSE_TOOL,
37
+ {'name': 'browser', 'description': 'Built-in Playwright browser checks (BUG-0202: this is the browser tool; no Playwright install is needed). Open the local app (http://127.0.0.1:3000 by default, start it with preview first; it is browsed under a preview-style *.vercel.run host, the way the user reaches it, so dev-server host and origin blocks show up here) in headless Chromium at a given viewport, run up to 12 steps and take a screenshot. Reports page errors, console errors, failed requests, horizontal overflow, visible text and whether the page became interactive (hydrated). For UI work check a phone width (<=480) and a desktop width (>=1024) with at least one click/fill/press and an assert_text. Each call starts a fresh browser profile: localStorage, cookies and sessions from an earlier call are gone, so do every step that depends on saved state (sign in, add items, then a goto step to the same URL to reload, then assert_text) inside one call.',
36
38
  'inputSchema': {'type': 'object', 'properties': {'url': {'type': 'string'}, 'width': {'type': 'integer', 'minimum': 320, 'maximum': 1920}, 'height': {'type': 'integer', 'minimum': 400, 'maximum': 1200},
37
39
  'steps': {'type': 'array', 'maxItems': 12, 'items': {'type': 'object', 'properties': {'action': {'type': 'string', 'enum': ['goto', 'click', 'fill', 'press', 'assert_text']}, 'role': {'type': 'string'}, 'name': {'type': 'string'}, 'selector': {'type': 'string'}, 'value': {'type': 'string'}, 'key': {'type': 'string'}, 'text': {'type': 'string'}, 'url': {'type': 'string'}}, 'required': ['action']}}}}},
38
40
  {'name': 'preview', 'description': 'Start (or check) the managed preview of this project on port 3000: Next.js and Vite dev/start scripts, or a static index.html. Installs missing packages first and runs the dev server (hot reload) during the task; after the task it is swapped for the production build the user opens and shares. Servers started with Bash in the background stop when the task ends.',
@@ -159,8 +161,13 @@ def ask(request, always=False):
159
161
  """Wait for the user's verdict on one request (one at a time, shared with the hook). Returns the verdict."""
160
162
  if not always and auto_mode(): return 'approve'
161
163
  import fcntl
164
+ queued = time.time()
162
165
  with (ROOT / 'approval.lock').open('a') as lock:
163
166
  fcntl.flock(lock, fcntl.LOCK_EX)
167
+ # BUG-0251: queued behind an approval the user rejected in the same step: rejected too, never shown later.
168
+ try:
169
+ if float((ROOT / 'last-reject').read_text().strip() or 0) >= queued: return None
170
+ except (OSError, ValueError): pass
164
171
  request = {'id': os.urandom(8).hex(), **request}
165
172
  tmp = ROOT / 'pending.json.tmp'; tmp.write_text(json.dumps(request)); tmp.replace(ROOT / 'pending.json'); emit('approval', **request)
166
173
  decision = ROOT / ('decision-' + request['id']); deadline = time.time() + 540
@@ -170,6 +177,7 @@ def ask(request, always=False):
170
177
  raise ValueError('Task stopped' if (ROOT / 'cancel').exists() else 'The user did not approve this call in time. Do not retry it; report what is waiting.')
171
178
  time.sleep(0.4)
172
179
  verdict = decision.read_text().strip(); decision.unlink(missing_ok=True); (ROOT / 'pending.json').unlink(missing_ok=True)
180
+ if verdict not in ('approve', 'approve_all'): (ROOT / 'last-reject').write_text(str(time.time()))
173
181
  if verdict == 'approve_all' and not always:
174
182
  (ROOT / 'kimi-approve-all').write_text('1'); emit('mode', mode='auto', content='Approved all remaining steps for this task.')
175
183
  return request['id'] if verdict in ('approve', 'approve_all') else None
@@ -181,9 +189,9 @@ def integration(args):
181
189
  if not match: raise ValueError('This tool is not enabled for this task. Use integration_search to find enabled tools.')
182
190
  if os.getenv('MINI_READONLY') == '1' and match.get('write') is not False:
183
191
  raise ValueError('This turn is read-only, so tools that change data in a connected app cannot run now. Tell the user what you would do and ask them to confirm.')
184
- req = {'kind': 'integration', 'connection': connection, 'name': name, 'arguments': args.get('arguments') or {}, 'command': 'Connected tool: ' + name}
185
- # The app runs the call with the user's sign-in, so the request still goes through the app. In Auto mode it runs without a prompt.
186
- if auto_mode(): req['autoAllowed'] = True
192
+ req = {'kind': 'integration', 'connection': connection, 'name': name, 'arguments': args.get('arguments') or {}, 'command': 'Connected tool: ' + name, 'write': match.get('write') is not False} # BUG-0457
193
+ # The app runs the call with the user's sign-in, so the request goes through the app. Connected-app calls ask even in
194
+ # Auto mode, as Connectors and the docs promise (BUG-0485); "Allow for this task" on the card covers that app afterwards.
187
195
  ident = ask(req, always=True)
188
196
  if not ident: raise ValueError('The user rejected this integration call.')
189
197
  result = ROOT / ('result-' + ident)
@@ -222,6 +230,12 @@ def fingerprint_now():
222
230
  from quality import fingerprint
223
231
  return fingerprint(REPO, run_state().get('base') or 'HEAD')
224
232
 
233
+ def readonly_browser():
234
+ """BUG-0202: the Browser panel says Playwright can open the local app, so the agent must have the tool in question and
235
+ no-change turns too. A browser check only looks at the running app (each scenario still asks first); it never edits files."""
236
+ if os.getenv('MINI_SUBAGENT') == '1': return []
237
+ return [t for t in WRITE_TOOLS if t.get('name') == 'browser']
238
+
225
239
  def browser(args):
226
240
  args = {k: v for k, v in args.items() if k in ('url', 'width', 'height', 'steps')}
227
241
  installed = False
@@ -284,7 +298,7 @@ def job(args):
284
298
  out = dev_jobs.stop(ROOT, args.get('name')); emit('job', name=out['name'], state='stopped', content='Stopped job ' + out['name']); return json.dumps(out)
285
299
  if action == 'start':
286
300
  if not ask({'kind': 'job', 'command': 'Start background job ' + str(args.get('name', '')) + ':' + chr(10) + str(args.get('command', ''))[:6000]}): raise ValueError('Job start rejected by the user')
287
- env = {k: v for k, v in os.environ.items() if k not in ('MODEL_API_KEY', 'MINI_KIMI_PROXY_TOKEN', 'VERCEL_OIDC_TOKEN', 'OPENROUTER_API_KEY', 'MINI_IMAGE_URL', 'MINI_IMAGE_TOKEN')}
301
+ env = {k: v for k, v in os.environ.items() if k not in ('MODEL_API_KEY', 'MINI_KIMI_PROXY_TOKEN', 'VERCEL_OIDC_TOKEN', 'OPENROUTER_API_KEY', 'PIXABAY_API_KEY', 'BRANDFETCH_API_KEY', 'MINI_IMAGE_URL', 'MINI_IMAGE_TOKEN')}
288
302
  meta = dev_jobs.start(ROOT, REPO, args, env)
289
303
  emit('job', name=meta['name'], state='running', content='Started background job ' + meta['name'])
290
304
  return 'Started job ' + meta['name'] + ' (pid ' + str(meta['pid']) + '). Log: ' + str(ROOT / 'jobs' / meta['name'] / 'log') + '. Check it with job {"action":"status"}.'
@@ -335,7 +349,15 @@ def simulator(args):
335
349
  if not seen: return text
336
350
  return {'_mcp_content': [{'type': 'text', 'text': text}, {'type': 'image', 'mimeType': 'image/jpeg', 'data': base64.b64encode(Path(seen['path']).read_bytes()).decode()}]}
337
351
 
352
+ try: # BUG-0523: structured "cannot complete" outcome
353
+ from mlai_hooks import CANNOT_COMPLETE_TOOL as _CC_TOOL
354
+ TOOLS.append(_CC_TOOL)
355
+ except Exception: pass
356
+
338
357
  def call(name, args):
358
+ if name == 'cannot_complete':
359
+ from mlai_hooks import record_cannot_complete
360
+ return record_cannot_complete(args, ROOT)
339
361
  if name == 'schedule_wakeup':
340
362
  import wakeups
341
363
  return wakeups.tool(ROOT, args, emit)
@@ -361,8 +383,24 @@ def call(name, args):
361
383
  if os.getenv('MINI_READONLY') == '1': raise ValueError('Image generation is unavailable in read-only mode')
362
384
  from image_generation import generate, validate
363
385
  validate(args)
364
- if not ask({'kind': 'image', 'command': 'Generate image '+args['filename']+' (included, no extra credits): '+args['prompt'][:500]}): raise ValueError('Image generation rejected')
386
+ if not ask({'kind': 'image', 'command': 'Generate image '+args['filename']+' (uses about %.2f credits): ' % (image_tokens(None)/1_000_000)+args['prompt'][:500]}): raise ValueError(IMAGE_REJECTED)
365
387
  return generate(args)
388
+ if name in ('stock_photo', 'brand_lookup'):
389
+ if os.getenv('MINI_READONLY') == '1': raise ValueError('Stock photos and brand lookup are unavailable in read-only mode')
390
+ import media_tools
391
+ return media_tools.call(name, args)
392
+ if name in deck_tools.NAMES:
393
+ if os.getenv('MINI_READONLY') == '1' and not (name == 'deck_check' and not args.get('fix') and not args.get('pdf')): raise ValueError('This deck tool writes files, which is unavailable in read-only mode (deck_check without fix or pdf still works)')
394
+ def ensure_browser():
395
+ if deck_tools.browser_ready(ROOT): return True
396
+ import browser_local
397
+ if not browser_local.laptop() or os.getenv('MINI_READONLY') == '1' or (ROOT / 'deck-browser-declined').exists(): return False
398
+ if not ask(browser_local.install_request(json.dumps({'check': 'render the deck slides to check them'})), always=True) or not (ROOT / 'browser-ready').exists():
399
+ (ROOT / 'deck-browser-declined').write_text('1'); return False
400
+ return True
401
+ out, shot = deck_tools.call(name, args, ROOT, REPO, ensure_browser)
402
+ if shot: return {'_text': json.dumps(out), '_image': shot}
403
+ return out
366
404
  if name == 'computer':
367
405
  # Computer use on the Mac: the app enforces the rules; every session and focus change asks, even in Auto mode.
368
406
  if os.getenv('MINI_READONLY') == '1' or not computer_use.available(): raise ValueError('Computer use is only available in local runs in the Mac app, with it turned on in Settings')
@@ -386,7 +424,7 @@ def call(name, args):
386
424
  return web('web_fetch', {'urls': [str(u) for u in urls]})
387
425
  if name == 'evidence': return ledger().run({'claims': args['claims']} if args.get('claims') else {})
388
426
  if name in ('browser', 'preview', 'job', 'network'):
389
- if os.getenv('MINI_READONLY') == '1': raise ValueError('Not available in read-only mode')
427
+ if os.getenv('MINI_READONLY') == '1' and name != 'browser': raise ValueError('Not available in read-only mode')
390
428
  return {'browser': browser, 'preview': preview, 'job': job, 'network': network}[name](args)
391
429
  if name in ('list_sessions', 'read_messages', 'send_message'): return hub(name, args)
392
430
  if name in ('repo_map', 'symbols'):
@@ -423,7 +461,7 @@ def main():
423
461
  if msg_id is None: continue # notifications
424
462
  if method == 'initialize':
425
463
  reply(msg_id, {'protocolVersion': (msg.get('params') or {}).get('protocolVersion') or '2025-06-18', 'capabilities': {'tools': {}}, 'serverInfo': {'name': 'mlai', 'version': '1.0'}})
426
- elif method == 'tools/list': reply(msg_id, {'tools': TOOLS + ([] if os.getenv('MINI_READONLY') == '1' else WRITE_TOOLS + (INTEGRATION_TOOLS if enabled_tools() else []) + ([DEPLOY_TOOL] if deploy_info() else []) + ([computer_use.TOOL] if computer_use.available() else []) + sim_tools()) + hub_tools()})
464
+ elif method == 'tools/list': reply(msg_id, {'tools': TOOLS + (readonly_browser() if os.getenv('MINI_READONLY') == '1' else WRITE_TOOLS + (INTEGRATION_TOOLS if enabled_tools() else []) + ([DEPLOY_TOOL] if deploy_info() else []) + ([computer_use.TOOL] if computer_use.available() else []) + sim_tools()) + hub_tools()})
427
465
  elif method == 'tools/call':
428
466
  p = msg.get('params') or {}
429
467
  try:
@@ -0,0 +1,35 @@
1
+ # ML AI Review
2
+
3
+ The verified reviewer (relevance filter, outline context and related code, linter diagnostics, three
4
+ independent readings, grouping and matching, refuter, noise budget, streaming inline comments,
5
+ "looks resolved" lifecycle, feedback from dismissed comments, security specialist, eval harness),
6
+ running inside our worker instead of Temporal and Azure.
7
+
8
+ python -m mlai_review run REQUEST.json # one review; events to request.out (JSONL)
9
+ python -m mlai_review analyse --root DIR --out FILE [--no-eslint] [--no-install]
10
+ python -m mlai_review feedback owner/repo --days 30
11
+ python -m mlai_review eval [--cases DIR] [--mode deep] [--record --request REQUEST.json]
12
+
13
+ The model key comes from `MODEL_API_KEY` (our model route or a run token for the gateway) and,
14
+ for pull requests, `GITHUB_TOKEN`; both are removed from the environment before anything else runs.
15
+
16
+ Where it runs:
17
+
18
+ - Chat in the cloud: `lib/code-review.ts` (actions `review_start`, `review_status`, `review_dismiss`).
19
+ - Chat on This Mac: `apps/laptop/src/review.mjs`, same actions, run token from `/api/laptop`.
20
+ - Pull requests: `lib/code-review-run.ts`, started by the "Review pull requests" routine
21
+ (`lib/code-review-routine.ts`). Linters run first with no secrets present; the review then posts
22
+ inline comments and an "ML AI Review" check run, or a commit status when the token cannot
23
+ create check runs. `workflows/watch-pr-review.ts` stops the computer as soon as the review ends
24
+ (or the reviewer exits); its 40-minute lifetime is only a ceiling.
25
+
26
+ Metering: cloud chat reviews are runs in the ledger (`lib/code-review-billing.ts`): gated like a task
27
+ start, capped by the request's `budget` (billable tokens left) and weighted by `creditRates`, exactly
28
+ as the task worker and model gateway weigh tokens. The final `usage` event carries `billable`; past
29
+ the cap no model call starts and a `limited` event explains why the review is partial.
30
+
31
+ Modes (`settings.for_mode`): `standard` (3 readings), `deep` (5 readings, refuter with more effort
32
+ and lookups, write-path check), `security` (security specialist, refuter). Scope `repo` reviews
33
+ the source files of the whole repository, sensitive paths first.
34
+
35
+ Without the tree-sitter wheel, outlines fall back to `infrastructure/structure/heuristic.py`.
@@ -0,0 +1 @@
1
+ """ML AI orchestrator: runs each pull request review as a durable workflow."""
@@ -0,0 +1,261 @@
1
+ """ML AI Review, run from the command line.
2
+
3
+ python -m mlai_review run REQUEST.json review a checkout or a pull request
4
+ python -m mlai_review analyse --root DIR --out FILE [--no-eslint] [--no-install]
5
+ python -m mlai_review feedback owner/name [--days 14] (GITHUB_TOKEN)
6
+ python -m mlai_review eval [--cases DIR] [--mode standard] [--record]
7
+
8
+ The request names the checkout, the scope, the mode and the model endpoint; the model key is
9
+ read from MODEL_API_KEY and a GitHub token from GITHUB_TOKEN, never from the request. Progress
10
+ and findings are appended to the request's `out` file as JSON lines (see events.py).
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import argparse
16
+ import asyncio
17
+ import json
18
+ import logging
19
+ import os
20
+ import sys
21
+ import uuid
22
+ from datetime import datetime, timedelta, timezone
23
+ from pathlib import Path
24
+ from typing import Any
25
+
26
+ from mlai_review import pipeline
27
+ from mlai_review.application.errors import AccessDenied
28
+ from mlai_review.application.usage import CreditsExhausted, metering
29
+ from mlai_review.contracts.review import ReviewPullRequestInput
30
+ from mlai_review.infrastructure.local.analyzer import LocalAnalyzer, StoredAnalysis
31
+ from mlai_review.infrastructure.local.events import EventLog, report_json
32
+ from mlai_review.infrastructure.local.git_reader import LocalGitReader
33
+ from mlai_review.infrastructure.local.publisher import EventPublisher, read_dismissals
34
+ from mlai_review.runtime import build_local, build_pull_request
35
+ from mlai_review.settings import MODES, ModelSettings, for_mode, with_repository
36
+
37
+ FAILED = "The review could not finish. Nothing was changed; try again."
38
+ GITHUB_DENIED = (
39
+ "GitHub refused the token in your Vault. Give it Contents and Pull requests (read and write)"
40
+ " access to this repository, then review again."
41
+ )
42
+ CREDITS_OUT = (
43
+ "You have used all your credits for this month, so the review stopped early. Findings so far"
44
+ " are kept. Pick a plan or buy a top-up in Settings > Billing, then review again."
45
+ )
46
+
47
+
48
+ def budget_of(value: object) -> int | None:
49
+ """Billable tokens the review may use (the account's remaining credits); None is no cap."""
50
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
51
+ return None
52
+ return max(0, int(value))
53
+
54
+
55
+ def model_settings(raw: dict[str, Any]) -> ModelSettings:
56
+ endpoint = str(raw.get("endpoint") or "").strip()
57
+ name = str(raw.get("model") or "").strip()
58
+ if not endpoint or not name:
59
+ raise SystemExit("request.model needs endpoint and model")
60
+ return ModelSettings(
61
+ endpoint=endpoint,
62
+ model=name,
63
+ provider=str(raw.get("provider") or ""),
64
+ json_mode=raw.get("jsonMode", True) is not False,
65
+ max_concurrent=max(1, min(12, int(raw.get("maxConcurrent") or 6))),
66
+ )
67
+
68
+
69
+ async def run(request: dict[str, Any]) -> int:
70
+ log = EventLog(Path(request["out"]) if request.get("out") else None)
71
+ review_id = str(request.get("id") or uuid.uuid4().hex[:12])
72
+ mode = request.get("mode") if request.get("mode") in MODES else "standard"
73
+ scope = str(request.get("scope") or "changes")
74
+ root = Path(str(request.get("root") or ".")).resolve()
75
+ api_key = os.environ.pop("MODEL_API_KEY", "")
76
+ log.emit("started", id=review_id, mode=mode, scope=scope, pid=os.getpid())
77
+ if not api_key:
78
+ log.emit("error", message="The model is not configured for reviews.")
79
+ return 2
80
+ model = model_settings(request.get("model") or {})
81
+ settings = with_repository(for_mode(mode, scope=scope), request.get("settings"))
82
+ analysis = request.get("analysis") or "auto"
83
+ analyzer = (
84
+ None
85
+ if analysis == "off"
86
+ else StoredAnalysis(Path(analysis))
87
+ if analysis not in ("auto", "local")
88
+ else LocalAnalyzer(root)
89
+ )
90
+ pr = request.get("pullRequest")
91
+ with metering(rates=request.get("creditRates"), budget=budget_of(request.get("budget"))) as used:
92
+ try:
93
+ if pr:
94
+ github_token = os.environ.pop("GITHUB_TOKEN", "")
95
+ if not github_token:
96
+ log.emit("error", message="GitHub is not connected for this repository.")
97
+ return 2
98
+ built = await build_pull_request(
99
+ root=root,
100
+ model=model,
101
+ api_key=api_key,
102
+ github_token=github_token,
103
+ review=settings,
104
+ analyzer=analyzer if analysis not in ("auto", "local") else None,
105
+ details_url=pr.get("detailsUrl"),
106
+ api_url=os.environ.get("MLAI_REVIEW_GITHUB_API") or "https://api.github.com",
107
+ )
108
+ target = ReviewPullRequestInput(
109
+ installation_id=0,
110
+ repository_id=0,
111
+ repository_full_name=str(pr["repository"]),
112
+ pull_number=int(pr["number"]),
113
+ head_sha=str(pr.get("headSha") or ""),
114
+ base_sha=str(pr.get("baseSha") or ""),
115
+ triggered_by_delivery=str(pr.get("delivery") or review_id),
116
+ previous_head_sha=pr.get("previousHeadSha") or None,
117
+ )
118
+ async with built.resources:
119
+ report = await pipeline.review(built.service, target)
120
+ _limited(log, used)
121
+ log.emit("done", report=report_json(report), usage=_usage(used))
122
+ return 0
123
+ reader = LocalGitReader(
124
+ root,
125
+ scope=scope,
126
+ base=str(request.get("base") or ""),
127
+ head=str(request.get("head") or ""),
128
+ title=str(request.get("title") or ""),
129
+ body=str(request.get("body") or ""),
130
+ paths=tuple(str(p) for p in request.get("paths") or ()),
131
+ )
132
+ out = Path(str(request.get("out") or ""))
133
+ publisher = EventPublisher(log, root, prior=_prior_logs(request.get("prior"), out))
134
+ dismissed = read_dismissals(
135
+ Path(request["dismissed"]) if request.get("dismissed") else None
136
+ )
137
+ built = await build_local(
138
+ root=root,
139
+ reader=reader,
140
+ publisher=publisher,
141
+ model=model,
142
+ api_key=api_key,
143
+ review=settings,
144
+ analyzer=analyzer,
145
+ dismissed=dismissed,
146
+ )
147
+ head, base = await reader.head(_local_target(root, "", ""))
148
+ async with built.resources:
149
+ await pipeline.review(
150
+ built.service, _local_target(root, head or "0" * 40, base or head or "0" * 40)
151
+ )
152
+ _limited(log, used)
153
+ log.emit("usage", usage=_usage(used))
154
+ return 0
155
+ except Exception as exc: # reported to the app; details stay in the log on stderr
156
+ if isinstance(exc, CreditsExhausted) or used.exhausted:
157
+ log.emit("error", message=CREDITS_OUT, detail="credits", limited=True, usage=_usage(used))
158
+ return 3
159
+ logging.getLogger("mlai.review").exception("review failed")
160
+ message = GITHUB_DENIED if pr and isinstance(exc, AccessDenied) else FAILED
161
+ log.emit("error", message=message, detail=type(exc).__name__, usage=_usage(used))
162
+ return 1
163
+
164
+
165
+ def _limited(log: EventLog, used: Any) -> None:
166
+ """Readings that stopped at the credit cap still finish the review; say why it is partial."""
167
+ if used.exhausted:
168
+ log.emit("limited", message=CREDITS_OUT, usage=_usage(used))
169
+
170
+
171
+ def _local_target(root: Path, head: str, base: str) -> ReviewPullRequestInput:
172
+ return ReviewPullRequestInput(
173
+ installation_id=0,
174
+ repository_id=0,
175
+ repository_full_name=f"local/{root.name or 'workspace'}",
176
+ pull_number=0,
177
+ head_sha=head,
178
+ base_sha=base,
179
+ triggered_by_delivery="local",
180
+ )
181
+
182
+
183
+ def _prior_logs(value: object, out: Path) -> tuple[Path, ...]:
184
+ """Earlier reviews' event logs, oldest first. A folder stands for every log in it."""
185
+ files: list[Path] = []
186
+ for item in value if isinstance(value, list) else [value] if value else []:
187
+ path = Path(str(item))
188
+ if path.is_dir():
189
+ files.extend(sorted(path.glob("*.jsonl"), key=lambda f: f.stat().st_mtime))
190
+ else:
191
+ files.append(path)
192
+ return tuple(f for f in files if f.resolve() != out.resolve())
193
+
194
+
195
+ def _usage(used: Any) -> dict[str, int]:
196
+ return {
197
+ "calls": used.calls,
198
+ "promptTokens": used.prompt_tokens,
199
+ "cachedTokens": used.cached_tokens,
200
+ "completionTokens": used.completion_tokens,
201
+ "billable": used.billable,
202
+ }
203
+
204
+
205
+ async def feedback(repositories: list[str], days: int) -> None:
206
+ import httpx
207
+
208
+ from mlai_review.application.feedback import FeedbackReporter
209
+ from mlai_review.feedback_report import render
210
+ from mlai_review.infrastructure.github.feedback import GitHubFeedbackSource
211
+ from mlai_review.infrastructure.github.token import StaticTokenProvider
212
+
213
+ token = os.environ.pop("GITHUB_TOKEN", "")
214
+ since = datetime.now(timezone.utc) - timedelta(days=days)
215
+ async with httpx.AsyncClient(base_url="https://api.github.com", timeout=30.0) as http:
216
+ reporter = FeedbackReporter(GitHubFeedbackSource(http=http, tokens=StaticTokenProvider(token))) # type: ignore[arg-type]
217
+ for full_name in repositories:
218
+ summary = await reporter.report(full_name, since)
219
+ sys.stdout.write(render(full_name, days, summary) + "\n")
220
+
221
+
222
+ def main(argv: list[str] | None = None) -> int:
223
+ logging.basicConfig(level=logging.INFO, stream=sys.stderr, format="%(name)s: %(message)s")
224
+ parser = argparse.ArgumentParser(prog="mlai_review", description=__doc__)
225
+ sub = parser.add_subparsers(dest="command", required=True)
226
+ run_parser = sub.add_parser("run")
227
+ run_parser.add_argument("request", type=Path)
228
+ analyse_parser = sub.add_parser("analyse")
229
+ analyse_parser.add_argument("--root", type=Path, required=True)
230
+ analyse_parser.add_argument("--out", type=Path, required=True)
231
+ analyse_parser.add_argument("--no-eslint", action="store_true")
232
+ analyse_parser.add_argument("--no-install", action="store_true", help="never install packages")
233
+ feedback_parser = sub.add_parser("feedback")
234
+ feedback_parser.add_argument("repositories", nargs="+")
235
+ feedback_parser.add_argument("--days", type=int, default=14)
236
+ eval_parser = sub.add_parser("eval")
237
+ eval_parser.add_argument("--cases", type=Path, default=None)
238
+ eval_parser.add_argument("--mode", default=None, choices=MODES)
239
+ eval_parser.add_argument("--record", action="store_true", help="call the model, save replies")
240
+ eval_parser.add_argument("--request", type=Path, help="model endpoint, as in run")
241
+ args = parser.parse_args(argv)
242
+ if args.command == "run":
243
+ return asyncio.run(run(json.loads(args.request.read_text(encoding="utf-8"))))
244
+ if args.command == "analyse":
245
+ from mlai_review.analysis.detect import Tool
246
+ from mlai_review.analysis.main import analyse
247
+
248
+ allowed = tuple(t for t in Tool if t is not Tool.ESLINT) if args.no_eslint else None
249
+ result = analyse(args.root, allowed=allowed, install=not args.no_install)
250
+ args.out.write_text(json.dumps(result.as_dict()), encoding="utf-8")
251
+ return 0
252
+ if args.command == "feedback":
253
+ asyncio.run(feedback(args.repositories, args.days))
254
+ return 0
255
+ from mlai_review.eval import main as eval_main
256
+
257
+ return eval_main(args)
258
+
259
+
260
+ if __name__ == "__main__":
261
+ sys.exit(main())
@@ -0,0 +1,29 @@
1
+ """Python 3.10 support: the engine on a Mac may run 3.10, the reviewer was written for 3.13."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ from enum import Enum
7
+ from typing import Any
8
+
9
+ try:
10
+ from enum import StrEnum
11
+ except ImportError: # Python 3.10
12
+
13
+ class StrEnum(str, Enum): # type: ignore[no-redef]
14
+ def __str__(self) -> str:
15
+ return str(self.value)
16
+
17
+ def __format__(self, spec: str) -> str:
18
+ return format(str(self.value), spec)
19
+
20
+
21
+ try:
22
+ from typing import Self
23
+ except ImportError: # Python 3.10
24
+ Self = Any # type: ignore[assignment,misc]
25
+
26
+ # asyncio.wait_for raises asyncio.TimeoutError, which is the builtin only from 3.11.
27
+ TIMEOUTS = (TimeoutError, asyncio.TimeoutError)
28
+
29
+ __all__ = ["TIMEOUTS", "Self", "StrEnum"]
@@ -0,0 +1,3 @@
1
+ """The static-analysis sandbox: clone one commit, run the tools the repository calls for,
2
+ report their messages. Runs as a job with no secrets beyond a short-lived, single-repository
3
+ token and nowhere to write except its result."""
@@ -0,0 +1,50 @@
1
+ """Which tools a repository calls for, from the files it contains. Nothing here is specific to
2
+ a customer: a tsconfig means TypeScript, a pyproject means Python, and so on."""
3
+
4
+ from __future__ import annotations
5
+
6
+ from mlai_review._compat import StrEnum
7
+ from pathlib import Path
8
+
9
+
10
+ class Tool(StrEnum):
11
+ RUFF = "ruff"
12
+ TSC = "tsc"
13
+ ESLINT = "eslint"
14
+
15
+
16
+ _ESLINT_CONFIGS = (
17
+ "eslint.config.js",
18
+ "eslint.config.mjs",
19
+ "eslint.config.cjs",
20
+ "eslint.config.ts",
21
+ ".eslintrc",
22
+ ".eslintrc.js",
23
+ ".eslintrc.cjs",
24
+ ".eslintrc.json",
25
+ ".eslintrc.yml",
26
+ ".eslintrc.yaml",
27
+ )
28
+ _MAX_SCAN = 20_000 # files to look at when deciding whether Python is present
29
+
30
+
31
+ def detect(root: Path) -> tuple[Tool, ...]:
32
+ tools: list[Tool] = []
33
+ if _has_python(root):
34
+ tools.append(Tool.RUFF)
35
+ if (root / "tsconfig.json").is_file():
36
+ tools.append(Tool.TSC)
37
+ if any((root / name).is_file() for name in _ESLINT_CONFIGS):
38
+ tools.append(Tool.ESLINT)
39
+ return tuple(tools)
40
+
41
+
42
+ def _has_python(root: Path) -> bool:
43
+ if any((root / name).is_file() for name in ("pyproject.toml", "setup.py", "setup.cfg")):
44
+ return True
45
+ for i, path in enumerate(root.rglob("*.py")):
46
+ if ".git" not in path.parts and "node_modules" not in path.parts:
47
+ return True
48
+ if i > _MAX_SCAN:
49
+ break
50
+ return False