mlai-code 0.3.6 → 0.3.8
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/package.json +1 -1
- package/src/browser-setup.mjs +1 -1
- package/src/cli.mjs +32 -7
- package/src/cloud.mjs +2 -0
- package/src/headless.mjs +6 -2
- package/src/home.mjs +1 -1
- package/src/netjail.py +7 -1
- package/src/render.mjs +1 -1
- package/src/run-record.mjs +114 -0
- package/src/sandbox.mjs +32 -0
- package/src/session.mjs +97 -17
- package/src/tui/agents-cli.mjs +2 -1
- package/src/tui/ansi.mjs +15 -2
- package/src/tui/app.mjs +56 -41
- package/src/tui/bg.mjs +5 -1
- package/src/tui/chat.mjs +3 -1
- package/src/tui/editor.mjs +83 -6
- package/src/tui/plain.mjs +36 -0
- package/src/tui/statusline.mjs +3 -3
- package/src/tui/transcript.mjs +24 -10
- package/src/two-words.mjs +2 -0
- package/worker/browser_local.py +2 -2
- package/worker/browser_tool.py +16 -2
- package/worker/command_safety.py +14 -0
- package/worker/deck_tools.py +4 -3
- package/worker/kimi_bridge.py +174 -35
- package/worker/kimi_gates.py +53 -7
- package/worker/kimi_hook.py +29 -6
- package/worker/lifecycle.py +26 -0
- package/worker/media_tools.py +115 -20
- package/worker/mlai_hooks.py +40 -2
- package/worker/mlai_mcp.py +3 -3
- package/worker/preview.py +11 -3
- package/worker/repo_policy.py +28 -1
- package/worker/roles.py +5 -1
- package/worker/runner.py +2 -1
- package/worker/runtime_control.py +15 -5
- package/worker/site_check.py +1 -1
- package/worker/tool_catalog.py +1 -1
- package/worker/verification.py +102 -0
- package/worker/winproc.py +23 -0
package/worker/deck_tools.py
CHANGED
|
@@ -32,7 +32,7 @@ DECK_IMPORT_TOOL = {'name': 'deck_import', 'description': "Import a file for a d
|
|
|
32
32
|
'inputSchema': {'type': 'object', 'properties': {'path': {'type': 'string', 'description': 'Workspace file, e.g. uploads/brand-template.pptx or data/revenue.xlsx'},
|
|
33
33
|
'mode': {'type': 'string', 'enum': ['theme', 'deck'], 'description': 'pptx only: theme (default) or deck'}, 'sheet': {'type': 'string', 'description': 'xlsx only: sheet name (default: the first)'},
|
|
34
34
|
'range': {'type': 'string', 'description': 'xlsx/csv only: A1-style range such as A1:D13'}}, 'required': ['path'], 'additionalProperties': False}}
|
|
35
|
-
FIND_IMAGE_TOOL = {'name': 'find_image', 'description': 'Find a freely licensed photo or illustration (CC0, public domain, CC BY, CC BY-SA) on Openverse or Wikimedia Commons and save it under public/stock/ with its credit (free, no credits). Best for real places, landmarks, historical images, people in the news, products, science and nature; stock_photo is better for generic business photos. Returns the saved path and a credit line to put in the slide\'s credit field, plus other matches (call again with pick).',
|
|
35
|
+
FIND_IMAGE_TOOL = {'name': 'find_image', 'description': 'Find a freely licensed photo or illustration (CC0, public domain, CC BY, CC BY-SA) on Openverse or Wikimedia Commons and save it under public/stock/ (or the project folder given in filename, e.g. images/peak) with its credit (free, no credits). Best for real places, landmarks, historical images, people in the news, products, science and nature; stock_photo is better for generic business photos. Returns the saved path and a credit line to put in the slide\'s credit field, plus other matches (call again with pick).',
|
|
36
36
|
'inputSchema': {'type': 'object', 'properties': {'query': {'type': 'string', 'maxLength': 100}, 'filename': {'type': 'string', 'description': 'New two-word kebab filename'},
|
|
37
37
|
'source': {'type': 'string', 'enum': ['auto', 'openverse', 'wikimedia']}, 'pick': {'type': 'string', 'description': 'id of an earlier match'}}, 'required': ['query', 'filename'], 'additionalProperties': False}}
|
|
38
38
|
FIND_ICON_TOOL = {'name': 'find_icon', 'description': 'Find an icon or brand logo among about 200,000 open icons (Lucide, Tabler, Material Design, Phosphor, Simple Icons and SVG Logos for company and product logos) and save it as an SVG under public/icons/ in the colour you ask for. Use the saved path as an item icon or diagram node icon, or a logos-slide image. name="simple-icons:stripe" fetches an exact icon.',
|
|
@@ -723,8 +723,9 @@ def find_image(args, root, repo):
|
|
|
723
723
|
_offline()
|
|
724
724
|
query = ' '.join(str(args.get('query') or '').split())[:100]
|
|
725
725
|
if not query: raise ValueError('query is required')
|
|
726
|
-
|
|
727
|
-
|
|
726
|
+
from media_tools import split_filename, asset_dir
|
|
727
|
+
folder, stem = split_filename(args.get('filename')); source = args.get('source') or 'auto'; pick = str(args.get('pick') or '')
|
|
728
|
+
d = asset_dir(repo, folder)[0] if folder else _public(repo, 'stock')
|
|
728
729
|
if any(d.glob(stem + '.*')): raise ValueError('Asset filename already exists. Choose a new name.')
|
|
729
730
|
_count(root, 'find_image')
|
|
730
731
|
hits = []
|
package/worker/kimi_bridge.py
CHANGED
|
@@ -17,7 +17,7 @@ import verification
|
|
|
17
17
|
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
|
-
from lifecycle import boot_id, identity, load
|
|
20
|
+
from lifecycle import boot_id, identity, load, watch_parent
|
|
21
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
|
|
@@ -47,6 +47,15 @@ FINISH_GRACE = int(os.getenv('MINI_KIMI_FINISH_GRACE', '20')) # after the done
|
|
|
47
47
|
LAND_SECONDS = 300 # final stretch: stop exploring, land the change and verify
|
|
48
48
|
from verification import TEST_COMMAND, INLINE_RUN, INLINE_ASSERT, looks_like_check as is_check
|
|
49
49
|
|
|
50
|
+
|
|
51
|
+
def scrub_log(path):
|
|
52
|
+
"""The engine's stderr captures raw command output; keep stored credential and Vault values out of the saved log
|
|
53
|
+
like every other session file (BUG-0528 covered events only)."""
|
|
54
|
+
try:
|
|
55
|
+
raw = path.read_text('utf-8', 'replace'); clean = unvault(raw)
|
|
56
|
+
if clean != raw: path.write_text(clean, 'utf-8')
|
|
57
|
+
except OSError: pass
|
|
58
|
+
|
|
50
59
|
def kimi_bin():
|
|
51
60
|
override = os.getenv('MINI_KIMI_BIN')
|
|
52
61
|
if override: return override
|
|
@@ -318,6 +327,7 @@ Working rules:
|
|
|
318
327
|
- 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.
|
|
319
328
|
- 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.
|
|
320
329
|
- 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.
|
|
330
|
+
- Keep a check's exit status the runner's own: no `| tail`/`| head` without `set -o pipefail`, and no `; echo $?`, an echo of PIPESTATUS, `|| true` or another command after the runner (for long output use `set -o pipefail; npm test 2>&1 | tail -40`). Run checks in the foreground; a check sent to the background counts only when you read its result with TaskOutput. In the final message, report only the checks that ran in this turn and their real results; never repeat counts from an earlier turn as if they ran now.
|
|
321
331
|
- Do not fabricate data, mocks or placeholder implementations in shipped code unless the user asked for them.
|
|
322
332
|
- 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
333
|
- 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.
|
|
@@ -470,6 +480,11 @@ ENGINE_ENV_HIDDEN = ('MODEL_API_KEY', 'SIDE_MODEL_API_KEY', 'VERCEL_OIDC_TOKEN',
|
|
|
470
480
|
'PIXABAY_API_KEY', 'BRANDFETCH_API_KEY', 'MINI_VAULT', 'MINI_KIMI_PROXY_TOKEN', 'MINI_IMAGE_URL', 'MINI_IMAGE_TOKEN',
|
|
471
481
|
'MINI_RESEARCH_URL', 'MINI_RESEARCH_TOKEN', 'MLAI_HUB_TOKEN')
|
|
472
482
|
|
|
483
|
+
# Always set for the engine. Its version is pinned and checked by ML AI Code (ensure_runtime, KIMI_VERSION); the engine's
|
|
484
|
+
# own update check fetched latest.json from an outside server on every run (2-3 s of network time) and could install a
|
|
485
|
+
# different, unchecked version in the background. KIMI_CLI_NO_AUTO_UPDATE is the older spelling.
|
|
486
|
+
ENGINE_FIXED_ENV = {'KIMI_DISABLE_TELEMETRY': '1', 'KIMI_CODE_NO_AUTO_UPDATE': '1', 'KIMI_CLI_NO_AUTO_UPDATE': '1'}
|
|
487
|
+
|
|
473
488
|
def engine_env(environ):
|
|
474
489
|
return {k: v for k, v in environ.items() if k not in ENGINE_ENV_HIDDEN}
|
|
475
490
|
|
|
@@ -702,11 +717,18 @@ class StreamMapper:
|
|
|
702
717
|
# Parallel calls are announced with their results so each step pairs with its own output.
|
|
703
718
|
self.deferred = {c.get('id') for c in calls} if len(calls) > 1 else set()
|
|
704
719
|
return
|
|
720
|
+
if role == 'user':
|
|
721
|
+
# A background check finished and the engine told the agent so (it may read the log instead of TaskOutput).
|
|
722
|
+
content = msg.get('content')
|
|
723
|
+
if isinstance(content, list): content = '\n'.join(p.get('text', '') for p in content if isinstance(p, dict))
|
|
724
|
+
self.background_notice(str(content or ''))
|
|
725
|
+
return
|
|
705
726
|
if role == 'tool':
|
|
706
727
|
name, args = self.calls.get(msg.get('tool_call_id'), ('', {}))
|
|
707
728
|
content = msg.get('content')
|
|
708
729
|
if isinstance(content, list): content = '\n'.join(p.get('text', '') for p in content if isinstance(p, dict))
|
|
709
730
|
content = str(content or '')
|
|
731
|
+
if name in ('TaskOutput', 'WaitFor'): self.background_result(content)
|
|
710
732
|
exit_code = re.search(r'Command failed with exit code: (\d+)', content)
|
|
711
733
|
code = int(exit_code.group(1)) if exit_code else (1 if FAILED.search(content) else 0)
|
|
712
734
|
# A refused call never ran: it is not a result, and never replaces the last real result of that command.
|
|
@@ -720,9 +742,16 @@ class StreamMapper:
|
|
|
720
742
|
if name == 'TodoList': return
|
|
721
743
|
if msg.get('tool_call_id') in getattr(self, 'deferred', set()): self.announce(name, args)
|
|
722
744
|
check_code, integrity = code, ''
|
|
723
|
-
|
|
745
|
+
command = str(args.get('command', '')) if name == 'Bash' else ''
|
|
746
|
+
# Round 6: a check started in the background, or a foreground check the engine moved there after its
|
|
747
|
+
# timeout, has not finished: its result is the later TaskOutput or completion notice, not this 0.
|
|
748
|
+
moved = name == 'Bash' and not code and bool(BACKGROUND_STARTED.search(content))
|
|
749
|
+
checkish = name == 'Bash' and not blocked and (is_check(command) or verification.script_check(command, '' if moved else content))
|
|
750
|
+
if checkish and moved: self.background_started(content, command)
|
|
751
|
+
checkish = checkish and not moved and not args.get('run_in_background')
|
|
752
|
+
if checkish:
|
|
724
753
|
# EXEC-001: `npm test | tail` exits with tail's status. Reconcile with the runner's own summary.
|
|
725
|
-
check_code, integrity = verification.check_exit(
|
|
754
|
+
check_code, integrity = verification.check_exit(command, code, content, lambda t: is_check(t) or verification.script_check(t))
|
|
726
755
|
event('output', output=content[:12000], returncode=code if check_code is None else check_code, **({'integrity': integrity} if integrity else {}), **({'blocked': True} if blocked else {}))
|
|
727
756
|
if name == 'Bash' and args.get('run_in_background') and not code:
|
|
728
757
|
# BUG-0203: remember the start command so a new computer can offer Restart (never restarted by itself).
|
|
@@ -745,16 +774,10 @@ class StreamMapper:
|
|
|
745
774
|
commands = (commands if isinstance(commands, list) else []) + [{'command': command[:2000], 'returncode': code, 'time': time.time(), **({'blocked': True} if blocked else {})}]
|
|
746
775
|
write('kimi-commands.json', commands[-300:])
|
|
747
776
|
except Exception: pass
|
|
748
|
-
if blocked: pass
|
|
749
|
-
elif
|
|
750
|
-
|
|
751
|
-
if integrity: record.update(shellReturncode=code, integrity=integrity); event('note', content=integrity)
|
|
777
|
+
if blocked or moved: pass
|
|
778
|
+
elif checkish:
|
|
779
|
+
self.record_check(command, code, check_code, integrity, content)
|
|
752
780
|
code = check_code if check_code is not None else code
|
|
753
|
-
key = check_key(record['command'])
|
|
754
|
-
checks = [c for c in load(ROOT, 'checks.json', []) if check_key(c.get('command')) != key] + [record]
|
|
755
|
-
write('checks.json', checks[-20:]); event('verification', **record)
|
|
756
|
-
if check_code == 0: st['last_check'] = time.time()
|
|
757
|
-
elif check_code is not None: st['last_failed_check'] = time.time()
|
|
758
781
|
elif code == 0 and not args.get('run_in_background') and not st.get('inspect') and not HOOK_BLOCKED.search(content):
|
|
759
782
|
# BUG-0542: no test suite here; running the changed program and seeing it work is the check.
|
|
760
783
|
try:
|
|
@@ -771,6 +794,66 @@ class StreamMapper:
|
|
|
771
794
|
write('checks.json', checks[-20:]); event('verification', **remote)
|
|
772
795
|
save_state(st)
|
|
773
796
|
|
|
797
|
+
def record_check(self, command, code, check_code, integrity, content):
|
|
798
|
+
st = self.state
|
|
799
|
+
record = {'label': clip(command, 160), 'command': command[:2000], 'returncode': check_code, 'executed': True, 'scope': 'supporting' if st.get('inspect') else 'repository', 'output': content[-4000:], 'time': time.time()}
|
|
800
|
+
if integrity: record.update(shellReturncode=code, integrity=integrity); event('note', content=integrity)
|
|
801
|
+
key = check_key(record['command'])
|
|
802
|
+
checks = [c for c in load(ROOT, 'checks.json', []) if check_key(c.get('command')) != key] + [record]
|
|
803
|
+
write('checks.json', checks[-20:]); event('verification', **record)
|
|
804
|
+
if check_code == 0: st['last_check'] = time.time()
|
|
805
|
+
elif check_code is not None: st['last_failed_check'] = time.time()
|
|
806
|
+
def background_started(self, content, command):
|
|
807
|
+
m = re.search(r'^task_id:\s*(\S+)', content, re.M)
|
|
808
|
+
if not m: return
|
|
809
|
+
pending = load(ROOT, BACKGROUND_CHECKS, {})
|
|
810
|
+
pending = pending if isinstance(pending, dict) else {}
|
|
811
|
+
pending[m.group(1)] = {'command': command[:2000], 'time': time.time()}
|
|
812
|
+
write(BACKGROUND_CHECKS, dict(list(pending.items())[-40:]))
|
|
813
|
+
event('note', content='Check moved to the background; its result counts once it finishes: ' + clip(command, 160))
|
|
814
|
+
def settle_background(self, task_id, code, output, command=None):
|
|
815
|
+
pending = load(ROOT, BACKGROUND_CHECKS, {})
|
|
816
|
+
pending = pending if isinstance(pending, dict) else {}
|
|
817
|
+
entry = pending.pop(task_id, None)
|
|
818
|
+
command = (entry or {}).get('command') or command
|
|
819
|
+
if not command or not (entry or is_check(command) or verification.script_check(command, output)): return
|
|
820
|
+
write(BACKGROUND_CHECKS, pending)
|
|
821
|
+
check_code, integrity = verification.check_exit(command, code, output, lambda t: is_check(t) or verification.script_check(t))
|
|
822
|
+
self.record_check(command, code, check_code, integrity, output)
|
|
823
|
+
save_state(self.state)
|
|
824
|
+
def background_result(self, content):
|
|
825
|
+
"""TaskOutput or WaitFor on finished background tasks: per task a record (`status: completed|failed`,
|
|
826
|
+
`exit_code: N`, `command: ...`) starting with `Wall time:`, then its [output]."""
|
|
827
|
+
blocks = re.split(r'(?m)^(?=Wall time:)', content)
|
|
828
|
+
for block in (blocks[1:] if len(blocks) > 1 else blocks): self.background_record(block)
|
|
829
|
+
def background_record(self, content):
|
|
830
|
+
head, _, output = content.partition('\n[output]\n')
|
|
831
|
+
fields = dict(re.findall(r'^(task_id|status|exit_code|command|kind):\s*(.*)$', head, re.M))
|
|
832
|
+
if fields.get('kind', 'process') != 'process' or fields.get('status') not in ('completed', 'failed', 'killed', 'timed_out'): return
|
|
833
|
+
try: code = int(fields.get('exit_code'))
|
|
834
|
+
except (TypeError, ValueError): code = 0 if fields.get('status') == 'completed' else 1
|
|
835
|
+
if fields.get('status') != 'completed' and not code: code = 1
|
|
836
|
+
self.settle_background(fields.get('task_id', ''), code, output.strip(), fields.get('command'))
|
|
837
|
+
def background_notice(self, content):
|
|
838
|
+
m = BACKGROUND_NOTICE.search(content)
|
|
839
|
+
if not m: return
|
|
840
|
+
task_id, kind = m.group(2), m.group(1)
|
|
841
|
+
pending = load(ROOT, BACKGROUND_CHECKS, {})
|
|
842
|
+
if not isinstance(pending, dict) or task_id not in pending: return
|
|
843
|
+
output = ''
|
|
844
|
+
path = re.search(r'<output-file path="([^"]+)"', content)
|
|
845
|
+
if path:
|
|
846
|
+
try:
|
|
847
|
+
with open(path.group(1), 'rb') as f:
|
|
848
|
+
f.seek(0, 2); size = f.tell(); f.seek(max(0, size - 8000)); output = f.read().decode('utf-8', 'replace')
|
|
849
|
+
except OSError: pass
|
|
850
|
+
code = re.search(r'exit(?:ed with)? code:?\s*(-?\d+)', content, re.I)
|
|
851
|
+
self.settle_background(task_id, int(code.group(1)) if code else (0 if kind == 'completed' else 1), output)
|
|
852
|
+
|
|
853
|
+
BACKGROUND_CHECKS = 'kimi-background-checks.json'
|
|
854
|
+
BACKGROUND_STARTED = re.compile(r'^task_id:\s*\S+[\s\S]*^automatic_notification:\s*true', re.M)
|
|
855
|
+
BACKGROUND_NOTICE = re.compile(r'<notification\b[^>]*\btype="task\.(completed|failed|killed|timed_out)"[^>]*\bsource_kind="background_task"[^>]*\bsource_id="([^"]+)"')
|
|
856
|
+
|
|
774
857
|
PROSE_PATH = re.compile(r'\.(?:md|mdx|markdown|rst|adoc|txt)$', re.I)
|
|
775
858
|
PUSHED = re.compile(r'(^|[;&|(\s])(git push\b|gh pr (create|merge)\b)')
|
|
776
859
|
CI_OBSERVED = re.compile(r'(^|[;&|(\s])(gh pr checks\b|gh run watch\b[^;&|]*--exit-status)')
|
|
@@ -880,26 +963,62 @@ def plan_turn_report(report):
|
|
|
880
963
|
if out.get('verificationStatus') == 'needs_attention': out['verificationStatus'] = 'passed' if int(report.get('checksPassed') or 0) else 'unverified'
|
|
881
964
|
return out
|
|
882
965
|
|
|
883
|
-
def
|
|
884
|
-
|
|
885
|
-
|
|
966
|
+
def soft_only(issues):
|
|
967
|
+
return bool(issues) and all(SOFT_ISSUE.search(str(i or '')) for i in issues)
|
|
968
|
+
|
|
969
|
+
def untested(report, state=None):
|
|
970
|
+
"""Code changed this turn and no check passed on it, nothing failed: done, not tested."""
|
|
971
|
+
state = state or {}
|
|
972
|
+
return bool(state.get('_untested_ok') or (report.get('changedFiles') and state.get('last_edit') and not int(report.get('checksPassed') or 0)
|
|
973
|
+
and (state.get('last_check') or 0) < state.get('last_edit')))
|
|
974
|
+
|
|
975
|
+
def soft_unverified(report, unresolved, state=None):
|
|
976
|
+
"""Nothing this task did failed: the only gaps are checks that predate the last edit, open task-list items, a code
|
|
977
|
+
change no check ran on, or failing checks that are not this task's (a commit or question, or a failure that is already
|
|
978
|
+
there on the base commit). The work is shown as done with a note, not as an interrupted run with a Resume button."""
|
|
979
|
+
state = state or {}
|
|
980
|
+
unresolved = list(unresolved or [])
|
|
981
|
+
if not all(SOFT_ISSUE.search(str(i or '')) for i in unresolved): return False
|
|
982
|
+
# CLI r5: "Commit changes" with the user's own red test, or a suite that already fails on the base commit, is done.
|
|
983
|
+
if not unresolved and (state.get('_non_code') or state.get('_preexisting')): return True
|
|
886
984
|
if any(int(report.get(k) or 0) for k in ('checksFailed', 'checksInconclusive', 'externalChecksFailed')): return False
|
|
887
|
-
if not all(SOFT_ISSUE.search(str(i or '')) for i in unresolved or []): return False
|
|
888
985
|
# Open task-list steps with no check passed at all is unfinished work, not a done run with a note (CLI bug list #7).
|
|
889
|
-
todo_open = any(re.match(r'Your todo list still has open items', str(i or ''), re.I) for i in unresolved
|
|
986
|
+
todo_open = any(re.match(r'Your todo list still has open items', str(i or ''), re.I) for i in unresolved)
|
|
890
987
|
if todo_open and not int(report.get('checksPassed') or 0) and not int(report.get('checksStale') or 0): return False
|
|
891
|
-
#
|
|
892
|
-
|
|
893
|
-
return
|
|
988
|
+
# CLI r5: an edit no check covered is "done, not tested" with a plain note, after one request to run the checks;
|
|
989
|
+
# it used to loop through every repair round and end as Not verified, also when the user said not to test.
|
|
990
|
+
return True
|
|
894
991
|
|
|
895
|
-
def
|
|
896
|
-
|
|
897
|
-
|
|
992
|
+
def _check_names(checks, status):
|
|
993
|
+
try: from runtime_control import latest_checks, check_status
|
|
994
|
+
except Exception: return []
|
|
995
|
+
out = []
|
|
996
|
+
for c in latest_checks(checks or []):
|
|
997
|
+
if (c.get('scope') or 'repository') == 'repository' and check_status(c) == status:
|
|
998
|
+
name = re.sub(r'\s+', ' ', str(c.get('command') or c.get('label') or 'a check')).replace('`', "'").strip()
|
|
999
|
+
out.append('`' + (name if len(name) <= 60 else name[:57].rstrip() + '...') + '`')
|
|
1000
|
+
out = list(dict.fromkeys(out))
|
|
1001
|
+
return out[:2] + (['%d more' % (len(out) - 2)] if len(out) > 2 else [])
|
|
1002
|
+
|
|
1003
|
+
def soft_note(report, state=None, checks=None):
|
|
1004
|
+
state = state or {}
|
|
1005
|
+
parts, more = [], 0 # more: parts that "continue" can finish
|
|
1006
|
+
failed = int(report.get('checksFailed') or 0)
|
|
1007
|
+
names = ', '.join(_check_names(checks, 'failed'))
|
|
1008
|
+
if failed and state.get('_preexisting'):
|
|
1009
|
+
parts.append('%s also fail%s on the code from before this task, so %s reported, not fixed' % (names or 'the failing check', '' if failed > 1 else 's', 'they were' if failed > 1 else 'it was'))
|
|
1010
|
+
elif failed and state.get('_non_code'):
|
|
1011
|
+
parts.append('%d check%s failed (%s); this task did not change code, so %s left as %s' % (failed, '' if failed == 1 else 's', names or 'see the checks', 'they were' if failed > 1 else 'it was', 'they are' if failed > 1 else 'it is'))
|
|
1012
|
+
if untested(report, state) and not int(report.get('checksStale') or 0) and not failed:
|
|
1013
|
+
if state.get('_untested_ok'): parts.append('not tested, as you asked: no test or check ran on this change')
|
|
1014
|
+
else: parts.append('not tested: no test, build or check ran after the code change'); more += 1
|
|
1015
|
+
if int(report.get('checksStale') or 0): parts.append('the last code change was made after the final checks ran, so it has not been re-tested yet'); more += 1
|
|
898
1016
|
open_items = len(report.get('unfinishedTasks') or [])
|
|
899
|
-
if open_items: parts.append('%d step%s from the task list %s still open' % (open_items, '' if open_items == 1 else 's', 'is' if open_items == 1 else 'are'))
|
|
900
|
-
if int(report.get('checksNotRun') or 0) and not parts: parts.append('some checks did not run')
|
|
1017
|
+
if open_items: parts.append('%d step%s from the task list %s still open' % (open_items, '' if open_items == 1 else 's', 'is' if open_items == 1 else 'are')); more += 1
|
|
1018
|
+
if int(report.get('checksNotRun') or 0) and not parts: parts.append('some checks did not run'); more += 1
|
|
901
1019
|
if not parts: return ''
|
|
902
|
-
|
|
1020
|
+
offer = (' Say "continue" if you want me to finish ' + ('that' if more == 1 else 'these') + '.') if more else ''
|
|
1021
|
+
return '\n\nNote: ' + '; '.join(parts) + '.' + offer
|
|
903
1022
|
def save_state(st, static=False):
|
|
904
1023
|
"""kimi-state.json holds the run settings (written once); kimi-progress.json the stream-derived facts. The hook writes kimi-hook.json."""
|
|
905
1024
|
name = 'kimi-state.json' if static else 'kimi-progress.json'
|
|
@@ -912,6 +1031,17 @@ def network_note(config):
|
|
|
912
1031
|
extra = [d for d in net.get('domains') or [] if isinstance(d, str)][:40]
|
|
913
1032
|
return 'Internet access: allowlist (GitHub, npm, PyPI, Hugging Face, Exa and the model APIs' + ('; also allowed by the user: ' + ', '.join(extra) if extra else '') + '). Other hosts are blocked and fail as "Could not resolve host"; when a task needs one, call mcp__mlai__network with the domain and reason instead of retrying.\n'
|
|
914
1033
|
|
|
1034
|
+
def windows_note():
|
|
1035
|
+
"""Windows bug list (round 6): after the browser check failed, the agent built its own Puppeteer harness in
|
|
1036
|
+
~/taskflow/.e2e-tmp and `npm init -y` refused the folder name; many calls were spent on it."""
|
|
1037
|
+
busybox = bool(os.getenv('MLAI_BUSYBOX'))
|
|
1038
|
+
shell, drive = ('busybox sh (the sandbox shell)', 'C:/') if busybox else ('Git Bash', '/c/')
|
|
1039
|
+
return ('This computer runs Windows. Shell commands run in ' + shell + ', a POSIX shell: use forward slashes, drives as ' + drive + '..., '
|
|
1040
|
+
'and /dev/null works there; do not use PowerShell or cmd syntax in shell commands. Windows programs live under '
|
|
1041
|
+
'"' + drive + 'Program Files". A scratch folder you run `npm init -y` in needs a valid package name (lowercase, no leading dot), '
|
|
1042
|
+
'so do not name it like ".e2e-tmp". If the browser tool says it cannot run here, do not build a replacement '
|
|
1043
|
+
'(Puppeteer, Playwright scripts, the system Chrome or Edge): verify with the project\'s tests and build and say the browser check was not available.\n')
|
|
1044
|
+
|
|
915
1045
|
def workspace_note(config, event):
|
|
916
1046
|
"""Jobs (restart the ones that died), project setup and environment facts for the agent's instructions."""
|
|
917
1047
|
note = ''
|
|
@@ -938,6 +1068,7 @@ def workspace_note(config, event):
|
|
|
938
1068
|
note += env_setup.tools_line(ROOT) + '\n'
|
|
939
1069
|
except Exception: pass
|
|
940
1070
|
note += R.preview_build_note()
|
|
1071
|
+
if sys.platform == 'win32': note += windows_note()
|
|
941
1072
|
if config.get('conversation_route', 'build') == 'build':
|
|
942
1073
|
try:
|
|
943
1074
|
import preview
|
|
@@ -1180,7 +1311,9 @@ def auto_continue(config, state, unresolved, reason, readonly, goal, plan_on_hol
|
|
|
1180
1311
|
except Exception: pass
|
|
1181
1312
|
timed_out = reason == 'limited' and (state.get('limit_kind') or 'time') == 'time'
|
|
1182
1313
|
if not timed_out and reason: return None # out of credits or another stop: never continue on its own
|
|
1183
|
-
|
|
1314
|
+
# CLI r5: soft gaps (untested or re-test needed, open list items) end as done with a note that offers "continue";
|
|
1315
|
+
# the chat does not restart by itself behind that note.
|
|
1316
|
+
failing = [i for i in unresolved or [] if not str(i).startswith(SETTLED) and not SOFT_ISSUE.search(str(i))]
|
|
1184
1317
|
if not failing and not timed_out:
|
|
1185
1318
|
if not unresolved: wakeups.verify_settled(ROOT, event)
|
|
1186
1319
|
return None
|
|
@@ -1207,6 +1340,7 @@ def stall_continue(config, state, readonly, goal, failure):
|
|
|
1207
1340
|
|
|
1208
1341
|
def main():
|
|
1209
1342
|
config = json.loads((ROOT / 'request.json').read_text())
|
|
1343
|
+
if not config.get('subagent'): watch_parent(ROOT) # the CLI ended without stopping this run: stop it
|
|
1210
1344
|
import goals
|
|
1211
1345
|
goal = None
|
|
1212
1346
|
if not config.get('subagent'):
|
|
@@ -1233,7 +1367,7 @@ def main():
|
|
|
1233
1367
|
research_proxy = start_research_proxy()
|
|
1234
1368
|
write('status.json', {'state': 'running', 'started': time.time(), 'boot': boot_id(), 'process': identity(os.getpid()), 'harness': 'kimi'})
|
|
1235
1369
|
(ROOT / 'kimi-stderr.log').unlink(missing_ok=True)
|
|
1236
|
-
for name in ('kimi-state.json', 'kimi-progress.json', 'kimi-hook.json', 'usage.json', 'kimi-stop-count', 'design-browser-evidence.json', 'design-review.json', 'acceptance.json', 'budget-declined', 'hard-deny-targets.json', BLOCKED_CALLS): (ROOT / name).unlink(missing_ok=True)
|
|
1370
|
+
for name in ('kimi-state.json', 'kimi-progress.json', 'kimi-hook.json', 'usage.json', 'kimi-stop-count', 'design-browser-evidence.json', 'design-review.json', 'acceptance.json', 'budget-declined', 'hard-deny-targets.json', BACKGROUND_CHECKS, BLOCKED_CALLS): (ROOT / name).unlink(missing_ok=True)
|
|
1237
1371
|
# "Approve all" covers the rest of the request: a Resume of the same request keeps it, a new request asks afresh.
|
|
1238
1372
|
if not config.get('resuming') or config.get('subagent'): (ROOT / 'kimi-approve-all').unlink(missing_ok=True)
|
|
1239
1373
|
shutil.rmtree(ROOT / 'acceptance', ignore_errors=True)
|
|
@@ -1352,7 +1486,7 @@ def main():
|
|
|
1352
1486
|
for stale in ('scope.json', 'kimi-commands.json', 'verification.json', 'kimi-last-text.json'): (ROOT / stale).unlink(missing_ok=True)
|
|
1353
1487
|
env = engine_env(os.environ)
|
|
1354
1488
|
env.update(VAULT)
|
|
1355
|
-
env.update({'KIMI_CODE_HOME': str(HOME),
|
|
1489
|
+
env.update({'KIMI_CODE_HOME': str(HOME), **ENGINE_FIXED_ENV, 'MINI_ROOT': str(ROOT), 'MINI_REPO': REPO, 'NO_COLOR': '1', 'CI': '1'})
|
|
1356
1490
|
# BUG-0460: after an Edit or Retry the old session still holds the replaced turn, so start fresh from the history.
|
|
1357
1491
|
prior = None if config.get('_handover') or config.get('replaces') else resumable_session(readonly, role_id, handover.model_key(config))
|
|
1358
1492
|
if prior:
|
|
@@ -1418,7 +1552,7 @@ def main():
|
|
|
1418
1552
|
except ValueError: continue
|
|
1419
1553
|
try: mapper.handle(msg)
|
|
1420
1554
|
except Exception as exc: event('note', content='Could not display one step: ' + str(exc)[:200])
|
|
1421
|
-
code = child.wait(); stderr.close()
|
|
1555
|
+
code = child.wait(); stderr.close(); scrub_log(ROOT / 'kimi-stderr.log')
|
|
1422
1556
|
(ROOT / 'child.json').unlink(missing_ok=True)
|
|
1423
1557
|
if not mapper.session: mapper.session = newest_session(launched)
|
|
1424
1558
|
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)})
|
|
@@ -1480,6 +1614,10 @@ def main():
|
|
|
1480
1614
|
unresolved = issues
|
|
1481
1615
|
if rounds >= MAX_REPAIR_ROUNDS or time_left() < 240 or not mapper.session:
|
|
1482
1616
|
break
|
|
1617
|
+
if soft_only(issues) and (rounds >= 1 or 'verify' in (load(ROOT, 'kimi-hook.json', {}).get('gates_done') or [])):
|
|
1618
|
+
# CLI r5: "run the tests" was already asked once; more rounds only repeat it (40 calls, 5 minutes). The run
|
|
1619
|
+
# ends as done, not tested, and says so.
|
|
1620
|
+
break
|
|
1483
1621
|
rounds += 1
|
|
1484
1622
|
event('final_gate', state='repair', round=rounds, issues=issues, content='Not done yet: ' + issues[0][:300])
|
|
1485
1623
|
previous = mapper.last_text; mapper.last_text = ''
|
|
@@ -1494,7 +1632,7 @@ def main():
|
|
|
1494
1632
|
if answer and state.get('_acceptance_note') and not unresolved: answer += '\n\n' + state['_acceptance_note']
|
|
1495
1633
|
if reason == 'finished': reason = None
|
|
1496
1634
|
continuing = auto_continue(config, state, unresolved, reason, readonly, goal, plan_on_hold)
|
|
1497
|
-
if unresolved and answer and not reason and not soft_unverified({'checksPassed': 1 if state.get('last_check') else 0}, unresolved):
|
|
1635
|
+
if unresolved and answer and not reason and not soft_unverified({'checksPassed': 1 if state.get('last_check') else 0}, unresolved, state):
|
|
1498
1636
|
answer += '\n\nVerification note: ' + ' '.join(i.splitlines()[0] for i in unresolved)[:1200]
|
|
1499
1637
|
if continuing: answer += '\n\nThis chat continues automatically in a minute to fix what is still open.'
|
|
1500
1638
|
event('final_gate', state='unresolved', issues=unresolved, content='Some final checks did not pass')
|
|
@@ -1513,7 +1651,7 @@ def main():
|
|
|
1513
1651
|
result = {'exit_status': 'LimitsExceeded', 'limit': limit, 'limitNote': limit_text, 'submission': answer or limit_text}
|
|
1514
1652
|
run_state = 'limited'
|
|
1515
1653
|
elif code != 0 and not answer:
|
|
1516
|
-
with open(ROOT / 'kimi-stderr.log', 'rb') as f: f.seek(holder.get('offset', 0)); tail = f.read().decode('utf-8', 'replace')[-800:]
|
|
1654
|
+
with open(ROOT / 'kimi-stderr.log', 'rb') as f: f.seek(holder.get('offset', 0)); tail = unvault(f.read().decode('utf-8', 'replace'))[-800:]
|
|
1517
1655
|
failure = (proxy.last_error or tail.strip() or 'The engine stopped with exit code %d' % code)[:800]
|
|
1518
1656
|
# A dropped or stalled model stream is temporary: continue by itself in a minute instead of leaving the
|
|
1519
1657
|
# task paused until someone presses Resume (Windows bug list, item 6). Bounded like the verify continue.
|
|
@@ -1556,10 +1694,11 @@ def main():
|
|
|
1556
1694
|
# BUG-0241: a Plan (read-only) turn that changed nothing is a plan, not unfinished work. Its task list is
|
|
1557
1695
|
# what the build will do later, so it never ends as Verification incomplete with a Resume that cannot help.
|
|
1558
1696
|
unresolved = []; report = plan_turn_report(report)
|
|
1559
|
-
if run_state == 'completed' and (unresolved or report.get('verificationStatus') == 'needs_attention') and soft_unverified(report, unresolved):
|
|
1697
|
+
if run_state == 'completed' and (unresolved or report.get('verificationStatus') == 'needs_attention' or untested(report, state)) and soft_unverified(report, unresolved, state):
|
|
1560
1698
|
# Done, with an honest note; the review card still lists the open steps and out-of-date checks.
|
|
1561
|
-
report
|
|
1562
|
-
|
|
1699
|
+
if unresolved or report.get('verificationStatus') == 'needs_attention': report['verificationStatus'] = 'needs_attention'
|
|
1700
|
+
state['_soft_unverified'] = True
|
|
1701
|
+
note = soft_note(report, state, load(ROOT, 'checks.json', []))
|
|
1563
1702
|
if answer and note and note.strip() not in answer:
|
|
1564
1703
|
answer += note; result['submission'] = answer
|
|
1565
1704
|
elif run_state == 'completed' and (unresolved or report.get('verificationStatus') == 'needs_attention'):
|
package/worker/kimi_gates.py
CHANGED
|
@@ -146,6 +146,17 @@ def adjudicate(config, model, language, code, output):
|
|
|
146
146
|
if not genuine and not wrong: return names, [] # unparseable review: keep the failures
|
|
147
147
|
return genuine, wrong
|
|
148
148
|
|
|
149
|
+
_REL_IMPORT = re.compile(r"""((?:\bfrom|\bimport|\bimport\(|\brequire\(|\bcreateRequire\(import\.meta\.url\)\()\s*)(['"])\./""")
|
|
150
|
+
|
|
151
|
+
def scratch_source(language, code):
|
|
152
|
+
"""CLI r5: the test runs from a scratch folder one level inside the project, so `import {total} from './cart.js'`
|
|
153
|
+
looked for the file in the scratch folder and the check was thrown away as a tester error (a wasted model call and no
|
|
154
|
+
independent check). Relative imports are pointed one level up; 'file://' + ACCEPTANCE_REPO_URL (already a URL) is
|
|
155
|
+
repaired to the URL itself."""
|
|
156
|
+
if language == 'python': return code
|
|
157
|
+
code = _REL_IMPORT.sub(lambda m: m.group(1) + m.group(2) + '../', code)
|
|
158
|
+
return re.sub(r"""['"]file://['"]\s*\+\s*(process\.env\.ACCEPTANCE_REPO_URL)""", r'\1', code)
|
|
159
|
+
|
|
149
160
|
def run_acceptance(root, repo, language, code, timeout=180):
|
|
150
161
|
d = Path(root) / ACCEPTANCE_DIR; d.mkdir(exist_ok=True)
|
|
151
162
|
name = 'test_acceptance.py' if language == 'python' else 'acceptance.test.mjs'
|
|
@@ -158,7 +169,7 @@ def run_acceptance(root, repo, language, code, timeout=180):
|
|
|
158
169
|
scratch = Path(repo) / ('.mlai-acceptance-' + os.urandom(4).hex())
|
|
159
170
|
try:
|
|
160
171
|
scratch.mkdir()
|
|
161
|
-
run_path = scratch / name; run_path.write_text(path.read_text())
|
|
172
|
+
run_path = scratch / name; run_path.write_text(scratch_source(language, path.read_text()))
|
|
162
173
|
except OSError:
|
|
163
174
|
scratch, run_path = None, path
|
|
164
175
|
cmd = [sys.executable, str(run_path), '-v'] if language == 'python' else ['node', '--test', str(run_path)]
|
|
@@ -172,6 +183,23 @@ def run_acceptance(root, repo, language, code, timeout=180):
|
|
|
172
183
|
finally:
|
|
173
184
|
if scratch is not None: shutil.rmtree(scratch, ignore_errors=True)
|
|
174
185
|
|
|
186
|
+
def task_text(config, root):
|
|
187
|
+
"""The task as the user now wants it: the request plus what they said during the turn (a rejection note such as
|
|
188
|
+
"name it subtract instead", a steering message). Without these the hidden test checked the original wording and
|
|
189
|
+
the repair step undid the change the user asked for."""
|
|
190
|
+
task = str(config.get('task', ''))
|
|
191
|
+
later = []
|
|
192
|
+
try:
|
|
193
|
+
for line in (Path(root) / 'events.jsonl').read_text(errors='replace').splitlines():
|
|
194
|
+
try: e = json.loads(line)
|
|
195
|
+
except ValueError: continue
|
|
196
|
+
if isinstance(e, dict) and e.get('type') == 'steering' and isinstance(e.get('content'), str) and e['content'].strip():
|
|
197
|
+
later.append(e['content'].strip()[:2000])
|
|
198
|
+
except OSError: pass
|
|
199
|
+
if later:
|
|
200
|
+
task += '\n\nThe user then said, during the work (this overrides the request above where they differ):\n' + '\n'.join('- ' + m for m in later[-10:])
|
|
201
|
+
return task
|
|
202
|
+
|
|
175
203
|
def acceptance(config, st, model, root, repo, changed, event):
|
|
176
204
|
"""Write and run the hidden acceptance test once. Returns {status, ...}: passed | failed | skipped | invalid."""
|
|
177
205
|
if os.getenv('MINI_ACCEPTANCE') == '0' or config.get('acceptance') is False: return {'status': 'skipped', 'reason': 'disabled'}
|
|
@@ -180,7 +208,8 @@ def acceptance(config, st, model, root, repo, changed, event):
|
|
|
180
208
|
diff = _diff(repo, st.get('base'))
|
|
181
209
|
if not diff.strip(): return {'status': 'skipped', 'reason': 'no diff'}
|
|
182
210
|
files = subprocess.run(['git', 'ls-files', '--cached', '--others', '--exclude-standard'], cwd=repo, capture_output=True, text=True).stdout.splitlines()[:300]
|
|
183
|
-
|
|
211
|
+
task = task_text(config, root)
|
|
212
|
+
user = json.dumps({'task': task[:16000], 'languages_changed': sorted(langs), 'repository_files': files, 'diff': diff})
|
|
184
213
|
event('acceptance', status='running', content='Independent acceptance check: writing tests from the task')
|
|
185
214
|
spec, text = None, ''
|
|
186
215
|
for attempt in range(2): # one retry: reasoning models sometimes run out of tokens or wrap the JSON oddly
|
|
@@ -197,7 +226,7 @@ def acceptance(config, st, model, root, repo, changed, event):
|
|
|
197
226
|
if code not in (0, 124) and tester_invalid(spec['language'], output):
|
|
198
227
|
# Web bug list Bug-017 and Bug-021: a test that cannot even load (JSX imported into plain Node, a wrong path)
|
|
199
228
|
# says nothing about the build. Give the tester its own error once and run the corrected test.
|
|
200
|
-
retry = json.dumps({'task':
|
|
229
|
+
retry = json.dumps({'task': task[:16000], 'languages_changed': sorted(langs), 'repository_files': files,
|
|
201
230
|
'previous_test': spec['code'][:20000], 'error': output[-3000:]})
|
|
202
231
|
try:
|
|
203
232
|
fixed_text, _ = model.request([{'role': 'system', 'content': TESTER_SYSTEM + TESTER_RETRY},
|
|
@@ -240,13 +269,15 @@ def code_fingerprint(repo, paths):
|
|
|
240
269
|
def pre_existing_failure(st, checks, repo, done, event):
|
|
241
270
|
"""When the newest failing check also fails on the base commit, the failure pre-dates this task: report it instead of demanding a fix."""
|
|
242
271
|
if 'preexisting' in done or not st.get('base'): return False
|
|
243
|
-
failing = [c for c in checks if c.get('executed') and c.get('returncode') not in (0, None) and c.get('command')]
|
|
272
|
+
failing = [c for c in checks if c.get('executed') and c.get('returncode') not in (0, None) and c.get('command') and (c.get('scope') or 'repository') == 'repository']
|
|
244
273
|
if not failing: return False
|
|
245
274
|
done.add('preexisting')
|
|
246
275
|
newest = max(failing, key=lambda c: c.get('time') or 0)
|
|
247
276
|
try:
|
|
248
277
|
import verification
|
|
249
|
-
|
|
278
|
+
# Every failing check must also fail on the base commit; one that only fails on the new code is this task's.
|
|
279
|
+
commands = list(dict.fromkeys(c['command'] for c in sorted(failing, key=lambda c: -(c.get('time') or 0))))[:3]
|
|
280
|
+
result = len(commands) == len(set(c['command'] for c in failing)) and all(verification.pre_existing(repo, st['base'], c) for c in commands)
|
|
250
281
|
except Exception: result = None
|
|
251
282
|
if result:
|
|
252
283
|
st['_preexisting'] = newest['command'][:300]
|
|
@@ -302,7 +333,16 @@ def final_issues(config, st, answer, done, model, root, repo, event, allow_accep
|
|
|
302
333
|
checks = []
|
|
303
334
|
try: checks = json.loads((Path(root) / 'checks.json').read_text())
|
|
304
335
|
except (OSError, ValueError): pass
|
|
305
|
-
|
|
336
|
+
try:
|
|
337
|
+
import verification as _v
|
|
338
|
+
task = config.get('task', '')
|
|
339
|
+
# CLI r5: a commit, cleanup or question that left no code change of its own is not held to the code gates, and
|
|
340
|
+
# "do not run tests, I will test it myself" is done, not tested, by request.
|
|
341
|
+
non_code = _v.non_code_task(task) and not code_changed
|
|
342
|
+
untested_ok = _v.no_tests_requested(task)
|
|
343
|
+
except Exception: non_code = untested_ok = False
|
|
344
|
+
st['_non_code'] = non_code; st['_untested_ok'] = untested_ok and bool(code_changed)
|
|
345
|
+
if code_changed and last_edit and last_check < last_edit and not untested_ok:
|
|
306
346
|
blamed = pre_existing_failure(st, checks, repo, done, event)
|
|
307
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.')
|
|
308
348
|
try:
|
|
@@ -330,7 +370,9 @@ def final_issues(config, st, answer, done, model, root, repo, event, allow_accep
|
|
|
330
370
|
done.add(f['kind']); issues.append(f['message'])
|
|
331
371
|
# A gate being mentioned once is not evidence it was repaired. The outer
|
|
332
372
|
# bridge bounds repair attempts; unresolved results must survive to it.
|
|
333
|
-
if report['status'] == 'failed' and not issues and not st.get('_preexisting') and not
|
|
373
|
+
if report['status'] == 'failed' and not issues and not st.get('_preexisting') and not non_code and code_changed:
|
|
374
|
+
pre_existing_failure(st, checks, repo, done, event) # a red suite from before the task is reported, not repaired
|
|
375
|
+
if report['status'] == 'failed' and not issues and not st.get('_preexisting') and not st.get('inspect') and not non_code:
|
|
334
376
|
issues.append('Repository verification still fails: ' + '; '.join(report['reasons']) + '. Fix and rerun the failing checks, or report the unresolved failure.')
|
|
335
377
|
except Exception as exc:
|
|
336
378
|
issue = 'Verification report could not complete: ' + str(exc)[:200]
|
|
@@ -374,6 +416,10 @@ def final_issues(config, st, answer, done, model, root, repo, event, allow_accep
|
|
|
374
416
|
if research_required(config) or ledger.load()['sources']:
|
|
375
417
|
issue = ledger.completion_issue(answer or '')
|
|
376
418
|
if issue: issues.append(issue.replace('evidence {claims', 'mcp__mlai__evidence {claims'))
|
|
419
|
+
if allow_acceptance and code_changed and not issues and 'acceptance' not in done and untested_ok:
|
|
420
|
+
# The user asked for no test runs; the hidden test would run their code anyway.
|
|
421
|
+
done.add('acceptance'); st['_acceptance_skipped'] = True
|
|
422
|
+
event('acceptance', status='skipped', content='Independent acceptance check skipped: you asked for no test runs')
|
|
377
423
|
if allow_acceptance and code_changed and not issues and 'acceptance' not in done and small_change(repo, st.get('base'), code_changed, checks, last_edit, last_check):
|
|
378
424
|
# A small edit with a passing check after it: writing and running a hidden test costs a model call and a test run
|
|
379
425
|
# for little extra signal. Larger changes still get the independent check.
|
package/worker/kimi_hook.py
CHANGED
|
@@ -107,10 +107,10 @@ def steer_block(messages, stopping=False):
|
|
|
107
107
|
|
|
108
108
|
def wait_decision(request, seconds=540, strict=False):
|
|
109
109
|
"""One approval at a time even when Kimi runs tool calls in parallel. Strict (repository policy) reviews ignore "Approve all"."""
|
|
110
|
-
import
|
|
110
|
+
from winproc import lock_file
|
|
111
111
|
queued = time.time()
|
|
112
112
|
with (ROOT / 'approval.lock').open('a') as lock:
|
|
113
|
-
|
|
113
|
+
lock_file(lock)
|
|
114
114
|
# BUG-0251: a call that queued behind an approval the user then rejected (parallel tool calls of one step)
|
|
115
115
|
# is rejected too, so a leftover card can never run a change the user just said no to.
|
|
116
116
|
if rejected_since(queued): block('The user rejected a related action in this step, so this call was not run. Do not retry it; explain what you would change and ask.')
|
|
@@ -134,6 +134,11 @@ def mlai_run(st):
|
|
|
134
134
|
REJECTED = ('The user rejected this action. Do not make the same change another way (another tool, a shell command or a retry) '
|
|
135
135
|
'and do not claim the permission mode changed. Stop now, say plainly what was not done, and ask the user how to proceed.')
|
|
136
136
|
|
|
137
|
+
def rejected_with(notes):
|
|
138
|
+
return ('The user rejected this action and said what to do instead:\n' + '\n'.join('- ' + n for n in notes) + '\n'
|
|
139
|
+
'This call was not run. Do not repeat it unchanged. Follow the instruction above now (it may need a different '
|
|
140
|
+
'change, which will ask for approval again); do not ask the user how to proceed.')
|
|
141
|
+
|
|
137
142
|
def _wait(request, seconds):
|
|
138
143
|
ident = request['id']
|
|
139
144
|
if request.get('kind') not in ('plan', 'brief'):
|
|
@@ -166,13 +171,17 @@ def _wait(request, seconds):
|
|
|
166
171
|
if verdict not in ('approve', 'approve_all'):
|
|
167
172
|
(ROOT / 'last-reject').write_text(str(time.time()))
|
|
168
173
|
# BUG-0491: "Choose another approach" made the agent retry the same write with Write, printf and touch.
|
|
174
|
+
# A note typed with the rejection ("name it subtract instead") is queued just before the answer; it goes back
|
|
175
|
+
# with the rejection, so the agent acts on it rather than stopping to ask how to proceed.
|
|
176
|
+
notes = steering()
|
|
177
|
+
if notes: block(rejected_with(notes))
|
|
169
178
|
block(REJECTED)
|
|
170
179
|
|
|
171
180
|
def wait_plan(request, seconds=540):
|
|
172
181
|
"""Plan review: returns the raw verdict (approve | approve:0,2 | reject), or None on timeout."""
|
|
173
|
-
import
|
|
182
|
+
from winproc import lock_file
|
|
174
183
|
with (ROOT / 'approval.lock').open('a') as lock:
|
|
175
|
-
|
|
184
|
+
lock_file(lock)
|
|
176
185
|
save('pending.json', request); event('approval', **request)
|
|
177
186
|
decision = ROOT / ('decision-' + request['id']); deadline = time.time() + seconds
|
|
178
187
|
while not decision.exists():
|
|
@@ -540,7 +549,7 @@ def pre(payload, st):
|
|
|
540
549
|
event('note', content='Large task: asked for a plan before editing')
|
|
541
550
|
block('This is a large task. Before editing, write a short plan with TodoList: 3 to 8 items, each a concrete outcome you can verify (a test, a build, a page that renders). Then build it item by item, verifying as you go. This edit was not applied; re-issue it after the plan.')
|
|
542
551
|
failed = st.get('last_failed_check') or 0
|
|
543
|
-
if failed and failed > (st.get('last_edit') or 0) and st.get('diagnosed_for') != failed and 'diagnose' not in nudged:
|
|
552
|
+
if failed and failed > (st.get('last_edit') or 0) and st.get('diagnosed_for') != failed and 'diagnose' not in nudged and not _non_code(st):
|
|
544
553
|
nudged.add('diagnose'); st['nudged'] = sorted(nudged); st['diagnosed_for'] = failed; save_state(st)
|
|
545
554
|
event('note', content='Check failed: asked for a root cause before the fix')
|
|
546
555
|
block('The last check failed. Before changing code, read the failing test or error and the code it exercises, and state the root cause in one sentence. Then make the smallest fix that addresses it and rerun the same check. This edit was not applied; re-issue it if it is still the right fix.')
|
|
@@ -715,6 +724,20 @@ def command_gate(command, st, mode, auto):
|
|
|
715
724
|
for r in rels: grant_area(st, r)
|
|
716
725
|
else: st['scope_ok'] = True; save_state(st)
|
|
717
726
|
|
|
727
|
+
def _non_code(st):
|
|
728
|
+
"""CLI r5: on "Commit changes" a red test is the user's to decide; asking for a root cause and a fix made the agent
|
|
729
|
+
edit the very code it was asked to commit."""
|
|
730
|
+
try:
|
|
731
|
+
import verification
|
|
732
|
+
return verification.non_code_task(st.get('task', ''))
|
|
733
|
+
except Exception: return False
|
|
734
|
+
|
|
735
|
+
def _no_tests(st):
|
|
736
|
+
try:
|
|
737
|
+
import verification
|
|
738
|
+
return verification.no_tests_requested(st.get('task', ''))
|
|
739
|
+
except Exception: return False
|
|
740
|
+
|
|
718
741
|
def ledger_record():
|
|
719
742
|
"""Earlier runs plus this run's own recorded results, and the statements earlier answers made about the code."""
|
|
720
743
|
try:
|
|
@@ -805,7 +828,7 @@ def stop(payload, st):
|
|
|
805
828
|
if open_items and 'todos' not in done:
|
|
806
829
|
done.add('todos'); issues.append('Your todo list still has open items: ' + '; '.join(open_items[:8]) + '. Finish them, or update the list (mark done) and explain in the summary why any item was dropped.')
|
|
807
830
|
last_edit, last_check = st.get('last_edit') or 0, st.get('last_check') or 0
|
|
808
|
-
if code_changed and last_edit and last_check < last_edit and 'verify' not in done:
|
|
831
|
+
if code_changed and last_edit and last_check < last_edit and 'verify' not in done and not _no_tests(st):
|
|
809
832
|
done.add('verify'); issues.append('You changed code (' + ', '.join(code_changed[:6]) + ') but no passing test, build or type check ran after the last edit. Run the relevant check now with Bash and report the real result. If the project has no runnable checks, say exactly that in the final message.')
|
|
810
833
|
if 'verification' not in done:
|
|
811
834
|
try:
|