mlai-code 0.0.0-stage → 0.3.1
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 +12 -2
- package/bin/mlai.mjs +3 -0
- package/package.json +18 -3
- package/src/browser-setup.mjs +77 -0
- package/src/cli-ext.mjs +146 -0
- package/src/cli.mjs +534 -0
- package/src/cloud.mjs +29 -0
- package/src/completion.mjs +159 -0
- package/src/credentials.mjs +54 -0
- package/src/deploy.mjs +134 -0
- package/src/distribution.mjs +373 -0
- package/src/engine-key.mjs +4 -0
- package/src/engine.mjs +167 -0
- package/src/headless.mjs +196 -0
- package/src/home.mjs +22 -0
- package/src/host.mjs +123 -0
- package/src/local-models.mjs +64 -0
- package/src/modes.mjs +38 -0
- package/src/netbox.mjs +97 -0
- package/src/netjail.py +59 -0
- package/src/offline.mjs +98 -0
- package/src/parity.mjs +86 -0
- package/src/project.mjs +68 -0
- package/src/relay.mjs +140 -0
- package/src/render.mjs +73 -0
- package/src/restricted.mjs +47 -0
- package/src/review.mjs +70 -0
- package/src/runner.mjs +127 -0
- package/src/runtime.mjs +75 -0
- package/src/sandbox.mjs +135 -0
- package/src/sdk.mjs +11 -0
- package/src/server.mjs +110 -0
- package/src/session.mjs +290 -0
- package/src/settings.mjs +135 -0
- package/src/shared-data.mjs +3 -0
- package/src/tui/acp.mjs +145 -0
- package/src/tui/agents-cli.mjs +114 -0
- package/src/tui/agents-local.mjs +65 -0
- package/src/tui/ansi.mjs +123 -0
- package/src/tui/app.mjs +710 -0
- package/src/tui/approval.mjs +88 -0
- package/src/tui/bg.mjs +172 -0
- package/src/tui/bgterm.mjs +79 -0
- package/src/tui/chat.mjs +230 -0
- package/src/tui/clipboard.mjs +74 -0
- package/src/tui/cloud-cli.mjs +57 -0
- package/src/tui/cloud-run.mjs +123 -0
- package/src/tui/cmd-agents.mjs +130 -0
- package/src/tui/cmd-auto-review.mjs +94 -0
- package/src/tui/cmd-cloud.mjs +17 -0
- package/src/tui/cmd-config.mjs +104 -0
- package/src/tui/cmd-core.mjs +160 -0
- package/src/tui/cmd-distribution.mjs +15 -0
- package/src/tui/cmd-ecosystem.mjs +169 -0
- package/src/tui/cmd-extensibility.mjs +333 -0
- package/src/tui/cmd-remote.mjs +18 -0
- package/src/tui/cmd-review.mjs +58 -0
- package/src/tui/cmd-session-extra.mjs +152 -0
- package/src/tui/cmd-tui.mjs +200 -0
- package/src/tui/commands.mjs +160 -0
- package/src/tui/custom-commands.mjs +98 -0
- package/src/tui/diff.mjs +60 -0
- package/src/tui/editor.mjs +190 -0
- package/src/tui/ext-state.mjs +16 -0
- package/src/tui/extensions-local.mjs +140 -0
- package/src/tui/files.mjs +72 -0
- package/src/tui/handoff.mjs +110 -0
- package/src/tui/import-setups.mjs +151 -0
- package/src/tui/init.mjs +104 -0
- package/src/tui/keymap.mjs +70 -0
- package/src/tui/keys.mjs +101 -0
- package/src/tui/loop.mjs +75 -0
- package/src/tui/markdown.mjs +118 -0
- package/src/tui/mcp-config.mjs +225 -0
- package/src/tui/mcp-oauth.mjs +162 -0
- package/src/tui/permissions.mjs +189 -0
- package/src/tui/plain.mjs +32 -0
- package/src/tui/plugins-local.mjs +103 -0
- package/src/tui/remote.mjs +125 -0
- package/src/tui/review-cli.mjs +332 -0
- package/src/tui/review-github.mjs +59 -0
- package/src/tui/screen.mjs +60 -0
- package/src/tui/session-ops.mjs +104 -0
- package/src/tui/skills-local.mjs +92 -0
- package/src/tui/snapshots.mjs +87 -0
- package/src/tui/statusline.mjs +98 -0
- package/src/tui/transcript.mjs +116 -0
- package/src/two-words.mjs +36 -0
- package/src/wakeups.mjs +53 -0
- package/src/winenv.mjs +94 -0
- package/src/winsandbox.py +351 -0
- package/src/workspace-api.mjs +621 -0
- package/src/worktree.mjs +128 -0
- package/vendor/client-sdk/controller.cjs +115 -0
- package/vendor/client-sdk/files.cjs +38 -0
- package/vendor/client-sdk/index.cjs +133 -0
- package/vendor/client-sdk/login.cjs +52 -0
- package/vendor/client-sdk/updates.cjs +41 -0
- package/vendor/cloud-cli/mlai.mjs +394 -0
- package/worker/architecture_parse.cjs +23 -0
- package/worker/architecture_worker.py +394 -0
- package/worker/ask_first.py +96 -0
- package/worker/attachment_reader.py +66 -0
- package/worker/background_jobs.py +111 -0
- package/worker/brief_questions.py +56 -0
- package/worker/browser_local.py +49 -0
- package/worker/browser_pane.py +89 -0
- package/worker/browser_tool.py +101 -0
- package/worker/build_planner.py +187 -0
- package/worker/chat_fork.py +277 -0
- package/worker/checkpoints.py +133 -0
- package/worker/cloud_pty.py +351 -0
- package/worker/command_policy.py +39 -0
- package/worker/command_safety.py +717 -0
- package/worker/computer_card.sh +23 -0
- package/worker/computer_setup.sh +86 -0
- package/worker/computer_use.py +221 -0
- package/worker/connector_search.py +43 -0
- package/worker/context_manager.py +60 -0
- package/worker/conversation.py +144 -0
- package/worker/deploy_pack.py +116 -0
- package/worker/design_director.py +240 -0
- package/worker/dev_jobs.py +166 -0
- package/worker/edit_guard.py +99 -0
- package/worker/env_setup.py +129 -0
- package/worker/evidence.py +109 -0
- package/worker/fast_search.py +24 -0
- package/worker/git_sync.py +333 -0
- package/worker/goals.py +156 -0
- package/worker/handover.py +98 -0
- package/worker/harness_memory.py +194 -0
- package/worker/image_generation.py +173 -0
- package/worker/intelligence.py +149 -0
- package/worker/intent_model.py +78 -0
- package/worker/intent_weights.json +1 -0
- package/worker/ios_simulator.py +87 -0
- package/worker/kimi_bridge.py +997 -0
- package/worker/kimi_compact.py +93 -0
- package/worker/kimi_gates.py +304 -0
- package/worker/kimi_hook.py +617 -0
- package/worker/lifecycle.py +95 -0
- package/worker/lsp.py +77 -0
- package/worker/mcp_local.py +293 -0
- package/worker/memory.py +99 -0
- package/worker/mlai_auto_review.py +177 -0
- package/worker/mlai_hooks.py +966 -0
- package/worker/mlai_mcp.py +441 -0
- package/worker/mlai_permissions.py +283 -0
- package/worker/model_stream.py +75 -0
- package/worker/nested_repos.py +76 -0
- package/worker/offline_guard.py +17 -0
- package/worker/preview.py +806 -0
- package/worker/proc_watch.py +124 -0
- package/worker/project_context.py +72 -0
- package/worker/project_rules.py +99 -0
- package/worker/quality.py +180 -0
- package/worker/reply_language.py +56 -0
- package/worker/repo_hygiene.py +132 -0
- package/worker/repo_memory.py +101 -0
- package/worker/repo_policy.py +269 -0
- package/worker/roles.json +3173 -0
- package/worker/roles.py +303 -0
- package/worker/runner.py +1795 -0
- package/worker/runtime_control.py +205 -0
- package/worker/secret_scan.py +168 -0
- package/worker/session_hub.py +80 -0
- package/worker/skill_library.py +129 -0
- package/worker/skill_pack.py +533 -0
- package/worker/subagents.py +91 -0
- package/worker/task_controller.py +139 -0
- package/worker/task_skills.py +159 -0
- package/worker/team_checkpoint.py +33 -0
- package/worker/token_count.py +32 -0
- package/worker/tool_catalog.py +38 -0
- package/worker/upload_storage.py +531 -0
- package/worker/verification.py +725 -0
- package/worker/vision.py +84 -0
- package/worker/wakeups.py +63 -0
- package/worker/web_tools.py +203 -0
- package/worker/winproc.py +135 -0
- package/worker/work_ledger.py +117 -0
- package/worker/worktrees.py +79 -0
|
@@ -0,0 +1,617 @@
|
|
|
1
|
+
"""Kimi Code hook for ML AI Code. One script, called as `kimi_hook.py <EventName>` with the event JSON on stdin.
|
|
2
|
+
|
|
3
|
+
PreToolUse: user steering, stop requests, the last-five-minutes rule, repeated-call detection, offline-network policy,
|
|
4
|
+
syntax guard for Write/Edit and Guided-mode approvals through the app's pending.json/decision files.
|
|
5
|
+
Stop: delivers pending steering and the done gate (open todos, unverified code changes, required patch, role done-check).
|
|
6
|
+
Exit 2 blocks with the stderr text as the reason; exit 0 allows. Kimi fails open on crashes, so every block is explicit
|
|
7
|
+
and every wait ends before the hook timeout."""
|
|
8
|
+
import json, os, sys, time, hashlib, re
|
|
9
|
+
try:
|
|
10
|
+
from brief_questions import normalize as normalize_questions
|
|
11
|
+
except ImportError:
|
|
12
|
+
def normalize_questions(raw): return [str(q).strip()[:300] for q in raw if str(q).strip()][:6]
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
|
15
|
+
ROOT = Path(os.getenv('MINI_ROOT', '/vercel/sandbox/.mini'))
|
|
16
|
+
REPO = os.getenv('MINI_REPO', '/vercel/sandbox/repo')
|
|
17
|
+
ACCEPTANCE = str(ROOT / 'acceptance')
|
|
18
|
+
HIDDEN = re.compile(r'\.mini/acceptance|test_acceptance\.py|acceptance\.test\.mjs')
|
|
19
|
+
|
|
20
|
+
INSPECT_BLOCK = ('The user asked for no changes in this turn, so files are not edited and nothing is installed or written. '
|
|
21
|
+
'Keep investigating with reads and test commands, then report each finding with its evidence and the fix you recommend, and ask for approval before fixing.')
|
|
22
|
+
|
|
23
|
+
def load(name, default):
|
|
24
|
+
try: return json.loads((ROOT / name).read_text())
|
|
25
|
+
except (OSError, ValueError): return default
|
|
26
|
+
|
|
27
|
+
def save(name, data):
|
|
28
|
+
tmp = ROOT / (name + '.tmp'); tmp.write_text(json.dumps(data)); tmp.replace(ROOT / name)
|
|
29
|
+
|
|
30
|
+
def event(event_type, **data):
|
|
31
|
+
with (ROOT / 'events.jsonl').open('a') as f: f.write(json.dumps({'type': event_type, 'time': time.time(), **data}) + '\n')
|
|
32
|
+
|
|
33
|
+
HOOK_KEYS = ('recent', 'landed', 'stuck_warned', 'gates_done', 'planned', 'plan_reviewed', 'plan_dismissed', 'brief_ok', 'brief_rounds', 'brief_nudged', 'mode', 'nudged', 'diagnosed_for', 'scope', 'scope_ok', 'approved_kinds', 'calls', 'agents', 'budget_warned', 'touched', 'policy_noted', 'policy_ok_paths', 'token_stage', 'account_stop', 'account_stop_at')
|
|
34
|
+
def save_state(st):
|
|
35
|
+
"""The hook owns only these keys; the bridge owns kimi-state.json (static) and kimi-progress.json."""
|
|
36
|
+
save('kimi-hook.json', {k: st[k] for k in HOOK_KEYS if k in st})
|
|
37
|
+
|
|
38
|
+
def state():
|
|
39
|
+
return {**load('kimi-state.json', {}), **load('kimi-progress.json', {}), **load('kimi-hook.json', {})}
|
|
40
|
+
|
|
41
|
+
def block(reason):
|
|
42
|
+
sys.stderr.write(reason); sys.stderr.flush(); sys.exit(2)
|
|
43
|
+
|
|
44
|
+
def steering():
|
|
45
|
+
"""Consume queued user instructions (oldest first)."""
|
|
46
|
+
d = ROOT / 'steering'
|
|
47
|
+
if not d.is_dir(): return []
|
|
48
|
+
out = []
|
|
49
|
+
for f in sorted(d.glob('*.json')):
|
|
50
|
+
try: msg = json.loads(f.read_text()).get('message', '')
|
|
51
|
+
except (OSError, ValueError): msg = ''
|
|
52
|
+
f.unlink(missing_ok=True)
|
|
53
|
+
if isinstance(msg, str) and msg.strip(): out.append(msg.strip()[:5000])
|
|
54
|
+
for m in out: event('steering', content=m)
|
|
55
|
+
return out
|
|
56
|
+
|
|
57
|
+
def platform_notes():
|
|
58
|
+
"""Notices from the platform itself (for example a hung process it stopped), oldest first."""
|
|
59
|
+
d = ROOT / 'platform-notes'
|
|
60
|
+
if not d.is_dir(): return []
|
|
61
|
+
out = []
|
|
62
|
+
for f in sorted(d.glob('*.json')):
|
|
63
|
+
try: msg = json.loads(f.read_text()).get('message', '')
|
|
64
|
+
except (OSError, ValueError): msg = ''
|
|
65
|
+
f.unlink(missing_ok=True)
|
|
66
|
+
if isinstance(msg, str) and msg.strip(): out.append(msg.strip()[:3000])
|
|
67
|
+
return out
|
|
68
|
+
|
|
69
|
+
def steer_block(messages, stopping=False):
|
|
70
|
+
text = '\n'.join('- ' + m for m in messages)
|
|
71
|
+
block(('The user sent a new instruction while you were working:\n' + text + '\n' + ('Apply it now, then finish.' if stopping else 'This tool call was not run. Take the instruction into account, then continue (re-issue the call only if it is still right).')))
|
|
72
|
+
|
|
73
|
+
def wait_decision(request, seconds=540, strict=False):
|
|
74
|
+
"""One approval at a time even when Kimi runs tool calls in parallel. Strict (repository policy) reviews ignore "Approve all"."""
|
|
75
|
+
import fcntl
|
|
76
|
+
with (ROOT / 'approval.lock').open('a') as lock:
|
|
77
|
+
fcntl.flock(lock, fcntl.LOCK_EX)
|
|
78
|
+
if not strict and (ROOT / 'kimi-approve-all').exists(): return
|
|
79
|
+
_wait(request, seconds)
|
|
80
|
+
|
|
81
|
+
def user_hooks(fn, *args):
|
|
82
|
+
"""Project hooks and hard-deny rules (mlai_hooks). They fail open on an internal error, like the rest of this hook."""
|
|
83
|
+
try:
|
|
84
|
+
import mlai_hooks
|
|
85
|
+
return getattr(mlai_hooks, fn)(*args)
|
|
86
|
+
except Exception: return None
|
|
87
|
+
|
|
88
|
+
def mlai_run(st):
|
|
89
|
+
return user_hooks('kimi_run', st) or {}
|
|
90
|
+
|
|
91
|
+
def _wait(request, seconds):
|
|
92
|
+
ident = request['id']
|
|
93
|
+
if request.get('kind') not in ('plan', 'brief'):
|
|
94
|
+
verdict = user_hooks('approval', request) or (None, '')
|
|
95
|
+
if verdict[0] == 'deny': block(verdict[1])
|
|
96
|
+
if verdict[0] == 'allow': return
|
|
97
|
+
save('pending.json', request); event('approval', **request)
|
|
98
|
+
decision = ROOT / ('decision-' + ident)
|
|
99
|
+
deadline = time.time() + seconds
|
|
100
|
+
while not decision.exists():
|
|
101
|
+
if (ROOT / 'cancel').exists(): (ROOT / 'pending.json').unlink(missing_ok=True); block('Task stopped by user.')
|
|
102
|
+
if time.time() > deadline:
|
|
103
|
+
(ROOT / 'pending.json').unlink(missing_ok=True); event('note', content='Approval timed out')
|
|
104
|
+
block('The user did not answer the approval request in time. Do not retry this action; summarize what is waiting for approval and finish.')
|
|
105
|
+
time.sleep(0.4)
|
|
106
|
+
verdict = decision.read_text().strip(); decision.unlink(missing_ok=True); (ROOT / 'pending.json').unlink(missing_ok=True)
|
|
107
|
+
if verdict == 'approve_all':
|
|
108
|
+
(ROOT / 'kimi-approve-all').write_text('1'); event('mode', mode='auto', content='Approved all remaining steps for this task.')
|
|
109
|
+
if verdict not in ('approve', 'approve_all'):
|
|
110
|
+
block('The user rejected this action. Choose another approach or explain what you need.')
|
|
111
|
+
|
|
112
|
+
def wait_plan(request, seconds=540):
|
|
113
|
+
"""Plan review: returns the raw verdict (approve | approve:0,2 | reject), or None on timeout."""
|
|
114
|
+
import fcntl
|
|
115
|
+
with (ROOT / 'approval.lock').open('a') as lock:
|
|
116
|
+
fcntl.flock(lock, fcntl.LOCK_EX)
|
|
117
|
+
save('pending.json', request); event('approval', **request)
|
|
118
|
+
decision = ROOT / ('decision-' + request['id']); deadline = time.time() + seconds
|
|
119
|
+
while not decision.exists():
|
|
120
|
+
if (ROOT / 'cancel').exists(): (ROOT / 'pending.json').unlink(missing_ok=True); block('Task stopped by user.')
|
|
121
|
+
if time.time() > deadline: (ROOT / 'pending.json').unlink(missing_ok=True); return None
|
|
122
|
+
time.sleep(0.4)
|
|
123
|
+
verdict = decision.read_text().strip(); decision.unlink(missing_ok=True); (ROOT / 'pending.json').unlink(missing_ok=True)
|
|
124
|
+
return verdict
|
|
125
|
+
|
|
126
|
+
def briefing(st):
|
|
127
|
+
"""Brief mode before the user has approved a task list: read-only, every TodoList opens a review."""
|
|
128
|
+
return bool(st.get('brief')) and not st.get('brief_ok') and not st.get('plan_dismissed')
|
|
129
|
+
|
|
130
|
+
def brief_unlock(st):
|
|
131
|
+
back = st.get('brief_return') if st.get('brief_return') in ('approve', 'auto') else 'approve'
|
|
132
|
+
st['brief_ok'] = True; st['mode'] = back; st['scope_ok'] = True; save_state(st)
|
|
133
|
+
event('mode', mode=back, content='Plan agreed. Building the approved list in %s mode.' % ('Auto' if back == 'auto' else 'Guided'))
|
|
134
|
+
|
|
135
|
+
def plan_gate(args, st):
|
|
136
|
+
"""First task list of a run: optional user review (Guided mode by default, or always when the user asked).
|
|
137
|
+
Brief mode: every task list is reviewed until the user approves; replies come back to the agent as feedback."""
|
|
138
|
+
items = [str(t.get('title', '')).strip()[:300] for t in (args.get('todos') or []) if isinstance(t, dict)]
|
|
139
|
+
items = [i for i in items if i]
|
|
140
|
+
first = not st.get('planned')
|
|
141
|
+
brief = briefing(st)
|
|
142
|
+
st['planned'] = True; save_state(st)
|
|
143
|
+
policy = st.get('plan_approval') or 'guided'
|
|
144
|
+
wants = brief or policy == 'always' or (policy == 'guided' and st.get('mode') == 'approve')
|
|
145
|
+
if brief:
|
|
146
|
+
if len(items) < 2: block('Brief mode: the task list needs at least two concrete items before the user can review it. Call TodoList again with the full plan.')
|
|
147
|
+
elif not first or st.get('readonly') or st.get('plan_reviewed') or len(items) < 2 or not wants or (ROOT / 'kimi-approve-all').exists(): return
|
|
148
|
+
st['plan_reviewed'] = True
|
|
149
|
+
rounds = int(st.get('brief_rounds') or 0) + 1
|
|
150
|
+
if brief: st['brief_rounds'] = rounds
|
|
151
|
+
save_state(st)
|
|
152
|
+
request = {'id': os.urandom(8).hex(), 'kind': 'plan', 'items': items, 'command': 'Review the task list:\n' + '\n'.join('- ' + t for t in items)}
|
|
153
|
+
if brief:
|
|
154
|
+
request['brief'] = True; request['round'] = rounds
|
|
155
|
+
if rounds == 1 and st.get('look'):
|
|
156
|
+
request['look'] = True # small optional look cards under the first plan, once
|
|
157
|
+
try: industry = ' '.join((ROOT / 'kimi-brief-industry.txt').read_text().split())[:80]
|
|
158
|
+
except OSError: industry = ''
|
|
159
|
+
if industry: request['industry'] = industry # the agent's own read of the product; the client matches sites to it
|
|
160
|
+
questions = normalize_questions(load('kimi-brief-questions.json', []) or [])
|
|
161
|
+
if questions: request['questions'] = questions
|
|
162
|
+
(ROOT / 'kimi-brief-questions.json').unlink(missing_ok=True) # shown with this review; not repeated after the reply
|
|
163
|
+
verdict = wait_plan(request, seconds=1500 if brief else 540)
|
|
164
|
+
if verdict is None:
|
|
165
|
+
event('plan_review', content='Plan review timed out')
|
|
166
|
+
st['plan_dismissed'] = True; save_state(st)
|
|
167
|
+
block('The user did not review the task list in time. Do not start the work. Summarize the proposed plan in your final message and finish, so the user can approve it later.')
|
|
168
|
+
if verdict.startswith('revise:'):
|
|
169
|
+
reply = verdict[7:].strip()[:2000]
|
|
170
|
+
st['plan_reviewed'] = False; st['planned'] = False; save_state(st)
|
|
171
|
+
event('plan_review', content='User replied: ' + reply[:160])
|
|
172
|
+
(ROOT / 'kimi-brief-questions.json').unlink(missing_ok=True)
|
|
173
|
+
block('The user replied to your plan: "' + reply + '"\nAnswer briefly if they asked something, then call TodoList again with the revised task list (3 to 10 items) and, if anything is still open, record your questions with mcp__mlai__brief_questions {"questions": [...]} before the TodoList. Nothing is built until they approve.')
|
|
174
|
+
if verdict in ('approve', 'approve_all'):
|
|
175
|
+
if brief: brief_unlock(st)
|
|
176
|
+
st['scope_ok'] = True; save_state(st); event('plan_review', content='Plan approved'); return
|
|
177
|
+
if verdict.startswith('approve:'):
|
|
178
|
+
keep = {int(x) for x in verdict[8:].split(',') if x.strip().isdigit()}
|
|
179
|
+
kept = [t for i, t in enumerate(items) if i in keep]; removed = [t for i, t in enumerate(items) if i not in keep]
|
|
180
|
+
if kept:
|
|
181
|
+
if brief: brief_unlock(st)
|
|
182
|
+
event('plan_review', content='%d of %d tasks approved' % (len(kept), len(items)))
|
|
183
|
+
block('The user approved only part of the task list.\nApproved: ' + '; '.join(kept) + '\nRemoved (keep these out of scope; do not do them): ' + '; '.join(removed) + '\nCall TodoList again with only the approved items, then build.')
|
|
184
|
+
event('plan_review', content='Plan dismissed')
|
|
185
|
+
st['plan_dismissed'] = True; save_state(st)
|
|
186
|
+
block('The user dismissed this task list. Do not start the work. Briefly ask what they want changed, then finish.')
|
|
187
|
+
|
|
188
|
+
def resolve(path):
|
|
189
|
+
p = Path(path)
|
|
190
|
+
return p if p.is_absolute() else Path(REPO) / p
|
|
191
|
+
|
|
192
|
+
# ---------------------------------------------------------------- repository policy and secret scanning
|
|
193
|
+
def policy():
|
|
194
|
+
"""The repository's .mlai/policy.yml merged with account rules; None when the policy module is unavailable."""
|
|
195
|
+
try:
|
|
196
|
+
from repo_policy import load_policy
|
|
197
|
+
return load_policy(REPO, ROOT)
|
|
198
|
+
except Exception:
|
|
199
|
+
return None
|
|
200
|
+
|
|
201
|
+
def policy_event(rule, decision, content, **data):
|
|
202
|
+
event('policy', rule=str(rule)[:200], decision=decision, content=content[:600], **data)
|
|
203
|
+
|
|
204
|
+
def account_gate(st, name):
|
|
205
|
+
"""Account allowance (LIMIT/BILL): once the plan's tokens are used, no new work starts; the agent summarizes."""
|
|
206
|
+
left = st.get('account_left')
|
|
207
|
+
if left is None or name in ('TodoList', 'WaitFor', 'TaskOutput', 'TaskList'): return
|
|
208
|
+
used = load('usage.json', {}).get('tokens') or 0
|
|
209
|
+
# Every tool stops at the allowance (reads too): more reads only burned credits while the screen looked stuck.
|
|
210
|
+
if used >= left:
|
|
211
|
+
if not st.get('account_stop'):
|
|
212
|
+
st['account_stop'] = True; st['account_stop_at'] = time.time(); save_state(st)
|
|
213
|
+
event('account_limit', phase='wrapping', content='Credits used up. The agent is writing a short summary and will stop.')
|
|
214
|
+
block('Your account has used all its credits. Do not start new work or call more tools. Write the final summary now in plain text: what changed, '
|
|
215
|
+
'what was verified, what is left. The user can continue after picking a plan or buying a top-up. This call was not run.')
|
|
216
|
+
|
|
217
|
+
def token_gate(pol, st, name):
|
|
218
|
+
"""Per-task token budget from policy: at 80% wrap up (Plan-style, no new work), at 100% stop and summarize."""
|
|
219
|
+
account_gate(st, name)
|
|
220
|
+
limit = (pol or {}).get('agent', {}).get('max_tokens_per_run') or 0
|
|
221
|
+
if not limit or name in ('TodoList', 'WaitFor', 'TaskOutput', 'TaskList'): return
|
|
222
|
+
u = load('usage.json', {}); used = u.get('raw') or u.get('tokens') or 0
|
|
223
|
+
stage = st.get('token_stage') or 0
|
|
224
|
+
if used >= limit and name in ('Write', 'Edit', 'Bash', 'Agent', 'AgentSwarm'):
|
|
225
|
+
if stage < 2: st['token_stage'] = 2; save_state(st); policy_event('max_tokens_per_run', 'stop', 'Token budget reached (%s of %s); stopping new work' % (format(used, ','), format(limit, ',')))
|
|
226
|
+
block('This repository caps a task at %s tokens and the budget is used up. Do not start new work. Write the final summary now: what changed, what was verified, what is left and the exact next step, so the task can be resumed.' % format(limit, ','))
|
|
227
|
+
if used >= 0.8 * limit and stage < 1 and name in ('Write', 'Edit', 'Bash', 'Agent', 'AgentSwarm'):
|
|
228
|
+
st['token_stage'] = 1; save_state(st); policy_event('max_tokens_per_run', 'warn', '80%% of the token budget used (%s of %s)' % (format(used, ','), format(limit, ',')))
|
|
229
|
+
block('80%% of this task\'s token budget is used (%s of %s, set by repository policy). Finish only the change in progress, run one focused check, then summarize. Do not start anything new. This call was not run; re-issue it only if it lands the current change.' % (format(used, ','), format(limit, ',')))
|
|
230
|
+
|
|
231
|
+
def secret_gate(name, args, rel, pol):
|
|
232
|
+
"""Never write a credential into the repository. The agent is told to read it from the environment instead."""
|
|
233
|
+
if pol is not None and not pol['secrets']['scan']: return
|
|
234
|
+
try:
|
|
235
|
+
from secret_scan import findings_for, describe
|
|
236
|
+
from repo_policy import path_matches
|
|
237
|
+
except Exception: return
|
|
238
|
+
if pol is not None and pol['secrets']['ignore_paths'] and path_matches(rel, pol['secrets']['ignore_paths']): return
|
|
239
|
+
text = str(args.get('content', '')) if name == 'Write' else str(args.get('new_string', ''))
|
|
240
|
+
found = findings_for(rel, text, tuple((pol or {}).get('secrets', {}).get('allow') or ()))
|
|
241
|
+
if not found: return
|
|
242
|
+
f = found[0]
|
|
243
|
+
event('secret_block', path=rel[:200], kind=f['kind'], name=f['name'], content='Blocked: ' + describe(f) + ' (' + f['preview'] + ')')
|
|
244
|
+
block('Blocked: this ' + name + ' would write ' + describe(f) + ' into the repository. Credentials never go into files or commits. '
|
|
245
|
+
'Read it from an environment variable instead (for example process.env.' + f['name'] + ' or os.environ["' + f['name'] + '"]), '
|
|
246
|
+
'add the name to .env.example with an empty value, and tell the user to store the real value in the Vault as ' + f['name'] + '. Re-issue the edit without the literal value.')
|
|
247
|
+
|
|
248
|
+
def protected_path_gate(name, args, rel, pol, st):
|
|
249
|
+
"""Paths the policy marks for review always ask, even in Auto mode (once per file per task)."""
|
|
250
|
+
if pol is None or rel.startswith('..'): return
|
|
251
|
+
from repo_policy import path_matches
|
|
252
|
+
pat = path_matches(rel, pol['production']['block_paths_without_review'])
|
|
253
|
+
if not pat: return
|
|
254
|
+
ok = list(st.get('policy_ok_paths') or [])
|
|
255
|
+
if rel in ok: return
|
|
256
|
+
policy_event(pat, 'ask', 'Protected path ' + rel + ' needs review (' + pat + ')', path=rel[:200])
|
|
257
|
+
wait_decision({'id': os.urandom(8).hex(), 'kind': 'scope', 'area': rel, 'policy': pat, 'reason': 'Repository policy: ' + pat + ' is reviewed by a person before it changes',
|
|
258
|
+
'command': name + ' ' + rel + '\n' + (str(args.get('content', ''))[:6000] if name == 'Write' else 'REMOVE:\n' + str(args.get('old_string', ''))[:4000] + '\nREPLACE WITH:\n' + str(args.get('new_string', ''))[:4000])}, strict=True)
|
|
259
|
+
st['policy_ok_paths'] = (ok + [rel])[-80:]; save_state(st)
|
|
260
|
+
|
|
261
|
+
def command_policy_gate(command, pol, st, mode, auto):
|
|
262
|
+
"""Repository command rules and network allowlist. Returns True when the policy allows the command outright."""
|
|
263
|
+
if pol is None: return False
|
|
264
|
+
from repo_policy import command_rule, network_hosts_outside
|
|
265
|
+
rule, pat = command_rule(command, pol)
|
|
266
|
+
if rule == 'deny':
|
|
267
|
+
policy_event(pat, 'deny', 'Refused by policy: ' + command[:300], command=command[:300])
|
|
268
|
+
block('Refused by repository policy (rule "' + pat + '"). This command never runs here, in any mode. Use a contained alternative; publishing and deploys go through the product\'s release and deploy approvals.')
|
|
269
|
+
hosts = network_hosts_outside(command, pol)
|
|
270
|
+
if hosts:
|
|
271
|
+
policy_event('network allowlist', 'ask', 'Outside the network allowlist: ' + ', '.join(hosts[:5]), command=command[:300])
|
|
272
|
+
wait_decision({'id': os.urandom(8).hex(), 'kind': 'command', 'effect': 'network', 'policy': 'network allowlist', 'reason': 'Repository policy: ' + ', '.join(hosts[:5]) + ' is not on the network allowlist', 'command': command[:20000]}, strict=True)
|
|
273
|
+
if rule == 'allow' and mode == 'approve' and not briefing(st):
|
|
274
|
+
from command_safety import classify, decide
|
|
275
|
+
verdict = classify(command, REPO, cwd=REPO, home=os.path.dirname(REPO))
|
|
276
|
+
d = decide(verdict, 'auto', scope=None, approved_kinds=[], approve_all=False, repo=REPO, cwd=REPO)
|
|
277
|
+
if d['decision'] == 'allow':
|
|
278
|
+
policy_event(pat, 'allow', 'Allowed by policy: ' + command[:300], command=command[:300]); return True
|
|
279
|
+
return False
|
|
280
|
+
|
|
281
|
+
def pre(payload, st):
|
|
282
|
+
name = str(payload.get('tool_name') or '')
|
|
283
|
+
args = payload.get('tool_input') or {}
|
|
284
|
+
if not isinstance(args, dict): args = {}
|
|
285
|
+
if (ROOT / 'cancel').exists(): block('Task stopped by user.')
|
|
286
|
+
hooked = user_hooks('kimi_pre', name, args, st) # hard-deny, credential block, before_tool / before_command hooks
|
|
287
|
+
if hooked: block(hooked)
|
|
288
|
+
queued = steering()
|
|
289
|
+
if queued: steer_block(queued)
|
|
290
|
+
notes = platform_notes()
|
|
291
|
+
if notes: block('Platform notice:\n' + '\n'.join('- ' + n for n in notes) + '\nThis tool call was not run. Take the notice into account, then continue.')
|
|
292
|
+
now = time.time()
|
|
293
|
+
if st.get('land_at') and now > st['land_at'] and not st.get('landed') and not st.get('readonly'):
|
|
294
|
+
st['landed'] = True; save_state(st)
|
|
295
|
+
event('note', content='Five minutes left: landing the change')
|
|
296
|
+
block('Time check: about five minutes remain for this task. Stop exploring. Finish the change in progress, run one focused check, and write the final summary (what changed, how it was verified, what is left). This call was not run; re-issue it only if it is needed to land the change.')
|
|
297
|
+
sig = hashlib.sha1((name + json.dumps(args, sort_keys=True)).encode()).hexdigest()[:16]
|
|
298
|
+
recent = (st.get('recent') or [])[-5:] + [sig]
|
|
299
|
+
st['recent'] = recent
|
|
300
|
+
warned = set(st.get('stuck_warned') or [])
|
|
301
|
+
if recent.count(sig) >= 3 and sig not in warned and name not in ('TodoList', 'WaitFor', 'TaskOutput', 'TaskList'):
|
|
302
|
+
warned.add(sig); st['stuck_warned'] = sorted(warned); save_state(st)
|
|
303
|
+
event('note', content='Repeated call detected; asked the agent to change approach')
|
|
304
|
+
block('You have made this exact call three times recently. Repeating it will not give new information. Step back: re-read the latest error, form one hypothesis about the root cause, and take a different action.')
|
|
305
|
+
save_state(st)
|
|
306
|
+
if ACCEPTANCE in json.dumps(args) or HIDDEN.search(json.dumps(args)): block('That path holds the independent acceptance check, which is hidden from the builder by design. Work from the task and the failure output instead.')
|
|
307
|
+
if name == 'TodoList': return plan_gate(args, st)
|
|
308
|
+
writes = name in ('Write', 'Edit', 'Bash', 'Agent', 'AgentSwarm')
|
|
309
|
+
if writes and st.get('plan_dismissed'): block('The user dismissed the task list, so no work may start. Ask what they want changed and finish.')
|
|
310
|
+
if briefing(st) and name in ('Write', 'Edit', 'Agent', 'AgentSwarm'):
|
|
311
|
+
block('Brief mode: nothing is built until the user approves your task list. Read the repository, then call TodoList with the proposed items and state your open questions. This call was not run.')
|
|
312
|
+
if st.get('inspect') and name in ('Write', 'Edit', 'Agent', 'AgentSwarm'):
|
|
313
|
+
event('safety', effect='write', decision='deny', command=name + ' ' + str(args.get('path', ''))[:300], content='Refused: the user asked for no changes in this turn')
|
|
314
|
+
block(INSPECT_BLOCK)
|
|
315
|
+
if name in ('Write', 'Edit') and not st.get('readonly'):
|
|
316
|
+
nudged = set(st.get('nudged') or [])
|
|
317
|
+
if st.get('large') and not st.get('planned') and 'plan' not in nudged:
|
|
318
|
+
nudged.add('plan'); st['nudged'] = sorted(nudged); save_state(st)
|
|
319
|
+
event('note', content='Large task: asked for a plan before editing')
|
|
320
|
+
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.')
|
|
321
|
+
failed = st.get('last_failed_check') or 0
|
|
322
|
+
if failed and failed > (st.get('last_edit') or 0) and st.get('diagnosed_for') != failed and 'diagnose' not in nudged:
|
|
323
|
+
nudged.add('diagnose'); st['nudged'] = sorted(nudged); st['diagnosed_for'] = failed; save_state(st)
|
|
324
|
+
event('note', content='Check failed: asked for a root cause before the fix')
|
|
325
|
+
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.')
|
|
326
|
+
pol = policy()
|
|
327
|
+
mode = st.get('mode', 'approve')
|
|
328
|
+
if pol is not None:
|
|
329
|
+
from repo_policy import clamp_mode
|
|
330
|
+
allowed = clamp_mode(mode, pol)
|
|
331
|
+
if allowed != mode:
|
|
332
|
+
if not st.get('policy_noted'):
|
|
333
|
+
st['policy_noted'] = True; save_state(st)
|
|
334
|
+
policy_event('modes_allowed', 'clamp', 'Repository policy allows ' + ', '.join(pol['agent']['modes_allowed']) + '; running with ' + {'approve': 'Guided'}.get(allowed, allowed.title()) + ' approvals')
|
|
335
|
+
mode = allowed
|
|
336
|
+
auto = mode == 'auto' or (ROOT / 'kimi-approve-all').exists()
|
|
337
|
+
runaway(name, args, st)
|
|
338
|
+
token_gate(pol, st, name)
|
|
339
|
+
if name == 'Bash':
|
|
340
|
+
command = str(args.get('command', ''))
|
|
341
|
+
try:
|
|
342
|
+
from command_policy import offline_network_wait_reason
|
|
343
|
+
reason = offline_network_wait_reason(command, st.get('task', ''))
|
|
344
|
+
except Exception: reason = None
|
|
345
|
+
if reason: event('retry', content=reason); block(reason)
|
|
346
|
+
masked = pipe_gate(command)
|
|
347
|
+
if masked: event('note', content='Check would report a later command\'s exit status; asked for pipefail'); block(masked)
|
|
348
|
+
if command_policy_gate(command, pol, st, mode, auto): return
|
|
349
|
+
return command_gate(command, st, mode, auto)
|
|
350
|
+
if name in ('Write', 'Edit'):
|
|
351
|
+
target = resolve(str(args.get('path', '')))
|
|
352
|
+
try: original = target.read_text() if target.is_file() else ''
|
|
353
|
+
except (OSError, UnicodeDecodeError): original = None
|
|
354
|
+
after = None
|
|
355
|
+
if original is not None:
|
|
356
|
+
if name == 'Write': after = (original + str(args.get('content', ''))) if args.get('mode') == 'append' else str(args.get('content', ''))
|
|
357
|
+
else:
|
|
358
|
+
old, new = str(args.get('old_string', '')), str(args.get('new_string', ''))
|
|
359
|
+
if old and old in original: after = original.replace(old, new) if args.get('replace_all') else original.replace(old, new, 1)
|
|
360
|
+
rel = os.path.relpath(str(target), REPO)
|
|
361
|
+
if not rel.startswith('..'): secret_gate(name, args, rel, pol)
|
|
362
|
+
if after is not None:
|
|
363
|
+
try:
|
|
364
|
+
from edit_guard import gate
|
|
365
|
+
problem = gate(rel, original, after, REPO) if not rel.startswith('..') else None
|
|
366
|
+
except Exception: problem = None
|
|
367
|
+
if problem: event('edit_guard', path=str(args.get('path', ''))[:200], content=problem[:600]); block(problem)
|
|
368
|
+
protected_path_gate(name, args, rel, pol, st)
|
|
369
|
+
return edit_gate(name, args, rel, str(target), st, auto)
|
|
370
|
+
if name in ('Agent', 'AgentSwarm') and not auto:
|
|
371
|
+
wait_decision({'id': os.urandom(8).hex(), 'command': 'Start helper agent: ' + str(args.get('description') or args.get('prompt') or '')[:4000]})
|
|
372
|
+
|
|
373
|
+
def pipe_gate(command):
|
|
374
|
+
"""EXEC-001: `npm test | tail` passes when tail succeeds. Ask for a form whose exit status is the runner's."""
|
|
375
|
+
try:
|
|
376
|
+
import verification
|
|
377
|
+
if not verification.masked_pipe(command, verification.looks_like_check): return None
|
|
378
|
+
except Exception: return None
|
|
379
|
+
return ('This check would report the exit status of a later pipe stage or command, so a failing test could look like a pass. '
|
|
380
|
+
'Re-issue it so the test runner\'s status is the command\'s status, for example: set -o pipefail; ' + command.strip()[:400] +
|
|
381
|
+
' (and drop any `|| true`, `|| echo`, or `; ...` after the runner). This call was not run.')
|
|
382
|
+
|
|
383
|
+
# ---------------------------------------------------------------- scope, command safety and runaway protection
|
|
384
|
+
CALL_WINDOW, CALL_BUDGET = 60, 48 # tool calls per minute before the agent must stop and think
|
|
385
|
+
AGENT_WINDOW, AGENT_BUDGET = 900, 10 # helper agents started per 15 minutes
|
|
386
|
+
|
|
387
|
+
def runaway(name, args, st):
|
|
388
|
+
"""Per-window tool-call budget and helper-agent breadth cap (Pixis tool-call guard). Each fires once per window."""
|
|
389
|
+
now = time.time()
|
|
390
|
+
calls = [t for t in (st.get('calls') or []) if now - t < CALL_WINDOW] + [now]
|
|
391
|
+
st['calls'] = calls[-(CALL_BUDGET + 10):]
|
|
392
|
+
if name in ('Agent', 'AgentSwarm'):
|
|
393
|
+
agents = [t for t in (st.get('agents') or []) if now - t < AGENT_WINDOW]
|
|
394
|
+
if len(agents) >= AGENT_BUDGET:
|
|
395
|
+
save_state(st); event('note', content='Helper agent limit reached (%d in 15 minutes)' % AGENT_BUDGET)
|
|
396
|
+
block('You already started %d helper agents in the last 15 minutes. Wait for them to finish and use their results (WaitFor/TaskOutput) before starting more.' % AGENT_BUDGET)
|
|
397
|
+
st['agents'] = agents + [now]
|
|
398
|
+
if len(calls) > CALL_BUDGET and (now - (st.get('budget_warned') or 0)) > CALL_WINDOW and name not in ('WaitFor', 'TaskOutput', 'TaskList'):
|
|
399
|
+
st['budget_warned'] = now; save_state(st)
|
|
400
|
+
event('note', content='Tool-call budget reached (%d calls in %d s); asked the agent to pause and summarize' % (len(calls), CALL_WINDOW))
|
|
401
|
+
block('You made %d tool calls in the last minute. Stop and think before acting again: write down what you learned, what the goal is and the next single step. Then continue with fewer, more targeted calls. This call was not run.' % len(calls))
|
|
402
|
+
save_state(st)
|
|
403
|
+
|
|
404
|
+
def scope_list(st):
|
|
405
|
+
"""Approved scope for Guided mode, or None when the user has not approved any work yet."""
|
|
406
|
+
if not st.get('scope_ok') and not st.get('scope'): return None
|
|
407
|
+
return list(st.get('scope') or [])
|
|
408
|
+
|
|
409
|
+
def grant_area(st, rel):
|
|
410
|
+
from command_safety import area
|
|
411
|
+
a = area(rel) if rel not in ('.', '') else '.'
|
|
412
|
+
scope = list(st.get('scope') or [])
|
|
413
|
+
if a not in scope: scope.append(a)
|
|
414
|
+
st['scope'] = scope[:60]; st['scope_ok'] = True; save_state(st)
|
|
415
|
+
save('scope.json', {'areas': st['scope'], 'declared': load('scope.json', {}).get('declared', [])})
|
|
416
|
+
event('scope', areas=st['scope'], content='Edits allowed in ' + a)
|
|
417
|
+
return a
|
|
418
|
+
|
|
419
|
+
def note_touch(st, rel):
|
|
420
|
+
from command_safety import area
|
|
421
|
+
touched = list(st.get('touched') or [])
|
|
422
|
+
a = area(rel)
|
|
423
|
+
if a not in touched: touched.append(a); st['touched'] = touched[:80]; save_state(st); save('scope.json', {**load('scope.json', {}), 'touched': touched})
|
|
424
|
+
|
|
425
|
+
def edit_gate(name, args, rel, target, st, auto):
|
|
426
|
+
"""Guided mode: one approval per area (or per declared scope), not per edit. Auto: record the touched areas."""
|
|
427
|
+
outside = rel.startswith('..') or os.path.isabs(rel)
|
|
428
|
+
if not outside: note_touch(st, rel)
|
|
429
|
+
if not outside and rel in (st.get('policy_ok_paths') or []): return # already reviewed under the repository policy
|
|
430
|
+
if auto:
|
|
431
|
+
if outside and not (ROOT / 'kimi-approve-all').exists() and not str(target).startswith(('/tmp', '/var/tmp')):
|
|
432
|
+
wait_decision({'id': os.urandom(8).hex(), 'kind': 'command', 'effect': 'external', 'reason': 'writes outside the workspace', 'command': name + ' ' + str(args.get('path', ''))[:300]})
|
|
433
|
+
return
|
|
434
|
+
if st.get('readonly'): wait_decision({'id': os.urandom(8).hex(), 'command': name + ' ' + str(args.get('path', ''))[:300]}); return
|
|
435
|
+
from command_safety import in_scope, area
|
|
436
|
+
declared = load('scope.json', {}).get('declared') or []
|
|
437
|
+
scope = scope_list(st)
|
|
438
|
+
if not outside and scope is not None and (in_scope(rel, scope) or in_scope(rel, declared)): return
|
|
439
|
+
if name == 'Edit': summary = 'Edit ' + str(args.get('path', '')) + '\nREMOVE:\n' + str(args.get('old_string', ''))[:6000] + '\nREPLACE WITH:\n' + str(args.get('new_string', ''))[:6000]
|
|
440
|
+
else: summary = 'Write ' + str(args.get('path', '')) + ' (' + str(len(str(args.get('content', '')))) + ' characters)\n' + str(args.get('content', ''))[:8000]
|
|
441
|
+
if outside:
|
|
442
|
+
wait_decision({'id': os.urandom(8).hex(), 'kind': 'command', 'effect': 'external', 'reason': 'writes outside the workspace', 'command': summary}); return
|
|
443
|
+
wait_decision({'id': os.urandom(8).hex(), 'kind': 'scope', 'area': area(rel), 'command': summary})
|
|
444
|
+
grant_area(st, rel)
|
|
445
|
+
|
|
446
|
+
def command_gate(command, st, mode, auto):
|
|
447
|
+
"""Classify the command; allow, ask or refuse according to the mode budget and the approved scope."""
|
|
448
|
+
from command_safety import classify, decide, describe, relative
|
|
449
|
+
verdict = classify(command, REPO, cwd=REPO, home=os.path.dirname(REPO))
|
|
450
|
+
budget_mode = 'plan' if briefing(st) else 'inspect' if st.get('inspect') else 'auto' if auto else ('approve' if mode != 'plan' else 'plan')
|
|
451
|
+
scope = None if st.get('readonly') else scope_list(st)
|
|
452
|
+
declared = load('scope.json', {}).get('declared') or []
|
|
453
|
+
if scope is not None and declared: scope = scope + list(declared)
|
|
454
|
+
decision = decide(verdict, budget_mode, scope=scope, approved_kinds=st.get('approved_kinds') or [], approve_all=(ROOT / 'kimi-approve-all').exists(), repo=REPO, cwd=REPO)
|
|
455
|
+
effect = decision['effect']
|
|
456
|
+
if decision['decision'] == 'deny':
|
|
457
|
+
event('safety', effect=effect, decision='deny', command=command[:2000], content='Refused. ' + (decision.get('reason') or describe(decision)))
|
|
458
|
+
if effect == 'catastrophic': block('Refused: ' + (decision.get('reason') or describe(decision)) + '. This command is never run, in any mode. Choose a contained alternative (delete specific files inside the project, keep the harness state alone, never touch devices or system directories).')
|
|
459
|
+
if briefing(st): block('Brief mode: only read-only commands run before the user approves the task list. ' + describe(decision) + ' was not run; put it in the plan instead.')
|
|
460
|
+
if st.get('inspect'): block('Not allowed: ' + describe(decision) + '. ' + INSPECT_BLOCK)
|
|
461
|
+
block('Not allowed in this mode: ' + describe(decision) + '. Plan mode only reads; propose the command in your answer instead.')
|
|
462
|
+
if decision['decision'] == 'allow':
|
|
463
|
+
if effect not in ('read', 'check'): event('safety', effect=effect, decision='allow', command=command[:300], content=describe(decision))
|
|
464
|
+
return
|
|
465
|
+
request = {'id': os.urandom(8).hex(), 'kind': 'command', 'effect': effect, 'reason': decision.get('reason') or '', 'command': command[:20000]}
|
|
466
|
+
event('safety', effect=effect, decision='ask', command=command[:300], content=describe(decision))
|
|
467
|
+
wait_decision(request)
|
|
468
|
+
if effect in ('install', 'service'):
|
|
469
|
+
kinds = sorted(set(st.get('approved_kinds') or []) | {effect}); st['approved_kinds'] = kinds; save_state(st)
|
|
470
|
+
elif effect in ('write', 'exec') and not st.get('readonly'):
|
|
471
|
+
rels = [r for r in (relative(p, REPO, REPO) for p in decision.get('paths') or []) if r]
|
|
472
|
+
if rels:
|
|
473
|
+
for r in rels: grant_area(st, r)
|
|
474
|
+
else: st['scope_ok'] = True; save_state(st)
|
|
475
|
+
|
|
476
|
+
def ledger_record():
|
|
477
|
+
"""Earlier runs plus this run's own recorded results, and the statements earlier answers made about the code."""
|
|
478
|
+
try:
|
|
479
|
+
import work_ledger
|
|
480
|
+
record = work_ledger.entries(ROOT)
|
|
481
|
+
try: record = record + [work_ledger.entry('', '', load('checks.json', []), load('design-browser-evidence.json', []))]
|
|
482
|
+
except Exception: pass
|
|
483
|
+
return record, work_ledger.statements(ROOT)
|
|
484
|
+
except Exception: return [], []
|
|
485
|
+
|
|
486
|
+
def repair_note(issues):
|
|
487
|
+
try:
|
|
488
|
+
import verification
|
|
489
|
+
return verification.repair_note(issues)
|
|
490
|
+
except Exception: return '- ' + '\n- '.join(str(i)[:1500] for i in issues[:12])
|
|
491
|
+
|
|
492
|
+
def statement_issues(st, done):
|
|
493
|
+
"""Answers are checked against the run record and the code even when nothing was edited: a denial of recorded tests,
|
|
494
|
+
a figure for how the code behaves with no file and line, a citation that does not exist."""
|
|
495
|
+
if 'statements' in done: return []
|
|
496
|
+
try:
|
|
497
|
+
import verification
|
|
498
|
+
last = load('kimi-last-text.json', {})
|
|
499
|
+
answer = last.get('text', '') if time.time() - (last.get('time') or 0) < 120 else ''
|
|
500
|
+
if not answer: return []
|
|
501
|
+
record, earlier = ledger_record()
|
|
502
|
+
findings = verification.citation_check(answer, REPO, st.get('task', '')) + verification.behaviour_check(answer, earlier) + verification.denial_check(answer, record) + verification.remote_claim_check(answer, load('checks.json', []))
|
|
503
|
+
except Exception: return []
|
|
504
|
+
if not findings: return []
|
|
505
|
+
done.add('statements')
|
|
506
|
+
event('verification_report', status='failed', reasons=[f['message'].split('.')[0] for f in findings], findings=findings, checks=0, passed=0)
|
|
507
|
+
return [f['message'] for f in findings[:3]]
|
|
508
|
+
|
|
509
|
+
def readonly_stop(st):
|
|
510
|
+
"""Answers and plans: only the research evidence rule applies."""
|
|
511
|
+
done = set(st.get('gates_done') or [])
|
|
512
|
+
count = int(load('kimi-stop-count', 0) or 0)
|
|
513
|
+
if count < 2:
|
|
514
|
+
issues = statement_issues(st, done)
|
|
515
|
+
if issues:
|
|
516
|
+
st['gates_done'] = sorted(done); save_state(st); save('kimi-stop-count', count + 1)
|
|
517
|
+
event('done_gate', content=' '.join(issues)[:2000])
|
|
518
|
+
block('Before answering:\n' + repair_note(issues) + '\nThen write the answer again from scratch, complete and self-contained. Do not mention this message.')
|
|
519
|
+
if 'evidence' in done: return
|
|
520
|
+
try:
|
|
521
|
+
from evidence import EvidenceLedger
|
|
522
|
+
data = EvidenceLedger(ROOT, st.get('evidence_key') or 'kimi').load()
|
|
523
|
+
except Exception: return
|
|
524
|
+
if data['sources'] and not data['claims']:
|
|
525
|
+
st['gates_done'] = sorted(done | {'evidence'}); save_state(st)
|
|
526
|
+
event('done_gate', content='Research claims not recorded yet')
|
|
527
|
+
block('Before answering, record the material claims with mcp__mlai__evidence {claims:[{claim, kind, source_ids, quote, uncertainty}]}. Facts need an exact quote from a retrieved source; label inferences and assumptions. Link the source URLs in the answer.')
|
|
528
|
+
|
|
529
|
+
def stop(payload, st):
|
|
530
|
+
if (ROOT / 'cancel').exists(): return
|
|
531
|
+
if st.get('account_stop'): return # out of credits: the summary is the last turn, no more gates
|
|
532
|
+
queued = steering()
|
|
533
|
+
if queued: steer_block(queued, stopping=True)
|
|
534
|
+
if st.get('readonly') or st.get('inspect'): return readonly_stop(st)
|
|
535
|
+
if briefing(st) and not st.get('planned') and not st.get('brief_nudged'):
|
|
536
|
+
st['brief_nudged'] = True; save_state(st)
|
|
537
|
+
event('done_gate', content='Brief mode: asked for the task list before finishing')
|
|
538
|
+
block('Brief mode: the user is waiting to review a task list. Call TodoList with 3 to 10 concrete items (and mcp__mlai__brief_questions for anything open) before finishing. If the request is already answered and nothing needs building, say so plainly and finish.')
|
|
539
|
+
if briefing(st): return
|
|
540
|
+
count = int(load('kimi-stop-count', 0) or 0)
|
|
541
|
+
if count >= 3 or time.time() > st.get('deadline', 1e18) - 90: return
|
|
542
|
+
done = set(st.get('gates_done') or [])
|
|
543
|
+
issues = []
|
|
544
|
+
import roles as role_engine
|
|
545
|
+
try: changed = role_engine.changed_files(REPO, st.get('base'))
|
|
546
|
+
except Exception: changed = []
|
|
547
|
+
code_changed = [p for p in changed if role_engine.CODE_EXT.search(p)]
|
|
548
|
+
if st.get('require_changes') and not changed and 'patch' not in done:
|
|
549
|
+
done.add('patch'); issues.append('This task requires a repository change, but the working tree is unchanged. Make the fix, or explain the blocker if it truly cannot be fixed.')
|
|
550
|
+
todos = load('todos.json', [])
|
|
551
|
+
open_items = [t.get('text', '') for t in todos if isinstance(t, dict) and t.get('status') not in ('done', 'cancelled')]
|
|
552
|
+
if open_items and 'todos' not in done:
|
|
553
|
+
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.')
|
|
554
|
+
last_edit, last_check = st.get('last_edit') or 0, st.get('last_check') or 0
|
|
555
|
+
if code_changed and last_edit and last_check < last_edit and 'verify' not in done:
|
|
556
|
+
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.')
|
|
557
|
+
if 'verification' not in done:
|
|
558
|
+
try:
|
|
559
|
+
import verification
|
|
560
|
+
last = load('kimi-last-text.json', {})
|
|
561
|
+
answer = last.get('text', '') if time.time() - (last.get('time') or 0) < 120 else ''
|
|
562
|
+
commands = [c for c in load('kimi-commands.json', []) if isinstance(c, dict)]
|
|
563
|
+
record, earlier = ledger_record()
|
|
564
|
+
report = verification.report(REPO, st.get('base'), answer, commands, load('checks.json', []), st.get('task', ''), last_edit=last_edit, edits=st.get('edits') or 0,
|
|
565
|
+
scope=load('scope.json', None), record=record, earlier=earlier)
|
|
566
|
+
save('verification.json', report); event('verification_report', **{k: report.get(k) for k in ('status', 'reasons', 'findings', 'checks', 'passed', 'stale')})
|
|
567
|
+
blocking = [f['message'] for f in report['findings'] if f.get('severity') == 'block']
|
|
568
|
+
if blocking: done.add('verification'); issues += blocking[:3]
|
|
569
|
+
except Exception: pass
|
|
570
|
+
role = st.get('role')
|
|
571
|
+
if role and 'role' not in done:
|
|
572
|
+
done.add('role')
|
|
573
|
+
try: gaps = role_engine.gate(role, REPO, st.get('base'), changed, st.get('task', ''))
|
|
574
|
+
except Exception: gaps = []
|
|
575
|
+
event('role_check', role=role['id'], title=role['title'], status='blocked' if gaps else 'passed', issues=[{'kind': i['kind'], 'label': i['label'], 'message': i['message'][:600]} for i in gaps])
|
|
576
|
+
if gaps: issues.append('Role done-check (' + role['title'] + '): ' + ' '.join(i['message'] for i in gaps) + ' Fix these for real (real data paths, real artifacts, verified). If one truly cannot apply, say why in the final summary.')
|
|
577
|
+
if st.get('selected_design') and 'design' not in done:
|
|
578
|
+
try:
|
|
579
|
+
from design_director import browser_review
|
|
580
|
+
from quality import fingerprint
|
|
581
|
+
report = browser_review(load('design-browser-evidence.json', []), fingerprint(REPO, st.get('base') or 'HEAD'))
|
|
582
|
+
save('design-review.json', report); event('design_review', designReview=report)
|
|
583
|
+
if report['status'] != 'passed':
|
|
584
|
+
done.add('design'); issues.append(report['message'] + ' Start the app with mcp__mlai__preview {"action":"start"}, then run mcp__mlai__browser at width 390 and at width 1280, each with at least one click/fill/press and an assert_text. Fix overflow, console or page errors and failed requests.')
|
|
585
|
+
except Exception: pass
|
|
586
|
+
if 'evidence' not in done:
|
|
587
|
+
try:
|
|
588
|
+
from evidence import EvidenceLedger
|
|
589
|
+
data = EvidenceLedger(ROOT, st.get('evidence_key') or 'kimi').load()
|
|
590
|
+
if data['sources'] and not data['claims']:
|
|
591
|
+
done.add('evidence'); issues.append('Record the material claims of your answer with mcp__mlai__evidence {claims:[{claim, kind, source_ids, quote, uncertainty}]} before finishing. Facts need an exact quote from a retrieved source; label inferences and assumptions. Link the source URLs in the final answer.')
|
|
592
|
+
except Exception: pass
|
|
593
|
+
st['gates_done'] = sorted(done); save_state(st)
|
|
594
|
+
if not issues:
|
|
595
|
+
note = user_hooks('run_end', mlai_run(st), str(payload.get('last_assistant_message') or payload.get('message') or ''))
|
|
596
|
+
if note: block(note)
|
|
597
|
+
if issues:
|
|
598
|
+
save('kimi-stop-count', count + 1)
|
|
599
|
+
event('done_gate', content=' '.join(issues)[:2000])
|
|
600
|
+
block('Not done yet:\n' + repair_note(issues) + '\nWhen these are handled, write your final message from scratch as if it were your first reply to the user (what changed, how you verified it, anything left open). Do not refer to this message or say which points you addressed.')
|
|
601
|
+
|
|
602
|
+
def main():
|
|
603
|
+
kind = sys.argv[1] if len(sys.argv) > 1 else ''
|
|
604
|
+
try: payload = json.loads(sys.stdin.read() or '{}')
|
|
605
|
+
except ValueError: payload = {}
|
|
606
|
+
st = state()
|
|
607
|
+
if kind == 'PreToolUse': pre(payload, st)
|
|
608
|
+
elif kind == 'PostToolUse':
|
|
609
|
+
feedback = user_hooks('kimi_post', payload, st) # after_tool / after_edit hooks
|
|
610
|
+
if feedback: block(feedback)
|
|
611
|
+
elif kind == 'Stop':
|
|
612
|
+
stop(payload, st)
|
|
613
|
+
# Turn accepted: tell the bridge, which ends the engine if it lingers waiting on background processes (preview servers).
|
|
614
|
+
save('kimi-stopped', {'time': time.time()})
|
|
615
|
+
sys.exit(0)
|
|
616
|
+
|
|
617
|
+
if __name__ == '__main__': main()
|