mlai-code 0.3.3 → 0.3.5

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 (136) 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 +39 -11
  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 +16 -5
  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/tui/transcript.mjs +13 -2
  30. package/src/two-words.mjs +14 -8
  31. package/src/view-sync.mjs +48 -0
  32. package/src/winenv.mjs +1 -1
  33. package/src/workspace-api.mjs +21 -4
  34. package/vendor/client-sdk/index.cjs +2 -1
  35. package/vendor/cloud-cli/mlai.mjs +23 -11
  36. package/worker/architecture_worker.py +33 -4
  37. package/worker/browser_tool.py +19 -1
  38. package/worker/chat_fork.py +4 -1
  39. package/worker/checkpoints.py +71 -8
  40. package/worker/command_safety.py +56 -3
  41. package/worker/connected_turn.py +30 -0
  42. package/worker/conversation.py +125 -13
  43. package/worker/git_sync.py +4 -4
  44. package/worker/image_generation.py +2 -2
  45. package/worker/kimi_bridge.py +251 -31
  46. package/worker/kimi_gates.py +25 -6
  47. package/worker/kimi_hook.py +154 -13
  48. package/worker/media_tools.py +4 -1
  49. package/worker/mlai_hooks.py +222 -3
  50. package/worker/mlai_mcp.py +26 -6
  51. package/worker/mlai_review/README.md +35 -0
  52. package/worker/mlai_review/__init__.py +1 -0
  53. package/worker/mlai_review/__main__.py +261 -0
  54. package/worker/mlai_review/_compat.py +29 -0
  55. package/worker/mlai_review/analysis/__init__.py +3 -0
  56. package/worker/mlai_review/analysis/detect.py +50 -0
  57. package/worker/mlai_review/analysis/main.py +128 -0
  58. package/worker/mlai_review/analysis/messages.py +8 -0
  59. package/worker/mlai_review/analysis/tools.py +194 -0
  60. package/worker/mlai_review/application/__init__.py +1 -0
  61. package/worker/mlai_review/application/asking.py +53 -0
  62. package/worker/mlai_review/application/challengers.py +142 -0
  63. package/worker/mlai_review/application/context_builder.py +194 -0
  64. package/worker/mlai_review/application/errors.py +17 -0
  65. package/worker/mlai_review/application/feedback.py +52 -0
  66. package/worker/mlai_review/application/matching.py +46 -0
  67. package/worker/mlai_review/application/messages.py +41 -0
  68. package/worker/mlai_review/application/ports.py +222 -0
  69. package/worker/mlai_review/application/prompts.py +342 -0
  70. package/worker/mlai_review/application/review_service.py +200 -0
  71. package/worker/mlai_review/application/reviewers.py +438 -0
  72. package/worker/mlai_review/application/streaming.py +91 -0
  73. package/worker/mlai_review/application/tools.py +138 -0
  74. package/worker/mlai_review/application/usage.py +145 -0
  75. package/worker/mlai_review/application/write_check.py +46 -0
  76. package/worker/mlai_review/contracts/__init__.py +5 -0
  77. package/worker/mlai_review/contracts/analysis.py +57 -0
  78. package/worker/mlai_review/contracts/review.py +42 -0
  79. package/worker/mlai_review/domain/__init__.py +4 -0
  80. package/worker/mlai_review/domain/changes.py +77 -0
  81. package/worker/mlai_review/domain/context.py +147 -0
  82. package/worker/mlai_review/domain/diagnostics.py +239 -0
  83. package/worker/mlai_review/domain/feedback.py +216 -0
  84. package/worker/mlai_review/domain/findings.py +505 -0
  85. package/worker/mlai_review/domain/lifecycle.py +85 -0
  86. package/worker/mlai_review/domain/partition.py +42 -0
  87. package/worker/mlai_review/domain/relations.py +166 -0
  88. package/worker/mlai_review/domain/relevance.py +202 -0
  89. package/worker/mlai_review/domain/report.py +99 -0
  90. package/worker/mlai_review/domain/structure.py +56 -0
  91. package/worker/mlai_review/domain/writes.py +86 -0
  92. package/worker/mlai_review/eval.py +221 -0
  93. package/worker/mlai_review/eval_cases/clean-rename.json +11 -0
  94. package/worker/mlai_review/eval_cases/missing-ownership-check.json +22 -0
  95. package/worker/mlai_review/eval_cases/off-by-one.json +22 -0
  96. package/worker/mlai_review/eval_cases/sql-injection.json +20 -0
  97. package/worker/mlai_review/feedback_report.py +60 -0
  98. package/worker/mlai_review/infrastructure/__init__.py +1 -0
  99. package/worker/mlai_review/infrastructure/analysis/__init__.py +1 -0
  100. package/worker/mlai_review/infrastructure/analysis/none.py +12 -0
  101. package/worker/mlai_review/infrastructure/analysis/translate.py +17 -0
  102. package/worker/mlai_review/infrastructure/github/__init__.py +0 -0
  103. package/worker/mlai_review/infrastructure/github/client.py +445 -0
  104. package/worker/mlai_review/infrastructure/github/feedback.py +212 -0
  105. package/worker/mlai_review/infrastructure/github/http.py +31 -0
  106. package/worker/mlai_review/infrastructure/github/rendering.py +398 -0
  107. package/worker/mlai_review/infrastructure/github/token.py +20 -0
  108. package/worker/mlai_review/infrastructure/local/__init__.py +1 -0
  109. package/worker/mlai_review/infrastructure/local/analyzer.py +48 -0
  110. package/worker/mlai_review/infrastructure/local/events.py +100 -0
  111. package/worker/mlai_review/infrastructure/local/git_reader.py +233 -0
  112. package/worker/mlai_review/infrastructure/local/publisher.py +138 -0
  113. package/worker/mlai_review/infrastructure/messages.py +54 -0
  114. package/worker/mlai_review/infrastructure/models/__init__.py +0 -0
  115. package/worker/mlai_review/infrastructure/models/openai_compatible.py +269 -0
  116. package/worker/mlai_review/infrastructure/structure/__init__.py +1 -0
  117. package/worker/mlai_review/infrastructure/structure/heuristic.py +186 -0
  118. package/worker/mlai_review/infrastructure/structure/tree_sitter.py +186 -0
  119. package/worker/mlai_review/infrastructure/workspace/__init__.py +1 -0
  120. package/worker/mlai_review/infrastructure/workspace/local.py +105 -0
  121. package/worker/mlai_review/infrastructure/workspace/memory.py +77 -0
  122. package/worker/mlai_review/infrastructure/workspace/paths.py +17 -0
  123. package/worker/mlai_review/pipeline.py +89 -0
  124. package/worker/mlai_review/runtime.py +194 -0
  125. package/worker/mlai_review/settings.py +139 -0
  126. package/worker/preview.py +15 -0
  127. package/worker/product_facts.py +3 -1
  128. package/worker/repo_policy.py +5 -0
  129. package/worker/roles.py +29 -2
  130. package/worker/runner.py +164 -23
  131. package/worker/runtime_control.py +95 -9
  132. package/worker/secret_scan.py +3 -2
  133. package/worker/server_memory.py +122 -0
  134. package/worker/subagents.py +6 -2
  135. package/worker/tool_catalog.py +5 -2
  136. package/worker/verification.py +113 -8
@@ -18,7 +18,7 @@ import handover
18
18
  STALL_SECONDS = int(os.getenv('MINI_KIMI_STALL_SECONDS', '60'))
19
19
  from runner import ROOT, REPO, event, write, unvault, VAULT, vault_guidance, connect_guidance, resolve_role, inference_progress, CREDITS_OUT_NOTE
20
20
  from lifecycle import boot_id, identity, load
21
- from conversation import enabled as conversation_enabled, readonly as conversation_readonly, route as route_conversation, recent_history, honor_no_change, NO_CHANGE_NOTE
21
+ from conversation import enabled as conversation_enabled, readonly as conversation_readonly, route as route_conversation, recent_history, honor_no_change, NO_CHANGE_NOTE, supersede
22
22
  from design_director import restore_choice, prepare as prepare_design, browser_review, DESIGN_BUILD_GUIDANCE, DESIGN_BRIEF_GUIDANCE
23
23
  import ask_first
24
24
  from runtime_control import completion_report, check_key, clip
@@ -172,6 +172,12 @@ class ModelProxy:
172
172
 
173
173
  def forward(self, handler, body):
174
174
  body = unvault(body) # Vault secret values never reach the model
175
+ try: # BUG-0527: search/list/command output lines from hard-denied files never reach the model
176
+ import mlai_hooks
177
+ for m in body.get('messages') or []:
178
+ if isinstance(m, dict) and m.get('role') == 'tool' and isinstance(m.get('content'), str):
179
+ m['content'] = mlai_hooks.filter_denied_lines(m['content'], repo=REPO)[0]
180
+ except Exception: pass
175
181
  body['model'] = self.model
176
182
  if getattr(self, 'images_off', False): strip_images(body)
177
183
  stream = bool(body.get('stream'))
@@ -217,6 +223,8 @@ class ModelProxy:
217
223
  # The endpoint refused image input: carry on text-only for the rest of the run instead of failing the step.
218
224
  self.images_off = True
219
225
  event('note', content='Images could not be sent to the model, so this run continues without them.')
226
+ # BUG-0230: the app offers a one-click resend with a model that can see images.
227
+ 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.')
220
228
  req = urllib.request.Request(self.endpoint, data=json.dumps(body).encode(), headers=dict(req.header_items()))
221
229
  res = urllib.request.urlopen(req, timeout=STALL_SECONDS)
222
230
  elif not (effort and exc.code == 400 and b'reasoning' in exc.detail.lower()): raise
@@ -308,9 +316,13 @@ Working rules:
308
316
  - The project is already a git repository. When a scaffolder runs inside it, skip its own git init (forge init --no-git, cargo new --vcs none, create-* --no-git); a nested repository breaks checkpoints and GitHub sync.
309
317
  - Read before you edit. Prefer Grep/Glob and focused Read ranges over dumping whole files. Use mcp__mlai__repo_map once to orient in an unfamiliar repository and mcp__mlai__symbols to find declarations.
310
318
  - Change source files with Edit (exact text replacement) or Write, never with sed -i, perl -pi or a python/node script that rewrites the file: those break silently on JSX/TSX quotes and braces. After a batch of edits, run the type check or build before you report anything as working.
311
- - Use mcp__mlai__web_search and mcp__mlai__web_fetch for current public documentation when the answer depends on versions or facts you cannot see in the repository. For research answers, record the material claims with mcp__mlai__evidence and link the source URLs. Never put credentials or private code in queries.
319
+ - You have live web access in every turn: use mcp__mlai__web_search and mcp__mlai__web_fetch whenever the answer depends on current public facts you cannot see in the repository (documentation and versions, but also weather, news, prices, scores or local time). Never say you lack web, real-time or weather access. For research answers, record the material claims with mcp__mlai__evidence and link the source URLs. Never put credentials or private code in queries.
312
320
  - After changing code, run the relevant tests, build or type check with Bash and read the real exit status. A passing unrelated suite does not prove the requested behavior. Never claim something works without running it.
313
321
  - Do not fabricate data, mocks or placeholder implementations in shipped code unless the user asked for them.
322
+ - Do what the user asked, and only that (BUG-0226). A request to install a package, run a command or answer a question is done when that is done: do not add features, tools, commands or files nobody asked for, do not rename the package, remove "private" from package.json, publish, install globally or push unless the user asked for it. When extra work looks useful, finish the request, then suggest it in one sentence and ask; do not start it.
323
+ - Once the user approves a plan or task list, build exactly what it says (BUG-0245). If an approved item turns out to need a different approach, stop and ask before changing it; if you had to change it, the final message must name the item, what you did instead and why, in plain words.
324
+ - Copy commit SHAs, PR numbers, branch names, IDs and version numbers into your answer from the tool output of this task, character for character; never type them from memory or guess them (BUG-0458). A PR's head commit is the head SHA the tool returned, not the base branch's commit.
325
+ - To look at the local app in a browser, use mcp__mlai__browser: it is the built-in Playwright browser. Do not search for, install or script Playwright or Chromium yourself; if the tool reports it is not set up, say so (BUG-0202).
314
326
  - For web apps, run the app with mcp__mlai__preview {"action":"start"} (port 3000, dev server with hot reload; it installs missing packages first and keeps running after the task, when it is swapped for the production build the user shares). Vite needs server.host true and server.allowedHosts true; Next.js and static index.html work as is. Servers you start with Bash in the background stop when the task ends. Check UI work with mcp__mlai__browser at a phone width (390) and a desktop width (1280). A hydration error that names data-myki, jcpwm, data-gr-*, data-lastpass or data-1p-* comes from the user's browser extension, not the app: do not rewrite components for it (the production preview does not show it); in Next.js root layouts keep suppressHydrationWarning on <html> and <body>.
315
327
  - Commands that run longer than a minute should use run_in_background, then WaitFor/TaskOutput. Never sleep in a loop. Work that must outlive this turn (training, benchmark sweeps, pipelines, extra servers) goes in mcp__mlai__job: it logs, survives the turn, and is restarted from its resume command if it stops unexpectedly. Make such work checkpoint its progress.
316
328
  - If a command cannot reach a host because the workspace network blocks it, call mcp__mlai__network {domain, reason} once, then retry after the user allows it.
@@ -318,13 +330,15 @@ Working rules:
318
330
  - Computer memory (mcp__mlai__memory) persists across tasks on this chat's computer only, not in the sidebar project's Memory card: when you learn how this project is run or tested, a convention, a user preference or a correction, save it with mcp__mlai__memory (never secrets). Read a listed fact before re-discovering it.
319
331
  - Only claim that tests, builds or type checks pass when you ran them in this task and saw the result; the final message is checked against the commands you actually ran. Do not edit, skip or delete existing tests to make them pass unless the task asks for it, and say so when you do.
320
332
  - Your final message is what the user reads on their phone: say what changed, how you verified it (commands and results) and anything left open, briefly. When the user asked to see output (for example "run it and show me the output"), paste that output in a code block (up to about 60 lines) instead of only saying it ran.
321
- - Refer to files by their path inside the project (src/app.js), never by the computer's absolute path.'''
333
+ - Refer to files by their path inside the project (src/app.js), never by the computer's absolute path.
334
+ - Earlier messages of this chat come with the request: answer questions about what the user already told you from them. Do not state a conclusion (such as "I don't know") before tool calls that could change it; say what you are checking instead.'''
322
335
 
323
336
  SHELL_ALWAYS = os.getenv('MINI_KIMI_SHELL', '1') != '0'
324
337
  TALK_RULES = '''This turn is a {route} request, and you have the full workspace shell. Run any command that helps: status checks, logs, processes, tests, network calls, CLIs that use the Vault keys in your environment. When the question is about work the user already started or approved (a job, sweep, deploy, server or earlier task), act on it in this turn: check it, and resume or restart it if it stalled, rather than asking the user to say go. Do not begin new implementation or edit project files the user has not asked for; recommend those changes instead. Answer directly and concisely.'''
325
338
  TALK_RESEARCH = '''Research with mcp__mlai__web_search and mcp__mlai__web_fetch, record material claims with mcp__mlai__evidence, and link the source URLs in the answer.'''
326
339
  INSPECT_RULES = '''The user asked for no changes in this turn (an assessment, review or "ask before fixing"). Do not edit, create or delete project files, install packages, start services or commit; those calls are refused. You may read the code and run existing tests and checks to reproduce defects. Report each finding with its evidence (file and line, failing command and output) and the fix you recommend, then ask whether to apply the fixes. Results of the checks you run are investigation evidence, not proof that the project is broken.'''
327
- PLAN_RULES = '''The user picked Plan mode: they review a plan before anything is built. Do not try to create or change files and do not ask the user to run commands themselves. If the message is only a question, just answer it. For work, write the plan as a short numbered list (files to add or change, what each step does and how it will be checked), using project paths such as index.html. End with one sentence saying they can tap Build this plan to start. Never describe this mode as a tool restriction and never list tool names.'''
340
+ # BUG-0235: a build or deploy request in Plan mode gets a pointer to the Mode switch, never a missing-tools story.
341
+ PLAN_RULES = '''The user picked Plan mode: they review a plan before anything is built. Do not try to create or change files and do not ask the user to run commands themselves. If the message is only a question, just answer it. For work, write the plan as a short numbered list (files to add or change, what each step does and how it will be checked), using project paths such as index.html. End with one sentence saying they can tap Build this plan to start. If they ask you to build, create files, deploy or go ahead while Plan mode is still on, do not try: say in one or two sentences that Plan mode only plans, and that they can tap Build this plan or switch Mode to Approve or Auto, then send the request again. Never describe this mode as a tool restriction, never say a tool is missing or not found, and never list tool names.'''
328
342
  READONLY_RULES = '''This request is read-only: answer, research or plan. Do not modify files, run builds or start servers. Inspect the repository with Read, Grep and Glob, research with mcp__mlai__web_search and mcp__mlai__web_fetch when needed (record claims with mcp__mlai__evidence and link sources), then answer directly and concisely. If you propose a plan, make it concrete and numbered.'''
329
343
 
330
344
  GLM_RULES = '''Model notes (GLM):
@@ -361,7 +375,7 @@ def context_size(config):
361
375
  def end_reason_for(run_state, result, state):
362
376
  """Why a run ended, stored with its usage so token spend can be split by outcome (e.g. verification_incomplete)."""
363
377
  if result.get('exit_status') == 'VerificationIncomplete' or state.get('_soft_unverified'): return 'verification_incomplete' # usage split keeps counting them
364
- if run_state == 'limited': return 'limited_' + ('tokens' if (state.get('limit_kind') or 'time') == 'tokens' else 'time')
378
+ if run_state == 'limited': return 'limited_' + ({'tokens': 'tokens', 'steps': 'steps', 'sandbox': 'sandbox'}.get(state.get('limit_kind') or 'time') or 'time')
365
379
  if (ROOT / 'budget-declined').exists(): return 'budget_declined'
366
380
  return run_state if run_state in ('completed', 'stopped', 'error', 'interrupted') else 'completed'
367
381
 
@@ -424,6 +438,10 @@ def attached_image_note(config):
424
438
  'sentence and suggest switching to the default model or describing the image; do not guess or run OCR as a substitute.]'
425
439
  % (len(images), '' if len(images) == 1 else 's', listed))
426
440
 
441
+ # BUG-0230: the model is told it cannot see the image, so it says so instead of guessing from pixel values.
442
+ IMAGE_OMITTED = ('[image omitted: this model cannot see images. Do not guess what the image shows from pixel values, file data or '
443
+ 'its name. Tell the person in one sentence that you could not see it and that they can switch to a model that can see images.]')
444
+
427
445
  def strip_images(body):
428
446
  """Replace image parts with a short text note. Returns how many were removed."""
429
447
  n = 0
@@ -432,9 +450,65 @@ def strip_images(body):
432
450
  if not isinstance(c, list): continue
433
451
  for i, part in enumerate(c):
434
452
  if isinstance(part, dict) and part.get('type') in ('image_url', 'input_image', 'image'):
435
- c[i] = {'type': 'text', 'text': '[image omitted: the model endpoint did not accept image input]'}; n += 1
453
+ c[i] = {'type': 'text', 'text': IMAGE_OMITTED}; n += 1
436
454
  return n
437
455
 
456
+ # Never in the engine's environment, so never in the environment of the commands it runs (BUG-0517). The MCP server
457
+ # gets the image/research/hub values it needs through its own env in mcp.json; the engine reads the proxy token from config.toml.
458
+ ENGINE_ENV_HIDDEN = ('MODEL_API_KEY', 'SIDE_MODEL_API_KEY', 'VERCEL_OIDC_TOKEN', 'EXA_API_KEY', 'FIRECRAWL_API_KEY', 'OPENROUTER_API_KEY',
459
+ 'PIXABAY_API_KEY', 'BRANDFETCH_API_KEY', 'MINI_VAULT', 'MINI_KIMI_PROXY_TOKEN', 'MINI_IMAGE_URL', 'MINI_IMAGE_TOKEN',
460
+ 'MINI_RESEARCH_URL', 'MINI_RESEARCH_TOKEN', 'MLAI_HUB_TOKEN')
461
+
462
+ def engine_env(environ):
463
+ return {k: v for k, v in environ.items() if k not in ENGINE_ENV_HIDDEN}
464
+
465
+ LAST_OUTPUT = '' # the newest successful shell output in this run
466
+ SANDBOX_DENIALS = 0 # tool calls the OS sandbox refused in this run
467
+ SANDBOX_DENIED = re.compile(r'Operation not permitted|Read-only file system|sandbox-exec: .*denied|deny\(\d+\) file-write', re.I)
468
+ SANDBOX_STUCK_AFTER = 3
469
+ 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. '
470
+ 'Nothing outside the project was changed. Run it interactively (mlai) to approve it, or work inside the project folder.' % SANDBOX_STUCK_AFTER)
471
+
472
+ def sandbox_stuck(config):
473
+ return bool(config.get('unattended')) and config.get('mode') == 'auto' and SANDBOX_DENIALS >= SANDBOX_STUCK_AFTER
474
+
475
+ def fill_dangling_output(answer, output, max_lines=40):
476
+ """BUG-0505: "Created squares.py and ran it - output:" followed by nothing (the model expects the UI to show the
477
+ command). The newest command output goes under such a line; an answer that already shows output is unchanged."""
478
+ text = str(output or '').strip('\n')
479
+ if not text.strip() or not answer: return answer
480
+ lines = answer.split('\n')
481
+ for i, line in enumerate(lines):
482
+ if not re.search(r'(?i)\boutput:\s*$', line): continue
483
+ rest = [l for l in lines[i + 1:] if l.strip()]
484
+ if rest and (rest[0].lstrip().startswith('```') or rest[0].startswith((' ', '\t'))): continue
485
+ if rest and not re.search(r'(?i)\boutput:\s*$', rest[0]) and i + 1 < len(lines) and lines[i + 1].strip(): continue
486
+ shown = text.split('\n')
487
+ if len(shown) > max_lines: shown = shown[:max_lines] + ['...']
488
+ block = '```\n' + '\n'.join(shown).replace('```', "'''") + '\n```'
489
+ return '\n'.join(lines[:i + 1] + [block] + lines[i + 1:])
490
+ return answer
491
+
492
+ # CLI tool names (--tools / --disallowedTools / permission rules) -> the engine tools that stay out of the offer.
493
+ DENY_TO_ENGINE = {'Bash': ('Bash',), 'Edit': ('Write', 'Edit'), 'WebSearch': ('WebSearch',), 'Agent': ('Agent',)}
494
+
495
+ def denied_tools(config):
496
+ """BUG-0510: a whole-tool deny rule (`--tools Read` denies Bash, Edit, ...) also removes the tool from what the agent
497
+ is offered, so it says at once that it cannot do the work instead of trying every tool and being blocked.
498
+ Rules with a pattern (Bash(rm:*)) still go through the permission check only."""
499
+ ext = config.get('extensions') if isinstance(config.get('extensions'), dict) else {}
500
+ perms = ext.get('permissions') if isinstance(ext.get('permissions'), dict) else {}
501
+ if perms.get('bypass') is True: return []
502
+ out = []
503
+ for rule in perms.get('deny') if isinstance(perms.get('deny'), list) else []:
504
+ if not isinstance(rule, str) or '(' in rule: continue
505
+ 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]
506
+ return out
507
+
508
+ def step_cap(config, steps):
509
+ """Agent steps per turn for the engine. CLI --max-turns (hardSteps) is an exact cap; otherwise at least 10 (BUG-0492)."""
510
+ return max(1, steps) if config.get('hardSteps') else max(10, steps)
511
+
438
512
  def write_home(config, proxy, mode, readonly, steps):
439
513
  HOME.mkdir(parents=True, exist_ok=True)
440
514
  hook = sys.executable + ' ' + str(Path(__file__).resolve().parent / 'kimi_hook.py')
@@ -444,13 +518,13 @@ def write_home(config, proxy, mode, readonly, steps):
444
518
  'telemetry = false',
445
519
  'extra_skill_dirs = [' + toml_str(HOME / 'skills') + ']',
446
520
  '',
447
- '[providers.mlai]', 'type = "openai"', 'base_url = ' + toml_str('http://127.0.0.1:%d/v1' % proxy.port), 'api_key_env = "MINI_KIMI_PROXY_TOKEN"', '',
521
+ '[providers.mlai]', 'type = "openai"', 'base_url = ' + toml_str('http://127.0.0.1:%d/v1' % proxy.port), 'api_key = ' + toml_str(proxy.token), '',
448
522
  '[models."mlai/main"]', 'provider = "mlai"', 'model = ' + toml_str(config.get('model') or 'glm'), 'max_context_size = %d' % context_size(config), 'capabilities = ' + json.dumps(model_capabilities(config)), '',
449
523
  '[image]', 'max_edge_px = 1568', '',
450
- '[loop_control]', 'max_steps_per_turn = %d' % max(10, steps), 'max_attempts_per_step = 4', 'reserved_context_size = %d' % RESERVED_CONTEXT, '',
524
+ '[loop_control]', 'max_steps_per_turn = %d' % step_cap(config, steps), 'max_attempts_per_step = 4', 'reserved_context_size = %d' % RESERVED_CONTEXT, '',
451
525
  '[task]', 'bash_auto_background_on_timeout = true', 'print_background_mode = "exit"', '',
452
526
  '[mcp]', 'startup_timeout_ms = 20000', 'tool_timeout_ms = 600000', '',
453
- '[tools]', 'disabled = ["CronCreate", "CronDelete", "CronList", "AskUserQuestion", "ExitPlanMode", "FetchURL", "AgentSwarm", "CreateGoal", "GetGoal", "SetGoalBudget", "UpdateGoal"' + (', "Write", "Edit", "Bash", "Agent"' if readonly else '') + ']', '',
527
+ '[tools]', 'disabled = ["CronCreate", "CronDelete", "CronList", "AskUserQuestion", "ExitPlanMode", "FetchURL", "AgentSwarm", "CreateGoal", "GetGoal", "SetGoalBudget", "UpdateGoal"' + (', "Write", "Edit", "Bash", "Agent"' if readonly else ''.join(', ' + toml_str(t) for t in denied_tools(config))) + ']', '',
454
528
  ]
455
529
  events = [('PreToolUse', '', 600), ('Stop', '', 120)]
456
530
  try:
@@ -459,8 +533,11 @@ def write_home(config, proxy, mode, readonly, steps):
459
533
  except Exception: pass
460
534
  for event_name, matcher, timeout in events:
461
535
  lines += ['[[hooks]]', 'event = ' + toml_str(event_name)] + (['matcher = ' + toml_str(matcher)] if matcher else []) + ['command = ' + toml_str(hook + ' ' + event_name), 'timeout = %d' % timeout, '']
536
+ # BUG-0517: the per-run proxy token lives in this private file, not in the environment every agent command inherits.
462
537
  (HOME / 'config.toml').write_text('\n'.join(lines))
463
- server = {'command': sys.executable, 'args': [str(Path(__file__).resolve().parent / 'mlai_mcp.py')], 'toolTimeoutMs': 600000, 'env': {'MINI_ROOT': str(ROOT), 'MINI_REPO': REPO, 'MINI_READONLY': '1' if readonly or config.get('inspect') else '0', 'MINI_SUBAGENT': '1' if config.get('subagent') else '0', **({'FIRECRAWL_API_KEY': os.environ['FIRECRAWL_API_KEY']} if os.getenv('FIRECRAWL_API_KEY') else {}), **({'MINI_RESEARCH_URL': os.environ['MINI_RESEARCH_URL'], 'MINI_RESEARCH_TOKEN': os.environ['MINI_RESEARCH_TOKEN']} if os.getenv('MINI_RESEARCH_URL') and os.getenv('MINI_RESEARCH_TOKEN') else {}), **({'EXA_API_KEY': os.environ['EXA_API_KEY'], 'MINI_RESEARCH_FALLBACK': 'exa'} if os.getenv('EXA_API_KEY') and os.getenv('MINI_RESEARCH_FALLBACK') == 'exa' else {}), **({} if readonly or config.get('inspect') else computer_use.env()), **hub_env()}}
538
+ try: os.chmod(HOME / 'config.toml', 0o600)
539
+ except OSError: pass
540
+ server = {'command': sys.executable, 'args': [str(Path(__file__).resolve().parent / 'mlai_mcp.py')], 'toolTimeoutMs': 600000, 'env': {'MINI_ROOT': str(ROOT), 'MINI_REPO': REPO, 'MINI_READONLY': '1' if readonly or config.get('inspect') or 'Write' in denied_tools(config) else '0', 'MINI_SUBAGENT': '1' if config.get('subagent') else '0', **({'FIRECRAWL_API_KEY': os.environ['FIRECRAWL_API_KEY']} if os.getenv('FIRECRAWL_API_KEY') else {}), **({'MINI_RESEARCH_URL': os.environ['MINI_RESEARCH_URL'], 'MINI_RESEARCH_TOKEN': os.environ['MINI_RESEARCH_TOKEN']} if os.getenv('MINI_RESEARCH_URL') and os.getenv('MINI_RESEARCH_TOKEN') else {}), **({'EXA_API_KEY': os.environ['EXA_API_KEY'], 'MINI_RESEARCH_FALLBACK': 'exa'} if os.getenv('EXA_API_KEY') and os.getenv('MINI_RESEARCH_FALLBACK') == 'exa' else {}), **({} if readonly or config.get('inspect') else computer_use.env()), **hub_env(), **{k: os.environ[k] for k in ('MINI_IMAGE_URL', 'MINI_IMAGE_TOKEN') if os.environ.get(k)}}}
464
541
  servers = {'mlai': server}
465
542
  try:
466
543
  import mcp_local # the user's own MCP servers from the CLI (/mcp): .mlai/mcp.json, .mcp.json, .cursor/mcp.json, settings
@@ -509,12 +586,27 @@ def agent_file(config, readonly, extra_system):
509
586
  # ---------------------------------------------------------------- stream mapping
510
587
  TOOL_EVENT = {'Read': ('read_file', 'path'), 'Write': ('write_file', 'path'), 'Edit': ('edit_file', 'path'), 'Grep': ('search_text', 'pattern'), 'Glob': ('list_files', 'pattern'),
511
588
  'FetchURL': ('web_fetch', 'url'), 'Skill': ('skill_load', 'skill'), 'mcp__mlai__web_search': ('web_search', 'query'), 'mcp__mlai__repo_map': ('repo_map', ''), 'mcp__mlai__symbols': ('symbols', 'query'), 'mcp__mlai__integration_search': ('tool_search', 'query'), 'mcp__mlai__integration_call': ('integration', 'name'), 'mcp__mlai__memory': ('memory', 'action'), 'mcp__mlai__scope': ('scope', ''), 'mcp__mlai__deploy': ('deploy', 'action')}
512
- FAILED = re.compile(r'Command failed with exit code: (\d+)|^(Error|error):|<system>ERROR|Tool execution failed|Tool call was blocked|was not run', re.M)
589
+ # A write the user or a permission rule refused never happened (BUG-0496: it was counted as an edit).
590
+ FAILED = re.compile(r'Command failed with exit code: (\d+)|^(Error|error):|<system>ERROR|Tool execution failed|Tool call was blocked|was not run|The user rejected this action|The user did not approve|Blocked by your permission rule', re.M)
513
591
  # A command the hook refused (e.g. a test masked by `| tail` or `; git status`) never ran, so it is not a failed check.
514
592
  HOOK_BLOCKED = re.compile(r'Tool call was blocked|This call was not run\.')
515
593
 
516
594
  ENGINE_NAMES = re.compile(r'\bKimi(?:[ -]Code)?[ -]CLI\b|\bKimi Code\b(?= (?:agent|engine|harness))', re.I)
517
595
 
596
+ REFERS_BACK = re.compile(r'\b(?:above|previous (?:message|reply|answer)|earlier (?:message|reply|answer)|already (?:listed|given|provided|written))\b', re.I)
597
+
598
+ def final_answer(last, texts):
599
+ """BUG-0192: the agent wrote the full answer, then a short closing message pointing back to it ("the tips above are
600
+ the complete deliverable"). Only the closing message was kept as the answer, so the list vanished from the chat after
601
+ the run (and after reload). When the last message is short and refers back, keep the long answer before it too."""
602
+ last = str(last or '').strip()
603
+ if not last or len(last) > 1500 or not REFERS_BACK.search(last): return last
604
+ earlier = [t for t in (texts or [])[:-1] if t and t.strip() != last]
605
+ if not earlier: return last
606
+ body = max(earlier[-4:], key=len)
607
+ if len(body) < max(600, 2 * len(last)) or body in last: return last
608
+ return body.rstrip() + '\n\n' + last
609
+
518
610
  def public_text(text):
519
611
  """What the user reads: project paths instead of the computer's absolute paths, and no internal engine name
520
612
  (BUG-0099, BUG-0185). The model's own words are otherwise unchanged."""
@@ -522,7 +614,9 @@ def public_text(text):
522
614
  for root in sorted({str(REPO).rstrip('/'), '/vercel/sandbox/repo'}, key=len, reverse=True):
523
615
  if root and len(root) > 1:
524
616
  out = re.sub(re.escape(root) + r'/(?=\S)', '', out)
525
- out = re.sub(re.escape(root) + r'(?![\w/.-])', 'the project folder', out)
617
+ # BUG-0537: on the user's own computer the folder has a real name; show it instead of a placeholder.
618
+ label = Path(root).name if os.getenv('MINI_LAPTOP') == '1' and root == str(REPO).rstrip('/') and Path(root).name else 'the project folder'
619
+ out = re.sub(re.escape(root) + r'(?![\w/.-])', lambda _m: label, out)
526
620
  out = re.sub(r'/vercel/sandbox(?:/[\w.-]+)*', 'the workspace', out)
527
621
  return ENGINE_NAMES.sub('ML AI Code', out)
528
622
 
@@ -562,6 +656,8 @@ class StreamMapper:
562
656
  if isinstance(content, str) and content.strip():
563
657
  content = public_text(content)
564
658
  self.last_text = content.strip(); event('assistant', content=content)
659
+ if not hasattr(self, 'texts'): self.texts = []
660
+ self.texts = (self.texts + [self.last_text])[-12:] # BUG-0192
565
661
  try: write('kimi-last-text.json', {'text': self.last_text[:20000], 'time': time.time()})
566
662
  except OSError: pass
567
663
  calls = msg.get('tool_calls') or []
@@ -594,12 +690,20 @@ class StreamMapper:
594
690
  # EXEC-001: `npm test | tail` exits with tail's status. Reconcile with the runner's own summary.
595
691
  check_code, integrity = verification.check_exit(str(args.get('command', '')), code, content, is_check)
596
692
  event('output', output=content[:12000], returncode=code if check_code is None else check_code, **({'integrity': integrity} if integrity else {}))
693
+ if name == 'Bash' and args.get('run_in_background') and not code:
694
+ # BUG-0203: remember the start command so a new computer can offer Restart (never restarted by itself).
695
+ try:
696
+ import server_memory; server_memory.remember(ROOT, str(args.get('command', '')), REPO)
697
+ except Exception: pass
597
698
  st = self.state
598
699
  if name in ('Write', 'Edit') and not code:
599
700
  st['edits'] = st.get('edits', 0) + 1
600
701
  # Editing prose does not make test evidence stale; editing anything else does.
601
702
  if not PROSE_PATH.search(str(args.get('path', ''))): st['last_edit'] = time.time()
602
703
  if not code: self.checkpoint(name, args)
704
+ global LAST_OUTPUT, SANDBOX_DENIALS
705
+ if name == 'Bash' and not code: LAST_OUTPUT = content
706
+ if code and name in ('Bash', 'Write', 'Edit') and SANDBOX_DENIED.search(content): SANDBOX_DENIALS += 1
603
707
  if name == 'Bash':
604
708
  command = str(args.get('command', ''))
605
709
  try:
@@ -616,6 +720,16 @@ class StreamMapper:
616
720
  write('checks.json', checks[-20:]); event('verification', **record)
617
721
  if check_code == 0: st['last_check'] = time.time()
618
722
  elif check_code is not None: st['last_failed_check'] = time.time()
723
+ elif code == 0 and not args.get('run_in_background') and not st.get('inspect') and not HOOK_BLOCKED.search(content):
724
+ # BUG-0542: no test suite here; running the changed program and seeing it work is the check.
725
+ try:
726
+ ran = verification.program_run_check(command, REPO)
727
+ if ran and not verification.has_test_suite(REPO):
728
+ record = {'label': clip('Ran ' + command, 160), 'command': command[:2000], 'returncode': 0, 'executed': True, 'scope': 'repository', 'kind': 'program-run', 'output': content[-4000:], 'time': time.time()}
729
+ checks = [c for c in load(ROOT, 'checks.json', []) if check_key(c.get('command')) != check_key(command)] + [record]
730
+ write('checks.json', checks[-20:]); event('verification', **record)
731
+ st['last_check'] = time.time()
732
+ except Exception: pass
619
733
  remote = remote_check(command, code, content)
620
734
  if remote:
621
735
  checks = [c for c in load(ROOT, 'checks.json', []) if c.get('command') != remote['command']] + [remote]
@@ -635,10 +749,39 @@ def remote_check(command, code, output):
635
749
  if pending and code in (0, 8):
636
750
  return {'label': 'Remote CI', 'command': REMOTE_CI, 'returncode': None, 'executed': False, 'scope': 'ci', 'output': 'Remote checks are still running.\n' + (output or '')[-1500:], 'time': time.time()}
637
751
  return {'label': 'Remote CI', 'command': REMOTE_CI, 'returncode': code, 'executed': True, 'scope': 'ci', 'output': (output or '')[-4000:], 'time': time.time()}
638
- if PUSHED.search(command) and not code:
752
+ if PUSHED.search(command) and not code and push_succeeded(command, output):
753
+ if not has_ci(REPO):
754
+ # BUG-0456: nothing will ever report on this push, so a pending row would never clear.
755
+ event('note', content='Changes were pushed. This repository has no CI workflow, so there are no remote checks to wait for.')
756
+ return None
639
757
  return {'label': 'Remote CI', 'command': REMOTE_CI, 'returncode': None, 'executed': False, 'scope': 'ci', 'output': 'Changes were pushed. The remote checks for that push were not observed in this run.', 'time': time.time()}
640
758
  return None
641
759
 
760
+ # BUG-0456: `git push ... 2>&1 | tail` or `git push; echo done` exits 0 even when the push failed
761
+ # ("fatal: could not read Username for 'https://github.com'"). Only a push whose output shows no failure counts.
762
+ PUSH_FAILED = re.compile(r'^\s*(?:fatal|error):|\[rejected\]|\[remote rejected\]|failed to push|could not read (?:Username|Password)|Authentication failed|Permission denied|Repository not found|could not resolve host|HTTP 4\d\d|GraphQL: |no commits between|pull request create failed|not mergeable', re.I | re.M)
763
+ PUSH_REF = re.compile(r'^\s*[-+*=!]?\s*(?:\[new branch\]|\[new tag\]|[0-9a-f]{7,}\.\.\.?[0-9a-f]{7,})?\s*\S+\s+->\s+\S+|Everything up-to-date|https://\S+/pull/\d+|\b(?:Merged|merged) pull request\b|\bwas already merged\b', re.M)
764
+
765
+ def push_succeeded(command, output):
766
+ """No failure in the output, and either a pushed ref / PR URL in it or a quiet command that printed nothing."""
767
+ text = str(output or '')
768
+ if PUSH_FAILED.search(text): return False
769
+ if PUSH_REF.search(text): return True
770
+ # `git push -q` prints nothing on success; anything else that printed but shows no ref did not confirm the push.
771
+ return not re.sub(r'Command (?:executed|ran) successfully\.?', '', text).strip()
772
+
773
+ CI_FILES = ('.github/workflows', '.gitlab-ci.yml', '.circleci', 'azure-pipelines.yml', 'bitbucket-pipelines.yml', '.buildkite', '.travis.yml', 'Jenkinsfile', '.drone.yml', 'vercel.json', 'netlify.toml')
774
+
775
+ def has_ci(repo):
776
+ """True when the repository configures a CI or deploy check that would report on a push."""
777
+ root = Path(repo or '.')
778
+ for name in CI_FILES:
779
+ p = root / name
780
+ try:
781
+ if p.is_file() or (p.is_dir() and any(p.iterdir())): return True
782
+ except OSError: continue
783
+ return False
784
+
642
785
  PROGRESS_KEYS = ('last_edit', 'last_check', 'last_failed_check', 'edits')
643
786
 
644
787
  # Commands the harness never replays on its own: builds that share the live preview's output folder (a Next.js build under a
@@ -692,6 +835,16 @@ def recheck_stale(state, env, seconds_left, limit=3):
692
835
 
693
836
  SOFT_ISSUE = re.compile(r'^(Code changed \(|You changed code \(|Your todo list still has open items)', re.I)
694
837
 
838
+ def plan_turn_ok(report):
839
+ """A read-only turn with no changed files and no failed check (BUG-0241)."""
840
+ return not (report.get('changedFiles') or []) and not any(int(report.get(k) or 0) for k in ('checksFailed', 'checksInconclusive', 'externalChecksFailed'))
841
+
842
+ def plan_turn_report(report):
843
+ out = dict(report, unfinishedTasks=[])
844
+ out['verification'] = re.sub(r' \d+ plan items? remains? unfinished\.', '', str(report.get('verification') or ''))
845
+ if out.get('verificationStatus') == 'needs_attention': out['verificationStatus'] = 'passed' if int(report.get('checksPassed') or 0) else 'unverified'
846
+ return out
847
+
695
848
  def soft_unverified(report, unresolved):
696
849
  """Nothing failed: the only gaps are checks that predate the last edit (and could not be replayed) or open task-list
697
850
  items. The work is shown as done with a note, not as an interrupted run with a Resume button."""
@@ -734,7 +887,13 @@ def workspace_note(config, event):
734
887
  _, rows = dev_jobs.reconcile(ROOT, REPO, event, env)
735
888
  note += dev_jobs.context_note(rows)
736
889
  except Exception as exc: note += 'Job supervisor unavailable: ' + str(exc)[:200] + '\n'
737
- if config.get('conversation_route', 'build') == 'build' and os.getenv('MINI_ENV_SETUP', '1') != '0':
890
+ laptop = bool(config.get('laptop')) or os.getenv('MINI_LAPTOP') == '1'
891
+ if laptop and config.get('conversation_route', 'build') == 'build':
892
+ # BUG-0550: on the user's own computer a repository's .mlai/setup.sh, devcontainer command or install scripts
893
+ # (npm postinstall) never run automatically: they come from the repo, not the user. Installs go through the
894
+ # agent's normal commands, which the user approves.
895
+ note += 'Project dependencies were not installed automatically on this computer. If the task needs them, run the install command as a normal step (it asks for approval when needed).\n'
896
+ elif config.get('conversation_route', 'build') == 'build' and os.getenv('MINI_ENV_SETUP', '1') != '0':
738
897
  try:
739
898
  import env_setup
740
899
  note += env_setup.ensure(ROOT, REPO, event, env)
@@ -794,6 +953,14 @@ def build_context(config):
794
953
  if config.get('conversation_history'):
795
954
  task = 'Recent conversation in this workspace (context only; the current request takes priority):\n' + json.dumps(config['conversation_history']) + '\n\n' + task
796
955
  if config.get('_handover'): task = config['_handover'] + task # model switch: brief sits right above the recent conversation
956
+ restored = load(ROOT, 'restored.json', None) # BUG-0598: the user restored a checkpoint since the last run
957
+ if isinstance(restored, dict) and restored.get('at'):
958
+ label = str(restored.get('label') or 'an earlier checkpoint')[:160]
959
+ task = ('Files restored: after the last reply, the user restored the project to ' + label + ' (' + str(restored['at'])[:40] + '). '
960
+ 'Changes made after that point were undone. Earlier replies in this chat that describe later changes no longer match the files; '
961
+ 'read the files before you say what the project contains.\n\n' + task)
962
+ try: (ROOT / 'restored.json').unlink()
963
+ except OSError: pass
797
964
  if not readonly and not config.get('resuming') and config.get('conversation_route', 'build') == 'build':
798
965
  try:
799
966
  guidance = planning_guidance(config['task'], REPO, config.get('mode', 'approve'), phase1=role_engine.phase1(config.get('_role')))
@@ -811,6 +978,7 @@ def build_context(config):
811
978
  try:
812
979
  import mlai_hooks
813
980
  if mlai_hooks.active(): task = mlai_hooks.guidance() + '\n' + task # project hooks and hard-deny rules
981
+ 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
814
982
  except Exception: pass
815
983
  try: # CLI custom subagents and opt-in project memory
816
984
  from subagents import agents_guidance
@@ -869,7 +1037,9 @@ def mode_rules(mode, ask_first=False):
869
1037
  '(naming, file layout, colours) or that the request already answers.\nOnce they agree, continue in the user\'s mode:\n' + after)
870
1038
  if mode == 'auto':
871
1039
  return ('Mode: Auto. Edits and ordinary commands run without approval. Still refused or asked: recursive deletes, history rewrites, force pushes, data drops, '
872
- 'sudo beyond package installs and services, and anything touching the harness state. Pick contained alternatives instead of asking.')
1040
+ 'sudo beyond package installs and services, and anything touching the harness state. Pick contained alternatives instead of asking. '
1041
+ 'Auto runs without approvals, so keep to the request: do only what the user asked, the smallest change that does it. Ask before any extra work '
1042
+ '(new features, tools or files, package.json name or "private" changes, publishing, global installs, pushes or PRs the user did not ask for).')
873
1043
  if mode == 'brief':
874
1044
  return ('Mode: Brief. Nothing is built until the user approves your task list. First read the repository (read-only commands, file reads, searches). Then clarify: record one to three short questions about what the request leaves open '
875
1045
  '(style, content, images, scope) with mcp__mlai__brief_questions, each with your recommended answer. Then call TodoList with 3 to 10 concrete, '
@@ -968,6 +1138,8 @@ def auto_continue(config, state, unresolved, reason, readonly, goal, plan_on_hol
968
1138
  import wakeups
969
1139
  if config.get('subagent') or readonly or state.get('inspect') or goal or reason == 'stopped': return None
970
1140
  if os.getenv('MINI_VERIFY_RESUMES', '2') == '0': return None
1141
+ # BUG-0557: a one-shot run (mlai -p) exits after this turn; nothing would continue it, so never promise it.
1142
+ if os.getenv('MINI_ONE_SHOT') == '1': return None
971
1143
  try:
972
1144
  if plan_on_hold(): return None
973
1145
  except Exception: pass
@@ -1011,6 +1183,7 @@ def main():
1011
1183
  if config.get('wake'): config['task'] = goals.wake_prompt(config['wake'], goals.read(ROOT))
1012
1184
  goal = goals.start(ROOT, config, event)
1013
1185
  global KIMI_VERSION
1186
+ os.environ['MINI_MODEL_LABEL'] = str(config.get('modelLabel') or ''); os.environ['MINI_MODEL_ID'] = str(config.get('modelId') or '')
1014
1187
  stage('Preparing the coding engine')
1015
1188
  try: ensure_runtime()
1016
1189
  except Exception as exc:
@@ -1045,11 +1218,20 @@ def main():
1045
1218
  event('finished', state='completed')
1046
1219
  return
1047
1220
  start_handover(config)
1221
+ servers_note = ''
1222
+ if not config.get('subagent'):
1223
+ try:
1224
+ import server_memory # BUG-0203: this chat moved to a new computer; say which servers stopped
1225
+ gone = server_memory.stopped(ROOT)
1226
+ if gone: event('servers_stopped', servers=gone, content='This chat is on a new cloud computer. Servers that were running before have stopped.')
1227
+ servers_note = server_memory.agent_note(ROOT)
1228
+ except Exception: pass
1048
1229
  if honor_no_change(config, shell=SHELL_ALWAYS): event('note', content=NO_CHANGE_NOTE)
1049
1230
  if conversation_enabled(config):
1050
1231
  stage('Reading your request')
1051
1232
  selected = restore_choice(config, ROOT)
1052
1233
  ask_first.apply(config, REPO) # the harness decides whether this run asks first, for every client
1234
+ if config.get('replaces') and supersede(ROOT, config['replaces']): event('note', content='The earlier version of this message was replaced; the agent continues from the new one.') # BUG-0460
1053
1235
  history = recent_history(ROOT) or load(ROOT, 'imported-context.json', {}).get('messages', [])
1054
1236
  config['conversation_history'] = history
1055
1237
  if selected:
@@ -1068,12 +1250,14 @@ def main():
1068
1250
  write_home(config, proxy, config.get('mode', 'approve'), readonly, steps)
1069
1251
  extra = ''
1070
1252
  talk = conversation_enabled(config) and not readonly and config.get('conversation_route') in ('chat', 'research', 'plan')
1253
+ if servers_note: extra += servers_note + '\n'
1071
1254
  if config.get('inspect') and not readonly: extra += INSPECT_RULES + '\n'
1072
1255
  if talk: extra += TALK_RULES.replace('{route}', config['conversation_route']) + ('\n' + TALK_RESEARCH if config['conversation_route'] == 'research' else '') + '\n'
1073
1256
  if config.get('require_changes') and not readonly: extra += 'This task explicitly requires a repository patch. An unchanged repository is not completion. If you cannot fix it, report the blocker honestly.\n'
1074
1257
  if config.get('selected_design') and not readonly: extra += DESIGN_BUILD_GUIDANCE + '\n'
1075
1258
  if config.get('design_in_brief') and brief_first(config) and not readonly: extra += DESIGN_BRIEF_GUIDANCE + '\n'
1076
1259
  from connector_search import compact_catalog, read_only as read_only_tools
1260
+ import connected_turn
1077
1261
  offered = read_only_tools(config.get('tools', [])) if readonly else config.get('tools', [])
1078
1262
  if offered:
1079
1263
  catalog, compacted = compact_catalog(offered)
@@ -1093,35 +1277,49 @@ def main():
1093
1277
  from reply_language import turn_note
1094
1278
  language_note = turn_note(config)
1095
1279
  image_note = attached_image_note(config)
1280
+ if image_note and 'image_in' not in model_capabilities(config) and not config.get('subagent'):
1281
+ event('vision_unavailable', model=str(config.get('modelId') or ''), content=str(config.get('modelLabel') or 'This model') + ' reads text only and cannot see the attached image.') # BUG-0230
1096
1282
  if image_note: task += '\n\n' + image_note
1097
1283
  if language_note: task += '\n\n' + language_note
1098
1284
  base = subprocess.run(['git', 'rev-parse', 'HEAD'], cwd=REPO, capture_output=True, text=True).stdout.strip() or None
1099
1285
  start_dirty = None
1100
- if config.get('inspect') and not readonly:
1101
- # Files already changed before a no-changes turn are the user's own work, not something this turn did.
1102
- try:
1103
- from runtime_control import dirty_snapshot
1104
- start_dirty = dirty_snapshot(REPO, base)
1105
- except Exception: start_dirty = None
1286
+ (ROOT / 'start-dirty.json').unlink(missing_ok=True)
1287
+ # Files already changed or untracked before the turn are the user's own work, not something this turn did
1288
+ # (no-changes turns; BUG-0495/0497: the checker and the changed-files summary; BUG-0558: changedFiles lists only what this turn changed).
1289
+ # Read-only turns too: a question in a folder with uncommitted work must not report that work as this turn's changes.
1290
+ try:
1291
+ from runtime_control import save_start_dirty
1292
+ start_dirty = save_start_dirty(ROOT, REPO, base)
1293
+ except Exception: start_dirty = None
1106
1294
  from conversation import research_required
1107
1295
  evidence_key = str(config.get('runId') or config.get('run_id') or hashlib.sha256((config['task'] + str(time.time())).encode()).hexdigest()[:16])
1108
1296
  role_id = (config.get('_role') or {}).get('id') if isinstance(config.get('_role'), dict) else config.get('_role')
1109
1297
  state = {'mode': config.get('mode', 'approve'), 'brief': config.get('mode') == 'brief' or brief_first(config), 'brief_return': config.get('mode', 'approve') if brief_first(config) else None, 'readonly': readonly, 'inspect': bool(config.get('inspect')) and not readonly, 'deadline': time.time() + WALL_SECONDS, 'land_at': time.time() + WALL_SECONDS - LAND_SECONDS,
1110
- 'require_changes': bool(config.get('require_changes')), 'task': config['task'][:4000], 'role': config.get('_role'), 'base': base, 'edits': 0,
1298
+ 'step_limit': steps, # BUG-0589: enforced per command/edit in kimi_hook.step_limit_gate
1299
+ 'require_changes': bool(config.get('require_changes')), 'task': config['task'][:4000], 'role': config.get('_role'), 'base': base, 'edits': 0, 'started': time.time(),
1111
1300
  'plan_approval': config.get('planApproval') if config.get('planApproval') in ('always', 'guided', 'off') else 'guided',
1112
1301
  'large': large, 'selected_design': bool(config.get('selected_design')) and not readonly, 'look': bool(config.get('design_in_brief')) and brief_first(config) and not readonly,
1113
- 'research': bool(research_required(config)), 'evidence_key': evidence_key,
1302
+ 'research': bool(research_required(config)), 'evidence_key': evidence_key, 'quick': bool(config.get('quick_question')),
1114
1303
  'account_left': account_left(config),
1115
1304
  # BUG-0127: Guided promises "approve the plan": a build turn shows its task list before the first edit.
1116
- 'plan_first': config.get('mode', 'approve') == 'approve' and config.get('planApproval', 'guided') in ('guided', 'always') and not readonly
1117
- and not config.get('resuming') and not config.get('go') and not config.get('subagent') and config.get('conversation_route', 'build') == 'build'}
1305
+ # BUG-0590: "Approve the task list first: Always" waits for the plan in Auto too.
1306
+ 'plan_first': ((config.get('mode', 'approve') == 'approve' and config.get('planApproval', 'guided') in ('guided', 'always'))
1307
+ or (config.get('mode', 'approve') == 'auto' and config.get('planApproval') == 'always')) and not readonly
1308
+ and not config.get('resuming') and not config.get('go') and not config.get('subagent') and config.get('conversation_route', 'build') in ('build', 'chat', 'research'),
1309
+ # BUG-0345: a pure question (chat/research route) skips the plan review; an edit in that turn still waits for it.
1310
+ 'question_turn': config.get('conversation_route', 'build') in ('chat', 'research') and not brief_first(config)}
1118
1311
  save_state(state, static=True)
1119
1312
  for stale in ('scope.json', 'kimi-commands.json', 'verification.json', 'kimi-last-text.json'): (ROOT / stale).unlink(missing_ok=True)
1120
- 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')}
1313
+ env = engine_env(os.environ)
1121
1314
  env.update(VAULT)
1122
- env.update({'KIMI_CODE_HOME': str(HOME), 'KIMI_DISABLE_TELEMETRY': '1', 'MINI_KIMI_PROXY_TOKEN': proxy.token, 'MINI_ROOT': str(ROOT), 'MINI_REPO': REPO, 'NO_COLOR': '1', 'CI': '1'})
1123
- prior = None if config.get('_handover') else resumable_session(readonly, role_id, handover.model_key(config))
1315
+ env.update({'KIMI_CODE_HOME': str(HOME), 'KIMI_DISABLE_TELEMETRY': '1', 'MINI_ROOT': str(ROOT), 'MINI_REPO': REPO, 'NO_COLOR': '1', 'CI': '1'})
1316
+ # BUG-0460: after an Edit or Retry the old session still holds the replaced turn, so start fresh from the history.
1317
+ prior = None if config.get('_handover') or config.get('replaces') else resumable_session(readonly, role_id, handover.model_key(config))
1124
1318
  if prior:
1319
+ try:
1320
+ sync = connected_turn.resume_note((load(ROOT, 'kimi-session.json', {}) or {}).get('connected'), offered, config.get('connected'))
1321
+ if sync: task = sync + '\n\n' + task; event('note', content='Connected apps changed since the last message; the agent has the current list')
1322
+ except Exception: pass # never blocks a run
1125
1323
  cmd = [*kimi_argv(), '-S', prior, '-p', task, '--output-format', 'stream-json']
1126
1324
  event('note', content='Continuing the previous engine session')
1127
1325
  else: cmd = [*kimi_argv(), '-p', task, '--output-format', 'stream-json', '--agent-file', str(agent)]
@@ -1150,7 +1348,14 @@ def main():
1150
1348
  except Exception: pass
1151
1349
  if stopped(): killed['reason'] = 'stopped'
1152
1350
  elif time.time() > state['deadline']: killed['reason'] = 'limited'; killed['limit'] = 'time'
1153
- elif state.get('account_left') is not None and (totals()['tokens'] > state['account_left'] + ACCOUNT_GRACE or time.time() - float((load(ROOT, 'kimi-hook.json', {}) or {}).get('account_stop_at') or 1e18) > ACCOUNT_WRAP_SECONDS):
1351
+ # CLI --max-turns: the whole run (repair rounds included) stops once the agent asked for more model
1352
+ # steps than allowed (BUG-0492).
1353
+ elif config.get('hardSteps') and proxy.calls > steps: killed['reason'] = 'limited'; killed['limit'] = 'steps'
1354
+ # BUG-0519: a -p run in auto mode has nobody to approve a write the OS sandbox refused; it used to
1355
+ # keep calling the model until the time limit.
1356
+ elif sandbox_stuck(config): killed['reason'] = 'limited'; killed['limit'] = 'sandbox'
1357
+ # CLI --max-budget-credits (hardBudget): the caller's own cap gets no grace past it (BUG-0509).
1358
+ 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):
1154
1359
  # The hook already asked the agent to wrap up at the allowance; this is the hard stop.
1155
1360
  event('account_limit', phase='stopped', content=CREDITS_OUT_NOTE); killed['reason'] = 'limited'; killed['limit'] = 'tokens'
1156
1361
  elif time.time() - (load(ROOT, 'kimi-stopped', {}) or {}).get('time', 1e18) > FINISH_GRACE: killed['reason'] = 'finished'
@@ -1176,7 +1381,7 @@ def main():
1176
1381
  code = child.wait(); stderr.close()
1177
1382
  (ROOT / 'child.json').unlink(missing_ok=True)
1178
1383
  if not mapper.session: mapper.session = newest_session(launched)
1179
- if mapper.session: write('kimi-session.json', {'session': mapper.session, 'time': time.time(), 'readonly': readonly, 'role': role_id, 'model': handover.model_key(config)})
1384
+ if mapper.session: write('kimi-session.json', {'session': mapper.session, 'time': time.time(), 'readonly': readonly, 'role': role_id, 'model': handover.model_key(config), 'connected': connected_turn.fingerprint(offered)})
1180
1385
  if killed.get('limit'): state['limit_kind'] = killed['limit']
1181
1386
  return code, killed['reason']
1182
1387
  def resume(prompt): return [*kimi_argv(), '-S', mapper.session, '-p', prompt + ('\n\n' + language_note if language_note else ''), '--output-format', 'stream-json']
@@ -1245,7 +1450,7 @@ def main():
1245
1450
  if checkpoints:
1246
1451
  try: checkpoints.flush()
1247
1452
  except Exception: pass
1248
- answer = mapper.last_text
1453
+ answer = final_answer(mapper.last_text, getattr(mapper, 'texts', []))
1249
1454
  if answer and state.get('_acceptance_note') and not unresolved: answer += '\n\n' + state['_acceptance_note']
1250
1455
  if reason == 'finished': reason = None
1251
1456
  continuing = auto_continue(config, state, unresolved, reason, readonly, goal, plan_on_hold)
@@ -1262,6 +1467,8 @@ def main():
1262
1467
  if killed['reason'] == 'limited':
1263
1468
  limit = state.get('limit_kind') or 'time'
1264
1469
  limit_text = (CREDITS_OUT_NOTE if limit == 'tokens'
1470
+ else 'Stopped after %d agent step%s (the --max-turns limit); your files are saved.' % (steps, '' if steps == 1 else 's') if limit == 'steps'
1471
+ else SANDBOX_STOP_NOTE if limit == 'sandbox'
1265
1472
  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'))
1266
1473
  result = {'exit_status': 'LimitsExceeded', 'limit': limit, 'limitNote': limit_text, 'submission': answer or limit_text}
1267
1474
  run_state = 'limited'
@@ -1295,10 +1502,20 @@ def main():
1295
1502
  if tidied: event('note', content=tidied)
1296
1503
  except Exception: pass
1297
1504
  report = completion_report(ROOT, REPO, state.get('base'))
1505
+ if start_dirty is not None and report.get('changedFiles'):
1506
+ # BUG-0558: the user's own uncommitted edits from before the turn are not this turn's changes.
1507
+ try:
1508
+ from runtime_control import changed_during_turn
1509
+ report['changedFiles'] = changed_during_turn(REPO, report['changedFiles'], start_dirty)
1510
+ except Exception: pass
1298
1511
  try:
1299
1512
  import work_ledger
1300
1513
  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)
1301
1514
  except Exception: pass
1515
+ if run_state == 'completed' and readonly and plan_turn_ok(report):
1516
+ # BUG-0241: a Plan (read-only) turn that changed nothing is a plan, not unfinished work. Its task list is
1517
+ # what the build will do later, so it never ends as Verification incomplete with a Resume that cannot help.
1518
+ unresolved = []; report = plan_turn_report(report)
1302
1519
  if run_state == 'completed' and (unresolved or report.get('verificationStatus') == 'needs_attention') and soft_unverified(report, unresolved):
1303
1520
  # Done, with an honest note; the review card still lists the open steps and out-of-date checks.
1304
1521
  report['verificationStatus'] = 'needs_attention'; state['_soft_unverified'] = True
@@ -1332,6 +1549,9 @@ def main():
1332
1549
  ticked = sync_plan_progress(REPO, load(ROOT, 'todos.json', []), report.get('verificationStatus') != 'needs_attention')
1333
1550
  if ticked: event('note', content='Marked %d finished deliverable%s in PLAN.md' % (ticked, '' if ticked == 1 else 's'))
1334
1551
  except Exception: pass
1552
+ if answer:
1553
+ filled = fill_dangling_output(answer, LAST_OUTPUT)
1554
+ if filled != answer: answer = filled; result['submission'] = answer
1335
1555
  if answer: event('answer', content=answer)
1336
1556
  open_questions = unshown_questions()
1337
1557
  if open_questions: event('questions', questions=open_questions)