mlai-code 0.3.3 → 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 (135) 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 +153 -26
  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 +17 -0
  14. package/src/relay.mjs +1 -1
  15. package/src/render.mjs +9 -2
  16. package/src/runtime.mjs +2 -0
  17. package/src/server.mjs +46 -7
  18. package/src/session.mjs +31 -8
  19. package/src/tui/acp.mjs +121 -19
  20. package/src/tui/app.mjs +2 -1
  21. package/src/tui/chat.mjs +35 -10
  22. package/src/tui/cmd-config.mjs +3 -1
  23. package/src/tui/cmd-core.mjs +9 -5
  24. package/src/tui/cmd-extensibility.mjs +5 -0
  25. package/src/tui/extensions-local.mjs +2 -0
  26. package/src/tui/mcp-config.mjs +22 -4
  27. package/src/tui/review-cli.mjs +15 -4
  28. package/src/tui/snapshots.mjs +57 -16
  29. package/src/two-words.mjs +14 -8
  30. package/src/view-sync.mjs +48 -0
  31. package/src/winenv.mjs +1 -1
  32. package/src/workspace-api.mjs +21 -4
  33. package/vendor/client-sdk/index.cjs +2 -1
  34. package/vendor/cloud-cli/mlai.mjs +23 -11
  35. package/worker/architecture_worker.py +33 -4
  36. package/worker/browser_tool.py +19 -1
  37. package/worker/chat_fork.py +4 -1
  38. package/worker/checkpoints.py +71 -8
  39. package/worker/command_safety.py +56 -3
  40. package/worker/connected_turn.py +30 -0
  41. package/worker/conversation.py +81 -11
  42. package/worker/git_sync.py +4 -4
  43. package/worker/image_generation.py +2 -2
  44. package/worker/kimi_bridge.py +247 -27
  45. package/worker/kimi_gates.py +25 -6
  46. package/worker/kimi_hook.py +153 -12
  47. package/worker/media_tools.py +4 -1
  48. package/worker/mlai_hooks.py +222 -3
  49. package/worker/mlai_mcp.py +26 -6
  50. package/worker/mlai_review/README.md +35 -0
  51. package/worker/mlai_review/__init__.py +1 -0
  52. package/worker/mlai_review/__main__.py +261 -0
  53. package/worker/mlai_review/_compat.py +29 -0
  54. package/worker/mlai_review/analysis/__init__.py +3 -0
  55. package/worker/mlai_review/analysis/detect.py +50 -0
  56. package/worker/mlai_review/analysis/main.py +128 -0
  57. package/worker/mlai_review/analysis/messages.py +8 -0
  58. package/worker/mlai_review/analysis/tools.py +194 -0
  59. package/worker/mlai_review/application/__init__.py +1 -0
  60. package/worker/mlai_review/application/asking.py +53 -0
  61. package/worker/mlai_review/application/challengers.py +142 -0
  62. package/worker/mlai_review/application/context_builder.py +194 -0
  63. package/worker/mlai_review/application/errors.py +17 -0
  64. package/worker/mlai_review/application/feedback.py +52 -0
  65. package/worker/mlai_review/application/matching.py +46 -0
  66. package/worker/mlai_review/application/messages.py +41 -0
  67. package/worker/mlai_review/application/ports.py +222 -0
  68. package/worker/mlai_review/application/prompts.py +342 -0
  69. package/worker/mlai_review/application/review_service.py +200 -0
  70. package/worker/mlai_review/application/reviewers.py +438 -0
  71. package/worker/mlai_review/application/streaming.py +91 -0
  72. package/worker/mlai_review/application/tools.py +138 -0
  73. package/worker/mlai_review/application/usage.py +145 -0
  74. package/worker/mlai_review/application/write_check.py +46 -0
  75. package/worker/mlai_review/contracts/__init__.py +5 -0
  76. package/worker/mlai_review/contracts/analysis.py +57 -0
  77. package/worker/mlai_review/contracts/review.py +42 -0
  78. package/worker/mlai_review/domain/__init__.py +4 -0
  79. package/worker/mlai_review/domain/changes.py +77 -0
  80. package/worker/mlai_review/domain/context.py +147 -0
  81. package/worker/mlai_review/domain/diagnostics.py +239 -0
  82. package/worker/mlai_review/domain/feedback.py +216 -0
  83. package/worker/mlai_review/domain/findings.py +505 -0
  84. package/worker/mlai_review/domain/lifecycle.py +85 -0
  85. package/worker/mlai_review/domain/partition.py +42 -0
  86. package/worker/mlai_review/domain/relations.py +166 -0
  87. package/worker/mlai_review/domain/relevance.py +202 -0
  88. package/worker/mlai_review/domain/report.py +99 -0
  89. package/worker/mlai_review/domain/structure.py +56 -0
  90. package/worker/mlai_review/domain/writes.py +86 -0
  91. package/worker/mlai_review/eval.py +221 -0
  92. package/worker/mlai_review/eval_cases/clean-rename.json +11 -0
  93. package/worker/mlai_review/eval_cases/missing-ownership-check.json +22 -0
  94. package/worker/mlai_review/eval_cases/off-by-one.json +22 -0
  95. package/worker/mlai_review/eval_cases/sql-injection.json +20 -0
  96. package/worker/mlai_review/feedback_report.py +60 -0
  97. package/worker/mlai_review/infrastructure/__init__.py +1 -0
  98. package/worker/mlai_review/infrastructure/analysis/__init__.py +1 -0
  99. package/worker/mlai_review/infrastructure/analysis/none.py +12 -0
  100. package/worker/mlai_review/infrastructure/analysis/translate.py +17 -0
  101. package/worker/mlai_review/infrastructure/github/__init__.py +0 -0
  102. package/worker/mlai_review/infrastructure/github/client.py +445 -0
  103. package/worker/mlai_review/infrastructure/github/feedback.py +212 -0
  104. package/worker/mlai_review/infrastructure/github/http.py +31 -0
  105. package/worker/mlai_review/infrastructure/github/rendering.py +398 -0
  106. package/worker/mlai_review/infrastructure/github/token.py +20 -0
  107. package/worker/mlai_review/infrastructure/local/__init__.py +1 -0
  108. package/worker/mlai_review/infrastructure/local/analyzer.py +48 -0
  109. package/worker/mlai_review/infrastructure/local/events.py +100 -0
  110. package/worker/mlai_review/infrastructure/local/git_reader.py +233 -0
  111. package/worker/mlai_review/infrastructure/local/publisher.py +138 -0
  112. package/worker/mlai_review/infrastructure/messages.py +54 -0
  113. package/worker/mlai_review/infrastructure/models/__init__.py +0 -0
  114. package/worker/mlai_review/infrastructure/models/openai_compatible.py +269 -0
  115. package/worker/mlai_review/infrastructure/structure/__init__.py +1 -0
  116. package/worker/mlai_review/infrastructure/structure/heuristic.py +186 -0
  117. package/worker/mlai_review/infrastructure/structure/tree_sitter.py +186 -0
  118. package/worker/mlai_review/infrastructure/workspace/__init__.py +1 -0
  119. package/worker/mlai_review/infrastructure/workspace/local.py +105 -0
  120. package/worker/mlai_review/infrastructure/workspace/memory.py +77 -0
  121. package/worker/mlai_review/infrastructure/workspace/paths.py +17 -0
  122. package/worker/mlai_review/pipeline.py +89 -0
  123. package/worker/mlai_review/runtime.py +194 -0
  124. package/worker/mlai_review/settings.py +139 -0
  125. package/worker/preview.py +15 -0
  126. package/worker/product_facts.py +3 -1
  127. package/worker/repo_policy.py +5 -0
  128. package/worker/roles.py +29 -2
  129. package/worker/runner.py +126 -18
  130. package/worker/runtime_control.py +64 -3
  131. package/worker/secret_scan.py +3 -2
  132. package/worker/server_memory.py +122 -0
  133. package/worker/subagents.py +6 -2
  134. package/worker/tool_catalog.py +1 -1
  135. package/worker/verification.py +113 -8
@@ -10,7 +10,7 @@ really done also run here, after the engine exits, and a failed check resumes th
10
10
  and the bridge runs them. Only assertion failures count; a broken test file is treated as the tester's fault.
11
11
 
12
12
  Also: deterministic trimming of oversized tool output in model requests (cache-friendly, saves tokens)."""
13
- import json, os, re, subprocess, sys, time
13
+ import json, os, re, shutil, subprocess, sys, time
14
14
  from pathlib import Path
15
15
 
16
16
  ACCEPTANCE_DIR = 'acceptance'
@@ -71,6 +71,8 @@ Rules:
71
71
  - 3 to 8 focused test cases. No network, no sleeping, no servers, no new dependencies, no file writes outside a temporary directory.
72
72
  - Python: a unittest module. The repository root is on sys.path, so import modules as the repository does (e.g. `from shop.cart import total`).
73
73
  - JavaScript: an ES module using node:test and node:assert/strict. Import repository files with absolute file URLs built from REPO_ROOT, e.g. `const m = await import(REPO_ROOT + '/calc.js')` where `const REPO_ROOT = 'file://' + process.env.ACCEPTANCE_REPO;`. If the module is CommonJS, use createRequire.
74
+ - To read a repository file, use a path, not a URL: `fs.readFileSync(path.join(process.env.ACCEPTANCE_REPO, 'src/styles.css'), 'utf8')`. ACCEPTANCE_REPO is a plain folder path; for URLs use process.env.ACCEPTANCE_REPO_URL (a file:// URL ending in /) or pathToFileURL from node:url. Never pass the plain path to new URL().
75
+ - Colours, sizes and other CSS values have many equal spellings (#141, #141210, #141210ff, rgb(20 18 16), a named colour). Never match a colour or CSS value with one spelling; if the task says "near-black", parse the colour and check its lightness.
74
76
  - Prefer expected values stated in the task or in the existing tests. When you compute one, write the arithmetic in a comment and check it twice.
75
77
  - If the task is not testable this way (UI-only, docs, config, research, or behaviour you cannot pin down from the task), say so.
76
78
 
@@ -113,7 +115,8 @@ def tester_invalid(language, output):
113
115
  if re.search(r'^FAIL: ', output, re.M): return False
114
116
  return bool(re.search(r'(ImportError|ModuleNotFoundError|SyntaxError|IndentationError|NameError)', output)) or not re.search(r'^ERROR: ', output, re.M)
115
117
  if re.search(r'AssertionError|ERR_ASSERTION', output): return False
116
- return bool(re.search(r'ERR_MODULE_NOT_FOUND|SyntaxError|Cannot find module|ReferenceError|does not provide an export', output)) or '# fail 0' in output
118
+ # ERR_INVALID_URL: new URL('./src/styles.css', ACCEPTANCE_REPO + '/') with a plain folder path (CLI bug list, 0.3.3).
119
+ return bool(re.search(r'ERR_MODULE_NOT_FOUND|SyntaxError|Cannot find module|ReferenceError|does not provide an export|ERR_INVALID_URL|TypeError: Invalid URL|ERR_INVALID_FILE_URL_PATH|ENOENT: no such file', output)) or '# fail 0' in output
117
120
 
118
121
  TESTER_RETRY = '''
119
122
 
@@ -122,7 +125,7 @@ module format, a missing loader) and return the same JSON shape. Test through fi
122
125
  Node or Python here: for a React or other bundled UI, test the server, data and pure modules, or read the built output,
123
126
  instead of importing JSX. If no test can run in this repository, return {"applicable": false, "reason": "..."}.'''
124
127
 
125
- REVIEW_SYSTEM = '''You check failing acceptance tests before they are reported to a builder. For each failing test, decide whether the test itself is right: does the task text really require this behaviour, and is the expected value correct? Recompute every expected number step by step from the task. A test is wrong if it asserts something the task does not require, or if its expected value is miscalculated.
128
+ REVIEW_SYSTEM = '''You check failing acceptance tests before they are reported to a builder. For each failing test, decide whether the test itself is right: does the task text really require this behaviour, and is the expected value correct? Recompute every expected number step by step from the task. A test is wrong if it matches a colour or CSS value by one spelling (a 3-digit hex pattern that rejects #141210), or if it fails while loading a file (Invalid URL, ENOENT) instead of on the behaviour. A test is wrong if it asserts something the task does not require, or if its expected value is miscalculated.
126
129
 
127
130
  Reply with JSON only: {"genuine": ["test_name", ...], "wrong": [{"test": "test_name", "why": "..."}]}'''
128
131
 
@@ -148,14 +151,26 @@ def run_acceptance(root, repo, language, code, timeout=180):
148
151
  name = 'test_acceptance.py' if language == 'python' else 'acceptance.test.mjs'
149
152
  path = d / name; path.write_text(code)
150
153
  env = {k: v for k, v in os.environ.items() if k not in ('MODEL_API_KEY', 'MINI_VAULT', 'EXA_API_KEY', 'FIRECRAWL_API_KEY', 'VERCEL_OIDC_TOKEN')}
151
- env.update({'PYTHONPATH': str(repo), 'ACCEPTANCE_REPO': str(repo), 'PYTHONDONTWRITEBYTECODE': '1'})
152
- cmd = [sys.executable, str(path), '-v'] if language == 'python' else ['node', '--test', str(path)]
154
+ env.update({'PYTHONPATH': str(repo), 'ACCEPTANCE_REPO': str(repo), 'ACCEPTANCE_REPO_URL': Path(repo).resolve().as_uri().rstrip('/') + '/', 'PYTHONDONTWRITEBYTECODE': '1'})
153
155
  if language == 'python': path.write_text(code if 'unittest.main' in code else code + '\n\nif __name__ == "__main__":\n import unittest; unittest.main()\n')
156
+ # BUG-0221: run the test from a scratch folder inside the project, so relative imports, package imports and
157
+ # __file__-based paths resolve against the project, not the engine's own folder. The copy in root stays for the log.
158
+ scratch = Path(repo) / ('.mlai-acceptance-' + os.urandom(4).hex())
159
+ try:
160
+ scratch.mkdir()
161
+ run_path = scratch / name; run_path.write_text(path.read_text())
162
+ except OSError:
163
+ scratch, run_path = None, path
164
+ cmd = [sys.executable, str(run_path), '-v'] if language == 'python' else ['node', '--test', str(run_path)]
154
165
  try:
155
166
  r = subprocess.run(cmd, cwd=repo, env=env, capture_output=True, text=True, timeout=timeout)
156
- return r.returncode, (r.stdout + '\n' + r.stderr)[-6000:]
167
+ out = (r.stdout + '\n' + r.stderr)
168
+ if scratch is not None: out = out.replace(str(scratch) + '/', '').replace(str(scratch), '.')
169
+ return r.returncode, out[-6000:]
157
170
  except subprocess.TimeoutExpired:
158
171
  return 124, 'Acceptance check timed out after %ds' % timeout
172
+ finally:
173
+ if scratch is not None: shutil.rmtree(scratch, ignore_errors=True)
159
174
 
160
175
  def acceptance(config, st, model, root, repo, changed, event):
161
176
  """Write and run the hidden acceptance test once. Returns {status, ...}: passed | failed | skipped | invalid."""
@@ -275,6 +290,10 @@ def final_issues(config, st, answer, done, model, root, repo, event, allow_accep
275
290
  issues = []
276
291
  try: changed = role_engine.changed_files(repo, st.get('base'))
277
292
  except Exception: changed = []
293
+ try:
294
+ from runtime_control import turn_changes
295
+ changed = turn_changes(root, repo, changed) # BUG-0495: not files that were already untracked or changed at the start
296
+ except Exception: pass
278
297
  code_changed = [p for p in changed if role_engine.CODE_EXT.search(p)]
279
298
  progress = {}
280
299
  try: progress = json.loads((Path(root) / 'kimi-progress.json').read_text())
@@ -30,7 +30,7 @@ def save(name, data):
30
30
  def event(event_type, **data):
31
31
  with (ROOT / 'events.jsonl').open('a') as f: f.write(json.dumps({'type': event_type, 'time': time.time(), **data}) + '\n')
32
32
 
33
- HOOK_KEYS = ('recent', 'landed', 'stuck_warned', 'gates_done', 'planned', 'plan_reviewed', 'plan_dismissed', 'brief_ok', 'brief_rounds', 'brief_nudged', 'mode', 'nudged', 'diagnosed_for', 'scope', 'scope_ok', 'approved_kinds', 'calls', 'agents', 'budget_warned', 'touched', 'policy_noted', 'policy_ok_paths', 'token_stage', 'account_stop', 'account_stop_at', 'helpers', 'budget_next', 'budget_declined', 'plan_items', 'brief_q_nudged', 'plan_nudged')
33
+ HOOK_KEYS = ('steps_used', 'step_limit_noted', 'recent', 'landed', 'stuck_warned', 'gates_done', 'planned', 'plan_reviewed', 'plan_dismissed', 'brief_ok', 'brief_rounds', 'brief_nudged', 'mode', 'nudged', 'diagnosed_for', 'scope', 'scope_ok', 'approved_kinds', 'calls', 'agents', 'budget_warned', 'touched', 'policy_noted', 'policy_ok_paths', 'token_stage', 'account_stop', 'account_stop_at', 'helpers', 'budget_next', 'budget_declined', 'plan_items', 'brief_q_nudged', 'plan_nudged', 'question_changes')
34
34
  def save_state(st):
35
35
  """The hook owns only these keys; the bridge owns kimi-state.json (static) and kimi-progress.json."""
36
36
  save('kimi-hook.json', {k: st[k] for k in HOOK_KEYS if k in st})
@@ -92,11 +92,19 @@ def steer_block(messages, stopping=False):
92
92
  def wait_decision(request, seconds=540, strict=False):
93
93
  """One approval at a time even when Kimi runs tool calls in parallel. Strict (repository policy) reviews ignore "Approve all"."""
94
94
  import fcntl
95
+ queued = time.time()
95
96
  with (ROOT / 'approval.lock').open('a') as lock:
96
97
  fcntl.flock(lock, fcntl.LOCK_EX)
98
+ # BUG-0251: a call that queued behind an approval the user then rejected (parallel tool calls of one step)
99
+ # is rejected too, so a leftover card can never run a change the user just said no to.
100
+ if rejected_since(queued): block('The user rejected a related action in this step, so this call was not run. Do not retry it; explain what you would change and ask.')
97
101
  if not strict and (ROOT / 'kimi-approve-all').exists(): return
98
102
  _wait(request, seconds)
99
103
 
104
+ def rejected_since(t):
105
+ try: return float((ROOT / 'last-reject').read_text().strip() or 0) >= t
106
+ except (OSError, ValueError): return False
107
+
100
108
  def user_hooks(fn, *args):
101
109
  """Project hooks and hard-deny rules (mlai_hooks). They fail open on an internal error, like the rest of this hook."""
102
110
  try:
@@ -107,6 +115,9 @@ def user_hooks(fn, *args):
107
115
  def mlai_run(st):
108
116
  return user_hooks('kimi_run', st) or {}
109
117
 
118
+ REJECTED = ('The user rejected this action. Do not make the same change another way (another tool, a shell command or a retry) '
119
+ 'and do not claim the permission mode changed. Stop now, say plainly what was not done, and ask the user how to proceed.')
120
+
110
121
  def _wait(request, seconds):
111
122
  ident = request['id']
112
123
  if request.get('kind') not in ('plan', 'brief'):
@@ -125,8 +136,21 @@ def _wait(request, seconds):
125
136
  verdict = decision.read_text().strip(); decision.unlink(missing_ok=True); (ROOT / 'pending.json').unlink(missing_ok=True)
126
137
  if verdict == 'approve_all':
127
138
  (ROOT / 'kimi-approve-all').write_text('1'); event('mode', mode='auto', content='Approved all remaining steps for this task.')
139
+ if verdict == 'approve_chat':
140
+ # BUG-0594: remember this exact command for the chat, only when it is a safe kind; otherwise it is a one-time approval.
141
+ try:
142
+ from command_safety import chat_allow_ok, chat_allow_key
143
+ if request.get('kind') == 'command' and not request.get('strict') and chat_allow_ok(request.get('effect'), request.get('command'), REPO):
144
+ allowed = [c for c in load('chat-allow.json', []) if isinstance(c, str)]
145
+ key = chat_allow_key(request.get('command'))
146
+ if key not in allowed: save('chat-allow.json', (allowed + [key])[-50:])
147
+ event('note', content='Always allowed in this chat: ' + key[:200])
148
+ except Exception: pass
149
+ verdict = 'approve'
128
150
  if verdict not in ('approve', 'approve_all'):
129
- block('The user rejected this action. Choose another approach or explain what you need.')
151
+ (ROOT / 'last-reject').write_text(str(time.time()))
152
+ # BUG-0491: "Choose another approach" made the agent retry the same write with Write, printf and touch.
153
+ block(REJECTED)
130
154
 
131
155
  def wait_plan(request, seconds=540):
132
156
  """Plan review: returns the raw verdict (approve | approve:0,2 | reject), or None on timeout."""
@@ -146,6 +170,13 @@ def briefing(st):
146
170
  """Brief mode before the user has approved a task list: read-only, every TodoList opens a review."""
147
171
  return bool(st.get('brief')) and not st.get('brief_ok') and not st.get('plan_dismissed')
148
172
 
173
+ def brief_label(st):
174
+ """BUG-0591: an ask-first brief in an Auto or Guided chat is not "Brief mode" (the composer still says Auto), so the
175
+ agent is not told, and does not tell the user, that the workspace is in Brief mode."""
176
+ back = st.get('brief_return')
177
+ if back in ('auto', 'approve'): return 'Ask first (the chat stays in %s)' % ('Auto' if back == 'auto' else 'Guided')
178
+ return 'Brief mode'
179
+
149
180
  def brief_unlock(st):
150
181
  back = st.get('brief_return') if st.get('brief_return') in ('approve', 'auto') else 'approve'
151
182
  st['brief_ok'] = True; st['mode'] = back; st['scope_ok'] = True; save_state(st)
@@ -172,8 +203,12 @@ def plan_gate(args, st):
172
203
  st['planned'] = True; save_state(st)
173
204
  policy = st.get('plan_approval') or 'guided'
174
205
  wants = brief or policy == 'always' or (policy == 'guided' and st.get('mode') == 'approve')
206
+ if wants and not brief and question_only(st):
207
+ # BUG-0345: a task list for answering a question needs no review. It does not count as the plan, so a later
208
+ # edit in this turn still asks for the plan first.
209
+ st['planned'] = False; save_state(st); return
175
210
  if brief:
176
- if len(items) < 2: block('Brief mode: the task list needs at least two concrete items before the user can review it. Call TodoList again with the full plan.')
211
+ if len(items) < 2: block(brief_label(st) + ': the task list needs at least two concrete items before the user can review it. Call TodoList again with the full plan.')
177
212
  if st.get('mode') == 'brief' and not int(st.get('brief_rounds') or 0) and not st.get('brief_q_nudged') and not load('kimi-brief-questions.json', []):
178
213
  # BUG-0124: Brief mode promises to clarify requirements before the task list. Ask once for the open questions.
179
214
  st['brief_q_nudged'] = True; st['planned'] = False; save_state(st)
@@ -334,6 +369,19 @@ def secret_gate(name, args, rel, pol):
334
369
  'Read it from an environment variable instead (for example process.env.' + f['name'] + ' or os.environ["' + f['name'] + '"]), '
335
370
  'add the name to .env.example with an empty value, and tell the user to store the real value in the Vault as ' + f['name'] + '. Re-issue the edit without the literal value.')
336
371
 
372
+ # BUG-0224: installed dependencies are not the project's code. Editing them in place (often to get past a check) is
373
+ # refused unless the task itself asks for it; the change would also vanish on the next install.
374
+ DEP_DIRS = ('node_modules', 'site-packages', 'dist-packages', 'bower_components')
375
+ DEP_WRITE = re.compile(r'(?:\bsed\s+(?:-\w+\s+)*-i|\bperl\s+-\w*i|>>?|\btee\b|\bpatch\b|write_text|writeFileSync)[^|;&\n]*\b(?:node_modules|site-packages)/')
376
+ def dependency_gate(what, rel, st):
377
+ parts = rel.replace('\\', '/').split('/')
378
+ if not any(p in DEP_DIRS for p in parts): return
379
+ if re.search(r'node_modules|site-packages|patch-package|vendored? (?:dependency|library)', str(st.get('task', '')), re.I): return
380
+ event('safety', effect='write', decision='deny', command=what[:300], content='Refused: installed dependencies are not edited in place')
381
+ block('Refused: this changes an installed dependency (' + rel[:120] + '), which is outside the project and is lost on the next install. '
382
+ 'Do not edit dependencies to get past a check. Fix the project code or its configuration, or explain the problem and ask the user. '
383
+ 'This step was not run.')
384
+
337
385
  def protected_path_gate(name, args, rel, pol, st):
338
386
  """Paths the policy marks for review always ask, even in Auto mode (once per file per task)."""
339
387
  if pol is None or rel.startswith('..'): return
@@ -367,10 +415,69 @@ def command_policy_gate(command, pol, st, mode, auto):
367
415
  policy_event(pat, 'allow', 'Allowed by policy: ' + command[:300], command=command[:300]); return True
368
416
  return False
369
417
 
418
+ BOM = b'\xef\xbb\xbf'
419
+
420
+ def remember_bom(name, args):
421
+ """BUG-0546: the file tools drop a UTF-8 byte order mark; note which edited files had one so PostToolUse puts it back."""
422
+ if name not in ('Write', 'Edit') or not args.get('path'): return
423
+ try:
424
+ target = resolve(str(args['path']))
425
+ with open(target, 'rb') as f: had = f.read(3) == BOM
426
+ except OSError: return
427
+ if had:
428
+ known = load('kimi-bom.json', [])
429
+ if str(target) not in known: save('kimi-bom.json', (known + [str(target)])[-200:])
430
+
431
+ def restore_bom():
432
+ """Runs before the next tool call and at Stop (PostToolUse is only registered for project hooks), so it never races an edit."""
433
+ for path in load('kimi-bom.json', []):
434
+ try:
435
+ target = Path(path)
436
+ data = target.read_bytes()
437
+ if data and not data.startswith(BOM): target.write_bytes(BOM + data)
438
+ except OSError: pass
439
+
440
+ def step_limit_gate(st):
441
+ """BUG-0589: Settings > Agent > Maximum steps per task. Each command, edit or app call is one step; at the limit
442
+ the agent stops working and reports instead of running more (the model loop alone never went below 10)."""
443
+ try: limit = int(st.get('step_limit') or 0)
444
+ except (TypeError, ValueError): limit = 0
445
+ if limit <= 0: return
446
+ used = int(st.get('steps_used') or 0)
447
+ if used >= limit:
448
+ if not st.get('step_limit_noted'):
449
+ st['step_limit_noted'] = True; save_state(st)
450
+ event('note', content='Step limit reached (%d). Asked the agent to wrap up' % limit)
451
+ block('Step limit reached: the user allows %d step%s per task (Settings > Agent > Maximum steps per task), and all are used. '
452
+ 'This call was not run. Do not call more tools: reply now with what is done, what is left, and that they can raise the limit or send a follow-up.' % (limit, '' if limit == 1 else 's'))
453
+ st['steps_used'] = used + 1; save_state(st)
454
+
455
+ def question_only(st):
456
+ """BUG-0345: this turn answers a question and has not tried to change anything yet."""
457
+ return bool(st.get('question_turn') and not st.get('question_changes'))
458
+
459
+ def plan_first_due(st):
460
+ """The task list must be approved before the first change: Guided (plan_first), or Always in Auto too (BUG-0590)."""
461
+ mode = st.get('mode', 'approve')
462
+ return bool(st.get('plan_first') and (mode == 'approve' or (mode == 'auto' and st.get('plan_approval') == 'always'))
463
+ and not st.get('planned') and not st.get('plan_reviewed') and not st.get('readonly') and not (ROOT / 'kimi-approve-all').exists())
464
+
465
+ def always_plan_gate(command, st):
466
+ """With "Approve the task list first: Always", a command that changes files waits for the plan in Auto, like Write and Edit
467
+ (in Guided the command approval already asks). Reads and checks still run (BUG-0590)."""
468
+ if st.get('mode') != 'auto' or st.get('plan_approval') != 'always' or not plan_first_due(st): return
469
+ from command_safety import classify
470
+ if classify(command, REPO, cwd=REPO, home=os.path.dirname(REPO)).get('effect') in ('read', 'check'): return
471
+ event('note', content='Approve the task list first: asked for the plan before the first change')
472
+ block('The user approves your task list before any change, even in Auto. Call TodoList with 2 to 6 short, concrete items '
473
+ '(what you will change and how you will check it), then wait for the review. This command was not run; re-issue it after the plan is approved.')
474
+
370
475
  def pre(payload, st):
371
476
  name = str(payload.get('tool_name') or '')
372
477
  args = payload.get('tool_input') or {}
373
478
  if not isinstance(args, dict): args = {}
479
+ try: restore_bom(); remember_bom(name, args)
480
+ except Exception: pass
374
481
  if (ROOT / 'cancel').exists(): block('Task stopped by user.')
375
482
  if st.get('plan_dismissed') and is_work_tool(name): # before any approval card: Not now means nothing else asks or runs
376
483
  event('plan_review', content='Plan on hold: ' + re.sub(r'^mcp__\w+?__', '', name) + ' was not run')
@@ -396,19 +503,19 @@ def pre(payload, st):
396
503
  block('You have made this exact call three times recently. Repeating it will not give new information. Step back: re-read the latest error, form one hypothesis about the root cause, and take a different action.')
397
504
  save_state(st)
398
505
  if ACCEPTANCE in json.dumps(args) or HIDDEN.search(json.dumps(args)): block('That path holds the independent acceptance check, which is hidden from the builder by design. Work from the task and the failure output instead.')
506
+ if is_work_tool(name): step_limit_gate(st)
399
507
  if name == 'TodoList': return plan_gate(args, st)
400
508
  if briefing(st) and (name in ('Write', 'Edit', 'Agent', 'AgentSwarm') or (name.startswith('mcp__') and is_work_tool(name))):
401
- block('Brief mode: nothing is built until the user approves your task list. Read the repository, then call TodoList with the proposed items and state your open questions. This call was not run.')
509
+ block(brief_label(st) + ': nothing is built until the user approves your task list. Read the repository, then call TodoList with the proposed items and state your open questions. This call was not run.')
402
510
  if st.get('inspect') and name in ('Write', 'Edit', 'Agent', 'AgentSwarm'):
403
511
  event('safety', effect='write', decision='deny', command=name + ' ' + str(args.get('path', ''))[:300], content='Refused: the user asked for no changes in this turn')
404
512
  block(INSPECT_BLOCK)
405
513
  if name in ('Write', 'Edit') and not st.get('readonly'):
406
514
  nudged = set(st.get('nudged') or [])
407
- if (st.get('plan_first') and st.get('mode', 'approve') == 'approve' and not st.get('planned') and not st.get('plan_reviewed')
408
- and 'guided_plan' not in nudged and not (ROOT / 'kimi-approve-all').exists()):
409
- nudged.add('guided_plan'); st['nudged'] = sorted(nudged); save_state(st)
515
+ if (plan_first_due(st) and ('guided_plan' not in nudged or st.get('plan_approval') == 'always')):
516
+ nudged.add('guided_plan'); st['nudged'] = sorted(nudged); st['question_changes'] = True; save_state(st)
410
517
  event('note', content='Guided mode: asked for the plan before the first edit')
411
- block('Guided mode: the user approves your plan before any file changes. Call TodoList with 2 to 6 short, concrete items '
518
+ block(('The user approves your task list before any change, even in Auto.' if st.get('mode') == 'auto' else 'Guided mode: the user approves your plan before any file changes.') + ' Call TodoList with 2 to 6 short, concrete items '
412
519
  '(what you will change and how you will check it), then wait for the review. This edit was not applied; re-issue it after the plan is approved.')
413
520
  if st.get('large') and not st.get('planned') and 'plan' not in nudged:
414
521
  nudged.add('plan'); st['nudged'] = sorted(nudged); save_state(st)
@@ -436,6 +543,7 @@ def pre(payload, st):
436
543
  helper_gate(name, args, st)
437
544
  if name == 'Bash':
438
545
  command = str(args.get('command', ''))
546
+ always_plan_gate(command, st)
439
547
  try:
440
548
  from command_policy import offline_network_wait_reason
441
549
  reason = offline_network_wait_reason(command, st.get('task', ''))
@@ -443,6 +551,7 @@ def pre(payload, st):
443
551
  if reason: event('retry', content=reason); block(reason)
444
552
  masked = pipe_gate(command)
445
553
  if masked: event('note', content='Check would report a later command\'s exit status; asked for pipefail'); block(masked)
554
+ if DEP_WRITE.search(command): dependency_gate(command, 'node_modules', st)
446
555
  if command_policy_gate(command, pol, st, mode, auto): return
447
556
  return command_gate(command, st, mode, auto)
448
557
  if name in ('Write', 'Edit'):
@@ -456,6 +565,10 @@ def pre(payload, st):
456
565
  old, new = str(args.get('old_string', '')), str(args.get('new_string', ''))
457
566
  if old and old in original: after = original.replace(old, new) if args.get('replace_all') else original.replace(old, new, 1)
458
567
  rel = os.path.relpath(str(target), REPO)
568
+ if re.search(r'(^|/)\.git/hooks(/|$)', rel.replace(os.sep, '/')): # BUG-0551: the team's git hooks are not the agent's to change
569
+ from mlai_hooks import GIT_HOOK_REASON
570
+ event('safety', effect='write', decision='deny', command=name + ' ' + rel[:300], content='Refused: editing a git hook')
571
+ block(GIT_HOOK_REASON)
459
572
  if not rel.startswith('..'): secret_gate(name, args, rel, pol)
460
573
  if after is not None:
461
574
  try:
@@ -463,6 +576,7 @@ def pre(payload, st):
463
576
  problem = gate(rel, original, after, REPO) if not rel.startswith('..') else None
464
577
  except Exception: problem = None
465
578
  if problem: event('edit_guard', path=str(args.get('path', ''))[:200], content=problem[:600]); block(problem)
579
+ dependency_gate(name + ' ' + rel, rel, st)
466
580
  protected_path_gate(name, args, rel, pol, st)
467
581
  return edit_gate(name, args, rel, str(target), st, auto)
468
582
  if name in ('Agent', 'AgentSwarm') and not auto:
@@ -541,6 +655,13 @@ def edit_gate(name, args, rel, target, st, auto):
541
655
  wait_decision({'id': os.urandom(8).hex(), 'kind': 'scope', 'area': area(rel), 'command': summary})
542
656
  grant_area(st, rel)
543
657
 
658
+ def chat_allowed(command, effect):
659
+ """BUG-0594: the person chose "Always allow in this chat" for this exact command (safe kinds only, re-checked)."""
660
+ try:
661
+ from command_safety import chat_allow_ok, chat_allow_key
662
+ return chat_allow_key(command) in load('chat-allow.json', []) and chat_allow_ok(effect, command, REPO)
663
+ except Exception: return False
664
+
544
665
  def command_gate(command, st, mode, auto):
545
666
  """Classify the command; allow, ask or refuse according to the mode budget and the approved scope."""
546
667
  from command_safety import classify, decide, describe, relative
@@ -554,12 +675,15 @@ def command_gate(command, st, mode, auto):
554
675
  if decision['decision'] == 'deny':
555
676
  event('safety', effect=effect, decision='deny', command=command[:2000], content='Refused. ' + (decision.get('reason') or describe(decision)))
556
677
  if effect == 'catastrophic': block('Refused: ' + (decision.get('reason') or describe(decision)) + '. This command is never run, in any mode. Choose a contained alternative (delete specific files inside the project, keep the harness state alone, never touch devices or system directories).')
557
- if briefing(st): block('Brief mode: only read-only commands run before the user approves the task list. ' + describe(decision) + ' was not run; put it in the plan instead.')
678
+ if briefing(st): block(brief_label(st) + ': only read-only commands run before the user approves the task list. ' + describe(decision) + ' was not run; put it in the plan instead.')
558
679
  if st.get('inspect'): block('Not allowed: ' + describe(decision) + '. ' + INSPECT_BLOCK)
559
680
  block('Not allowed in this mode: ' + describe(decision) + '. Plan mode only reads; propose the command in your answer instead.')
560
681
  if decision['decision'] == 'allow':
561
682
  if effect not in ('read', 'check'): event('safety', effect=effect, decision='allow', command=command[:300], content=describe(decision))
562
683
  return
684
+ if effect not in ('destructive', 'privilege') and chat_allowed(command, effect):
685
+ event('safety', effect=effect, decision='allow', command=command[:300], content='Always allowed in this chat')
686
+ return
563
687
  request = {'id': os.urandom(8).hex(), 'kind': 'command', 'effect': effect, 'reason': decision.get('reason') or '', 'command': command[:20000]}
564
688
  # Deletes and sudo ask every time, even after Approve all (BUG-0101). The card says so and offers no Approve all for them.
565
689
  if effect in ('destructive', 'privilege'): request['strict'] = True
@@ -626,6 +750,12 @@ def readonly_stop(st):
626
750
  event('done_gate', content='Research claims not recorded yet')
627
751
  block('Before answering, record the material claims with mcp__mlai__evidence {claims:[{claim, kind, source_ids, quote, uncertainty}]}. Facts need an exact quote from a retrieved source; label inferences and assumptions. Link the source URLs in the answer.')
628
752
 
753
+ def _laptop_run():
754
+ """BUG-0531: the run is on the person's own computer (CLI or Mac app)."""
755
+ if os.getenv('MINI_LAPTOP') == '1': return True
756
+ try: return json.loads((ROOT / 'request.json').read_text()).get('laptop') is True
757
+ except (OSError, ValueError, AttributeError): return False
758
+
629
759
  def stop(payload, st):
630
760
  if (ROOT / 'cancel').exists(): return
631
761
  if st.get('account_stop'): return # out of credits: the summary is the last turn, no more gates
@@ -635,8 +765,8 @@ def stop(payload, st):
635
765
  if st.get('plan_dismissed'): return # Not now: the run ends here; no done gate may send the agent back to work (BUG-0102)
636
766
  if briefing(st) and not st.get('planned') and not st.get('brief_nudged'):
637
767
  st['brief_nudged'] = True; save_state(st)
638
- event('done_gate', content='Brief mode: asked for the task list before finishing')
639
- block('Brief mode: the user is waiting to review a task list. Call TodoList with 3 to 10 concrete items (and mcp__mlai__brief_questions for anything open) before finishing. If the request is already answered and nothing needs building, say so plainly and finish.')
768
+ event('done_gate', content=brief_label(st) + ': asked for the task list before finishing')
769
+ block(brief_label(st) + ': the user is waiting to review a task list. Call TodoList with 3 to 10 concrete items (and mcp__mlai__brief_questions for anything open) before finishing. If the request is already answered and nothing needs building, say so plainly and finish.')
640
770
  if briefing(st): return
641
771
  count = int(load('kimi-stop-count', 0) or 0)
642
772
  if count >= 3 or time.time() > st.get('deadline', 1e18) - 90: return
