mlai-code 0.3.2 → 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.
Files changed (53) hide show
  1. package/README.md +1 -1
  2. package/package.json +1 -1
  3. package/src/cli.mjs +27 -7
  4. package/src/engine.mjs +1 -1
  5. package/src/home.mjs +1 -1
  6. package/src/parity.mjs +3 -1
  7. package/src/render.mjs +3 -1
  8. package/src/runtime.mjs +21 -1
  9. package/src/sandbox.mjs +19 -3
  10. package/src/session.mjs +22 -2
  11. package/src/shared-data.mjs +1 -1
  12. package/src/tui/app.mjs +22 -4
  13. package/src/tui/chat.mjs +8 -6
  14. package/src/tui/cmd-core.mjs +2 -2
  15. package/src/tui/cmd-extensibility.mjs +8 -2
  16. package/src/tui/commands.mjs +2 -1
  17. package/src/tui/statusline.mjs +2 -1
  18. package/src/wakeups.mjs +2 -2
  19. package/vendor/client-sdk/index.cjs +3 -3
  20. package/vendor/cloud-cli/mlai.mjs +169 -25
  21. package/worker/build_planner.py +75 -7
  22. package/worker/cloud_pty.py +91 -2
  23. package/worker/command_safety.py +25 -1
  24. package/worker/compaction_brief.py +186 -0
  25. package/worker/context_manager.py +6 -0
  26. package/worker/conversation.py +58 -1
  27. package/worker/deck_render.js +11 -0
  28. package/worker/deck_tools.py +825 -0
  29. package/worker/git_sync.py +38 -13
  30. package/worker/goals.py +4 -0
  31. package/worker/image_generation.py +102 -23
  32. package/worker/kimi_bridge.py +340 -32
  33. package/worker/kimi_gates.py +49 -0
  34. package/worker/kimi_hook.py +65 -12
  35. package/worker/media_tools.py +179 -0
  36. package/worker/memory.py +2 -2
  37. package/worker/mlai_hooks.py +93 -3
  38. package/worker/mlai_mcp.py +23 -5
  39. package/worker/model_stream.py +21 -7
  40. package/worker/offline_guard.py +1 -1
  41. package/worker/preview.py +47 -4
  42. package/worker/product_facts.py +18 -0
  43. package/worker/project_context.py +33 -7
  44. package/worker/reply_language.py +92 -10
  45. package/worker/roles.json +199 -37
  46. package/worker/roles.py +243 -8
  47. package/worker/runner.py +241 -36
  48. package/worker/site_check.py +279 -0
  49. package/worker/skill_library.py +15 -3
  50. package/worker/skill_pack.py +170 -16
  51. package/worker/tool_catalog.py +3 -2
  52. package/worker/verification.py +43 -11
  53. 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
@@ -98,6 +98,54 @@ def vault_guidance():
98
98
  def _clean_name(value, limit=60):
99
99
  return ' '.join(str(value or '').split())[:limit]
100
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
+
101
149
  def connection_status_lines(config, accounts):
102
150
  """Exact connected / not-connected facts for this run, so the agent never guesses.
103
151
  Sources: apps the account signed in to through Pipedream (read server-side at start), Vault secrets tagged for a
@@ -132,6 +180,10 @@ def connection_status_lines(config, accounts):
132
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.')
133
181
  elif apps is None and 'apps' in accounts:
134
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))
135
187
  kinds = accounts.get('vaultKinds')
136
188
  if isinstance(kinds, list) and kinds:
137
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.')
@@ -154,7 +206,9 @@ def connect_guidance(config=None):
154
206
  return ' '.join(lines)+'\n\n'
155
207
 
156
208
  def write(name, data):
157
- tmp = ROOT / (name + '.tmp')
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')
158
212
  tmp.write_text(json.dumps(unvault(data)))
159
213
  tmp.replace(ROOT / name)
160
214
 
@@ -167,14 +221,67 @@ def event(event_type, **data):
167
221
  f.write(json.dumps(unvault({'type': event_type, 'time': time.time(), **data})) + '\n')
168
222
 
169
223
  INFERENCE_TEXT_SEEN=set()
224
+ INFERENCE_LOCK=threading.RLock()
225
+ INFERENCE_SEQ=[0]
226
+ INFERENCE_LIVE={}
170
227
  def inference_progress(**data):
171
- snapshot={'type':'inference_progress','time':time.time(),**data}
172
- write('inference-progress.json',snapshot)
173
- first_text=bool(data.get('content')) and data['id'] not in INFERENCE_TEXT_SEEN
174
- if first_text:INFERENCE_TEXT_SEEN.add(data['id'])
175
- # Keep initial/first-text/final evidence, not every cumulative snapshot in history.
176
- if data.get('state')!='running' or data.get('seconds')==0 or first_text:
177
- event('inference_progress',**data)
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:]
178
285
 
179
286
  PARALLEL_READS=frozenset(('read_file','read_files','list_files','search_text','context_read','command_output','repo_map','symbols','skill_load','tool_search'))
180
287
  def run_parallel(jobs,workers=4):
@@ -299,7 +406,18 @@ def billable_tokens(usage, rates=None):
299
406
  return int(math.ceil((prompt - cached - written) * rates['input'] + cached * rates['cached'] + written * rates['cacheWrite'] + output * rates['output']))
300
407
  return int(math.ceil(prompt - cached + cached * CACHED_INPUT_WEIGHT + output * OUTPUT_WEIGHT))
301
408
 
302
- CREDITS_OUT_NOTE='You have used all your credits for this month, so this run stopped. Your files are saved. Pick a plan or buy a top-up in Settings > Billing, then press Resume to continue.'
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.'
303
421
  ACCOUNT_WRAP_TOKENS=60_000 # room for the final summary after the account runs out; then the run stops
304
422
 
305
423
  class Model:
@@ -307,13 +425,14 @@ class Model:
307
425
  """Account credits (LIMIT/BILL): at the allowance ask for a final summary, and stop shortly after. The user sees both."""
308
426
  left=self.config.get('accountTokensLeft')
309
427
  if self.config.get('subagent') or not isinstance(left,(int,float)) or isinstance(left,bool):return
310
- if self.tokens>=max(0,int(left))+ACCOUNT_WRAP_TOKENS:
428
+ used=self.tokens+image_billed()
429
+ if used>=max(0,int(left))+ACCOUNT_WRAP_TOKENS:
311
430
  event('account_limit',phase='stopped',content=CREDITS_OUT_NOTE)
312
431
  raise LimitsExceeded({'role':'exit','content':CREDITS_OUT_NOTE,'extra':{'exit_status':'LimitsExceeded','limit':'tokens','limitNote':CREDITS_OUT_NOTE,'submission':CREDITS_OUT_NOTE}})
313
- if self.tokens>=max(0,int(left)) and not getattr(self,'account_warned',False):
432
+ if used>=max(0,int(left)) and not getattr(self,'account_warned',False):
314
433
  self.account_warned=True
315
- event('account_limit',phase='wrapping',content='Credits used up. The agent is writing a short summary and will stop.')
316
- messages.append({'role':'user','content':'The account has used all its credits. Do not start new work or run more commands. Write the final summary now (what changed, what was verified, what is left) and finish.'})
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.'})
317
436
 
318
437
  def __init__(self, config):
319
438
  self.config = config
@@ -374,7 +493,10 @@ class Model:
374
493
  message=instruction.get('message','')
375
494
  if isinstance(message,str) and message.strip():
376
495
  messages.append({'role':'user','content':message[:5000]})
377
- 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
378
500
  if 'attachments/' in message and not self.vision_disabled:
379
501
  import browser_pane;seen=browser_pane.steering_image(ROOT,message)
380
502
  if seen:self.pending_vision=seen
@@ -520,8 +642,8 @@ class Model:
520
642
  # This GLM endpoint accepts low/high/max only. Medium is adaptive: deep reasoning for the opening plan,
521
643
  # plan/research routes and recovery after a failed step; fast reasoning for routine steps.
522
644
  if effort=='medium':effort='high' if self.needs_depth(clean) else 'low'
523
- payload.update(reasoning_effort=effort if effort in ('low','high','max') else 'low',include_reasoning=False,parallel_tool_calls=os.environ.get('MINI_PARALLEL_TOOLS','1')!='0')
524
- 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}}}]
525
647
  if self.config.get('subagent') and self.config.get('mode')=='plan':
526
648
  file_properties={'path':{'type':'string'},'start':{'type':'integer','minimum':1},'end':{'type':'integer','minimum':1}}
527
649
  schemas=[('read_file','Read a repository file range.',file_properties,['path']),
@@ -535,10 +657,10 @@ class Model:
535
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}}})
536
658
  if self.config.get('mode')!='plan' and not self.config.get('subagent'):
537
659
  direct_schemas=[
538
- ('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']),
539
- ('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'])]
540
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)
541
- 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}}})
542
664
  if conversation_readonly(self.config):
543
665
  tools[0]['function']['parameters']['properties']['name']['enum']=sorted(READ_TOOLS)
544
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}}})
@@ -567,8 +689,16 @@ class Model:
567
689
  if streaming:
568
690
  stream_id=os.urandom(8).hex()
569
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)
570
700
  try:
571
- result=request_stream(request,stopped,lambda content,seconds,first:inference_progress(id=stream_id,state='running',content=content[:20000],seconds=round(seconds,3),first_text_seconds=first),timeout=240 if self.config.get('provider')=='isoquant' else 100)
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)
572
702
  except Exception:
573
703
  inference_progress(id=stream_id,state='failed',content='')
574
704
  raise
@@ -591,12 +721,24 @@ class Model:
591
721
  request=urllib.request.Request(self.config['endpoint']+suffix,data=json.dumps(payload).encode(),headers=headers)
592
722
  event('retry',content='Provider does not support streaming; using complete responses for this request.')
593
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
594
730
  if exc.code==400 and 'reasoning' in detail.lower() and payload.get('reasoning_effort') not in (None,'low') and attempt<2:
595
731
  payload['reasoning_effort']='low'
596
732
  self.config['_effective_reasoning_effort']='low'
597
733
  request=urllib.request.Request(self.config['endpoint']+suffix,data=json.dumps(payload).encode(),headers=headers)
598
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)
599
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
600
742
  exc.msg='Model provider rejected request'+(': '+detail if detail else '')
601
743
  raise
602
744
  exc.close()
@@ -616,6 +758,8 @@ class Model:
616
758
  cached=int(details.get('cached_tokens') or usage.get('cache_read_input_tokens') or 0)
617
759
  spent=time.monotonic()-request_started
618
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))
619
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)
620
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')
621
765
  self.tokens += billable_tokens(usage, self.config.get('creditRates'))
@@ -656,6 +800,8 @@ class Model:
656
800
  except (ValueError,TypeError):
657
801
  return self.reject_native('Tool arguments were invalid JSON.'),usage
658
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))
659
805
  alias=function.get('name')
660
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:
661
807
  function={'name':'workspace_tool'};arguments={'name':arguments['name'],'arguments':arguments['arguments']}
@@ -693,6 +839,7 @@ class Model:
693
839
  text+=('\n```bash\n'+value+'\n```') if kind=='bash' else ('\n```tool\n'+json.dumps(value)+'\n```')
694
840
  else:
695
841
  return self.reject_native('Unsupported native tool '+str(function.get('name',''))[:100]+'.'),usage
842
+ if why:remember_step(function.get('name'),arguments,why)
696
843
  finish=result.get('choices',[{}])[0].get('finish_reason') if result.get('choices') else result.get('stop_reason')
697
844
  if finish in ('length','max_tokens') or not text.strip():
698
845
  if not retried:
@@ -758,6 +905,9 @@ class Environment(LocalEnvironment):
758
905
  if self.mode=='brief':
759
906
  # Brief: read-only until the user approves a task list, then Guided. The model sees plan-mode tools until then.
760
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'
761
911
  self.tools = {(t.get('connection'),t.get('name')) for t in config.get('tools',[])}
762
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)}
763
913
  self.plan_depth=0;self.actions_since_plan=0;self.plan_completion_nudged=False;self.plan_creation_nudged=False
@@ -811,6 +961,8 @@ class Environment(LocalEnvironment):
811
961
  """'approve_all' approves this request and lets the rest of the task run without further prompts."""
812
962
  if verdict=='approve_all' and self.mode=='approve':
813
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
814
966
  return verdict in ('approve','approve_all') or verdict is None
815
967
  def plan_policy(self):
816
968
  """Whether a fresh task list waits for the user's pick. 'guided' (default) asks in Guided mode only."""
@@ -821,8 +973,13 @@ class Environment(LocalEnvironment):
821
973
  def approve_plan(self,texts):
822
974
  """Show the proposed task list; return (approved, excluded_texts). Verdicts: approve | approve:0,2 | reject."""
823
975
  brief=bool(self.agent_config.get('brief'))
824
- if (getattr(self,'plan_reviewed',False) and not brief) or len(texts)<2 or not self.plan_policy():return True,[]
825
- self.plan_reviewed=True
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}
826
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)}
827
984
  if brief:
828
985
  self.brief_rounds=getattr(self,'brief_rounds',0)+1;request['brief']=True;request['round']=self.brief_rounds
@@ -863,7 +1020,8 @@ class Environment(LocalEnvironment):
863
1020
  target=next((str(args[k]) for k in ('path','query','label','url','operation') if isinstance(args.get(k),(str,int))),'')
864
1021
  if not target and isinstance(args.get('paths'),list):target=str(len(args['paths']))+' files'
865
1022
  if not target and isinstance(args.get('urls'),list) and args['urls']:target=str(args['urls'][0])
866
- event('tool',name=str(tool),target=target[:200])
1023
+ why=step_intent('tool',tool,args)
1024
+ event('tool',name=str(tool),target=target[:200],**({'why':why} if why else {}))
867
1025
  if hasattr(self,'usage_counts') and tool not in ('read_files','parallel_reads'):self.usage_counts['tools']+=1
868
1026
  if not isinstance(args,dict):return {'returncode':1,'output':'Tool arguments must be an object'}
869
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.'}
@@ -1001,19 +1159,37 @@ class Environment(LocalEnvironment):
1001
1159
  result='Draft skill saved, disabled until user review: '+ident;event('skill',content=result)
1002
1160
  elif tool=='generate_image':
1003
1161
  if self.mode=='plan' or self.agent_config.get('subagent'):raise ValueError('Image generation is not available in read-only or child sessions')
1004
- from image_generation import generate, validate
1162
+ from image_generation import generate, validate, IMAGE_REJECTED
1005
1163
  validate(args)
1006
1164
  if self.mode!='auto':
1007
- ident=os.urandom(8).hex();request={'id':ident,'kind':'image','command':'Generate image '+args['filename']+' (included, no extra credits): '+args['prompt'][:500]}
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]}
1008
1166
  write('pending.json',request);event('approval',**request);decision=ROOT/('decision-'+ident);deadline=time.time()+600
1009
1167
  while not decision.exists():
1010
1168
  stopped()
1011
1169
  if time.time()>deadline:raise RuntimeError('Image approval timed out')
1012
1170
  time.sleep(.4)
1013
1171
  approved=self.decide(decision.read_text());decision.unlink();(ROOT/'pending.json').unlink(missing_ok=True)
1014
- if not approved:raise ValueError('Image generation rejected')
1172
+ if not approved:raise ValueError(IMAGE_REJECTED)
1015
1173
  result=json.dumps(generate(args))
1016
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)
1017
1193
  elif tool=='computer':
1018
1194
  # Computer use on the Mac. The app enforces every rule; each session (and focus change) asks here, even in Auto mode.
1019
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')
@@ -1449,6 +1625,16 @@ class Environment(LocalEnvironment):
1449
1625
  if self.design_review_waits>1:
1450
1626
  raise LimitsExceeded({'role':'exit','content':reason,'extra':{'exit_status':'VerificationIncomplete','submission':reason}})
1451
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}
1452
1638
  raise Submitted({'role':'exit','content':'Task complete','extra':{'exit_status':'Submitted','submission':'Task complete'}})
1453
1639
  if self.mode == 'plan' and self.agent_config.get('brief'):
1454
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.'}
@@ -1472,9 +1658,10 @@ class Environment(LocalEnvironment):
1472
1658
  decision.unlink()
1473
1659
  (ROOT / 'pending.json').unlink(missing_ok=True)
1474
1660
  if not approved: return {'returncode':1,'output':'User rejected the command. Choose another approach.'}
1475
- event('command', command=command)
1661
+ why=step_intent('cmd',None,command)
1662
+ event('command', command=command,**({'why':why} if why else {}))
1476
1663
  # Never pass model credentials into generated shell commands.
1477
- 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','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')}
1478
1665
  env.update(VAULT)
1479
1666
  # The preview iframe reaches dev servers through the sandbox's public *.vercel.run host; Vite rejects unknown hosts otherwise.
1480
1667
  env.setdefault('__VITE_ADDITIONAL_SERVER_ALLOWED_HOSTS','.vercel.run')
@@ -1573,13 +1760,22 @@ def goal_loop(agent,model,config,result):
1573
1760
  def run_usage(model,environment):
1574
1761
  """Usage by category for the Settings breakdown (model and subagent tokens; counts for the rest)."""
1575
1762
  counts=getattr(environment,'usage_counts',None) or {}
1576
- return {'model':int(getattr(model,'tokens',0) or 0),'subagents':int(getattr(environment,'subagent_tokens',0) or 0),'images':int(counts.get('images',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 {}),
1577
1764
  'research':int(getattr(environment,'web_attempts',0) or 0),'connectors':int(counts.get('connectors',0)),'tools':int(counts.get('tools',0)),
1578
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'))}}
1579
1766
 
1580
1767
  def main():
1581
1768
  config = json.loads((ROOT / 'request.json').read_text())
1582
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
1583
1779
  import goals
1584
1780
  goal=None
1585
1781
  if not config.get('subagent'):
@@ -1610,7 +1806,7 @@ def main():
1610
1806
  else:ask_first.apply(config,REPO)
1611
1807
  except Exception as exc:
1612
1808
  message=str(exc).replace(os.environ.get('MODEL_API_KEY','__absent__'),'[redacted]')
1613
- 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})
1614
1810
  event('error',content=message)
1615
1811
  (ROOT/'pending.json').unlink(missing_ok=True);(ROOT/'run.lock').unlink(missing_ok=True)
1616
1812
  return
@@ -1647,12 +1843,12 @@ def main():
1647
1843
  if config.get('subagent') and config.get('mode')=='plan':
1648
1844
  system = REVIEW_SYSTEM
1649
1845
  if conversation_readonly(config):
1650
- system=READONLY_SYSTEM
1846
+ system=READONLY_SYSTEM+'\n'+reply_language_rule(config) # the project's reply language holds in chat turns too
1651
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}}'
1652
1848
  if config.get('conversation_fallback'):system+=' Intent classification was inconclusive. Ask a concise clarification about the desired outcome; do not assume implementation authorization.'
1653
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.'
1654
1850
  if conversation_enabled(config) and config.get('focused_tools') and not conversation_readonly(config):
1655
- system=CORE_PRODUCT_SYSTEM
1851
+ system=CORE_PRODUCT_SYSTEM+'\n'+reply_language_rule(config)
1656
1852
  if config.get('require_changes'):system+=' A repository patch is required; an unchanged repository is not completion.'
1657
1853
  if config.get('tools'):system+=' Enabled integration catalog (the app runs each call; Auto mode needs no approval): {{tool_catalog}}'
1658
1854
  if conversation_enabled(config):system+='\n'+WORKFLOW_GUIDANCE
@@ -1676,6 +1872,11 @@ def main():
1676
1872
  except Exception:pass
1677
1873
  except Exception:pass # hooks guidance never blocks a run
1678
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
1679
1880
  if config.get('_design_lead'):system+='\n'+role_engine.design_prompt(config['_design_lead'],config.get('_role'))
1680
1881
  task = config['task']
1681
1882
  if config.get('saved_design') and not config.get('selected_design'):
@@ -1714,7 +1915,7 @@ def main():
1714
1915
  if not config.get('subagent'):
1715
1916
  try:
1716
1917
  import handover
1717
- 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 {}))
1718
1919
  change=handover.detect(ROOT,config)
1719
1920
  if change:
1720
1921
  event('handover',content=handover.notice(change),**{'from':change['from'],'to':change['to']})
@@ -1743,6 +1944,10 @@ def main():
1743
1944
  from project_context import prompt as project_prompt
1744
1945
  task=project_prompt(config,ROOT)+task
1745
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
1746
1951
  memory=load(ROOT,'project-memory.json',{})
1747
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
1748
1953
  environment=None
@@ -1755,7 +1960,7 @@ def main():
1755
1960
  result = agent.run(task, tool_catalog=catalog_text)
1756
1961
  if goal:result=goal_loop(agent,model,config,result)
1757
1962
  state = 'completed' if result.get('exit_status') == 'Submitted' else 'limited'
1758
- 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),'endReason':'verification_incomplete' if result.get('exit_status')=='VerificationIncomplete' else ('limited_'+str(result.get('limit') or 'time')) if state=='limited' else state}})
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}})
1759
1964
  if state=='completed' and config.get('mode')!='plan' and not config.get('subagent'):
1760
1965
  try:
1761
1966
  from build_planner import sync_plan_progress
@@ -1783,7 +1988,7 @@ def main():
1783
1988
  if (ROOT/'cancel').exists():
1784
1989
  import goals
1785
1990
  goals.stop(ROOT)
1786
- 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),'endReason':'stopped' if (ROOT/'cancel').exists() else 'error'}})
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'}})
1787
1992
  event('error', content=message)
1788
1993
  finally:
1789
1994
  try: