mlai-code 0.3.9 → 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.
- package/README.md +1 -1
- package/bin/mlai.mjs +4 -1
- package/package.json +1 -1
- package/src/cli.mjs +67 -12
- package/src/headless.mjs +59 -9
- package/src/home.mjs +1 -1
- package/src/modes.mjs +5 -1
- package/src/render.mjs +3 -0
- package/src/session.mjs +15 -1
- package/src/tui/agents-cli.mjs +2 -0
- package/src/tui/chat.mjs +7 -3
- package/src/tui/cmd-core.mjs +1 -1
- package/src/tui/extensions-local.mjs +5 -2
- package/src/tui/plain.mjs +16 -0
- package/src/tui/review-cli.mjs +2 -1
- package/src/tui/snapshots.mjs +30 -1
- package/src/tui/transcript.mjs +2 -1
- package/src/two-words.mjs +9 -0
- package/vendor/cloud-cli/mlai.mjs +41 -10
- package/worker/checkpoints.py +23 -3
- package/worker/command_safety.py +18 -0
- package/worker/conversation.py +18 -1
- package/worker/kimi_bridge.py +186 -40
- package/worker/kimi_gates.py +6 -1
- package/worker/kimi_hook.py +50 -9
- package/worker/mcp_local.py +33 -0
- package/worker/mlai_auto_review.py +25 -4
- package/worker/mlai_hooks.py +113 -7
- package/worker/mlai_permissions.py +5 -3
- package/worker/mlai_review/__main__.py +3 -1
- package/worker/mlai_review/application/streaming.py +10 -0
- package/worker/mlai_review/infrastructure/local/publisher.py +25 -3
- package/worker/preview.py +54 -7
- package/worker/runner.py +72 -1
package/worker/kimi_bridge.py
CHANGED
|
@@ -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
|
-
|
|
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 =
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
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
|
-
|
|
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
|
|
@@ -710,6 +827,7 @@ class StreamMapper:
|
|
|
710
827
|
try: write('kimi-last-text.json', {'text': self.last_text[:20000], 'time': time.time()})
|
|
711
828
|
except OSError: pass
|
|
712
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)
|
|
713
831
|
for call in calls:
|
|
714
832
|
fn = call.get('function') or {}; name = fn.get('name', '')
|
|
715
833
|
try: args = json.loads(fn.get('arguments') or '{}')
|
|
@@ -769,9 +887,10 @@ class StreamMapper:
|
|
|
769
887
|
# Editing prose does not make test evidence stale; editing anything else does.
|
|
770
888
|
if not PROSE_PATH.search(str(args.get('path', ''))): st['last_edit'] = time.time()
|
|
771
889
|
if not code: self.checkpoint(name, args)
|
|
772
|
-
global LAST_OUTPUT, SANDBOX_DENIALS
|
|
890
|
+
global LAST_OUTPUT, SANDBOX_DENIALS, BACKGROUND_RAN
|
|
773
891
|
if name == 'Bash' and not code: LAST_OUTPUT = content
|
|
774
|
-
if code and name
|
|
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
|
|
775
894
|
if name == 'Bash':
|
|
776
895
|
command = str(args.get('command', ''))
|
|
777
896
|
try:
|
|
@@ -994,6 +1113,14 @@ def soft_unverified(report, unresolved, state=None):
|
|
|
994
1113
|
# it used to loop through every repair round and end as Not verified, also when the user said not to test.
|
|
995
1114
|
return True
|
|
996
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
|
+
|
|
997
1124
|
def _check_names(checks, status):
|
|
998
1125
|
try: from runtime_control import latest_checks, check_status
|
|
999
1126
|
except Exception: return []
|
|
@@ -1050,7 +1177,7 @@ def windows_note():
|
|
|
1050
1177
|
def workspace_note(config, event):
|
|
1051
1178
|
"""Jobs (restart the ones that died), project setup and environment facts for the agent's instructions."""
|
|
1052
1179
|
note = ''
|
|
1053
|
-
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')}
|
|
1054
1181
|
env.update(VAULT)
|
|
1055
1182
|
try:
|
|
1056
1183
|
import dev_jobs
|
|
@@ -1151,6 +1278,11 @@ def build_context(config):
|
|
|
1151
1278
|
if mlai_hooks.active(): task = mlai_hooks.guidance() + '\n' + task # project hooks and hard-deny rules
|
|
1152
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
|
|
1153
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
|
|
1154
1286
|
try: # CLI custom subagents and opt-in project memory
|
|
1155
1287
|
from subagents import agents_guidance
|
|
1156
1288
|
from project_rules import memory_note
|
|
@@ -1260,7 +1392,7 @@ def finish_files():
|
|
|
1260
1392
|
|
|
1261
1393
|
def fallback(reason):
|
|
1262
1394
|
"""Run the task on the built-in engine instead. Restores the Vault payload that importing runner consumed."""
|
|
1263
|
-
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
|
|
1264
1396
|
if VAULT: os.environ['MINI_VAULT'] = json.dumps(VAULT)
|
|
1265
1397
|
runner = str(Path(__file__).resolve().parent / 'runner.py')
|
|
1266
1398
|
if sys.platform == 'win32':
|
|
@@ -1424,7 +1556,7 @@ def main():
|
|
|
1424
1556
|
else: ask_first.apply(config, REPO)
|
|
1425
1557
|
resolve_role(config)
|
|
1426
1558
|
readonly = conversation_readonly(config) or config.get('mode') == 'plan'
|
|
1427
|
-
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', ''))
|
|
1428
1560
|
steps = int(config.get('steps') or 120)
|
|
1429
1561
|
write_home(config, proxy, config.get('mode', 'approve'), readonly, steps)
|
|
1430
1562
|
extra = ''
|
|
@@ -1488,6 +1620,9 @@ def main():
|
|
|
1488
1620
|
# BUG-0345: a pure question (chat/research route) skips the plan review; an edit in that turn still waits for it.
|
|
1489
1621
|
'question_turn': config.get('conversation_route', 'build') in ('chat', 'research') and not brief_first(config)}
|
|
1490
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
|
|
1491
1626
|
for stale in ('scope.json', 'kimi-commands.json', 'verification.json', 'kimi-last-text.json'): (ROOT / stale).unlink(missing_ok=True)
|
|
1492
1627
|
env = engine_env(os.environ)
|
|
1493
1628
|
env.update(VAULT)
|
|
@@ -1534,6 +1669,7 @@ def main():
|
|
|
1534
1669
|
# keep calling the model until the time limit.
|
|
1535
1670
|
elif sandbox_stuck(config): killed['reason'] = 'limited'; killed['limit'] = 'sandbox'
|
|
1536
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'
|
|
1537
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):
|
|
1538
1674
|
# The hook already asked the agent to wrap up at the allowance; this is the hard stop.
|
|
1539
1675
|
event('account_limit', phase='stopped', content=CREDITS_OUT_NOTE); killed['reason'] = 'limited'; killed['limit'] = 'tokens'
|
|
@@ -1588,6 +1724,7 @@ def main():
|
|
|
1588
1724
|
code, reason = launch(cmd)
|
|
1589
1725
|
continue
|
|
1590
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
|
|
1591
1728
|
if os.getenv('MINI_KIMI_FINAL_GATES', '1') == '0': break
|
|
1592
1729
|
if plan_on_hold(): break # Not now on the plan: no repair round may restart the work (BUG-0102)
|
|
1593
1730
|
if not readonly and not state.get('inspect'):
|
|
@@ -1604,8 +1741,7 @@ def main():
|
|
|
1604
1741
|
# The tester's own test could not run, even after one corrected try. That is not a fault in the build,
|
|
1605
1742
|
# and Resume would only repeat it (web bug list, Bug-017 and Bug-021). Finish on the repository checks
|
|
1606
1743
|
# and say so plainly instead of leaving the run as Verification incomplete.
|
|
1607
|
-
state['_acceptance_note'] = ('
|
|
1608
|
-
'result rests on the project\'s own checks shown below.')
|
|
1744
|
+
state['_acceptance_note'] = acceptance_note(load(ROOT, 'checks.json', []))
|
|
1609
1745
|
event('acceptance', status='skipped', content='Independent acceptance test could not run here; using the repository checks')
|
|
1610
1746
|
unresolved = []; break
|
|
1611
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'))
|
|
@@ -1631,14 +1767,17 @@ def main():
|
|
|
1631
1767
|
previous = mapper.last_text; mapper.last_text = ''
|
|
1632
1768
|
asked = re.sub(r'\s+', ' ', str(config.get('task') or '').split('User attachments (untrusted data', 1)[0]).strip()[:600]
|
|
1633
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.'))
|
|
1634
|
-
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
|
|
1635
1771
|
proc = holder.get('proc')
|
|
1636
1772
|
if checkpoints:
|
|
1637
1773
|
try: checkpoints.flush()
|
|
1638
1774
|
except Exception: pass
|
|
1639
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
|
|
1640
1777
|
if answer and state.get('_acceptance_note') and not unresolved: answer += '\n\n' + state['_acceptance_note']
|
|
1778
|
+
answer = one_shot_background_note(answer)
|
|
1641
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'
|
|
1642
1781
|
continuing = auto_continue(config, state, unresolved, reason, readonly, goal, plan_on_hold)
|
|
1643
1782
|
if unresolved and answer and not reason and not soft_unverified({'checksPassed': 1 if state.get('last_check') else 0}, unresolved, state):
|
|
1644
1783
|
answer += '\n\nVerification note: ' + ' '.join(i.splitlines()[0] for i in unresolved)[:1200]
|
|
@@ -1653,10 +1792,11 @@ def main():
|
|
|
1653
1792
|
if killed['reason'] == 'limited':
|
|
1654
1793
|
limit = state.get('limit_kind') or 'time'
|
|
1655
1794
|
limit_text = (CREDITS_OUT_NOTE if limit == 'tokens'
|
|
1656
|
-
else 'Stopped after %d agent step%s (the
|
|
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'
|
|
1657
1796
|
else SANDBOX_STOP_NOTE if limit == 'sandbox'
|
|
1658
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'))
|
|
1659
|
-
|
|
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}
|
|
1660
1800
|
run_state = 'limited'
|
|
1661
1801
|
elif code != 0 and not answer:
|
|
1662
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:]
|
|
@@ -1694,6 +1834,12 @@ def main():
|
|
|
1694
1834
|
from runtime_control import changed_during_turn
|
|
1695
1835
|
report['changedFiles'] = changed_during_turn(REPO, report['changedFiles'], start_dirty)
|
|
1696
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
|
|
1697
1843
|
try:
|
|
1698
1844
|
import work_ledger
|
|
1699
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)
|
|
@@ -1762,7 +1908,7 @@ def main():
|
|
|
1762
1908
|
p = proxy
|
|
1763
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),
|
|
1764
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,
|
|
1765
|
-
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)
|
|
1766
1912
|
except Exception: pass
|
|
1767
1913
|
if proxy: proxy.close()
|
|
1768
1914
|
finish_files()
|
package/worker/kimi_gates.py
CHANGED
|
@@ -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 = []
|
|
@@ -425,7 +429,8 @@ def final_issues(config, st, answer, done, model, root, repo, event, allow_accep
|
|
|
425
429
|
from conversation import research_required
|
|
426
430
|
from evidence import EvidenceLedger
|
|
427
431
|
ledger = EvidenceLedger(root, st.get('evidence_key') or 'kimi')
|
|
428
|
-
|
|
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
|
|
429
434
|
issue = ledger.completion_issue(answer or '')
|
|
430
435
|
if issue: issues.append(issue.replace('evidence {claims', 'mcp__mlai__evidence {claims'))
|
|
431
436
|
if allow_acceptance and code_changed and not issues and 'acceptance' not in done and untested_ok:
|
package/worker/kimi_hook.py
CHANGED
|
@@ -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 = ('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')
|
|
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', 'bom_warned', 'last_tool', 'hook_feedback')
|
|
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})
|
|
@@ -454,13 +454,41 @@ def remember_bom(name, args):
|
|
|
454
454
|
if str(target) not in known: save('kimi-bom.json', (known + [str(target)])[-200:])
|
|
455
455
|
|
|
456
456
|
def restore_bom():
|
|
457
|
-
"""Runs before the next tool call and at Stop (PostToolUse is only registered for project hooks), so it never races an edit.
|
|
457
|
+
"""Runs before the next tool call and at Stop (PostToolUse is only registered for project hooks), so it never races an edit.
|
|
458
|
+
Returns the files it put the mark back on."""
|
|
459
|
+
restored = []
|
|
458
460
|
for path in load('kimi-bom.json', []):
|
|
459
461
|
try:
|
|
460
462
|
target = Path(path)
|
|
461
463
|
data = target.read_bytes()
|
|
462
|
-
if data and not data.startswith(BOM): target.write_bytes(BOM + data)
|
|
464
|
+
if data and not data.startswith(BOM): target.write_bytes(BOM + data); restored.append(path)
|
|
463
465
|
except OSError: pass
|
|
466
|
+
return restored
|
|
467
|
+
|
|
468
|
+
BOM_NOTE = ('%s starts with a UTF-8 byte order mark (BOM) that the file had before this task. ML AI Code keeps it, so it was put back; '
|
|
469
|
+
'it is not a bug and no other process or session is changing the file. Do not remove it or try again another way. If a check '
|
|
470
|
+
'fails on it (JSON.parse in Node rejects a BOM), strip it in memory inside the check (text.replace(/^\\uFEFF/, "")) and leave the file as it is.')
|
|
471
|
+
|
|
472
|
+
def bom_fight(restored, last_tool, st):
|
|
473
|
+
"""BUG-0610: the edit tools keep the mark, but the agent then removed it itself (python, printf, rm and recreate) and,
|
|
474
|
+
seeing it come back, fought it until the time limit. The first time a command removes it, the agent is told why it
|
|
475
|
+
stays. Returns the note, or None."""
|
|
476
|
+
if not restored or last_tool in ('Write', 'Edit'): return None
|
|
477
|
+
warned = set(st.get('bom_warned') or [])
|
|
478
|
+
fresh = [p for p in restored if p not in warned]
|
|
479
|
+
if not fresh: return None
|
|
480
|
+
st['bom_warned'] = sorted(warned | set(fresh))[-50:]; save_state(st)
|
|
481
|
+
shown = ', '.join(os.path.relpath(p, REPO) if str(p).startswith(str(REPO)) else str(p) for p in fresh[:3])
|
|
482
|
+
event('note', content='Kept the byte order mark at the start of ' + shown)
|
|
483
|
+
return BOM_NOTE % shown
|
|
484
|
+
|
|
485
|
+
def step_limit_where():
|
|
486
|
+
"""BUG-0683: where the step limit is set. On the person's computer there is no Settings > Agent page: the terminal's
|
|
487
|
+
--max-turns or --max-steps flag, or /config maxSteps."""
|
|
488
|
+
if not _laptop_run(): return 'Settings > Agent > Maximum steps per task'
|
|
489
|
+
try: hard = json.loads((ROOT / 'request.json').read_text()).get('hardSteps') is True
|
|
490
|
+
except (OSError, ValueError, AttributeError): hard = False
|
|
491
|
+
return 'the --max-turns limit of this run' if hard else 'set with --max-steps, or /config maxSteps'
|
|
464
492
|
|
|
465
493
|
def step_limit_gate(st):
|
|
466
494
|
"""BUG-0589: Settings > Agent > Maximum steps per task. Each command, edit or app call is one step; at the limit
|
|
@@ -473,8 +501,8 @@ def step_limit_gate(st):
|
|
|
473
501
|
if not st.get('step_limit_noted'):
|
|
474
502
|
st['step_limit_noted'] = True; save_state(st)
|
|
475
503
|
event('note', content='Step limit reached (%d). Asked the agent to wrap up' % limit)
|
|
476
|
-
block('Step limit reached: the user allows %d step%s per task (
|
|
477
|
-
'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'))
|
|
504
|
+
block('Step limit reached: the user allows %d step%s per task (%s), and all are used. '
|
|
505
|
+
'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', step_limit_where()))
|
|
478
506
|
st['steps_used'] = used + 1; save_state(st)
|
|
479
507
|
|
|
480
508
|
def question_only(st):
|
|
@@ -503,8 +531,16 @@ def pre(payload, st):
|
|
|
503
531
|
name = str(payload.get('tool_name') or '')
|
|
504
532
|
args = payload.get('tool_input') or {}
|
|
505
533
|
if not isinstance(args, dict): args = {}
|
|
506
|
-
|
|
534
|
+
restored = []
|
|
535
|
+
try: restored = restore_bom(); remember_bom(name, args)
|
|
507
536
|
except Exception: pass
|
|
537
|
+
last_tool = st.get('last_tool'); st['last_tool'] = name; save_state(st)
|
|
538
|
+
fight = bom_fight(restored, last_tool, st)
|
|
539
|
+
if fight: block(fight + ' This call was not run; re-issue it if it is still needed.')
|
|
540
|
+
pending = st.pop('hook_feedback', None)
|
|
541
|
+
if pending: # BUG-0693: an after_edit / after_tool hook block reaches the agent even if the engine drops PostToolUse output
|
|
542
|
+
save_state(st)
|
|
543
|
+
block('A project hook reported a problem after your previous step:\n' + str(pending)[:4000] + '\nThis call was not run. Fix what the hook reports first, then re-issue it if it is still needed.')
|
|
508
544
|
if (ROOT / 'cancel').exists(): block('Task stopped by user.')
|
|
509
545
|
if st.get('plan_dismissed') and is_work_tool(name): # before any approval card: Not now means nothing else asks or runs
|
|
510
546
|
event('plan_review', content='Plan on hold: ' + re.sub(r'^mcp__\w+?__', '', name) + ' was not run')
|
|
@@ -786,7 +822,9 @@ def readonly_stop(st):
|
|
|
786
822
|
from evidence import EvidenceLedger
|
|
787
823
|
data = EvidenceLedger(ROOT, st.get('evidence_key') or 'kimi').load()
|
|
788
824
|
except Exception: return
|
|
789
|
-
|
|
825
|
+
# BUG-0611: on the person's computer a plan or answer about the code that looked something up on the web is not a
|
|
826
|
+
# research report; asking it for a claims ledger only cost repair rounds and left talk about the ledger as the answer.
|
|
827
|
+
if data['sources'] and not data['claims'] and (st.get('research') or not _laptop_run()):
|
|
790
828
|
st['gates_done'] = sorted(done | {'evidence'}); save_state(st)
|
|
791
829
|
event('done_gate', content='Research claims not recorded yet')
|
|
792
830
|
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.')
|
|
@@ -887,10 +925,13 @@ def main():
|
|
|
887
925
|
st = state()
|
|
888
926
|
if kind == 'PreToolUse': pre(payload, st)
|
|
889
927
|
elif kind == 'PostToolUse':
|
|
890
|
-
|
|
928
|
+
fight = None
|
|
929
|
+
try: fight = bom_fight(restore_bom(), str(payload.get('tool_name') or ''), st)
|
|
891
930
|
except Exception: pass
|
|
892
931
|
feedback = user_hooks('kimi_post', payload, st) # after_tool / after_edit hooks
|
|
893
|
-
if feedback:
|
|
932
|
+
if feedback:
|
|
933
|
+
st['hook_feedback'] = feedback; save_state(st)
|
|
934
|
+
if feedback or fight: block('\n\n'.join(t for t in (fight, feedback) if t))
|
|
894
935
|
elif kind == 'Stop':
|
|
895
936
|
try: restore_bom()
|
|
896
937
|
except Exception: pass
|
package/worker/mcp_local.py
CHANGED
|
@@ -80,6 +80,39 @@ def kimi_servers(config, readonly=False):
|
|
|
80
80
|
return out
|
|
81
81
|
|
|
82
82
|
|
|
83
|
+
def _found(spec, cwd=None):
|
|
84
|
+
"""Whether a stdio server's command can be started: an existing file, or a program on its PATH."""
|
|
85
|
+
import shutil
|
|
86
|
+
cmd = os.path.expanduser(spec.get('command') or '')
|
|
87
|
+
if os.sep in cmd or '/' in cmd: return os.path.exists(os.path.join(spec.get('cwd') or cwd or os.getcwd(), cmd))
|
|
88
|
+
path = (spec.get('env') or {}).get('PATH') or os.environ.get('PATH')
|
|
89
|
+
return shutil.which(cmd, path=path) is not None
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def check(kimi, config, emit, cwd=None, readonly=False, timeout=20):
|
|
93
|
+
"""BUG-0661: a user's MCP server that cannot start or never answers is reported, not silently left out.
|
|
94
|
+
Servers whose command is not found are warned about and dropped from `kimi` (Kimi's mcp.json entries) at once;
|
|
95
|
+
the others are tried in the background while the run starts, and a warning is sent if one does not answer."""
|
|
96
|
+
specs = servers(config, readonly)
|
|
97
|
+
for name in [n for n in kimi if n in specs and 'url' not in specs[n] and not _found(specs[n], cwd)]:
|
|
98
|
+
kimi.pop(name, None)
|
|
99
|
+
emit('MCP server ' + name + ' could not start: the command ' + specs[name]['command'][:200] + ' was not found. Its tools are unavailable.')
|
|
100
|
+
def probe(name, spec):
|
|
101
|
+
start = time.time()
|
|
102
|
+
try: connect(spec, cwd, timeout).close()
|
|
103
|
+
except Exception as exc:
|
|
104
|
+
msg = str(exc)[:200]
|
|
105
|
+
if msg.startswith('No answer') and time.time() - start >= timeout - 1:
|
|
106
|
+
emit('MCP server ' + name + ' did not answer within ' + str(timeout) + ' seconds. Its tools are unavailable.')
|
|
107
|
+
elif msg.startswith('No answer'):
|
|
108
|
+
emit('MCP server ' + name + ' stopped before it answered. Its tools are unavailable.')
|
|
109
|
+
else:
|
|
110
|
+
emit('MCP server ' + name + ' could not start: ' + msg + '. Its tools are unavailable.')
|
|
111
|
+
threads = [threading.Thread(target=probe, args=(n, specs[n]), daemon=True) for n in kimi if n in specs]
|
|
112
|
+
for t in threads: t.start()
|
|
113
|
+
return threads
|
|
114
|
+
|
|
115
|
+
|
|
83
116
|
def guidance(config, readonly=False):
|
|
84
117
|
names = sorted(servers(config, readonly))
|
|
85
118
|
if not names: return ''
|