@@ -645,6 +775,10 @@ def stop(payload, st):
645
775
  import roles as role_engine
646
776
  try: changed = role_engine.changed_files(REPO, st.get('base'))
647
777
  except Exception: changed = []
778
+ try:
779
+ from runtime_control import turn_changes
780
+ changed = turn_changes(ROOT, REPO, changed) # BUG-0495: not files that were already untracked or changed at the start
781
+ except Exception: pass
648
782
  code_changed = [p for p in changed if role_engine.CODE_EXT.search(p)]
649
783
  if st.get('require_changes') and not changed and 'patch' not in done:
650
784
  done.add('patch'); issues.append('This task requires a repository change, but the working tree is unchanged. Make the fix, or explain the blocker if it truly cannot be fixed.')
@@ -669,9 +803,12 @@ def stop(payload, st):
669
803
  if blocking: done.add('verification'); issues += blocking[:3]
670
804
  except Exception: pass
671
805
  role = st.get('role')
806
+ if role and 'role' not in done and (ROOT / 'last-reject').exists() and float((ROOT / 'last-reject').read_text().strip() or 0) >= float(st.get('started') or 0):
807
+ done.add('role') # BUG-0529: after a denial the done-check must not push unrequested work; the agent stops and asks
808
+ event('role_check', role=role['id'], title=role['title'], status='skipped', issues=[])
672
809
  if role and 'role' not in done:
673
810
  done.add('role')
674
- try: gaps = role_engine.gate(role, REPO, st.get('base'), changed, st.get('task', ''))
811
+ try: gaps = role_engine.gate(role, REPO, st.get('base'), changed, st.get('task', ''), laptop=_laptop_run())
675
812
  except Exception: gaps = []
676
813
  event('role_check', role=role['id'], title=role['title'], status='blocked' if gaps else 'passed', issues=[{'kind': i['kind'], 'label': i['label'], 'message': i['message'][:600]} for i in gaps])
677
814
  if gaps: issues.append('Role done-check (' + role['title'] + '): ' + ' '.join(i['message'] for i in gaps) + ' Fix these for real (real data paths, real artifacts, verified). If one truly cannot apply, say why in the final summary.')
@@ -707,9 +844,13 @@ def main():
707
844
  st = state()
708
845
  if kind == 'PreToolUse': pre(payload, st)
709
846
  elif kind == 'PostToolUse':
847
+ try: restore_bom()
848
+ except Exception: pass
710
849
  feedback = user_hooks('kimi_post', payload, st) # after_tool / after_edit hooks
711
850
  if feedback: block(feedback)
712
851
  elif kind == 'Stop':
852
+ try: restore_bom()
853
+ except Exception: pass
713
854
  stop(payload, st)
714
855
  # Turn accepted: tell the bridge, which ends the engine if it lingers waiting on background processes (preview servers).
715
856
  save('kimi-stopped', {'time': time.time()})
@@ -164,11 +164,14 @@ class Media:
164
164
  return {'name': info.get('name'), 'domain': domain, 'description': info.get('description'), 'colors': info.get('colors'), 'fonts': info.get('fonts'), 'logos': saved,
165
165
  'note': 'Pick the logo whose use_on matches the deck background (theme.logo). Use the brand colours as accent/accent2 only if text stays readable (4.5:1).'}
166
166
 
167
+ # Said once, plainly, so the agent stops asking (CLI bug list: four parallel calls, then more until the run was stopped).
168
+ NOT_CONFIGURED = 'Stock photos and brand lookup are not available in this run. Do not call stock_photo or brand_lookup again; use the images already in the project or a styled placeholder.'
169
+
167
170
  def call(name, args):
168
171
  """Tool side (runner or the Kimi MCP server): forward to the loopback gateway, which holds the keys."""
169
172
  import os
170
173
  base, token = os.getenv('MINI_IMAGE_URL', ''), os.getenv('MINI_IMAGE_TOKEN', '')
171
- if not base or not token: raise ValueError('Stock photos and brand lookup are not configured on this server.')
174
+ if not base or not token: raise ValueError(NOT_CONFIGURED)
172
175
  url = base.rsplit('/', 1)[0] + ('/stock' if name == 'stock_photo' else '/brand')
173
176
  req = urllib.request.Request(url, data=json.dumps(args).encode(), headers={'Authorization': 'Bearer ' + token, 'Content-Type': 'application/json'})
174
177
  try: