mlai-code 0.3.1 → 0.3.3
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 +2 -2
- package/src/cli.mjs +27 -7
- package/src/distribution.mjs +5 -5
- package/src/engine-key.mjs +18 -4
- package/src/engine.mjs +4 -9
- package/src/home.mjs +1 -1
- package/src/parity.mjs +3 -1
- package/src/render.mjs +3 -1
- package/src/runtime.mjs +21 -1
- package/src/sandbox.mjs +19 -3
- package/src/session.mjs +22 -2
- package/src/shared-data.mjs +1 -1
- package/src/tui/app.mjs +22 -4
- package/src/tui/chat.mjs +8 -6
- package/src/tui/cmd-core.mjs +2 -2
- package/src/tui/cmd-extensibility.mjs +8 -2
- package/src/tui/commands.mjs +2 -1
- package/src/tui/statusline.mjs +2 -1
- package/src/wakeups.mjs +2 -2
- package/vendor/client-sdk/index.cjs +3 -3
- package/vendor/cloud-cli/mlai.mjs +169 -25
- package/worker/build_planner.py +75 -7
- package/worker/cloud_pty.py +91 -2
- package/worker/command_safety.py +25 -1
- package/worker/compaction_brief.py +186 -0
- package/worker/context_manager.py +9 -3
- package/worker/conversation.py +58 -1
- package/worker/deck_render.js +11 -0
- package/worker/deck_tools.py +825 -0
- package/worker/git_sync.py +38 -13
- package/worker/goals.py +4 -0
- package/worker/image_generation.py +102 -23
- package/worker/kimi_bridge.py +406 -40
- package/worker/kimi_gates.py +84 -1
- package/worker/kimi_hook.py +113 -12
- package/worker/media_tools.py +179 -0
- package/worker/memory.py +2 -2
- package/worker/mlai_hooks.py +93 -3
- package/worker/mlai_mcp.py +23 -5
- package/worker/model_stream.py +21 -7
- package/worker/obs_mask.py +97 -0
- package/worker/offline_guard.py +1 -1
- package/worker/preview.py +47 -4
- package/worker/product_facts.py +18 -0
- package/worker/project_context.py +33 -7
- package/worker/reply_language.py +92 -10
- package/worker/roles.json +199 -37
- package/worker/roles.py +243 -8
- package/worker/runner.py +253 -42
- package/worker/site_check.py +279 -0
- package/worker/skill_library.py +15 -3
- package/worker/skill_pack.py +170 -16
- package/worker/tool_catalog.py +3 -2
- package/worker/verification.py +43 -11
- package/worker/wakeups.py +56 -4
package/worker/runner.py
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
"""mini-SWE-agent adapter. Runs only inside an isolated Vercel Sandbox."""
|
|
2
|
-
import json, math, os, re, sys, time, threading, urllib.request, urllib.error, subprocess, signal, tempfile, shutil
|
|
2
|
+
import json, math, os, re, sys, time, threading, urllib.request, urllib.error, urllib.parse, subprocess, signal, tempfile, shutil
|
|
3
3
|
try:
|
|
4
4
|
from brief_questions import normalize as normalize_questions
|
|
5
5
|
except ImportError: # older bundle on the computer
|
|
@@ -14,6 +14,8 @@ import computer_use
|
|
|
14
14
|
from conversation import enabled as conversation_enabled, readonly as conversation_readonly, route as route_conversation, answer_text, recent_history, READONLY_SYSTEM, READ_TOOLS, WORKFLOW_GUIDANCE, research_required, honor_no_change, NO_CHANGE_NOTE
|
|
15
15
|
from lifecycle import boot_id, identity, nested_guidance, load
|
|
16
16
|
from context_manager import ContextManager, read_archive
|
|
17
|
+
import obs_mask
|
|
18
|
+
OUTPUT_CAP=int(os.getenv('MINI_OUTPUT_CAP','12000') or 12000) # one command's output in the model context (the full log is kept)
|
|
17
19
|
from web_tools import WebResearch
|
|
18
20
|
from runtime_control import request_json, completion_report, approve_operation, safe_command, clip
|
|
19
21
|
from quality import RepairTracker, review as final_review, fingerprint, verification_scope, check_verdict, verification_gate, junit_verdict, report_stamp
|
|
@@ -96,6 +98,54 @@ def vault_guidance():
|
|
|
96
98
|
def _clean_name(value, limit=60):
|
|
97
99
|
return ' '.join(str(value or '').split())[:limit]
|
|
98
100
|
|
|
101
|
+
# Host (exact or parent domain), optional path prefix -> Pipedream app slug. Mirrors LINK_RULES in lib/link-apps.ts.
|
|
102
|
+
LINK_HOSTS = [
|
|
103
|
+
('docs.google.com', '/document/', 'google_docs'), ('docs.google.com', '/spreadsheets/', 'google_sheets'),
|
|
104
|
+
('docs.google.com', '/presentation/', 'google_slides'), ('docs.google.com', '/forms/', 'google_forms'),
|
|
105
|
+
('drive.google.com', '', 'google_drive'), ('notion.so', '', 'notion'), ('notion.site', '', 'notion'),
|
|
106
|
+
('github.com', '', 'github'), ('gitlab.com', '', 'gitlab'), ('figma.com', '', 'figma'), ('linear.app', '', 'linear'),
|
|
107
|
+
('airtable.com', '', 'airtable_oauth'), ('dropbox.com', '', 'dropbox'), ('onedrive.live.com', '', 'microsoft_onedrive'),
|
|
108
|
+
('1drv.ms', '', 'microsoft_onedrive'), ('sharepoint.com', '', 'sharepoint'), ('box.com', '', 'box'),
|
|
109
|
+
('atlassian.net', '/wiki/', 'confluence'), ('atlassian.net', '', 'jira'), ('trello.com', '', 'trello'),
|
|
110
|
+
('app.asana.com', '', 'asana'), ('app.hubspot.com', '', 'hubspot'), ('slack.com', '', 'slack_v2'),
|
|
111
|
+
('app.clickup.com', '', 'clickup'), ('miro.com', '', 'miro'), ('canva.com', '', 'canva'),
|
|
112
|
+
]
|
|
113
|
+
GOOGLE_FILE_APPS = {'google_docs', 'google_sheets', 'google_slides', 'google_drive'}
|
|
114
|
+
_LINK_RE = re.compile(r"https?://[^\s<>\"'`)\]]+", re.I)
|
|
115
|
+
|
|
116
|
+
def link_app(url):
|
|
117
|
+
try:
|
|
118
|
+
parsed = urllib.parse.urlsplit(url)
|
|
119
|
+
except ValueError:
|
|
120
|
+
return ''
|
|
121
|
+
host, path = (parsed.hostname or '').lower(), parsed.path or '/'
|
|
122
|
+
for rule, prefix, slug in LINK_HOSTS:
|
|
123
|
+
if (host == rule or host.endswith('.' + rule)) and (not prefix or path.startswith(prefix)):
|
|
124
|
+
return slug
|
|
125
|
+
return ''
|
|
126
|
+
|
|
127
|
+
def link_lines(task, connected_slugs):
|
|
128
|
+
"""Links in the message that belong to an app the account connected: open them with that app's tools.
|
|
129
|
+
A public fetch of a private Doc, Notion page or repo only returns a sign-in page."""
|
|
130
|
+
found = []
|
|
131
|
+
for m in _LINK_RE.finditer(str(task or '')[:20000]):
|
|
132
|
+
url = m.group(0).rstrip('.,;:!?')
|
|
133
|
+
slug = link_app(url)
|
|
134
|
+
if slug and (url, slug) not in found:
|
|
135
|
+
found.append((url, slug))
|
|
136
|
+
if len(found) >= 10:
|
|
137
|
+
break
|
|
138
|
+
out = []
|
|
139
|
+
drive_on = 'google_drive' in connected_slugs
|
|
140
|
+
for url, slug in found:
|
|
141
|
+
if slug in GOOGLE_FILE_APPS and drive_on:
|
|
142
|
+
out.append('The link ' + url[:200] + ' is a Google file the user can open with their connected Google Drive. The composer reads such links through that Drive and attaches the file to this message: read the attachment first. If it is not attached, use the Google Drive or ' + slug + ' tools (workspace_tool tool_search "' + slug + '"), not a web fetch.')
|
|
143
|
+
elif slug in connected_slugs or (slug in GOOGLE_FILE_APPS and slug != 'google_drive' and 'google_drive' in connected_slugs):
|
|
144
|
+
out.append('The link ' + url[:200] + ' belongs to ' + slug + ', which this account has connected. Open it with that app\'s tools (workspace_tool tool_search "' + slug + '"), not a web fetch: a public fetch of a private page returns a sign-in page.')
|
|
145
|
+
else:
|
|
146
|
+
out.append('The link ' + url[:200] + ' belongs to ' + slug + ', which is not connected. Try a normal fetch; if it needs a sign-in, offer [Connect](/?connect=' + slug + ') so you can read it through the user\'s account.')
|
|
147
|
+
return out
|
|
148
|
+
|
|
99
149
|
def connection_status_lines(config, accounts):
|
|
100
150
|
"""Exact connected / not-connected facts for this run, so the agent never guesses.
|
|
101
151
|
Sources: apps the account signed in to through Pipedream (read server-side at start), Vault secrets tagged for a
|
|
@@ -130,6 +180,10 @@ def connection_status_lines(config, accounts):
|
|
|
130
180
|
out.append('This account has no apps signed in through Pipedream Connect yet (checked just now). When a task needs one, offer its connect link.')
|
|
131
181
|
elif apps is None and 'apps' in accounts:
|
|
132
182
|
out.append('The connected-app check did not answer in time. Do not claim an app is missing: if a needed app has no tools in your catalog, say you could not confirm the connection and offer its link to check or sign in.')
|
|
183
|
+
connected_slugs = {c['app'] for c in with_tools if c['app']}
|
|
184
|
+
if isinstance(apps, list):
|
|
185
|
+
connected_slugs |= {str(a.get('slug')).lower() for a in apps if isinstance(a, dict) and a.get('slug') and a.get('healthy') is not False}
|
|
186
|
+
out.extend(link_lines(config.get('task'), connected_slugs))
|
|
133
187
|
kinds = accounts.get('vaultKinds')
|
|
134
188
|
if isinstance(kinds, list) and kinds:
|
|
135
189
|
out.append('Vault holds tokens tagged for: ' + ', '.join(_clean_name(k, 40) for k in kinds[:20]) + '. Treat those services as connected through the Vault; use them by environment variable when the secret is shared with the agent.')
|
|
@@ -152,7 +206,9 @@ def connect_guidance(config=None):
|
|
|
152
206
|
return ' '.join(lines)+'\n\n'
|
|
153
207
|
|
|
154
208
|
def write(name, data):
|
|
155
|
-
|
|
209
|
+
# One temp file per thread: concurrent model streams write progress at the same time, and a shared temp
|
|
210
|
+
# name let one thread move the other's half-written file into place (or fail on a vanished temp).
|
|
211
|
+
tmp = ROOT / (name + '.' + str(threading.get_ident()) + '.tmp')
|
|
156
212
|
tmp.write_text(json.dumps(unvault(data)))
|
|
157
213
|
tmp.replace(ROOT / name)
|
|
158
214
|
|
|
@@ -165,14 +221,67 @@ def event(event_type, **data):
|
|
|
165
221
|
f.write(json.dumps(unvault({'type': event_type, 'time': time.time(), **data})) + '\n')
|
|
166
222
|
|
|
167
223
|
INFERENCE_TEXT_SEEN=set()
|
|
224
|
+
INFERENCE_LOCK=threading.RLock()
|
|
225
|
+
INFERENCE_SEQ=[0]
|
|
226
|
+
INFERENCE_LIVE={}
|
|
168
227
|
def inference_progress(**data):
|
|
169
|
-
snapshot
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
228
|
+
# Every snapshot carries a run-wide sequence number so readers keep the newest state per stream id, and
|
|
229
|
+
# inference-live.json holds every stream still running: helper calls stream at the same time, and the single
|
|
230
|
+
# latest-snapshot file alone made the other stream fall back to its first, stale text (reasoning flicker).
|
|
231
|
+
with INFERENCE_LOCK:
|
|
232
|
+
INFERENCE_SEQ[0]+=1
|
|
233
|
+
snapshot={'type':'inference_progress','time':time.time(),**data,'seq':INFERENCE_SEQ[0]}
|
|
234
|
+
sid=data.get('id')
|
|
235
|
+
if sid is not None:
|
|
236
|
+
if data.get('state')=='running':INFERENCE_LIVE[sid]=snapshot
|
|
237
|
+
else:INFERENCE_LIVE.pop(sid,None)
|
|
238
|
+
write('inference-progress.json',snapshot)
|
|
239
|
+
write('inference-live.json',list(INFERENCE_LIVE.values()))
|
|
240
|
+
first_text=bool(data.get('content')) and sid not in INFERENCE_TEXT_SEEN
|
|
241
|
+
if first_text:INFERENCE_TEXT_SEEN.add(sid)
|
|
242
|
+
# Keep initial/first-text/final evidence, not every cumulative snapshot in history.
|
|
243
|
+
if data.get('state')!='running' or data.get('seconds')==0 or first_text:
|
|
244
|
+
event('inference_progress',**{**data,'seq':snapshot['seq']})
|
|
245
|
+
|
|
246
|
+
STEP_INTENTS={}
|
|
247
|
+
def step_why(value):
|
|
248
|
+
"""A short plain-words step title from the model, or '' when missing or unusable."""
|
|
249
|
+
if not isinstance(value,str):return ''
|
|
250
|
+
value=' '.join(value.split()).strip(' .')
|
|
251
|
+
return value[:1].upper()+value[1:140] if 3<=len(value)<=140 else ''
|
|
252
|
+
def step_key(kind,name,args):
|
|
253
|
+
if kind=='cmd':return 'cmd:'+str(args or '').strip()
|
|
254
|
+
try:return 'tool:'+str(name)+':'+json.dumps(args,sort_keys=True,default=str)
|
|
255
|
+
except (TypeError,ValueError):return ''
|
|
256
|
+
def remember_step(function,arguments,why):
|
|
257
|
+
"""Remember the plain-words title for the action this native call becomes, so the step event can carry it."""
|
|
258
|
+
if function=='run_command':key=step_key('cmd',None,arguments.get('command'))
|
|
259
|
+
elif function in ('edit_file','verify'):key=step_key('tool',function,arguments)
|
|
260
|
+
elif function=='workspace_tool':key=step_key('tool',arguments.get('name'),arguments.get('arguments'))
|
|
261
|
+
else:return
|
|
262
|
+
if not key:return
|
|
263
|
+
STEP_INTENTS[key]=why
|
|
264
|
+
while len(STEP_INTENTS)>50:STEP_INTENTS.pop(next(iter(STEP_INTENTS)))
|
|
265
|
+
def step_intent(kind,name,args):
|
|
266
|
+
key=step_key(kind,name,args)
|
|
267
|
+
return STEP_INTENTS.pop(key,'') if key else ''
|
|
268
|
+
|
|
269
|
+
def show_thinking(config):
|
|
270
|
+
"""Ask the provider for the model's reasoning so the activity view can show its thought process (display only:
|
|
271
|
+
never executed, never sent back to the model). Off with MINI_SHOW_THINKING=0 or showThinking: false."""
|
|
272
|
+
return os.environ.get('MINI_SHOW_THINKING','1')!='0' and config.get('showThinking') is not False and not config.get('_thinking_disabled')
|
|
273
|
+
|
|
274
|
+
THOUGHT_EVENT_MAX=6000
|
|
275
|
+
def thought_text(result):
|
|
276
|
+
"""The reasoning text a response carried (streamed or complete), trimmed for the activity view; '' when none."""
|
|
277
|
+
if not isinstance(result,dict):return ''
|
|
278
|
+
text=result.get('thought_display')
|
|
279
|
+
if not isinstance(text,str) or not text.strip():
|
|
280
|
+
message=((result.get('choices') or [{}])[0] or {}).get('message') if isinstance(result.get('choices'),list) else None
|
|
281
|
+
text=next((message.get(k) for k in ('reasoning_content','reasoning') if isinstance(message,dict) and isinstance(message.get(k),str) and message.get(k).strip()),'')
|
|
282
|
+
text=str(text or '').strip()
|
|
283
|
+
if len(text)<20:return ''
|
|
284
|
+
return text if len(text)<=THOUGHT_EVENT_MAX else '…'+text[-THOUGHT_EVENT_MAX:]
|
|
176
285
|
|
|
177
286
|
PARALLEL_READS=frozenset(('read_file','read_files','list_files','search_text','context_read','command_output','repo_map','symbols','skill_load','tool_search'))
|
|
178
287
|
def run_parallel(jobs,workers=4):
|
|
@@ -297,7 +406,18 @@ def billable_tokens(usage, rates=None):
|
|
|
297
406
|
return int(math.ceil((prompt - cached - written) * rates['input'] + cached * rates['cached'] + written * rates['cacheWrite'] + output * rates['output']))
|
|
298
407
|
return int(math.ceil(prompt - cached + cached * CACHED_INPUT_WEIGHT + output * OUTPUT_WEIGHT))
|
|
299
408
|
|
|
300
|
-
|
|
409
|
+
def image_credit_label():
|
|
410
|
+
from image_generation import image_tokens
|
|
411
|
+
return '%.2f'%(image_tokens(None)/1_000_000)
|
|
412
|
+
|
|
413
|
+
def image_billed():
|
|
414
|
+
"""Image generation billed in this run (tokens: provider cost plus margin; see image_generation.image_tokens)."""
|
|
415
|
+
try:
|
|
416
|
+
from image_generation import billed_tokens
|
|
417
|
+
return billed_tokens()
|
|
418
|
+
except Exception: return 0
|
|
419
|
+
|
|
420
|
+
CREDITS_OUT_NOTE='You have used this cycle’s included usage, so this run stopped. Your files are saved. Pick a plan or add capacity in Settings > Billing, then press Resume to continue.'
|
|
301
421
|
ACCOUNT_WRAP_TOKENS=60_000 # room for the final summary after the account runs out; then the run stops
|
|
302
422
|
|
|
303
423
|
class Model:
|
|
@@ -305,13 +425,14 @@ class Model:
|
|
|
305
425
|
"""Account credits (LIMIT/BILL): at the allowance ask for a final summary, and stop shortly after. The user sees both."""
|
|
306
426
|
left=self.config.get('accountTokensLeft')
|
|
307
427
|
if self.config.get('subagent') or not isinstance(left,(int,float)) or isinstance(left,bool):return
|
|
308
|
-
|
|
428
|
+
used=self.tokens+image_billed()
|
|
429
|
+
if used>=max(0,int(left))+ACCOUNT_WRAP_TOKENS:
|
|
309
430
|
event('account_limit',phase='stopped',content=CREDITS_OUT_NOTE)
|
|
310
431
|
raise LimitsExceeded({'role':'exit','content':CREDITS_OUT_NOTE,'extra':{'exit_status':'LimitsExceeded','limit':'tokens','limitNote':CREDITS_OUT_NOTE,'submission':CREDITS_OUT_NOTE}})
|
|
311
|
-
if
|
|
432
|
+
if used>=max(0,int(left)) and not getattr(self,'account_warned',False):
|
|
312
433
|
self.account_warned=True
|
|
313
|
-
event('account_limit',phase='wrapping',content='
|
|
314
|
-
messages.append({'role':'user','content':'The account has used all its
|
|
434
|
+
event('account_limit',phase='wrapping',content='Usage limit reached. The agent is writing a short summary and will stop.')
|
|
435
|
+
messages.append({'role':'user','content':'The account has used all its included usage. Do not start new work or run more commands. Write the final summary now (what changed, what was verified, what is left) and finish.'})
|
|
315
436
|
|
|
316
437
|
def __init__(self, config):
|
|
317
438
|
self.config = config
|
|
@@ -328,7 +449,8 @@ class Model:
|
|
|
328
449
|
self.transport_note=''
|
|
329
450
|
self.workspace_tool_names=set()
|
|
330
451
|
self.fenced_successes=0
|
|
331
|
-
|
|
452
|
+
compact_at=int(os.getenv('MINI_COMPACT_AT','180000') or 180000) # where compaction starts (never above the model window)
|
|
453
|
+
threshold=min(compact_at,max(16000,int(config['contextWindow'])-int(config.get('responseReserve',32768)))) if config.get('contextWindow') else compact_at
|
|
332
454
|
self.context = ContextManager(ROOT,event,threshold=threshold)
|
|
333
455
|
self.pending_vision=None
|
|
334
456
|
self.vision_disabled=not config.get('vision') or bool(config.get('subagent'))
|
|
@@ -371,12 +493,17 @@ class Model:
|
|
|
371
493
|
message=instruction.get('message','')
|
|
372
494
|
if isinstance(message,str) and message.strip():
|
|
373
495
|
messages.append({'role':'user','content':message[:5000]})
|
|
374
|
-
event('steering',content=message[:5000])
|
|
496
|
+
event('steering',content=message[:5000],note=note.stem,**({'source':str(instruction['source'])} if instruction.get('source') else {}))
|
|
497
|
+
# Delivered notes are removed (as the hook does), so the app can tell delivered from still waiting.
|
|
498
|
+
try:note.unlink()
|
|
499
|
+
except OSError:pass
|
|
375
500
|
if 'attachments/' in message and not self.vision_disabled:
|
|
376
501
|
import browser_pane;seen=browser_pane.steering_image(ROOT,message)
|
|
377
502
|
if seen:self.pending_vision=seen
|
|
378
503
|
clean = [{'role': m['role'] if m['role'] in ('system','user','assistant') else 'user', 'content': m.get('content','')} for m in messages]
|
|
379
504
|
clean = self.context.prepare(clean,self.summarize)
|
|
505
|
+
clean,masked = obs_mask.mask_messages(clean,json_observations=True) # old observations become pointers
|
|
506
|
+
if masked:self.metrics['masked_chars']=self.metrics.get('masked_chars',0)+masked
|
|
380
507
|
review_wrapup=self.config.get('subagent') and self.config.get('mode')=='plan' and self.calls>=max(1,limit-2)
|
|
381
508
|
if review_wrapup:
|
|
382
509
|
clean.append({'role':'user','content':'Review time is nearly exhausted. Stop inspecting. Return concise findings from the evidence already read, with file references and concrete counterexamples. State unverified requirements and incomplete inspection explicitly. Do not claim a clean review without evidence. Return prose only, no tools or code fences.'})
|
|
@@ -515,8 +642,8 @@ class Model:
|
|
|
515
642
|
# This GLM endpoint accepts low/high/max only. Medium is adaptive: deep reasoning for the opening plan,
|
|
516
643
|
# plan/research routes and recovery after a failed step; fast reasoning for routine steps.
|
|
517
644
|
if effort=='medium':effort='high' if self.needs_depth(clean) else 'low'
|
|
518
|
-
payload.update(reasoning_effort=effort if effort in ('low','high','max') else 'low',include_reasoning=
|
|
519
|
-
tools=[{'type':'function','function':{'name':'workspace_tool','description':'Use a built-in repository/research tool. Permissions are checked by the runner.','parameters':{'type':'object','properties':{'name':{'type':'string','enum':['read_file','read_files','parallel_reads','list_files','search_text','edit_file','todo','task_contract','evidence','tool_catalog','background_jobs','verify','subagents','skill_create','browser','web_search','web_fetch','context_read','command_output','repo_map','symbols','test_plan','capability_check','skill_load','tool_search','delegate_changes','agent_diff','agent_integrate','lsp','generate_image','impact','browser_pane','list_sessions','send_message','read_messages','ios_simulator','schedule_wakeup','mcp']},'arguments':{'type':'object','additionalProperties':True}},'required':['name','arguments'],'additionalProperties':False}}}]
|
|
645
|
+
payload.update(reasoning_effort=effort if effort in ('low','high','max') else 'low',include_reasoning=show_thinking(self.config),parallel_tool_calls=os.environ.get('MINI_PARALLEL_TOOLS','1')!='0')
|
|
646
|
+
tools=[{'type':'function','function':{'name':'workspace_tool','description':'Use a built-in repository/research tool. Permissions are checked by the runner.','parameters':{'type':'object','properties':{'name':{'type':'string','enum':['read_file','read_files','parallel_reads','list_files','search_text','edit_file','todo','task_contract','evidence','tool_catalog','background_jobs','verify','subagents','skill_create','browser','web_search','web_fetch','context_read','command_output','repo_map','symbols','test_plan','capability_check','skill_load','tool_search','delegate_changes','agent_diff','agent_integrate','lsp','generate_image','impact','browser_pane','list_sessions','send_message','read_messages','ios_simulator','schedule_wakeup','mcp']},'arguments':{'type':'object','additionalProperties':True},'why':{'type':'string','maxLength':140,'description':'Optional. What this step is for, in a few plain words for the user (e.g. "Checking the tests pass"). Shown in the activity view only.'}},'required':['name','arguments'],'additionalProperties':False}}}]
|
|
520
647
|
if self.config.get('subagent') and self.config.get('mode')=='plan':
|
|
521
648
|
file_properties={'path':{'type':'string'},'start':{'type':'integer','minimum':1},'end':{'type':'integer','minimum':1}}
|
|
522
649
|
schemas=[('read_file','Read a repository file range.',file_properties,['path']),
|
|
@@ -530,10 +657,10 @@ class Model:
|
|
|
530
657
|
tools.append({'type':'function','function':{'name':'finish_review','description':'Finish a read-only review with evidence-backed findings and explicit limitations. This returns the report to the parent; it executes no shell commands.','parameters':{'type':'object','properties':{'report':{'type':'string'}},'required':['report'],'additionalProperties':False}}})
|
|
531
658
|
if self.config.get('mode')!='plan' and not self.config.get('subagent'):
|
|
532
659
|
direct_schemas=[
|
|
533
|
-
('edit_file','Replace one exact text match; existing edit approvals and path checks apply.',{'path':{'type':'string','minLength':1},'old':{'type':'string','minLength':1},'new':{'type':'string','maxLength':100000}},['path','old','new']),
|
|
534
|
-
('verify','Run a repository check; optionally require a fresh JUnit report and explicit test IDs.',{'command':{'type':'string','minLength':1,'maxLength':10000},'label':{'type':'string','minLength':1,'maxLength':200},'junitReport':{'type':'string'},'requiredTests':{'type':'array','items':{'type':'string'}}},['command'])]
|
|
660
|
+
('edit_file','Replace one exact text match; existing edit approvals and path checks apply.',{'path':{'type':'string','minLength':1},'old':{'type':'string','minLength':1},'new':{'type':'string','maxLength':100000},'why':{'type':'string','maxLength':140,'description':'Optional. What this step is for, in a few plain words for the user (e.g. "Checking the tests pass"). Shown in the activity view only.'}},['path','old','new']),
|
|
661
|
+
('verify','Run a repository check; optionally require a fresh JUnit report and explicit test IDs.',{'command':{'type':'string','minLength':1,'maxLength':10000},'label':{'type':'string','minLength':1,'maxLength':200},'junitReport':{'type':'string'},'requiredTests':{'type':'array','items':{'type':'string'}},'why':{'type':'string','maxLength':140,'description':'Optional. What this step is for, in a few plain words for the user (e.g. "Checking the tests pass"). Shown in the activity view only.'}},['command'])]
|
|
535
662
|
tools.extend({'type':'function','function':{'name':name,'description':description,'parameters':{'type':'object','properties':properties,'required':required,'additionalProperties':False}}} for name,description,properties,required in direct_schemas)
|
|
536
|
-
if self.config.get('mode')!='plan':tools.append({'type':'function','function':{'name':'run_command','description':'Run a shell command in the repository. To finish use echo COMPLETE_TASK_AND_SUBMIT_FINAL_OUTPUT.','parameters':{'type':'object','properties':{'command':{'type':'string'}},'required':['command'],'additionalProperties':False}}})
|
|
663
|
+
if self.config.get('mode')!='plan':tools.append({'type':'function','function':{'name':'run_command','description':'Run a shell command in the repository. To finish use echo COMPLETE_TASK_AND_SUBMIT_FINAL_OUTPUT.','parameters':{'type':'object','properties':{'command':{'type':'string'},'why':{'type':'string','maxLength':140,'description':'Optional. What this step is for, in a few plain words for the user (e.g. "Checking the tests pass"). Shown in the activity view only.'}},'required':['command'],'additionalProperties':False}}})
|
|
537
664
|
if conversation_readonly(self.config):
|
|
538
665
|
tools[0]['function']['parameters']['properties']['name']['enum']=sorted(READ_TOOLS)
|
|
539
666
|
tools.append({'type':'function','function':{'name':'finish_response','description':'Return the final conversational answer without executing commands.','parameters':{'type':'object','properties':{'text':{'type':'string','minLength':1,'maxLength':20000}},'required':['text'],'additionalProperties':False}}})
|
|
@@ -544,7 +671,7 @@ class Model:
|
|
|
544
671
|
if self.config.get('tools') and (not conversation_readonly(self.config) or read_only_tools(self.config.get('tools'))):tools.append({'type':'function','function':{'name':'connected_tool','description':'Request an explicitly enabled integration tool (in a read-only turn, only its reading tools); requires user approval.','parameters':{'type':'object','properties':{'connection':{'type':'string'},'name':{'type':'string'},'arguments':{'type':'object','additionalProperties':True}},'required':['connection','name','arguments'],'additionalProperties':False}}})
|
|
545
672
|
if allow_tools and self.native_tool_failures<2:payload['tools']=tools
|
|
546
673
|
if allow_tools:self.workspace_tool_names=set(next((t['function']['parameters']['properties']['name'].get('enum',[]) for t in tools if t['function']['name']=='workspace_tool'),[]))-{'edit_file','verify'}
|
|
547
|
-
key = os.environ.get('MODEL_API_KEY','')
|
|
674
|
+
key = os.environ.get(self.config.get('_key_env') or 'MODEL_API_KEY','') # the side model has its own key
|
|
548
675
|
headers={'Authorization': 'Bearer ' + key, 'Content-Type':'application/json'}
|
|
549
676
|
suffix='/chat/completions'
|
|
550
677
|
if self.config.get('provider') == 'openai':payload['max_completion_tokens']=payload.pop('max_tokens')
|
|
@@ -562,8 +689,16 @@ class Model:
|
|
|
562
689
|
if streaming:
|
|
563
690
|
stream_id=os.urandom(8).hex()
|
|
564
691
|
inference_progress(id=stream_id,state='running',content='',seconds=0)
|
|
692
|
+
# One snapshot per stream carries both the reply text and the thought text, so neither erases the other.
|
|
693
|
+
live={'content':'','thought':'','first':None}
|
|
694
|
+
def on_text(content,seconds,first,live=live,stream_id=stream_id):
|
|
695
|
+
live['content']=content[:20000];live['first']=first
|
|
696
|
+
inference_progress(id=stream_id,state='running',content=live['content'],seconds=round(seconds,3),first_text_seconds=first,**({'thought':live['thought'],'thinking':True} if live['thought'] else {}))
|
|
697
|
+
def on_thought(text,seconds,live=live,stream_id=stream_id):
|
|
698
|
+
live['thought']=text[-4000:]
|
|
699
|
+
inference_progress(id=stream_id,state='running',content=live['content'],seconds=round(seconds,3),first_text_seconds=live['first'],thought=live['thought'],thinking=True)
|
|
565
700
|
try:
|
|
566
|
-
result=request_stream(request,stopped,
|
|
701
|
+
result=request_stream(request,stopped,on_text,timeout=240 if self.config.get('provider')=='isoquant' else 100,on_thought=on_thought if payload.get('include_reasoning') else None)
|
|
567
702
|
except Exception:
|
|
568
703
|
inference_progress(id=stream_id,state='failed',content='')
|
|
569
704
|
raise
|
|
@@ -586,12 +721,24 @@ class Model:
|
|
|
586
721
|
request=urllib.request.Request(self.config['endpoint']+suffix,data=json.dumps(payload).encode(),headers=headers)
|
|
587
722
|
event('retry',content='Provider does not support streaming; using complete responses for this request.')
|
|
588
723
|
continue
|
|
724
|
+
if exc.code==400 and 'include_reasoning' in detail.lower() and payload.get('include_reasoning') and attempt<2:
|
|
725
|
+
# The thought process is display-only: a provider that refuses to return it just runs without it.
|
|
726
|
+
payload['include_reasoning']=False;self.config['_thinking_disabled']=True
|
|
727
|
+
request=urllib.request.Request(self.config['endpoint']+suffix,data=json.dumps(payload).encode(),headers=headers)
|
|
728
|
+
event('retry',content='Provider does not return the thought process; continuing without it. Nothing was executed.',attempt=attempt+1)
|
|
729
|
+
continue
|
|
589
730
|
if exc.code==400 and 'reasoning' in detail.lower() and payload.get('reasoning_effort') not in (None,'low') and attempt<2:
|
|
590
731
|
payload['reasoning_effort']='low'
|
|
591
732
|
self.config['_effective_reasoning_effort']='low'
|
|
592
733
|
request=urllib.request.Request(self.config['endpoint']+suffix,data=json.dumps(payload).encode(),headers=headers)
|
|
593
734
|
event('retry',content='Provider rejected reasoning effort; retrying inference with low effort. Nothing was executed.',effective_reasoning_effort='low',attempt=attempt+1,detail=detail)
|
|
594
735
|
continue
|
|
736
|
+
if exc.code==400 and 'reasoning' in detail.lower() and payload.get('include_reasoning') and attempt<2:
|
|
737
|
+
# The thought process is display-only: a provider that refuses to return it just runs without it.
|
|
738
|
+
payload['include_reasoning']=False;self.config['_thinking_disabled']=True
|
|
739
|
+
request=urllib.request.Request(self.config['endpoint']+suffix,data=json.dumps(payload).encode(),headers=headers)
|
|
740
|
+
event('retry',content='Provider does not return the thought process; continuing without it. Nothing was executed.',attempt=attempt+1)
|
|
741
|
+
continue
|
|
595
742
|
exc.msg='Model provider rejected request'+(': '+detail if detail else '')
|
|
596
743
|
raise
|
|
597
744
|
exc.close()
|
|
@@ -611,6 +758,8 @@ class Model:
|
|
|
611
758
|
cached=int(details.get('cached_tokens') or usage.get('cache_read_input_tokens') or 0)
|
|
612
759
|
spent=time.monotonic()-request_started
|
|
613
760
|
self.metrics['inference_seconds']+=spent;self.metrics['cached_tokens']+=cached
|
|
761
|
+
thought=thought_text(result)
|
|
762
|
+
if thought:event('thought',content=thought,seconds=round(spent,1))
|
|
614
763
|
self.metrics['prompt_tokens']+=int(usage.get('prompt_tokens',usage.get('input_tokens',0)) or 0);self.metrics['completion_tokens']+=int(usage.get('completion_tokens',usage.get('output_tokens',0)) or 0)
|
|
615
764
|
event('inference',cached_tokens=cached,seconds=round(spent,3),attempts=attempt+1,prompt_tokens=usage.get('prompt_tokens',usage.get('input_tokens',0)),completion_tokens=usage.get('completion_tokens',usage.get('output_tokens',0)),purpose='action' if allow_tools else 'summary-or-review-wrapup')
|
|
616
765
|
self.tokens += billable_tokens(usage, self.config.get('creditRates'))
|
|
@@ -651,6 +800,8 @@ class Model:
|
|
|
651
800
|
except (ValueError,TypeError):
|
|
652
801
|
return self.reject_native('Tool arguments were invalid JSON.'),usage
|
|
653
802
|
if not isinstance(arguments,dict):return self.reject_native('Rejected non-object native arguments.'),usage
|
|
803
|
+
# The plain-words step title is display-only; strip it before any argument validation or execution.
|
|
804
|
+
why=step_why(arguments.pop('why',None))
|
|
654
805
|
alias=function.get('name')
|
|
655
806
|
if alias=='tool' and isinstance(arguments.get('name'),str) and isinstance(arguments.get('arguments'),dict) and arguments.get('connection','workspace')=='workspace' and arguments['name'] in self.workspace_tool_names:
|
|
656
807
|
function={'name':'workspace_tool'};arguments={'name':arguments['name'],'arguments':arguments['arguments']}
|
|
@@ -688,6 +839,7 @@ class Model:
|
|
|
688
839
|
text+=('\n```bash\n'+value+'\n```') if kind=='bash' else ('\n```tool\n'+json.dumps(value)+'\n```')
|
|
689
840
|
else:
|
|
690
841
|
return self.reject_native('Unsupported native tool '+str(function.get('name',''))[:100]+'.'),usage
|
|
842
|
+
if why:remember_step(function.get('name'),arguments,why)
|
|
691
843
|
finish=result.get('choices',[{}])[0].get('finish_reason') if result.get('choices') else result.get('stop_reason')
|
|
692
844
|
if finish in ('length','max_tokens') or not text.strip():
|
|
693
845
|
if not retried:
|
|
@@ -753,6 +905,9 @@ class Environment(LocalEnvironment):
|
|
|
753
905
|
if self.mode=='brief':
|
|
754
906
|
# Brief: read-only until the user approves a task list, then Guided. The model sees plan-mode tools until then.
|
|
755
907
|
config['brief']=True;self.mode='plan';config['mode']='plan'
|
|
908
|
+
# Resume keeps an earlier "Approve all" for the same request instead of asking again from the first step.
|
|
909
|
+
if config.get('resuming') and self.mode=='approve' and not config.get('subagent') and (ROOT/'kimi-approve-all').exists():
|
|
910
|
+
self.mode='auto';config['mode']='auto'
|
|
756
911
|
self.tools = {(t.get('connection'),t.get('name')) for t in config.get('tools',[])}
|
|
757
912
|
self.tool_writes = {(t.get('connection'),t.get('name')):t.get('write') is not False for t in config.get('tools',[]) if isinstance(t,dict)}
|
|
758
913
|
self.plan_depth=0;self.actions_since_plan=0;self.plan_completion_nudged=False;self.plan_creation_nudged=False
|
|
@@ -806,6 +961,8 @@ class Environment(LocalEnvironment):
|
|
|
806
961
|
"""'approve_all' approves this request and lets the rest of the task run without further prompts."""
|
|
807
962
|
if verdict=='approve_all' and self.mode=='approve':
|
|
808
963
|
self.mode='auto';self.agent_config['mode']='auto';event('mode',mode='auto',content='Approved all remaining steps for this task.')
|
|
964
|
+
try:(ROOT/'kimi-approve-all').write_text('1') # remembered if this request is resumed
|
|
965
|
+
except OSError:pass
|
|
809
966
|
return verdict in ('approve','approve_all') or verdict is None
|
|
810
967
|
def plan_policy(self):
|
|
811
968
|
"""Whether a fresh task list waits for the user's pick. 'guided' (default) asks in Guided mode only."""
|
|
@@ -816,8 +973,13 @@ class Environment(LocalEnvironment):
|
|
|
816
973
|
def approve_plan(self,texts):
|
|
817
974
|
"""Show the proposed task list; return (approved, excluded_texts). Verdicts: approve | approve:0,2 | reject."""
|
|
818
975
|
brief=bool(self.agent_config.get('brief'))
|
|
819
|
-
if
|
|
820
|
-
|
|
976
|
+
if len(texts)<2 or not self.plan_policy():return True,[]
|
|
977
|
+
# Guided: a reviewed list is not asked again; a later list that adds new work asks again (BUG-0039).
|
|
978
|
+
# Items the user already saw count as known whether they kept or declined them.
|
|
979
|
+
key=lambda t:' '.join(str(t).lower().split())
|
|
980
|
+
known=getattr(self,'plan_items',set())
|
|
981
|
+
if getattr(self,'plan_reviewed',False) and not brief and all(key(t) in known for t in texts):return True,[]
|
|
982
|
+
self.plan_reviewed=True;self.plan_items=known|{key(t) for t in texts}
|
|
821
983
|
ident=os.urandom(8).hex();request={'id':ident,'kind':'plan','items':texts,'command':'Review the task list:\n'+'\n'.join('- '+t for t in texts)}
|
|
822
984
|
if brief:
|
|
823
985
|
self.brief_rounds=getattr(self,'brief_rounds',0)+1;request['brief']=True;request['round']=self.brief_rounds
|
|
@@ -858,7 +1020,8 @@ class Environment(LocalEnvironment):
|
|
|
858
1020
|
target=next((str(args[k]) for k in ('path','query','label','url','operation') if isinstance(args.get(k),(str,int))),'')
|
|
859
1021
|
if not target and isinstance(args.get('paths'),list):target=str(len(args['paths']))+' files'
|
|
860
1022
|
if not target and isinstance(args.get('urls'),list) and args['urls']:target=str(args['urls'][0])
|
|
861
|
-
|
|
1023
|
+
why=step_intent('tool',tool,args)
|
|
1024
|
+
event('tool',name=str(tool),target=target[:200],**({'why':why} if why else {}))
|
|
862
1025
|
if hasattr(self,'usage_counts') and tool not in ('read_files','parallel_reads'):self.usage_counts['tools']+=1
|
|
863
1026
|
if not isinstance(args,dict):return {'returncode':1,'output':'Tool arguments must be an object'}
|
|
864
1027
|
if conversation_readonly(self.agent_config) and tool not in READ_TOOLS:return {'returncode':1,'output':'This conversational turn permits repository reads and web research only.'}
|
|
@@ -996,19 +1159,37 @@ class Environment(LocalEnvironment):
|
|
|
996
1159
|
result='Draft skill saved, disabled until user review: '+ident;event('skill',content=result)
|
|
997
1160
|
elif tool=='generate_image':
|
|
998
1161
|
if self.mode=='plan' or self.agent_config.get('subagent'):raise ValueError('Image generation is not available in read-only or child sessions')
|
|
999
|
-
from image_generation import generate, validate
|
|
1162
|
+
from image_generation import generate, validate, IMAGE_REJECTED
|
|
1000
1163
|
validate(args)
|
|
1001
1164
|
if self.mode!='auto':
|
|
1002
|
-
ident=os.urandom(8).hex();request={'id':ident,'kind':'image','command':'Generate image '+args['filename']+' (
|
|
1165
|
+
ident=os.urandom(8).hex();request={'id':ident,'kind':'image','command':'Generate image '+args['filename']+' (uses about '+image_credit_label()+' credits): '+args['prompt'][:500]}
|
|
1003
1166
|
write('pending.json',request);event('approval',**request);decision=ROOT/('decision-'+ident);deadline=time.time()+600
|
|
1004
1167
|
while not decision.exists():
|
|
1005
1168
|
stopped()
|
|
1006
1169
|
if time.time()>deadline:raise RuntimeError('Image approval timed out')
|
|
1007
1170
|
time.sleep(.4)
|
|
1008
1171
|
approved=self.decide(decision.read_text());decision.unlink();(ROOT/'pending.json').unlink(missing_ok=True)
|
|
1009
|
-
if not approved:raise ValueError(
|
|
1172
|
+
if not approved:raise ValueError(IMAGE_REJECTED)
|
|
1010
1173
|
result=json.dumps(generate(args))
|
|
1011
1174
|
self.usage_counts['images']+=1
|
|
1175
|
+
elif tool in ('stock_photo','brand_lookup'):
|
|
1176
|
+
if self.mode=='plan' or self.agent_config.get('subagent'):raise ValueError('Stock photos and brand lookup are not available in read-only or child sessions')
|
|
1177
|
+
import media_tools
|
|
1178
|
+
result=json.dumps(media_tools.call(tool,args))
|
|
1179
|
+
elif tool in ('deck_check','deck_import','find_image','find_icon','image_prep'):
|
|
1180
|
+
# Deck quality tools (worker/deck_tools.py). A plain deck_check only reads; everything else writes files.
|
|
1181
|
+
read_only=tool=='deck_check' and not args.get('fix') and not args.get('pdf')
|
|
1182
|
+
if (self.mode=='plan' or self.agent_config.get('subagent')) and not read_only:raise ValueError('This deck tool writes files, which is disabled in plan/subagent mode (deck_check without fix or pdf still works)')
|
|
1183
|
+
import deck_tools
|
|
1184
|
+
def ensure_browser():
|
|
1185
|
+
if (ROOT/'browser-ready').exists() or os.getenv('MINI_DECK_CHROMIUM'):return True
|
|
1186
|
+
import browser_local
|
|
1187
|
+
if not browser_local.laptop() or self.mode=='plan' or self.agent_config.get('subagent') or getattr(self,'deck_browser_declined',False):return False
|
|
1188
|
+
try:return browser_local.ask_install(ROOT,{'check':'render the deck slides to check them'},event,stopped)
|
|
1189
|
+
except ValueError:self.deck_browser_declined=True;return False
|
|
1190
|
+
out,shot=deck_tools.call(tool,args,ROOT,REPO,ensure_browser)
|
|
1191
|
+
result=json.dumps(out)
|
|
1192
|
+
if shot:self.attach_vision(shot)
|
|
1012
1193
|
elif tool=='computer':
|
|
1013
1194
|
# Computer use on the Mac. The app enforces every rule; each session (and focus change) asks here, even in Auto mode.
|
|
1014
1195
|
if self.mode=='plan' or self.agent_config.get('subagent') or not computer_use.available():raise ValueError('Computer use is only available in local runs in the Mac app, with it turned on in Settings')
|
|
@@ -1444,6 +1625,16 @@ class Environment(LocalEnvironment):
|
|
|
1444
1625
|
if self.design_review_waits>1:
|
|
1445
1626
|
raise LimitsExceeded({'role':'exit','content':reason,'extra':{'exit_status':'VerificationIncomplete','submission':reason}})
|
|
1446
1627
|
return {'returncode':1,'output':reason}
|
|
1628
|
+
if self.mode!='plan' and not self.agent_config.get('subagent') and not getattr(self,'deliverable_nudged',False) and self.agent_config.get('conversation_route') in (None,'build'):
|
|
1629
|
+
# A presentation or PDF request must leave a file the app can open (sent once; the agent's explanation stands after that).
|
|
1630
|
+
try:
|
|
1631
|
+
from conversation import deliverable_issue
|
|
1632
|
+
from runtime_control import completion_paths
|
|
1633
|
+
note=deliverable_issue(self.agent_config.get('task',''),completion_paths(REPO,self.review_base),REPO)
|
|
1634
|
+
except Exception:note=None
|
|
1635
|
+
if note:
|
|
1636
|
+
self.deliverable_nudged=True;event('retry',content='Completion held: the requested presentation or document file is missing.')
|
|
1637
|
+
return {'returncode':1,'output':note}
|
|
1447
1638
|
raise Submitted({'role':'exit','content':'Task complete','extra':{'exit_status':'Submitted','submission':'Task complete'}})
|
|
1448
1639
|
if self.mode == 'plan' and self.agent_config.get('brief'):
|
|
1449
1640
|
return {'returncode':1,'output':'Brief mode: shell commands unlock after the user approves your task list. Read files with the workspace tools, then call todo with the proposed items and your questions and wait for the review.'}
|
|
@@ -1467,9 +1658,10 @@ class Environment(LocalEnvironment):
|
|
|
1467
1658
|
decision.unlink()
|
|
1468
1659
|
(ROOT / 'pending.json').unlink(missing_ok=True)
|
|
1469
1660
|
if not approved: return {'returncode':1,'output':'User rejected the command. Choose another approach.'}
|
|
1470
|
-
|
|
1661
|
+
why=step_intent('cmd',None,command)
|
|
1662
|
+
event('command', command=command,**({'why':why} if why else {}))
|
|
1471
1663
|
# Never pass model credentials into generated shell commands.
|
|
1472
|
-
env = {k:v for k,v in os.environ.items() if k not in ('MODEL_API_KEY','VERCEL_OIDC_TOKEN','EXA_API_KEY','FIRECRAWL_API_KEY','OPENROUTER_API_KEY','MINI_IMAGE_URL','MINI_IMAGE_TOKEN','MINI_RESEARCH_TOKEN')}
|
|
1664
|
+
env = {k:v for k,v in os.environ.items() if k not in ('MODEL_API_KEY','SIDE_MODEL_API_KEY','VERCEL_OIDC_TOKEN','EXA_API_KEY','FIRECRAWL_API_KEY','OPENROUTER_API_KEY','PIXABAY_API_KEY','BRANDFETCH_API_KEY','MINI_IMAGE_URL','MINI_IMAGE_TOKEN','MINI_RESEARCH_TOKEN')}
|
|
1473
1665
|
env.update(VAULT)
|
|
1474
1666
|
# The preview iframe reaches dev servers through the sandbox's public *.vercel.run host; Vite rejects unknown hosts otherwise.
|
|
1475
1667
|
env.setdefault('__VITE_ADDITIONAL_SERVER_ALLOWED_HOSTS','.vercel.run')
|
|
@@ -1490,9 +1682,9 @@ class Environment(LocalEnvironment):
|
|
|
1490
1682
|
time.sleep(.1)
|
|
1491
1683
|
proc.wait()
|
|
1492
1684
|
size = os.fstat(log.fileno()).st_size
|
|
1493
|
-
log.seek(max(0, size-
|
|
1494
|
-
output = log.read(
|
|
1495
|
-
if size >
|
|
1685
|
+
log.seek(max(0, size-OUTPUT_CAP))
|
|
1686
|
+
output = log.read(OUTPUT_CAP).decode('utf-8',errors='replace')
|
|
1687
|
+
if size > OUTPUT_CAP: output = '[Earlier output truncated; the full log is saved under command-logs]\n' + output
|
|
1496
1688
|
if interrupted: output += '\nCommand stopped or exceeded time/output limit.'
|
|
1497
1689
|
saved_log=None
|
|
1498
1690
|
if size>12000 or time.time()-start>=30:
|
|
@@ -1568,12 +1760,22 @@ def goal_loop(agent,model,config,result):
|
|
|
1568
1760
|
def run_usage(model,environment):
|
|
1569
1761
|
"""Usage by category for the Settings breakdown (model and subagent tokens; counts for the rest)."""
|
|
1570
1762
|
counts=getattr(environment,'usage_counts',None) or {}
|
|
1571
|
-
return {'model':int(getattr(model,'tokens',0) or 0),'subagents':int(getattr(environment,'subagent_tokens',0) or 0),'images':int(counts.get('images',0)),
|
|
1572
|
-
'research':int(getattr(environment,'web_attempts',0) or 0),'connectors':int(counts.get('connectors',0)),'tools':int(counts.get('tools',0))
|
|
1763
|
+
return {'model':int(getattr(model,'tokens',0) or 0),'subagents':int(getattr(environment,'subagent_tokens',0) or 0),'images':int(counts.get('images',0)),**({'imageTokens':int(image_billed())} if image_billed() else {}),
|
|
1764
|
+
'research':int(getattr(environment,'web_attempts',0) or 0),'connectors':int(counts.get('connectors',0)),'tools':int(counts.get('tools',0)),
|
|
1765
|
+
**{k:int((getattr(model,'metrics',None) or {}).get(src,0) or 0) for k,src in (('prompt','prompt_tokens'),('cached','cached_tokens'),('completion','completion_tokens'),('masked','masked_chars'))}}
|
|
1573
1766
|
|
|
1574
1767
|
def main():
|
|
1575
1768
|
config = json.loads((ROOT / 'request.json').read_text())
|
|
1576
1769
|
write('status.json', {'state':'running','started':time.time(),'boot':boot_id(),'process':identity(os.getpid())})
|
|
1770
|
+
if not config.get('resuming') and not config.get('subagent'):(ROOT/'kimi-approve-all').unlink(missing_ok=True) # a new request asks afresh
|
|
1771
|
+
from build_planner import finished_phase_reply
|
|
1772
|
+
nothing_to_do=finished_phase_reply(REPO,config.get('task'))
|
|
1773
|
+
if nothing_to_do and not config.get('subagent'):
|
|
1774
|
+
event('answer',content=nothing_to_do)
|
|
1775
|
+
write('status.json',{'state':'completed','result':{'exit_status':'Submitted','submission':nothing_to_do},'tokens':0,'calls':0,'usage':{'endReason':'completed'}})
|
|
1776
|
+
event('finished',state='completed')
|
|
1777
|
+
for name in ('pending.json','run.lock'):(ROOT/name).unlink(missing_ok=True)
|
|
1778
|
+
return
|
|
1577
1779
|
import goals
|
|
1578
1780
|
goal=None
|
|
1579
1781
|
if not config.get('subagent'):
|
|
@@ -1604,7 +1806,7 @@ def main():
|
|
|
1604
1806
|
else:ask_first.apply(config,REPO)
|
|
1605
1807
|
except Exception as exc:
|
|
1606
1808
|
message=str(exc).replace(os.environ.get('MODEL_API_KEY','__absent__'),'[redacted]')
|
|
1607
|
-
write('status.json',{'state':'error','error':message,'tokens':model.tokens,'calls':model.calls})
|
|
1809
|
+
write('status.json',{'state':'error','error':message,'tokens':model.tokens+image_billed(),'calls':model.calls})
|
|
1608
1810
|
event('error',content=message)
|
|
1609
1811
|
(ROOT/'pending.json').unlink(missing_ok=True);(ROOT/'run.lock').unlink(missing_ok=True)
|
|
1610
1812
|
return
|
|
@@ -1641,12 +1843,12 @@ def main():
|
|
|
1641
1843
|
if config.get('subagent') and config.get('mode')=='plan':
|
|
1642
1844
|
system = REVIEW_SYSTEM
|
|
1643
1845
|
if conversation_readonly(config):
|
|
1644
|
-
system=READONLY_SYSTEM
|
|
1846
|
+
system=READONLY_SYSTEM+'\n'+reply_language_rule(config) # the project's reply language holds in chat turns too
|
|
1645
1847
|
if read_only_tools(config.get('tools')):system+=' Connected apps: you may call their reading tools listed below (for example list or search emails, read a sheet) with one tool fence {"connection":"connection-id","name":"tool-name","arguments":{}} or connected_tool; each call still needs the user\'s approval unless they chose Auto. Tools that change data wait for a build turn. Reading tools catalog: {{tool_catalog}}'
|
|
1646
1848
|
if config.get('conversation_fallback'):system+=' Intent classification was inconclusive. Ask a concise clarification about the desired outcome; do not assume implementation authorization.'
|
|
1647
1849
|
elif conversation_enabled(config):system+='\nAct as a practical CTO: explain the recommendation, reason and meaningful tradeoffs concisely. Prioritize the current user requirements; distinguish evidence from assumptions. Implement the authorized scope and retain every verification requirement.'
|
|
1648
1850
|
if conversation_enabled(config) and config.get('focused_tools') and not conversation_readonly(config):
|
|
1649
|
-
system=CORE_PRODUCT_SYSTEM
|
|
1851
|
+
system=CORE_PRODUCT_SYSTEM+'\n'+reply_language_rule(config)
|
|
1650
1852
|
if config.get('require_changes'):system+=' A repository patch is required; an unchanged repository is not completion.'
|
|
1651
1853
|
if config.get('tools'):system+=' Enabled integration catalog (the app runs each call; Auto mode needs no approval): {{tool_catalog}}'
|
|
1652
1854
|
if conversation_enabled(config):system+='\n'+WORKFLOW_GUIDANCE
|
|
@@ -1670,6 +1872,11 @@ def main():
|
|
|
1670
1872
|
except Exception:pass
|
|
1671
1873
|
except Exception:pass # hooks guidance never blocks a run
|
|
1672
1874
|
if config.get('_role'):system+='\n'+role_engine.prompt(config['_role'],readonly=conversation_readonly(config) or config.get('mode')=='plan')
|
|
1875
|
+
elif not conversation_readonly(config):
|
|
1876
|
+
try:
|
|
1877
|
+
rule=role_engine.stack_rule(config.get('task',''),REPO)
|
|
1878
|
+
if rule:system+='\n'+rule
|
|
1879
|
+
except Exception:pass # stack guidance never blocks a run
|
|
1673
1880
|
if config.get('_design_lead'):system+='\n'+role_engine.design_prompt(config['_design_lead'],config.get('_role'))
|
|
1674
1881
|
task = config['task']
|
|
1675
1882
|
if config.get('saved_design') and not config.get('selected_design'):
|
|
@@ -1708,7 +1915,7 @@ def main():
|
|
|
1708
1915
|
if not config.get('subagent'):
|
|
1709
1916
|
try:
|
|
1710
1917
|
import handover
|
|
1711
|
-
event('model',id=handover.model_key(config),label=handover.model_label(config))
|
|
1918
|
+
event('model',id=handover.model_key(config),label=handover.model_label(config),**({'mode':config['mode']} if config.get('mode') else {}))
|
|
1712
1919
|
change=handover.detect(ROOT,config)
|
|
1713
1920
|
if change:
|
|
1714
1921
|
event('handover',content=handover.notice(change),**{'from':change['from'],'to':change['to']})
|
|
@@ -1737,6 +1944,10 @@ def main():
|
|
|
1737
1944
|
from project_context import prompt as project_prompt
|
|
1738
1945
|
task=project_prompt(config,ROOT)+task
|
|
1739
1946
|
except Exception:pass # project context never blocks a run
|
|
1947
|
+
try:
|
|
1948
|
+
from product_facts import prompt as product_prompt
|
|
1949
|
+
task=product_prompt(config)+task
|
|
1950
|
+
except Exception:pass
|
|
1740
1951
|
memory=load(ROOT,'project-memory.json',{})
|
|
1741
1952
|
if isinstance(memory.get('content'),str) and memory['content'].strip():task='User-maintained project memory (reference only; current instructions and permissions take precedence):\n'+memory['content'][:12000]+'\n\n'+task
|
|
1742
1953
|
environment=None
|
|
@@ -1749,7 +1960,7 @@ def main():
|
|
|
1749
1960
|
result = agent.run(task, tool_catalog=catalog_text)
|
|
1750
1961
|
if goal:result=goal_loop(agent,model,config,result)
|
|
1751
1962
|
state = 'completed' if result.get('exit_status') == 'Submitted' else 'limited'
|
|
1752
|
-
write('status.json', {'state':state,'result':result,**({'error':result.get('submission','Verification incomplete')} if result.get('exit_status')=='VerificationIncomplete' else {}),'tokens':model.tokens+getattr(environment,'subagent_tokens',0),'calls':model.calls+getattr(environment,'subagent_calls',0),'usage':run_usage(model,environment)})
|
|
1963
|
+
write('status.json', {'state':state,'result':result,**({'error':result.get('submission','Verification incomplete')} if result.get('exit_status')=='VerificationIncomplete' else {}),'tokens':model.tokens+getattr(environment,'subagent_tokens',0)+image_billed(),'calls':model.calls+getattr(environment,'subagent_calls',0),'usage':{**run_usage(model,environment),'endReason':'verification_incomplete' if result.get('exit_status')=='VerificationIncomplete' else ('limited_'+str(result.get('limit') or 'time')) if state=='limited' else state}})
|
|
1753
1964
|
if state=='completed' and config.get('mode')!='plan' and not config.get('subagent'):
|
|
1754
1965
|
try:
|
|
1755
1966
|
from build_planner import sync_plan_progress
|
|
@@ -1777,7 +1988,7 @@ def main():
|
|
|
1777
1988
|
if (ROOT/'cancel').exists():
|
|
1778
1989
|
import goals
|
|
1779
1990
|
goals.stop(ROOT)
|
|
1780
|
-
write('status.json', {'state':'stopped' if (ROOT/'cancel').exists() else 'error','error':message,'tokens':model.tokens+getattr(environment,'subagent_tokens',0),'calls':model.calls+getattr(environment,'subagent_calls',0),'usage':run_usage(model,environment)})
|
|
1991
|
+
write('status.json', {'state':'stopped' if (ROOT/'cancel').exists() else 'error','error':message,'tokens':model.tokens+getattr(environment,'subagent_tokens',0)+image_billed(),'calls':model.calls+getattr(environment,'subagent_calls',0),'usage':{**run_usage(model,environment),'endReason':'stopped' if (ROOT/'cancel').exists() else 'error'}})
|
|
1781
1992
|
event('error', content=message)
|
|
1782
1993
|
finally:
|
|
1783
1994
|
try:
|