mlai-code 0.3.8 → 0.3.10

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.
@@ -141,9 +141,24 @@ def pick_effort(setting, body, provider, calls):
141
141
  tail.append(_text(m.get('content'))[-3000:])
142
142
  return 'high' if any(FAILURE_SIGNS.search(t) for t in tail) else 'low'
143
143
 
144
+ FALLBACK_STICKY = 3 # calls that go straight to the backup after Pixis fails, before Pixis is tried again
145
+
146
+ def backup_route(spec, key):
147
+ """The backup model for Opus 5.5R (lib/model-config.ts fallbackConfig), or None. The key comes from the env only."""
148
+ if not isinstance(spec, dict) or not key or not spec.get('endpoint') or not spec.get('model'): return None
149
+ try: cap = max(0, int(spec.get('maxCalls', 40)))
150
+ except (TypeError, ValueError): cap = 40
151
+ return {'endpoint': chat_url(spec['endpoint']), 'model': str(spec['model']), 'label': str(spec.get('label') or spec['model']), 'maxCalls': cap, 'key': key}
152
+
153
+ def describe_failure(exc):
154
+ if isinstance(exc, urllib.error.HTTPError): return 'HTTP ' + str(exc.code)
155
+ return type(exc).__name__
156
+
144
157
  class ModelProxy:
145
- def __init__(self, endpoint, key, model, provider='', effort='medium', rates=None):
158
+ def __init__(self, endpoint, key, model, provider='', effort='medium', rates=None, fallback=None, fallback_key=''):
146
159
  self.endpoint, self.key, self.model, self.provider = chat_url(endpoint), key, model, provider
160
+ self.fallback = backup_route(fallback, fallback_key) # Opus 5.5R: a failed Pixis call is sent here once
161
+ self.fallback_calls = self.fallback_sticky = self.escalations = 0
147
162
  self.rates = R.credit_rates(rates) # gateway models: credits follow their public price (lib/model-prices.ts)
148
163
  self.effort = effort
149
164
  self.effort_counts = {}
@@ -218,38 +233,45 @@ class ModelProxy:
218
233
  except OSError: pass
219
234
  if saved:
220
235
  with self.lock: self.trimmed += saved
236
+ if self.over_budget(body):
237
+ return handler._send(400, {'error': {'message': 'Budget limit reached: this step would go past the credit cap for this run, so it was not started.', 'type': 'budget_exceeded'}})
221
238
  stream_id = 'kimi-' + pysecrets.token_hex(6)
222
239
  started = time.monotonic()
223
240
  with self.lock: self.calls += 1
224
241
  inference_progress(id=stream_id, state='running', content='', seconds=0)
225
242
  req = urllib.request.Request(self.endpoint, data=json.dumps(body).encode(), headers={'Content-Type': 'application/json', 'Authorization': 'Bearer ' + self.key, 'Accept': 'text/event-stream' if stream else 'application/json'})
226
- try:
243
+ res = None
244
+ escalate = self.backup_ready() and bool(body.get('tools')) and not summary_request and R.failing_streak(body.get('messages')) >= R.ESCALATE_AFTER
245
+ if self.backup_ready() and (self.fallback_sticky > 0 or escalate):
246
+ # Pixis failed moments ago (the next few calls skip it), or its last steps kept failing: this step goes to the backup.
247
+ if not escalate: self.fallback_sticky -= 1
227
248
  try:
228
- res = urllib.request.urlopen(req, timeout=STALL_SECONDS) # per-read: a stream silent this long is dead; the engine retries
229
- except urllib.error.HTTPError as exc:
230
- exc.detail = exc.read()[:4000]
231
- if exc.code in (400, 413, 415, 422) and not getattr(self, 'images_off', False) and strip_images(body):
232
- # The endpoint refused image input: carry on text-only for the rest of the run instead of failing the step.
233
- self.images_off = True
234
- event('note', content='Images could not be sent to the model, so this run continues without them.')
235
- # BUG-0230: the app offers a one-click resend with a model that can see images.
236
- event('vision_unavailable', model=os.getenv('MINI_MODEL_ID', ''), content=(os.getenv('MINI_MODEL_LABEL') or 'This model') + ' could not see the attached image, so its answer is not based on what the image shows.')
237
- req = urllib.request.Request(self.endpoint, data=json.dumps(body).encode(), headers=dict(req.header_items()))
238
- res = urllib.request.urlopen(req, timeout=STALL_SECONDS)
239
- elif not (effort and exc.code == 400 and b'reasoning' in exc.detail.lower()): raise
240
- else:
241
- # The provider rejected the effort value: retry once with the provider default rather than fail the step.
242
- body.pop('reasoning_effort', None); self.provider = ''
243
- req = urllib.request.Request(self.endpoint, data=json.dumps(body).encode(), headers=dict(req.header_items()))
244
- res = urllib.request.urlopen(req, timeout=STALL_SECONDS)
245
- except urllib.error.HTTPError as exc:
246
- detail = getattr(exc, 'detail', None) or exc.read()[:4000]; self.last_error = 'Model HTTP ' + str(exc.code) + ': ' + detail.decode('utf-8', 'replace')[:300]
247
- inference_progress(id=stream_id, state='failed', content='')
248
- return handler._send(exc.code, detail or b'{}')
249
- except Exception as exc:
250
- self.last_error = 'Model connection failed: ' + str(exc)[:300]
251
- inference_progress(id=stream_id, state='failed', content='')
252
- return handler._send(502, {'error': {'message': self.last_error}})
249
+ res = self.open_backup(body, stream)
250
+ if escalate:
251
+ with self.lock: self.escalations += 1
252
+ event('model_fallback', content='Pixis could not get the last steps working, so ' + self.fallback['label'] + ' took this step.', model=self.fallback['model'], reason='steps_failing', calls=self.fallback_calls)
253
+ except Exception: res = None # the backup failed too: try Pixis as usual
254
+ if res is None:
255
+ try: res = self.open_primary(req, body, effort)
256
+ except Exception as exc:
257
+ failure = exc
258
+ if self.backup_ready():
259
+ try:
260
+ res = self.open_backup(body, stream); self.fallback_sticky = FALLBACK_STICKY
261
+ event('model_fallback', content='Pixis did not answer this step, so it ran on ' + self.fallback['label'] + '.', model=self.fallback['model'], reason=describe_failure(exc), calls=self.fallback_calls)
262
+ except Exception as backup_exc: failure = backup_exc
263
+ if res is None:
264
+ if isinstance(failure, urllib.error.HTTPError):
265
+ detail = getattr(failure, 'detail', None)
266
+ if detail is None:
267
+ try: detail = failure.read()[:4000]
268
+ except Exception: detail = b''
269
+ self.last_error = 'Model HTTP ' + str(failure.code) + ': ' + detail.decode('utf-8', 'replace')[:300]
270
+ inference_progress(id=stream_id, state='failed', content='')
271
+ return handler._send(failure.code, detail or b'{}')
272
+ self.last_error = 'Model connection failed: ' + str(failure)[:300]
273
+ inference_progress(id=stream_id, state='failed', content='')
274
+ return handler._send(502, {'error': {'message': self.last_error}})
253
275
  stream_usage = None
254
276
  try:
255
277
  if not stream:
@@ -290,20 +312,72 @@ class ModelProxy:
290
312
  with self.lock: self.inference += time.monotonic() - started
291
313
  inference_progress(id=stream_id, state='completed', content='')
292
314
 
315
+ def open_primary(self, req, body, effort):
316
+ """One call to the run's model, with the existing image and effort recoveries. Raises on failure."""
317
+ try:
318
+ return urllib.request.urlopen(req, timeout=STALL_SECONDS) # per-read: a stream silent this long is dead; the engine retries
319
+ except urllib.error.HTTPError as exc:
320
+ exc.detail = exc.read()[:4000]
321
+ if exc.code in (400, 413, 415, 422) and not getattr(self, 'images_off', False) and strip_images(body):
322
+ # The endpoint refused image input: carry on text-only for the rest of the run instead of failing the step.
323
+ self.images_off = True
324
+ event('note', content='Images could not be sent to the model, so this run continues without them.')
325
+ # BUG-0230: the app offers a one-click resend with a model that can see images.
326
+ event('vision_unavailable', model=os.getenv('MINI_MODEL_ID', ''), content=(os.getenv('MINI_MODEL_LABEL') or 'This model') + ' could not see the attached image, so its answer is not based on what the image shows.')
327
+ req = urllib.request.Request(self.endpoint, data=json.dumps(body).encode(), headers=dict(req.header_items()))
328
+ return urllib.request.urlopen(req, timeout=STALL_SECONDS)
329
+ if not (effort and exc.code == 400 and b'reasoning' in exc.detail.lower()): raise
330
+ # The provider rejected the effort value: retry once with the provider default rather than fail the step.
331
+ body.pop('reasoning_effort', None); self.provider = ''
332
+ req = urllib.request.Request(self.endpoint, data=json.dumps(body).encode(), headers=dict(req.header_items()))
333
+ return urllib.request.urlopen(req, timeout=STALL_SECONDS)
334
+
335
+ def backup_ready(self):
336
+ return bool(self.fallback) and self.fallback_calls < self.fallback['maxCalls']
337
+
338
+ def open_backup(self, body, stream):
339
+ """The same request on the backup model (Opus 5.5R). Usage is counted like any Pixis call."""
340
+ fb = self.fallback
341
+ with self.lock: self.fallback_calls += 1
342
+ out = {k: v for k, v in body.items() if k not in ('reasoning_effort', 'include_reasoning')} # Isoquant-only controls
343
+ out['model'] = fb['model']
344
+ req = urllib.request.Request(fb['endpoint'], data=json.dumps(out).encode(), headers={'Content-Type': 'application/json', 'Authorization': 'Bearer ' + fb['key'], 'Accept': 'text/event-stream' if stream else 'application/json'})
345
+ try: return urllib.request.urlopen(req, timeout=STALL_SECONDS)
346
+ except urllib.error.HTTPError as exc:
347
+ exc.detail = exc.read()[:4000]
348
+ raise
349
+
293
350
  def write_usage(self, total, raw):
294
351
  # The hook enforces the account allowance (billable tokens) and the repository's per-task budget (raw) from this file.
295
352
  try:
296
353
  tmp = ROOT / 'usage.json.tmp'; tmp.write_text(json.dumps({'tokens': total, 'raw': raw})); tmp.replace(ROOT / 'usage.json')
297
354
  except OSError: pass
298
355
 
356
+ def over_budget(self, body):
357
+ """BUG-0615: under a hard cap (--max-budget-credits) the next call's likely cost is checked before it starts: its
358
+ whole prompt for the first call (nothing cached yet), the previous call's cost after that."""
359
+ cap = getattr(self, 'hard_left', None)
360
+ if cap is None: return False
361
+ if getattr(self, 'budget_refused', False): return True
362
+ try: spent = self.billable + max(0, int(self.spent_elsewhere()))
363
+ except Exception: spent = self.billable
364
+ if self.calls and getattr(self, 'last_billable', 0): est = self.last_billable
365
+ else: est = R.billable_tokens({'prompt_tokens': len(json.dumps(body, default=str)) // 4, 'completion_tokens': int(body.get('max_tokens') or body.get('max_completion_tokens') or 0) // 8}, self.rates)
366
+ if spent + est <= cap: return False
367
+ self.budget_refused = True
368
+ event('account_limit', phase='stopped', content=CREDITS_OUT_NOTE)
369
+ return True
370
+
299
371
  def count(self, usage):
300
372
  with self.lock:
373
+ before = self.billable
301
374
  self.prompt += int(usage.get('prompt_tokens') or 0)
302
375
  self.completion += int(usage.get('completion_tokens') or 0)
303
376
  details = usage.get('prompt_tokens_details') or {}
304
377
  self.cached += int(details.get('cached_tokens') or usage.get('cached_tokens') or 0)
305
378
  self.reasoning += int((usage.get('completion_tokens_details') or {}).get('reasoning_tokens') or 0)
306
379
  self.billable += R.billable_tokens(usage, self.rates)
380
+ self.last_billable = self.billable - before
307
381
  total, raw = self.billable, self.prompt + self.completion
308
382
  self.write_usage(total, raw)
309
383
  if os.getenv('MINI_KIMI_DUMP'): # local profiling only
@@ -476,7 +550,7 @@ def strip_images(body):
476
550
 
477
551
  # Never in the engine's environment, so never in the environment of the commands it runs (BUG-0517). The MCP server
478
552
  # gets the image/research/hub values it needs through its own env in mcp.json; the engine reads the proxy token from config.toml.
479
- ENGINE_ENV_HIDDEN = ('MODEL_API_KEY', 'SIDE_MODEL_API_KEY', 'VERCEL_OIDC_TOKEN', 'EXA_API_KEY', 'FIRECRAWL_API_KEY', 'OPENROUTER_API_KEY',
553
+ ENGINE_ENV_HIDDEN = ('MODEL_API_KEY', 'SIDE_MODEL_API_KEY', 'FALLBACK_MODEL_API_KEY', 'VERCEL_OIDC_TOKEN', 'EXA_API_KEY', 'FIRECRAWL_API_KEY', 'OPENROUTER_API_KEY',
480
554
  'PIXABAY_API_KEY', 'BRANDFETCH_API_KEY', 'MINI_VAULT', 'MINI_KIMI_PROXY_TOKEN', 'MINI_IMAGE_URL', 'MINI_IMAGE_TOKEN',
481
555
  'MINI_RESEARCH_URL', 'MINI_RESEARCH_TOKEN', 'MLAI_HUB_TOKEN')
482
556
 
@@ -490,8 +564,25 @@ def engine_env(environ):
490
564
 
491
565
  LAST_OUTPUT = '' # the newest successful shell output in this run
492
566
  SANDBOX_DENIALS = 0 # tool calls the OS sandbox refused in this run
567
+ BACKGROUND_RAN = False # BUG-0682: this run started a server or other background command
568
+ DETACHED = re.compile(r'(?:^|[^&])&\s*(?:disown\s*)?$|\bnohup\b|\bsetsid\b', re.M)
569
+ ONE_SHOT_BACKGROUND_NOTE = ('Note: servers and other background commands started in this run stop when mlai exits. To keep one running, '
570
+ 'start it yourself in a terminal, or run mlai without -p and leave the session open.')
571
+ ALREADY_WARNED = re.compile(r'\bstop(?:s|ped)?\s+when\b|\bwhen\s+(?:mlai|this\s+run|the\s+run|the\s+session)\s+(?:exits|ends|stops|closes)\b|\bno\s+longer\s+running\b|\bnot\s+(?:still\s+)?running\b', re.I)
572
+
573
+ def one_shot_background_note(answer):
574
+ """BUG-0682: a one-shot run (mlai -p) ends its background processes on exit; the answer must not leave the user
575
+ thinking a server it started is still up."""
576
+ if os.getenv('MINI_ONE_SHOT') != '1' or not BACKGROUND_RAN or not answer or ALREADY_WARNED.search(answer): return answer
577
+ return answer + '\n\n' + ONE_SHOT_BACKGROUND_NOTE
493
578
  SANDBOX_DENIED = re.compile(r'Operation not permitted|Read-only file system|sandbox-exec: .*denied|deny\(\d+\) file-write', re.I)
494
579
  SANDBOX_STUCK_AFTER = 3
580
+ # BUG-0616: in a -p run nobody can approve a write outside the project, so its card is refused at once; the agent then
581
+ # tried one way after another (14 to 52 model calls). A refused write counts toward the stop like a sandbox denial.
582
+ UNANSWERED = re.compile(r'The user rejected (?:this|a related) action|The user did not approve')
583
+
584
+ def sandbox_denial(name, code, content):
585
+ return bool(code) and name in ('Bash', 'Write', 'Edit') and bool(SANDBOX_DENIED.search(content) or UNANSWERED.search(content))
495
586
  SANDBOX_STOP_NOTE = ('Stopped: the OS sandbox blocked writing outside this project %d times, and a run started with -p cannot ask you to allow it. '
496
587
  'Nothing outside the project was changed. Run it interactively (mlai) to approve it, or work inside the project folder.' % SANDBOX_STUCK_AFTER)
497
588
 
@@ -531,6 +622,16 @@ def denied_tools(config):
531
622
  out += [t for t in DENY_TO_ENGINE.get({'write': 'Edit', 'edit': 'Edit', 'bash': 'Bash', 'shell': 'Bash', 'websearch': 'WebSearch', 'agent': 'Agent'}.get(rule.strip().lower(), ''), ()) if t not in out]
532
623
  return out
533
624
 
625
+ def step_limit_reached(config, mapper, calls, steps):
626
+ """BUG-0614/0683: on the person's computer, a run whose step limit cut the work short is limited, not a success: the
627
+ hook refused a call at the --max-steps limit, or with --max-turns the engine stopped while the agent still had a tool
628
+ call in progress (its last reply asked for one)."""
629
+ if not (config.get('laptop') or os.getenv('MINI_LAPTOP') == '1'): return False
630
+ try: hook = json.loads((ROOT / 'kimi-hook.json').read_text())
631
+ except (OSError, ValueError): hook = {}
632
+ if isinstance(hook, dict) and hook.get('step_limit_noted'): return True
633
+ return bool(config.get('hardSteps')) and calls >= steps and bool(getattr(mapper, 'open_calls', False))
634
+
534
635
  def step_cap(config, steps):
535
636
  """Agent steps per turn for the engine. CLI --max-turns (hardSteps) is an exact cap; otherwise at least 10 (BUG-0492)."""
536
637
  return max(1, steps) if config.get('hardSteps') else max(10, steps)
@@ -567,7 +668,9 @@ def write_home(config, proxy, mode, readonly, steps):
567
668
  servers = {'mlai': server}
568
669
  try:
569
670
  import mcp_local # the user's own MCP servers from the CLI (/mcp): .mlai/mcp.json, .mcp.json, .cursor/mcp.json, settings
570
- servers.update(mcp_local.kimi_servers(config, readonly=readonly))
671
+ mine = mcp_local.kimi_servers(config, readonly=readonly)
672
+ if mine: mcp_local.check(mine, config, lambda text: event('note', level='warning', content=text), cwd=REPO, readonly=readonly) # BUG-0661
673
+ servers.update(mine)
571
674
  except Exception as exc: print('MCP servers skipped: ' + str(exc)[:200], file=sys.stderr)
572
675
  (HOME / 'mcp.json').write_text(json.dumps({'mcpServers': servers}))
573
676
 
@@ -641,6 +744,20 @@ ENGINE_NAMES = re.compile(r'\bKimi(?:[ -]Code)?[ -]CLI\b|\bKimi Code\b(?= (?:age
641
744
 
642
745
  REFERS_BACK = re.compile(r'\b(?:above|previous (?:message|reply|answer)|earlier (?:message|reply|answer)|already (?:listed|given|provided|written))\b', re.I)
643
746
 
747
+ # BUG-0609: the old engine's finish marker, written by the model as its whole last message.
748
+ INTERNAL_ANSWER = re.compile(r'^\s*(?:```(?:bash|sh|shell)?\s*)?(?:echo\s+)?COMPLETE_TASK_AND_SUBMIT_FINAL_OUTPUT\s*(?:```)?\s*$')
749
+ # BUG-0609/0611: a reply after a repair round that talks about the harness (the evidence tool, source IDs, the task
750
+ # contract) instead of answering the user.
751
+ REPAIR_TALK = re.compile(r'\b(?:evidence (?:tool|ledger|record)|source[_ ]ids?|task[_ ]contract|completion gate|repair (?:step|round)|mcp__mlai__)', re.I)
752
+
753
+ def internal_answer(text):
754
+ return bool(INTERNAL_ANSWER.match(str(text or '')))
755
+
756
+ def repair_talk(text):
757
+ """A short reply about the harness's own tools, not an answer for the user."""
758
+ t = str(text or '').strip()
759
+ return bool(t) and len(t) < 600 and bool(REPAIR_TALK.search(t))
760
+
644
761
  def final_answer(last, texts):
645
762
  """BUG-0192: the agent wrote the full answer, then a short closing message pointing back to it ("the tips above are
646
763
  the complete deliverable"). Only the closing message was kept as the answer, so the list vanished from the chat after
@@ -684,7 +801,10 @@ class StreamMapper:
684
801
  except Exception: pass
685
802
  def todos(self, items):
686
803
  shown = [{'text': str(t.get('title', ''))[:300], 'status': t.get('status') if t.get('status') in ('pending', 'in_progress', 'done') else 'pending'} for t in items if isinstance(t, dict)][:40]
687
- write('todos.json', shown); event('todos', items=shown)
804
+ write('todos.json', shown)
805
+ # The same list again (a repeated TodoList call) is not shown twice (tester report, CLI 0.3.8).
806
+ if shown != getattr(self, 'last_todos', None): event('todos', items=shown)
807
+ self.last_todos = shown
688
808
  def announce(self, name, args):
689
809
  if name == 'Bash': event('command', command=str(args.get('command', ''))[:20000])
690
810
  elif name in ('Agent', 'AgentSwarm'): event('subagent', state='running', content=str(args.get('description') or args.get('prompt') or '')[:400])
@@ -707,11 +827,13 @@ class StreamMapper:
707
827
  try: write('kimi-last-text.json', {'text': self.last_text[:20000], 'time': time.time()})
708
828
  except OSError: pass
709
829
  calls = msg.get('tool_calls') or []
830
+ self.open_calls = bool(calls) # the agent's newest reply asked for a tool: it was not finished (BUG-0614)
710
831
  for call in calls:
711
832
  fn = call.get('function') or {}; name = fn.get('name', '')
712
833
  try: args = json.loads(fn.get('arguments') or '{}')
713
834
  except ValueError: args = {}
714
835
  self.calls[call.get('id')] = (name, args)
836
+ if name == 'Bash' and not args.get('run_in_background'): proc_watch.foreground(call.get('id'), args.get('command')) # CLI r7
715
837
  if name == 'TodoList' and isinstance(args.get('todos'), list): self.todos(args['todos'])
716
838
  elif len(calls) == 1: self.announce(name, args)
717
839
  # Parallel calls are announced with their results so each step pairs with its own output.
@@ -725,6 +847,7 @@ class StreamMapper:
725
847
  return
726
848
  if role == 'tool':
727
849
  name, args = self.calls.get(msg.get('tool_call_id'), ('', {}))
850
+ proc_watch.done(msg.get('tool_call_id'))
728
851
  content = msg.get('content')
729
852
  if isinstance(content, list): content = '\n'.join(p.get('text', '') for p in content if isinstance(p, dict))
730
853
  content = str(content or '')
@@ -764,9 +887,10 @@ class StreamMapper:
764
887
  # Editing prose does not make test evidence stale; editing anything else does.
765
888
  if not PROSE_PATH.search(str(args.get('path', ''))): st['last_edit'] = time.time()
766
889
  if not code: self.checkpoint(name, args)
767
- global LAST_OUTPUT, SANDBOX_DENIALS
890
+ global LAST_OUTPUT, SANDBOX_DENIALS, BACKGROUND_RAN
768
891
  if name == 'Bash' and not code: LAST_OUTPUT = content
769
- if code and name in ('Bash', 'Write', 'Edit') and SANDBOX_DENIED.search(content): SANDBOX_DENIALS += 1
892
+ if not code and not blocked and ((name == 'Bash' and (args.get('run_in_background') or moved or DETACHED.search(command))) or name == 'mcp__mlai__preview'): BACKGROUND_RAN = True
893
+ if sandbox_denial(name, code, content): SANDBOX_DENIALS += 1
770
894
  if name == 'Bash':
771
895
  command = str(args.get('command', ''))
772
896
  try:
@@ -931,11 +1055,11 @@ def recheck_stale(state, env, seconds_left, limit=3):
931
1055
  if budget < 20 or stopped(): break
932
1056
  command = str(check.get('command'))
933
1057
  began = time.time()
934
- try:
935
- r = subprocess.run(['bash', '-lc', command], cwd=REPO, env=env, capture_output=True, text=True, timeout=min(REPLAY_SECONDS, budget))
936
- code, output = r.returncode, (r.stdout + r.stderr)[-4000:]
937
- except subprocess.TimeoutExpired:
938
- code, output = None, 'Timed out when rerun on the final code.'
1058
+ # Bounded on every OS: output goes to a file and the whole tree is stopped on timeout or Esc (a headless browser
1059
+ # left by an e2e script kept a Windows run at "Working" for 45 minutes after its final answer).
1060
+ code, output, why = verification.bounded_run(['bash', '-lc', command], cwd=REPO, env=env, timeout=int(min(REPLAY_SECONDS, budget)), stop=stopped)
1061
+ if why == 'stopped': break
1062
+ if code is None: output = (output + '\n' if output else '') + 'Timed out when rerun on the final code.'
939
1063
  budget -= time.time() - began
940
1064
  check_code, integrity = verification.check_exit(command, code, output, is_check) if code is not None else (None, '')
941
1065
  code = check_code if check_code is not None else code
@@ -989,6 +1113,14 @@ def soft_unverified(report, unresolved, state=None):
989
1113
  # it used to loop through every repair round and end as Not verified, also when the user said not to test.
990
1114
  return True
991
1115
 
1116
+ def acceptance_note(checks):
1117
+ """BUG-0684: name the project checks the result rests on; never point at a list below that is not there."""
1118
+ try: names = _check_names(checks, 'passed')
1119
+ except Exception: names = []
1120
+ if names: return 'An extra independent test could not be set up for this project, so this result rests on the project\'s own checks: ' + ', '.join(names[:4]) + '.'
1121
+ return 'An extra independent test could not be set up for this project, and no project check passed, so this result is not independently tested.'
1122
+
1123
+
992
1124
  def _check_names(checks, status):
993
1125
  try: from runtime_control import latest_checks, check_status
994
1126
  except Exception: return []
@@ -1045,7 +1177,7 @@ def windows_note():
1045
1177
  def workspace_note(config, event):
1046
1178
  """Jobs (restart the ones that died), project setup and environment facts for the agent's instructions."""
1047
1179
  note = ''
1048
- env = {k: v for k, v in os.environ.items() if k not in ('MODEL_API_KEY', 'SIDE_MODEL_API_KEY', 'VERCEL_OIDC_TOKEN', 'EXA_API_KEY', 'FIRECRAWL_API_KEY', 'OPENROUTER_API_KEY', 'PIXABAY_API_KEY', 'BRANDFETCH_API_KEY', 'MINI_VAULT')}
1180
+ env = {k: v for k, v in os.environ.items() if k not in ('MODEL_API_KEY', 'SIDE_MODEL_API_KEY', 'FALLBACK_MODEL_API_KEY', 'VERCEL_OIDC_TOKEN', 'EXA_API_KEY', 'FIRECRAWL_API_KEY', 'OPENROUTER_API_KEY', 'PIXABAY_API_KEY', 'BRANDFETCH_API_KEY', 'MINI_VAULT')}
1049
1181
  env.update(VAULT)
1050
1182
  try:
1051
1183
  import dev_jobs
@@ -1146,6 +1278,11 @@ def build_context(config):
1146
1278
  if mlai_hooks.active(): task = mlai_hooks.guidance() + '\n' + task # project hooks and hard-deny rules
1147
1279
  if config.get('laptop') or os.getenv('MINI_LAPTOP') == '1': task = mlai_hooks.LAPTOP_RULES.replace('call cannot_complete', 'call mcp__mlai__cannot_complete') + '\n' + task # BUG-0523/0529/0531
1148
1280
  except Exception: pass
1281
+ try:
1282
+ from conversation import terminal_deck_rule
1283
+ rule = terminal_deck_rule(config.get('task', ''))
1284
+ if rule: task = rule.replace('deck_check {', 'mcp__mlai__deck_check {') + '\n' + task # BUG-0691
1285
+ except Exception: pass
1149
1286
  try: # CLI custom subagents and opt-in project memory
1150
1287
  from subagents import agents_guidance
1151
1288
  from project_rules import memory_note
@@ -1255,7 +1392,7 @@ def finish_files():
1255
1392
 
1256
1393
  def fallback(reason):
1257
1394
  """Run the task on the built-in engine instead. Restores the Vault payload that importing runner consumed."""
1258
- event('note', content='The main coding engine is unavailable; using the built-in engine. ' + str(reason)[:300])
1395
+ event('note', level='warning', content='The main coding engine is unavailable; using the built-in engine. ' + str(reason)[:300]) # BUG-0717: shown in every output
1259
1396
  if VAULT: os.environ['MINI_VAULT'] = json.dumps(VAULT)
1260
1397
  runner = str(Path(__file__).resolve().parent / 'runner.py')
1261
1398
  if sys.platform == 'win32':
@@ -1367,7 +1504,7 @@ def main():
1367
1504
  research_proxy = start_research_proxy()
1368
1505
  write('status.json', {'state': 'running', 'started': time.time(), 'boot': boot_id(), 'process': identity(os.getpid()), 'harness': 'kimi'})
1369
1506
  (ROOT / 'kimi-stderr.log').unlink(missing_ok=True)
1370
- for name in ('kimi-state.json', 'kimi-progress.json', 'kimi-hook.json', 'usage.json', 'kimi-stop-count', 'design-browser-evidence.json', 'design-review.json', 'acceptance.json', 'budget-declined', 'hard-deny-targets.json', BACKGROUND_CHECKS, BLOCKED_CALLS): (ROOT / name).unlink(missing_ok=True)
1507
+ for name in ('kimi-state.json', 'kimi-progress.json', 'kimi-hook.json', 'usage.json', 'kimi-stop-count', 'design-browser-evidence.json', 'design-review.json', 'browser-unavailable.json', 'acceptance.json', 'budget-declined', 'hard-deny-targets.json', BACKGROUND_CHECKS, BLOCKED_CALLS): (ROOT / name).unlink(missing_ok=True)
1371
1508
  # "Approve all" covers the rest of the request: a Resume of the same request keeps it, a new request asks afresh.
1372
1509
  if not config.get('resuming') or config.get('subagent'): (ROOT / 'kimi-approve-all').unlink(missing_ok=True)
1373
1510
  shutil.rmtree(ROOT / 'acceptance', ignore_errors=True)
@@ -1419,7 +1556,7 @@ def main():
1419
1556
  else: ask_first.apply(config, REPO)
1420
1557
  resolve_role(config)
1421
1558
  readonly = conversation_readonly(config) or config.get('mode') == 'plan'
1422
- proxy = ModelProxy(config['endpoint'], os.environ.get('MODEL_API_KEY', ''), config.get('model') or 'glm', config.get('provider', ''), config.get('reasoningEffort', 'medium'), config.get('creditRates'))
1559
+ proxy = ModelProxy(config['endpoint'], os.environ.get('MODEL_API_KEY', ''), config.get('model') or 'glm', config.get('provider', ''), config.get('reasoningEffort', 'medium'), config.get('creditRates'), config.get('fallback'), os.environ.get('FALLBACK_MODEL_API_KEY', ''))
1423
1560
  steps = int(config.get('steps') or 120)
1424
1561
  write_home(config, proxy, config.get('mode', 'approve'), readonly, steps)
1425
1562
  extra = ''
@@ -1483,6 +1620,9 @@ def main():
1483
1620
  # BUG-0345: a pure question (chat/research route) skips the plan review; an edit in that turn still waits for it.
1484
1621
  'question_turn': config.get('conversation_route', 'build') in ('chat', 'research') and not brief_first(config)}
1485
1622
  save_state(state, static=True)
1623
+ if config.get('hardBudget') and proxy and state.get('account_left') is not None:
1624
+ # BUG-0615: --max-budget-credits: a model call that would go past the cap is not started.
1625
+ proxy.hard_left = state['account_left']; proxy.spent_elsewhere = lambda: totals()['tokens'] - proxy.tokens
1486
1626
  for stale in ('scope.json', 'kimi-commands.json', 'verification.json', 'kimi-last-text.json'): (ROOT / stale).unlink(missing_ok=True)
1487
1627
  env = engine_env(os.environ)
1488
1628
  env.update(VAULT)
@@ -1529,12 +1669,16 @@ def main():
1529
1669
  # keep calling the model until the time limit.
1530
1670
  elif sandbox_stuck(config): killed['reason'] = 'limited'; killed['limit'] = 'sandbox'
1531
1671
  # CLI --max-budget-credits (hardBudget): the caller's own cap gets no grace past it (BUG-0509).
1672
+ elif getattr(proxy, 'budget_refused', False): killed['reason'] = 'limited'; killed['limit'] = 'tokens'
1532
1673
  elif state.get('account_left') is not None and (totals()['tokens'] > state['account_left'] + (0 if config.get('hardBudget') else ACCOUNT_GRACE) or time.time() - float((load(ROOT, 'kimi-hook.json', {}) or {}).get('account_stop_at') or 1e18) > ACCOUNT_WRAP_SECONDS):
1533
1674
  # The hook already asked the agent to wrap up at the allowance; this is the hard stop.
1534
1675
  event('account_limit', phase='stopped', content=CREDITS_OUT_NOTE); killed['reason'] = 'limited'; killed['limit'] = 'tokens'
1535
1676
  elif time.time() - (load(ROOT, 'kimi-stopped', {}) or {}).get('time', 1e18) > FINISH_GRACE: killed['reason'] = 'finished'
1536
1677
  if killed['reason']:
1537
1678
  if killed['reason'] == 'finished': event('note', content='Work finished; background processes such as preview servers keep running')
1679
+ # CLI r7: Windows has no process groups; end every process this run owns first, also a headless
1680
+ # browser whose parent already exited (it holds the engine's pipes, so Stop never finished).
1681
+ if os.name == 'nt' and killed['reason'] != 'finished': proc_watch.kill_all(child.pid, supervisor)
1538
1682
  try:
1539
1683
  os.killpg(child.pid, signal.SIGTERM)
1540
1684
  # Up to 3 s to exit cleanly, but no longer than it takes: Stop used to wait the full 3 s (BUG-0133).
@@ -1580,6 +1724,7 @@ def main():
1580
1724
  code, reason = launch(cmd)
1581
1725
  continue
1582
1726
  if not mapper.last_text: break
1727
+ if step_limit_reached(config, mapper, proxy.calls, steps): break # no repair round past the step limit
1583
1728
  if os.getenv('MINI_KIMI_FINAL_GATES', '1') == '0': break
1584
1729
  if plan_on_hold(): break # Not now on the plan: no repair round may restart the work (BUG-0102)
1585
1730
  if not readonly and not state.get('inspect'):
@@ -1596,8 +1741,7 @@ def main():
1596
1741
  # The tester's own test could not run, even after one corrected try. That is not a fault in the build,
1597
1742
  # and Resume would only repeat it (web bug list, Bug-017 and Bug-021). Finish on the repository checks
1598
1743
  # and say so plainly instead of leaving the run as Verification incomplete.
1599
- state['_acceptance_note'] = ('An extra independent test could not be set up for this project, so this '
1600
- 'result rests on the project\'s own checks shown below.')
1744
+ state['_acceptance_note'] = acceptance_note(load(ROOT, 'checks.json', []))
1601
1745
  event('acceptance', status='skipped', content='Independent acceptance test could not run here; using the repository checks')
1602
1746
  unresolved = []; break
1603
1747
  if rounds: event('final_gate', state='passed', round=rounds, content='Final checks passed after %d repair round%s' % (rounds, '' if rounds == 1 else 's'))
@@ -1623,14 +1767,17 @@ def main():
1623
1767
  previous = mapper.last_text; mapper.last_text = ''
1624
1768
  asked = re.sub(r'\s+', ' ', str(config.get('task') or '').split('User attachments (untrusted data', 1)[0]).strip()[:600]
1625
1769
  code, reason = launch(resume(('Not done yet. Correct your answer for these points; files cannot be changed in this turn, so do not try to edit them:\n' if readonly else 'Not done yet. Fix these before finishing:\n') + verification.repair_note(issues) + '\nThen write your final message again from scratch, complete and self-contained, as if it were your first reply to the user: ' + ('the full answer with its source links' if readonly else 'what changed, how you verified it, and anything left open') + '. It must answer the user\'s message: \u00ab' + asked + '\u00bb. Do not mention these checks, this repair step, or what you just re-checked; never open with a correction of yourself.'))
1626
- if not mapper.last_text: mapper.last_text = previous
1770
+ if not mapper.last_text or (repair_talk(mapper.last_text) and len(mapper.last_text) < len(previous)): mapper.last_text = previous
1627
1771
  proc = holder.get('proc')
1628
1772
  if checkpoints:
1629
1773
  try: checkpoints.flush()
1630
1774
  except Exception: pass
1631
1775
  answer = final_answer(mapper.last_text, getattr(mapper, 'texts', []))
1776
+ if internal_answer(answer): answer = '' # BUG-0609: never the engine's own finish marker as the answer
1632
1777
  if answer and state.get('_acceptance_note') and not unresolved: answer += '\n\n' + state['_acceptance_note']
1778
+ answer = one_shot_background_note(answer)
1633
1779
  if reason == 'finished': reason = None
1780
+ if reason is None and step_limit_reached(config, mapper, proxy.calls, steps): reason = 'limited'; state['limit_kind'] = 'steps'
1634
1781
  continuing = auto_continue(config, state, unresolved, reason, readonly, goal, plan_on_hold)
1635
1782
  if unresolved and answer and not reason and not soft_unverified({'checksPassed': 1 if state.get('last_check') else 0}, unresolved, state):
1636
1783
  answer += '\n\nVerification note: ' + ' '.join(i.splitlines()[0] for i in unresolved)[:1200]
@@ -1645,10 +1792,11 @@ def main():
1645
1792
  if killed['reason'] == 'limited':
1646
1793
  limit = state.get('limit_kind') or 'time'
1647
1794
  limit_text = (CREDITS_OUT_NOTE if limit == 'tokens'
1648
- else 'Stopped after %d agent step%s (the --max-turns limit); your files are saved.' % (steps, '' if steps == 1 else 's') if limit == 'steps'
1795
+ else 'Stopped after %d agent step%s (the %s limit); your files are saved.' % (steps, '' if steps == 1 else 's', '--max-turns' if config.get('hardSteps') else '--max-steps') if limit == 'steps'
1649
1796
  else SANDBOX_STOP_NOTE if limit == 'sandbox'
1650
1797
  else 'Each run can work for up to %d minutes. This one reached that limit and stopped; your files are saved and %s.' % (max(1, WALL_SECONDS // 60), 'the work continues automatically in a minute' if continuing else 'Resume continues from them'))
1651
- result = {'exit_status': 'LimitsExceeded', 'limit': limit, 'limitNote': limit_text, 'submission': answer or limit_text}
1798
+ # BUG-0609: the sandbox stop ends the agent mid-task, so its last words are not an answer; the stop note is.
1799
+ result = {'exit_status': 'LimitsExceeded', 'limit': limit, 'limitNote': limit_text, 'submission': limit_text if limit == 'sandbox' else answer or limit_text}
1652
1800
  run_state = 'limited'
1653
1801
  elif code != 0 and not answer:
1654
1802
  with open(ROOT / 'kimi-stderr.log', 'rb') as f: f.seek(holder.get('offset', 0)); tail = unvault(f.read().decode('utf-8', 'replace'))[-800:]
@@ -1686,6 +1834,12 @@ def main():
1686
1834
  from runtime_control import changed_during_turn
1687
1835
  report['changedFiles'] = changed_during_turn(REPO, report['changedFiles'], start_dirty)
1688
1836
  except Exception: pass
1837
+ if run_state == 'completed' and (config.get('laptop') or os.getenv('MINI_LAPTOP') == '1') and not (ROOT / 'cannot-complete.json').exists():
1838
+ try: # BUG-0695: a project hook blocked the action the user asked for; the run is "cannot complete", not done
1839
+ import mlai_hooks
1840
+ why = mlai_hooks.blocked_request(config.get('task', ''), load(ROOT, 'kimi-commands.json', []), ROOT, R.RUN_STARTED)
1841
+ if why: mlai_hooks.record_cannot_complete({'reason': why}, ROOT)
1842
+ except Exception: pass
1689
1843
  try:
1690
1844
  import work_ledger
1691
1845
  work_ledger.record(ROOT, config.get('task', ''), locals().get('stated') or answer or '', load(ROOT, 'checks.json', []), load(ROOT, 'design-browser-evidence.json', []), run_state)
@@ -1754,7 +1908,7 @@ def main():
1754
1908
  p = proxy
1755
1909
  event('run_metrics', engine='kimi', calls=totals()['calls'], wall_seconds=round(wall, 2), inference_seconds=round(p.inference if p else 0, 2), tool_seconds=round(max(0.0, wall - (p.inference if p else 0)), 2),
1756
1910
  prompt_tokens=p.prompt if p else 0, trimmed_chars=p.trimmed if p else 0, masked_chars=p.masked if p else 0, cached_tokens=p.cached if p else 0, completion_tokens=p.completion if p else 0, cache_hit_rate=round(p.cached / p.prompt, 3) if p and p.prompt else 0,
1757
- reasoning_tokens=p.reasoning if p else 0, effort=config.get('reasoningEffort', 'medium') if p else '', effort_steps=dict(p.effort_counts) if p else {})
1911
+ reasoning_tokens=p.reasoning if p else 0, effort=config.get('reasoningEffort', 'medium') if p else '', effort_steps=dict(p.effort_counts) if p else {}, backup_calls=p.fallback_calls if p else 0, backup_escalations=p.escalations if p else 0)
1758
1912
  except Exception: pass
1759
1913
  if proxy: proxy.close()
1760
1914
  finish_files()
@@ -345,6 +345,10 @@ def final_issues(config, st, answer, done, model, root, repo, event, allow_accep
345
345
  if code_changed and last_edit and last_check < last_edit and not untested_ok:
346
346
  blamed = pre_existing_failure(st, checks, repo, done, event)
347
347
  if not blamed: issues.append('Code changed (' + ', '.join(code_changed[:6]) + ') after the last passing check. Run the relevant tests or build now and report the real result.')
348
+ try:
349
+ import mlai_hooks
350
+ issues.extend(mlai_hooks.open_after_edit(root=root)) # BUG-0693: a blocking after_edit hook still rejects a file
351
+ except Exception: pass
348
352
  try:
349
353
  import verification
350
354
  commands = []
@@ -408,12 +412,25 @@ def final_issues(config, st, answer, done, model, root, repo, event, allow_accep
408
412
  except (OSError, ValueError): records = []
409
413
  report = browser_review(records, fingerprint(repo, st.get('base') or 'HEAD'))
410
414
  (Path(root) / 'design-review.json').write_text(json.dumps(report)); event('design_review', designReview=report)
411
- if report['status'] != 'passed':
415
+ unavailable = None
416
+ try: unavailable = json.loads((Path(root) / 'browser-unavailable.json').read_text())
417
+ except (OSError, ValueError): pass
418
+ if report['status'] != 'passed' and unavailable:
419
+ # Browser checks cannot run on this computer: asking again only loops the run (27 minutes in one Windows
420
+ # report). The review stays "not verified" and the agent's summary says why.
421
+ if 'design-unavailable' not in done:
422
+ done.add('design-unavailable')
423
+ event('note', content='Browser checks are not available on this computer, so the design review is reported as not verified.')
424
+ elif report['status'] != 'passed' and 'design-final' in done:
425
+ pass # asked once already in a final round; the outer bridge reports it as unresolved instead of looping
426
+ elif report['status'] != 'passed':
427
+ done.add('design-final')
412
428
  issues.append(report['message'] + ' Start the app with mcp__mlai__preview {"action":"start"}, then run mcp__mlai__browser at width 390 and at width 1280, each with at least one click/fill/press and an assert_text. Fix overflow, console or page errors and failed requests, then check again.')
413
429
  from conversation import research_required
414
430
  from evidence import EvidenceLedger
415
431
  ledger = EvidenceLedger(root, st.get('evidence_key') or 'kimi')
416
- if research_required(config) or ledger.load()['sources']:
432
+ laptop = bool(config.get('laptop')) or os.getenv('MINI_LAPTOP') == '1'
433
+ if research_required(config) or (ledger.load()['sources'] and not laptop): # BUG-0611: see kimi_hook.readonly_stop
417
434
  issue = ledger.completion_issue(answer or '')
418
435
  if issue: issues.append(issue.replace('evidence {claims', 'mcp__mlai__evidence {claims'))
419
436
  if allow_acceptance and code_changed and not issues and 'acceptance' not in done and untested_ok: