mixdog 1.4.3 → 1.4.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (281) hide show
  1. package/package.json +1 -2
  2. package/src/cli.mjs +5 -1
  3. package/src/defaults/shipped-history.json +30 -2
  4. package/src/defaults/skills/browser-use/SKILL.md +148 -273
  5. package/src/defaults/skills/browser-use/references/devtools.md +14 -0
  6. package/src/defaults/skills/browser-use/references/page-flows.md +66 -0
  7. package/src/defaults/skills/browser-use/references/sign-in.md +70 -0
  8. package/src/defaults/skills/code-tidy/SKILL.md +60 -84
  9. package/src/defaults/skills/code-tidy/references/agent-cleanup.md +27 -2
  10. package/src/defaults/skills/computer-use/SKILL.md +145 -229
  11. package/src/defaults/skills/computer-use/references/flows.md +35 -0
  12. package/src/defaults/skills/computer-use/references/operations.md +22 -0
  13. package/src/defaults/skills/computer-use/references/platforms.md +12 -0
  14. package/src/defaults/skills/docx/SKILL.md +23 -31
  15. package/src/defaults/skills/docx/references/native-authoring.md +26 -3
  16. package/src/defaults/skills/docx/references/redlining.md +15 -0
  17. package/src/defaults/skills/image/SKILL.md +37 -77
  18. package/src/defaults/skills/image/references/prompt-forms.md +51 -0
  19. package/src/defaults/skills/image/references/text.md +6 -0
  20. package/src/defaults/skills/local-provider/SKILL.md +75 -105
  21. package/src/defaults/skills/local-provider/references/lifecycle.md +14 -0
  22. package/src/defaults/skills/local-provider/references/maintenance.md +19 -0
  23. package/src/defaults/skills/local-provider/references/recovery.md +30 -0
  24. package/src/defaults/skills/memory-management/SKILL.md +22 -21
  25. package/src/defaults/skills/pdf/SKILL.md +21 -23
  26. package/src/defaults/skills/pdf/references/blocks.md +20 -0
  27. package/src/defaults/skills/pdf/references/forms.md +12 -0
  28. package/src/defaults/skills/pdf/references/html.md +2 -2
  29. package/src/defaults/skills/pdf/references/ocr.md +7 -0
  30. package/src/defaults/skills/pdf/references/security.md +8 -0
  31. package/src/defaults/skills/pptx/SKILL.md +30 -109
  32. package/src/defaults/skills/pptx/references/audit.md +45 -0
  33. package/src/defaults/skills/pptx/references/brief-critique.md +47 -0
  34. package/src/defaults/skills/pptx/references/editing.md +24 -0
  35. package/src/defaults/skills/pptx/references/html.md +1 -1
  36. package/src/defaults/skills/pptx/references/script.md +33 -0
  37. package/src/defaults/skills/setup/SKILL.md +34 -102
  38. package/src/defaults/skills/setup/references/actions.md +73 -14
  39. package/src/defaults/skills/setup/references/surfaces.md +23 -8
  40. package/src/defaults/skills/setup-guide/SKILL.md +28 -115
  41. package/src/defaults/skills/setup-guide/references/features.md +36 -0
  42. package/src/defaults/skills/setup-guide/references/glossary.md +38 -0
  43. package/src/defaults/skills/setup-guide/references/workflow-models.md +62 -0
  44. package/src/defaults/skills/test-suite/SKILL.md +15 -127
  45. package/src/defaults/skills/test-suite/references/case-management.md +17 -9
  46. package/src/defaults/skills/test-suite/references/diagnose.md +23 -0
  47. package/src/defaults/skills/test-suite/references/prune.md +27 -0
  48. package/src/defaults/skills/test-suite/references/write.md +44 -0
  49. package/src/defaults/skills/video/SKILL.md +28 -42
  50. package/src/defaults/skills/video/references/prompting.md +31 -0
  51. package/src/defaults/skills/visualize/SKILL.md +73 -107
  52. package/src/defaults/skills/visualize/references/craft.md +1 -2
  53. package/src/defaults/skills/visualize/references/feedback.md +36 -0
  54. package/src/defaults/skills/visualize/references/showing.md +13 -0
  55. package/src/defaults/skills/xlsx/SKILL.md +23 -50
  56. package/src/defaults/skills/xlsx/references/editing.md +15 -0
  57. package/src/defaults/skills/xlsx/references/model-conventions.md +1 -1
  58. package/src/defaults/skills/xlsx/references/recalculation.md +37 -0
  59. package/src/defaults/skills/xlsx/references/report-design.md +18 -2
  60. package/src/lib/keychain-cjs.cjs +22 -1
  61. package/src/lib/rules-builder.cjs +1 -1
  62. package/src/rules/agent/AGENT.md +3 -0
  63. package/src/rules/agent-mode/MIXY.md +5 -3
  64. package/src/rules/lead/LEAD.md +3 -1
  65. package/src/runtime/agent/orchestrator/agent-runtime/cache-strategy.mjs +8 -30
  66. package/src/runtime/agent/orchestrator/agent-runtime/title-completion.mjs +5 -0
  67. package/src/runtime/agent/orchestrator/mcp/oauth-request.mjs +21 -2
  68. package/src/runtime/agent/orchestrator/providers/account-pool.mjs +3 -0
  69. package/src/runtime/agent/orchestrator/providers/admission-scheduler.mjs +4 -3
  70. package/src/runtime/agent/orchestrator/providers/anthropic-api-request.mjs +11 -1
  71. package/src/runtime/agent/orchestrator/providers/anthropic-api-transport.mjs +2 -0
  72. package/src/runtime/agent/orchestrator/providers/anthropic-message-threads.mjs +583 -0
  73. package/src/runtime/agent/orchestrator/providers/anthropic-oauth-client-version.mjs +1 -1
  74. package/src/runtime/agent/orchestrator/providers/anthropic-oauth.mjs +81 -19
  75. package/src/runtime/agent/orchestrator/providers/anthropic-sse-turn/turn-events/content-block-start.mjs +4 -0
  76. package/src/runtime/agent/orchestrator/providers/anthropic-sse-turn/turn-outcome.mjs +2 -0
  77. package/src/runtime/agent/orchestrator/providers/anthropic-sse.mjs +180 -13
  78. package/src/runtime/agent/orchestrator/providers/anthropic-turn-result.mjs +2 -0
  79. package/src/runtime/agent/orchestrator/providers/anthropic.mjs +58 -6
  80. package/src/runtime/agent/orchestrator/providers/cursor-wire.mjs +4 -2
  81. package/src/runtime/agent/orchestrator/providers/custom-provider-config.mjs +121 -9
  82. package/src/runtime/agent/orchestrator/providers/custom-provider.mjs +4 -1
  83. package/src/runtime/agent/orchestrator/providers/gemini-error-contract.mjs +6 -6
  84. package/src/runtime/agent/orchestrator/providers/gemini-model-redirect.mjs +44 -0
  85. package/src/runtime/agent/orchestrator/providers/gemini-reasoning-relay.mjs +5 -0
  86. package/src/runtime/agent/orchestrator/providers/gemini-request-body.mjs +34 -5
  87. package/src/runtime/agent/orchestrator/providers/gemini-response.mjs +10 -0
  88. package/src/runtime/agent/orchestrator/providers/gemini-schema.mjs +11 -6
  89. package/src/runtime/agent/orchestrator/providers/gemini-sdk-request.mjs +4 -100
  90. package/src/runtime/agent/orchestrator/providers/gemini-stream.mjs +3 -227
  91. package/src/runtime/agent/orchestrator/providers/gemini.mjs +226 -118
  92. package/src/runtime/agent/orchestrator/providers/lib/anthropic-request-utils.mjs +11 -1
  93. package/src/runtime/agent/orchestrator/providers/lib/claude-bridge-schema.mjs +15 -3
  94. package/src/runtime/agent/orchestrator/providers/lib/gemini-model-catalog.mjs +2 -1
  95. package/src/runtime/agent/orchestrator/providers/lib/generation-window.mjs +9 -0
  96. package/src/runtime/agent/orchestrator/providers/openai-compat-chat-send.mjs +9 -1
  97. package/src/runtime/agent/orchestrator/providers/openai-compat-chat-stream/stream-result.mjs +2 -0
  98. package/src/runtime/agent/orchestrator/providers/openai-compat-chat-stream/stream-state.mjs +5 -0
  99. package/src/runtime/agent/orchestrator/providers/openai-compat-options.mjs +3 -0
  100. package/src/runtime/agent/orchestrator/providers/openai-compat-response-normalization.mjs +2 -0
  101. package/src/runtime/agent/orchestrator/providers/openai-compat-responses.mjs +10 -1
  102. package/src/runtime/agent/orchestrator/providers/openai-direct-request.mjs +5 -28
  103. package/src/runtime/agent/orchestrator/providers/openai-http-sse-response-state/response-events.mjs +3 -0
  104. package/src/runtime/agent/orchestrator/providers/openai-http-sse-response-state/response-outcome.mjs +2 -0
  105. package/src/runtime/agent/orchestrator/providers/openai-ws-pool.mjs +50 -28
  106. package/src/runtime/agent/orchestrator/providers/openai-ws-response-state.mjs +9 -2
  107. package/src/runtime/agent/orchestrator/providers/openai-ws-stream/socket-handlers.mjs +14 -10
  108. package/src/runtime/agent/orchestrator/providers/openai-ws.mjs +1 -3
  109. package/src/runtime/agent/orchestrator/providers/openrouter-provider-routing.mjs +28 -0
  110. package/src/runtime/agent/orchestrator/providers/openrouter.mjs +4 -1
  111. package/src/runtime/agent/orchestrator/providers/registry.mjs +30 -25
  112. package/src/runtime/agent/orchestrator/providers/stream-json-pool/worker-slots/slot-spawn.mjs +8 -3
  113. package/src/runtime/agent/orchestrator/providers/vertex-ai-maas.mjs +2 -2
  114. package/src/runtime/agent/orchestrator/runtime-core/ask-user-result.mjs +66 -0
  115. package/src/runtime/agent/orchestrator/runtime-core/config-helpers.mjs +4 -5
  116. package/src/runtime/agent/orchestrator/runtime-core/goal-tool-defs.mjs +2 -2
  117. package/src/runtime/agent/orchestrator/runtime-core/provider-request-tools.mjs +15 -8
  118. package/src/runtime/agent/orchestrator/runtime-core/session-title.mjs +1 -0
  119. package/src/runtime/agent/orchestrator/runtime-core/todo-list.mjs +9 -32
  120. package/src/runtime/agent/orchestrator/runtime-core/todo-tool-defs.mjs +4 -5
  121. package/src/runtime/agent/orchestrator/session/compact/summary-route.mjs +1 -3
  122. package/src/runtime/agent/orchestrator/session/loop/compact-policy.mjs +5 -2
  123. package/src/runtime/agent/orchestrator/session/loop/no-tool-turn/todo-check.mjs +2 -17
  124. package/src/runtime/agent/orchestrator/session/loop/usage.mjs +7 -3
  125. package/src/runtime/agent/orchestrator/session/manager/ask-turn-settle.mjs +9 -2
  126. package/src/runtime/agent/orchestrator/session/manager/runtime-liveness.mjs +8 -1
  127. package/src/runtime/agent/orchestrator/session/manager/session-close.mjs +26 -13
  128. package/src/runtime/agent/orchestrator/session/manager/session-lifecycle.mjs +4 -5
  129. package/src/runtime/agent/orchestrator/session/manager/usage-metrics.mjs +16 -5
  130. package/src/runtime/agent/orchestrator/session/store/lifecycle-barriers.mjs +22 -1
  131. package/src/runtime/agent/orchestrator/session/store/live-state.mjs +4 -0
  132. package/src/runtime/agent/orchestrator/session/store.mjs +12 -6
  133. package/src/runtime/agent/orchestrator/tools/builtin/cache-layers.mjs +11 -9
  134. package/src/runtime/agent/orchestrator/tools/builtin/grep-formatting.mjs +2 -8
  135. package/src/runtime/agent/orchestrator/tools/builtin/lib/search-input-helpers.mjs +1 -9
  136. package/src/runtime/agent/orchestrator/tools/builtin/lib/shell-output-silence.mjs +64 -0
  137. package/src/runtime/agent/orchestrator/tools/builtin/lib/shell-task-output.mjs +20 -6
  138. package/src/runtime/agent/orchestrator/tools/builtin/local-search-telemetry.mjs +2 -2
  139. package/src/runtime/agent/orchestrator/tools/builtin/native-search-client.mjs +1 -1
  140. package/src/runtime/agent/orchestrator/tools/builtin/runtime-capabilities.mjs +12 -3
  141. package/src/runtime/agent/orchestrator/tools/builtin/task-tool.mjs +12 -1
  142. package/src/runtime/agent/orchestrator/tools/code-graph/ast-calls.mjs +9 -2
  143. package/src/runtime/agent/orchestrator/tools/code-graph/build.mjs +137 -7
  144. package/src/runtime/agent/orchestrator/tools/code-graph/calls-cache.mjs +43 -14
  145. package/src/runtime/agent/orchestrator/tools/code-graph/calls-sidecar-worker.mjs +33 -0
  146. package/src/runtime/agent/orchestrator/tools/code-graph/disk-cache.mjs +146 -11
  147. package/src/runtime/agent/orchestrator/tools/code-graph/dispatch.mjs +31 -24
  148. package/src/runtime/agent/orchestrator/tools/code-graph/graph-binary/spawn-jsonl.mjs +172 -25
  149. package/src/runtime/agent/orchestrator/tools/code-graph/graph-model.mjs +100 -2
  150. package/src/runtime/agent/orchestrator/tools/code-graph/main-thread-slice.mjs +18 -0
  151. package/src/runtime/agent/orchestrator/tools/code-graph/mask-pool.mjs +219 -0
  152. package/src/runtime/agent/orchestrator/tools/code-graph/mask-worker.mjs +12 -0
  153. package/src/runtime/agent/orchestrator/tools/code-graph/memory-cache.mjs +6 -1
  154. package/src/runtime/agent/orchestrator/tools/code-graph/modes/calls.mjs +9 -2
  155. package/src/runtime/agent/orchestrator/tools/code-graph/modes/dependents.mjs +5 -1
  156. package/src/runtime/agent/orchestrator/tools/code-graph/modes/structure.mjs +8 -2
  157. package/src/runtime/agent/orchestrator/tools/code-graph/modes/symbols.mjs +14 -11
  158. package/src/runtime/agent/orchestrator/tools/code-graph/search-references.mjs +41 -18
  159. package/src/runtime/agent/orchestrator/tools/code-graph/search.mjs +391 -83
  160. package/src/runtime/agent/orchestrator/tools/code-graph/symbol-index.mjs +109 -9
  161. package/src/runtime/agent/orchestrator/tools/code-graph/text-mask.mjs +73 -29
  162. package/src/runtime/agent/orchestrator/tools/code-graph-prewarm-worker.mjs +6 -5
  163. package/src/runtime/agent/orchestrator/tools/lib/native-spawn-client.mjs +7 -3
  164. package/src/runtime/channels/lib/crash-log.mjs +21 -1
  165. package/src/runtime/channels/lib/routines-db.mjs +35 -0
  166. package/src/runtime/channels/lib/schedules-db.mjs +4 -0
  167. package/src/runtime/channels/lib/webhooks-db.mjs +4 -0
  168. package/src/runtime/channels/lib/worker-main.mjs +8 -25
  169. package/src/runtime/computer-bridge/action-schema.mjs +2 -2
  170. package/src/runtime/computer-bridge/core-actions.mjs +16 -2
  171. package/src/runtime/computer-bridge/result-canonical.mjs +6 -0
  172. package/src/runtime/media/jobs.mjs +5 -0
  173. package/src/runtime/media/store.mjs +146 -3
  174. package/src/runtime/memory/tool-defs.mjs +1 -1
  175. package/src/runtime/office/core/office-write-ledger.mjs +2 -2
  176. package/src/runtime/shared/agent-reap-state.mjs +19 -0
  177. package/src/runtime/shared/desktop-notice-host.d.mts +13 -0
  178. package/src/runtime/shared/desktop-notice-host.mjs +87 -0
  179. package/src/runtime/shared/file-lock.mjs +2 -2
  180. package/src/runtime/shared/heap-cap.mjs +9 -11
  181. package/src/runtime/shared/llm/http-agent.mjs +11 -1
  182. package/src/runtime/shared/llm/system-proxy.mjs +100 -25
  183. package/src/runtime/shared/llm/usage-accounting.mjs +121 -19
  184. package/src/runtime/shared/llm/usage-context.mjs +3 -3
  185. package/src/runtime/shared/llm/usage-ledger-quota.mjs +2 -0
  186. package/src/runtime/shared/llm/usage-ledger-requests.mjs +190 -0
  187. package/src/runtime/shared/llm/usage-ledger-rollup.mjs +7 -3
  188. package/src/runtime/shared/llm/usage-ledger-worker.mjs +2 -0
  189. package/src/runtime/shared/llm/usage-ledger.mjs +69 -1
  190. package/src/runtime/shared/llm/usage-request-status.mjs +48 -0
  191. package/src/runtime/shared/provider-accounts.mjs +22 -0
  192. package/src/runtime/shared/provider-auth-binding.mjs +2 -2
  193. package/src/runtime/shared/resource-admission.mjs +2 -2
  194. package/src/runtime/shared/root-async-context.mjs +51 -0
  195. package/src/runtime/shared/run-child.mjs +18 -1
  196. package/src/runtime/shared/slow-span.mjs +2 -2
  197. package/src/runtime/shared/tool-execution-owner.mjs +2 -2
  198. package/src/runtime/shared/tool-result-summary.mjs +1 -1
  199. package/src/runtime/shared/tool-work-units.mjs +2 -0
  200. package/src/runtime/shared/turn-snapshot-store.mjs +75 -18
  201. package/src/runtime/shared/turn-worktree-snapshot.mjs +38 -8
  202. package/src/runtime/shared/user-cwd.mjs +2 -2
  203. package/src/runtime/shared/worker-requests.mjs +3 -1
  204. package/src/runtime/shared/worktrees/lock.mjs +2 -2
  205. package/src/runtime/visualize-bridge/client.mjs +26 -4
  206. package/src/runtime/visualize-bridge/tool-defs.mjs +46 -5
  207. package/src/session-runtime/agent-home-delivery.mjs +76 -8
  208. package/src/session-runtime/agent-task-sessions.mjs +63 -22
  209. package/src/session-runtime/boot/apis.mjs +16 -0
  210. package/src/session-runtime/boot/begin.mjs +2 -0
  211. package/src/session-runtime/boot/tools.mjs +8 -2
  212. package/src/session-runtime/internal-tool-executor/ask-user-tool.mjs +3 -58
  213. package/src/session-runtime/media-api.mjs +15 -0
  214. package/src/session-runtime/model-route/route-persist.mjs +12 -4
  215. package/src/session-runtime/provider-models/row-hydration.mjs +2 -0
  216. package/src/session-runtime/provider-readiness.mjs +10 -2
  217. package/src/session-runtime/routine-owner.mjs +9 -3
  218. package/src/session-runtime/runtime-core.mjs +35 -8
  219. package/src/session-runtime/runtime-review-api.mjs +3 -1
  220. package/src/session-runtime/services/agent-task-status.mjs +29 -1
  221. package/src/session-runtime/services/agent-tool/close-flow.mjs +6 -1
  222. package/src/session-runtime/services/agent-tool/execute-resume.mjs +94 -0
  223. package/src/session-runtime/services/agent-tool/execute-send.mjs +77 -27
  224. package/src/session-runtime/services/agent-tool/execute-spawn.mjs +28 -7
  225. package/src/session-runtime/services/agent-tool/execute.mjs +6 -1
  226. package/src/session-runtime/services/agent-tool/helpers.mjs +11 -0
  227. package/src/session-runtime/services/agent-tool/job-views/job-render.mjs +13 -10
  228. package/src/session-runtime/services/agent-tool/job-views/session-progress.mjs +3 -0
  229. package/src/session-runtime/services/agent-tool/render.mjs +8 -1
  230. package/src/session-runtime/services/agent-tool/send-flow.mjs +1 -0
  231. package/src/session-runtime/services/agent-tool/spawn-flow/spawn-prep.mjs +6 -0
  232. package/src/session-runtime/services/agent-tool/spawn-flow/spawn-run.mjs +2 -1
  233. package/src/session-runtime/services/agent-tool/tag-registry/reaped-sessions.mjs +82 -0
  234. package/src/session-runtime/services/agent-tool/tag-registry/record-facts-worker.mjs +36 -0
  235. package/src/session-runtime/services/agent-tool/tag-registry.mjs +4 -0
  236. package/src/session-runtime/services/agent-tool/terminal-reaper/row-helpers.mjs +29 -0
  237. package/src/session-runtime/services/agent-tool/terminal-reaper/scan-admission.mjs +11 -3
  238. package/src/session-runtime/services/agent-tool/terminal-reaper/stale-rows.mjs +19 -8
  239. package/src/session-runtime/services/agent-tool/terminal-reaper.mjs +5 -2
  240. package/src/session-runtime/services/agent-tool/worker-index.mjs +1 -0
  241. package/src/session-runtime/services/channel-admin.mjs +44 -3
  242. package/src/session-runtime/services/daemon-crash-capture/daemon-exit-record.mjs +2 -2
  243. package/src/session-runtime/services/plugin-admin.mjs +46 -7
  244. package/src/session-runtime/services/provider-admin.mjs +5 -0
  245. package/src/session-runtime/session-create.mjs +5 -0
  246. package/src/session-runtime/setup-tool/agent-settings-actions.mjs +1 -1
  247. package/src/session-runtime/setup-tool/executor.mjs +1 -1
  248. package/src/session-runtime/setup-tool/extended-actions.mjs +1 -1
  249. package/src/session-runtime/setup-tool/settings-contract.mjs +4 -2
  250. package/src/session-runtime/usage-stats-api.mjs +120 -1
  251. package/src/session-runtime/workflow-agents-api/agent-connectors.mjs +36 -29
  252. package/src/session-runtime/workflow-agents-api/agent-editor.mjs +183 -23
  253. package/src/session-runtime/workspace/admission-gate.mjs +25 -7
  254. package/src/session-runtime/workspace/transitions.mjs +4 -0
  255. package/src/standalone/daemon-log.mjs +28 -4
  256. package/src/standalone/daemon-owner.mjs +41 -7
  257. package/src/standalone/daemon-work-gate.mjs +139 -0
  258. package/src/standalone/daemon.mjs +80 -11
  259. package/src/standalone/desktop-service-registry.mjs +11 -4
  260. package/src/standalone/session-client.mjs +57 -5
  261. package/src/standalone/session-protocol.mjs +6 -0
  262. package/src/standalone/session-service/agent-tree/agent-cancel.mjs +17 -1
  263. package/src/standalone/session-service/agent-tree.mjs +7 -0
  264. package/src/standalone/session-service/retention/busy.mjs +3 -2
  265. package/src/standalone/session-service/session-calls/session-turns.mjs +12 -5
  266. package/src/standalone/session-transport/call-route.mjs +10 -4
  267. package/src/standalone/session-transport/routes.mjs +21 -0
  268. package/src/standalone/session-transport/stack.mjs +3 -1
  269. package/src/standalone/session-transport.mjs +5 -0
  270. package/src/tui/app/model-picker/model-footer.mjs +1 -1
  271. package/src/tui/app/model-picker/provider-models-list.mjs +7 -3
  272. package/src/tui/app/model-picker/route-selection/fast-parameters.mjs +23 -3
  273. package/src/tui/app/model-picker/route-selection.mjs +1 -0
  274. package/src/tui/dist/index.mjs +536 -484
  275. package/src/tui/session/session-api/integrations.mjs +3 -0
  276. package/src/tui/session/session-api/media.mjs +5 -0
  277. package/src/tui/session/tool-approval-settle.mjs +24 -4
  278. package/src/tui/session/tool-approval.mjs +35 -10
  279. package/src/tui/session/turn.mjs +13 -0
  280. package/src/runtime/agent/orchestrator/providers/gemini-sdk-stream/cancellation.mjs +0 -71
  281. package/src/runtime/agent/orchestrator/providers/gemini-sdk-stream/reader.mjs +0 -108
@@ -66,7 +66,7 @@ export const AGENT_SETTINGS_HANDLERS = {
66
66
  }
67
67
  const name = requireText(args.name, 'name');
68
68
  await rt.restoreAgentDefinition(name);
69
- return { restored: name, note: 'Its chat is back; its routines stay off until they are turned on.' };
69
+ return { restored: name, note: 'Its chat is back, and its routines run again as they were.' };
70
70
  },
71
71
  set_bot_order: (rt, args) => ({ botOrder: rt.setBotOrder(args.botOrder).order }),
72
72
  set_cache_warming_enabled: (rt, args) => ({
@@ -79,7 +79,7 @@ const ACTION_APPLIES_TO = {
79
79
  set_agent_connector: "that agent's next connector tool call, in every session",
80
80
  set_agent_connector_tool: "that agent's next call of the tool, in every session",
81
81
  set_project_connector: 'the next connector tool call of sessions in that Project',
82
- restore_definition: 'now: the bot and its chat return; its routines stay off',
82
+ restore_definition: 'now: the bot, its chat and its routines (as they were) return',
83
83
  set_bot_order: 'the Bots page and the Sessions bot section on every device',
84
84
  set_orchestration_mode:
85
85
  "new sessions and an empty current one (the default mode); a conversation keeps its own mode until it is switched with the composer's mode selector",
@@ -284,7 +284,7 @@ export const EXTENDED_SETUP_HANDLERS = Object.freeze({
284
284
  recovery:
285
285
  args.definitionKind === 'workflow'
286
286
  ? 'User-authored definition files are deleted. A built-in override may revert to its built-in definition.'
287
- : 'A custom agent or bot is archived with its chat and its routines are switched off; the user can restore it from Sessions → Archived, or delete it there for good. A built-in override reverts to its built-in definition.',
287
+ : 'A custom agent or bot is archived with its chat; its schedules and webhooks are paused and hidden, unchanged. The user can restore it, routines included, from Sessions → Archived, or delete it there for good, which deletes its routines too. A built-in override reverts to its built-in definition.',
288
288
  };
289
289
  },
290
290
  async save_automation(rt, args, context = {}) {
@@ -56,6 +56,7 @@ export const SETUP_ACTIVITY_RAIL_PIN_IDS = Object.freeze([
56
56
  'source-control',
57
57
  'search',
58
58
  'webhooks',
59
+ 'studio',
59
60
  ]);
60
61
 
61
62
  export const SETUP_EXTENDED_DOMAINS = Object.freeze([
@@ -236,6 +237,7 @@ export const SETUP_EXTENDED_PROPERTIES = Object.freeze({
236
237
  usageRailSlotsAll: boolean,
237
238
  computerObserveOnly: boolean,
238
239
  browserAutoSignIn: boolean,
240
+ browserHidDevices: boolean,
239
241
  saveChatLogins: boolean,
240
242
  notificationVolume: {
241
243
  type: 'integer',
@@ -299,8 +301,8 @@ export const SETUP_EXTENDED_PROPERTIES = Object.freeze({
299
301
  uiScale: {
300
302
  type: 'number',
301
303
  minimum: 0.85,
302
- maximum: 1.2,
303
- description: 'UI size multiplier, 0.85-1.2 in steps of 0.05 (default 1).',
304
+ maximum: 1.5,
305
+ description: 'UI size multiplier, 0.85-1.5 in steps of 0.05 (default 1).',
304
306
  },
305
307
  codeSize: {
306
308
  type: 'integer',
@@ -6,7 +6,9 @@ import { refreshUnpricedUsageAsync } from '../runtime/shared/llm/usage-pricing-r
6
6
  import { resolvePluginData } from '../runtime/shared/plugin-paths.mjs';
7
7
  import { sessionUsageSnapshot, usageStatsSnapshot } from './services/usage-stats-model.mjs';
8
8
  import { resolveUsageStatsPeriod } from './services/usage-stats-period.mjs';
9
- import { usageRollupDayKey } from '../runtime/shared/llm/usage-rollup.mjs';
9
+ import { isConversationUsageSource, usageRollupDayKey } from '../runtime/shared/llm/usage-rollup.mjs';
10
+ import { isLeadVisibleRow } from '../runtime/agent/orchestrator/session/store-summary-catalog.mjs';
11
+ import { agentIdOfHomeSession } from '../runtime/agent/orchestrator/session/agent-home.mjs';
10
12
  import {
11
13
  ACCOUNT_PROVIDERS,
12
14
  accountScopedSessionId,
@@ -164,6 +166,86 @@ function usageRollupQuery(period) {
164
166
  };
165
167
  }
166
168
 
169
+ async function readSessionMetadata(sessionId) {
170
+ const { readStoredSessionTranscript } = await import(
171
+ '../runtime/agent/orchestrator/session/store-summary-reader.mjs'
172
+ );
173
+ return readStoredSessionTranscript(sessionId, { metadataOnly: true });
174
+ }
175
+
176
+ /**
177
+ * What the request log names a session by: its title, and for an agent's
178
+ * session the title of the session it ran for with its role (`agent: true`
179
+ * with no role when only the ledger's owner link survives). A background
180
+ * request on such an openable session adds its source type as
181
+ * `backgroundKind`. A request whose own session the user cannot open (an
182
+ * internal dispatch, or a session file that is gone) carries its source type
183
+ * as `internalKind` instead, and no title: the first prompt line of a
184
+ * background run says nothing about it.
185
+ */
186
+ async function describeRequestSessions(requests, sessionMetadata) {
187
+ // `exec` is hidden by the catalog but counts as conversation in usage
188
+ // totals; every other hidden source is one the rollup calls background.
189
+ const internalKindOf = (sourceType) => {
190
+ const id = String(sourceType || '')
191
+ .trim()
192
+ .toLowerCase();
193
+ // A title call is recorded under the session it titles: that session
194
+ // stays openable, so it is named like any other background request.
195
+ if (id === 'session-title') return id;
196
+ const hidden = id && !isLeadVisibleRow({ sourceType: id, preview: id });
197
+ return hidden && (id === 'exec' || !isConversationUsageSource(id)) ? id : '';
198
+ };
199
+ const metadata = new Map();
200
+ const read = async (id) => {
201
+ if (!id) return null;
202
+ if (!metadata.has(id))
203
+ metadata.set(
204
+ id,
205
+ Promise.resolve(sessionMetadata(id)).catch(() => null)
206
+ );
207
+ return metadata.get(id);
208
+ };
209
+ const labels = new Map();
210
+ for (const request of requests) {
211
+ const key = `${request.sessionId}\u0000${request.ownerSessionId}\u0000${request.sourceType}`;
212
+ if (labels.has(key)) continue;
213
+ const own = await read(request.sessionId);
214
+ const kind = internalKindOf(request.sourceType || own?.sourceType);
215
+ // A session the user can open keeps its label whatever the request's
216
+ // route (a cache warm-up records under the real session id); only the
217
+ // work's kind is added. A session file that is gone cannot be opened, nor
218
+ // can a session that is itself an internal run (a memory-cycle dispatch
219
+ // is stored as an owned agent session).
220
+ const openable =
221
+ Boolean(own) &&
222
+ !internalKindOf(own.sourceType) &&
223
+ ((own.agent && (own.ownerSessionId || request.ownerSessionId)) || isLeadVisibleRow({ ...own, preview: 'x' }));
224
+ if (kind && !openable) {
225
+ labels.set(key, { title: '', role: '', agent: false, internalKind: kind });
226
+ continue;
227
+ }
228
+ const ownerId = own?.ownerSessionId || request.ownerSessionId;
229
+ let label = { title: own?.title || agentIdOfHomeSession(request.sessionId) || '', role: '', agent: false };
230
+ if (ownerId && ownerId !== request.sessionId && (own?.agent || !own)) {
231
+ const owner = await read(ownerId);
232
+ label = { title: owner?.title || agentIdOfHomeSession(ownerId) || '', role: own?.agent || '', agent: true };
233
+ }
234
+ labels.set(key, { ...label, backgroundKind: kind });
235
+ }
236
+ return requests.map(({ ownerSessionId, sourceType, ...request }) => {
237
+ const label = labels.get(`${request.sessionId}\u0000${ownerSessionId}\u0000${sourceType}`);
238
+ return {
239
+ ...request,
240
+ sessionTitle: label.title,
241
+ agentRole: label.role,
242
+ agent: label.agent,
243
+ internalKind: label.internalKind || '',
244
+ backgroundKind: label.backgroundKind || '',
245
+ };
246
+ });
247
+ }
248
+
167
249
  export function createUsageStatsApi({
168
250
  ledger = getUsageLedger,
169
251
  importHistory = importUsageHistory,
@@ -171,6 +253,8 @@ export function createUsageStatsApi({
171
253
  // provider -> { [accountId]: email } for the picker's secondary text.
172
254
  accountEmails = () => ({}),
173
255
  getSessionId = () => null,
256
+ // sessionId -> stored metadata ({ title, agent, ownerSessionId }) or null.
257
+ sessionMetadata = readSessionMetadata,
174
258
  } = {}) {
175
259
  let importing = null;
176
260
  let imported = false;
@@ -234,6 +318,41 @@ export function createUsageStatsApi({
234
318
  return snapshot;
235
319
  },
236
320
 
321
+ /**
322
+ * The request log: one page of requests in a statistics period (`view`,
323
+ * `anchor`, custom dates; the 24-hour view by default), newest first,
324
+ * optionally of one `status` and one answering `model`. `cursor` is an
325
+ * earlier page's `nextCursor`. `models` lists the models that answered in
326
+ * the period.
327
+ */
328
+ async getUsageRequests(options = {}) {
329
+ const store = ledger();
330
+ if (!store) throw new Error('Usage ledger is unavailable');
331
+ await store.settleWrites();
332
+ // `asOf` is the first page's `generatedAt`: later pages resolve the same
333
+ // period bounds, so a rolling window does not slide while it is browsed.
334
+ const asOf = Number(options?.asOf);
335
+ const real = Date.now();
336
+ if (options?.asOf != null && !(asOf > 0 && asOf <= real)) throw new RangeError('asOf must be a past timestamp');
337
+ const now = asOf > 0 ? asOf : real;
338
+ const period = usagePeriodFor({ ...options, view: options?.view ?? 'hour' }, now);
339
+ const page = await store.requestsAsync({
340
+ fromMs: period.fromMs,
341
+ toMs: period.toMs,
342
+ status: quotaText(options?.status),
343
+ model: quotaText(options?.model),
344
+ cursor: quotaText(options?.cursor) || null,
345
+ limit: options?.limit,
346
+ });
347
+ return {
348
+ generatedAt: now,
349
+ period,
350
+ requests: await describeRequestSessions(page.requests, sessionMetadata),
351
+ nextCursor: page.nextCursor,
352
+ models: page.models,
353
+ };
354
+ },
355
+
237
356
  /**
238
357
  * This runtime's session from its first request, compactions included; null before it has one.
239
358
  * `sessionIds` adds the same totals for each named session (the agents it spawned) under
@@ -50,8 +50,18 @@ export function createAgentConnectorsApi(deps, editor) {
50
50
  const switches = (policy) => installedIds().map((id) => ({ id, enabled: connectorEnabled(policy, id) }));
51
51
  // A legacy list or an unreadable policy becomes its deny-list equivalent
52
52
  // over today's connectors before any edit, so an edit never widens it.
53
- const editablePolicy = (agentId) =>
54
- migrateLegacyConnectorPolicy(editor.getAgentConnectorPolicy(agentId), installedIds()) || { off: [], tools: {} };
53
+ const editablePolicyOf = (stored) =>
54
+ migrateLegacyConnectorPolicy(stored, installedIds()) || { off: [], tools: {} };
55
+ const editablePolicy = (agentId) => editablePolicyOf(editor.getAgentConnectorPolicy(agentId));
56
+ // An edit is derived from the policy stored when its turn in the agent's
57
+ // write queue comes, so two edits started together never undo each other,
58
+ // and the remote no-widen check judges that same policy.
59
+ const editPolicy = (agentId, options, derive) =>
60
+ editor.updateAgentConnectorPolicy(agentId, (stored) => {
61
+ const next = derive(editablePolicyOf(stored));
62
+ if (options?.noWiden) assertConnectorPolicyNotWidened(stored, next);
63
+ return storedConnectorPolicy(next);
64
+ });
55
65
 
56
66
  function listConnectors() {
57
67
  return (mcpStatus()?.servers || []).map((row) => ({
@@ -102,12 +112,10 @@ export function createAgentConnectorsApi(deps, editor) {
102
112
  async function setAgentConnectorEnabled(agentId, connectorId, enabled, options) {
103
113
  const id = requireId(connectorId, 'connector id');
104
114
  if (typeof enabled !== 'boolean') throw new TypeError('enabled must be a boolean');
105
- const policy = editablePolicy(agentId);
106
- const off = enabled ? policy.off.filter((entry) => entry !== id) : [...policy.off, id];
107
- if (options?.noWiden) {
108
- assertConnectorPolicyNotWidened(editor.getAgentConnectorPolicy(agentId), { off, tools: policy.tools });
109
- }
110
- await editor.setAgentConnectorPolicy(agentId, storedConnectorPolicy({ off, tools: policy.tools }));
115
+ await editPolicy(agentId, options, (policy) => ({
116
+ off: enabled ? policy.off.filter((entry) => entry !== id) : [...policy.off, id],
117
+ tools: policy.tools,
118
+ }));
111
119
  return getAgentConnectors(agentId);
112
120
  }
113
121
 
@@ -119,26 +127,24 @@ export function createAgentConnectorsApi(deps, editor) {
119
127
  }
120
128
  const server = requireId(connectorId, 'connector id');
121
129
  const tool = requireId(toolName, 'tool name');
122
- const policy = editablePolicy(agentId);
123
130
  // The accounts of one connector (`gmail`, `gmail-2`…) share the permission,
124
131
  // stored once under the connector's id; an entry an account kept of its own
125
132
  // for this tool goes in the same write.
126
133
  const group = connectorGroupId(server);
127
- const tools = Object.fromEntries(
128
- Object.entries(policy.tools).map(([id, entries]) => {
129
- if (id === group || connectorGroupId(id) !== group) return [id, entries];
130
- const { [tool]: _dropped, ...rest } = entries;
131
- return [id, rest];
132
- })
133
- );
134
- const own = { ...tools[group] };
135
- if (permission == null) delete own[tool];
136
- else own[tool] = permission;
137
- tools[group] = own;
138
- if (options?.noWiden) {
139
- assertConnectorPolicyNotWidened(editor.getAgentConnectorPolicy(agentId), { off: policy.off, tools });
140
- }
141
- return editor.setAgentConnectorPolicy(agentId, storedConnectorPolicy({ off: policy.off, tools }));
134
+ return editPolicy(agentId, options, (policy) => {
135
+ const tools = Object.fromEntries(
136
+ Object.entries(policy.tools).map(([id, entries]) => {
137
+ if (id === group || connectorGroupId(id) !== group) return [id, entries];
138
+ const { [tool]: _dropped, ...rest } = entries;
139
+ return [id, rest];
140
+ })
141
+ );
142
+ const own = { ...tools[group] };
143
+ if (permission == null) delete own[tool];
144
+ else own[tool] = permission;
145
+ tools[group] = own;
146
+ return { off: policy.off, tools };
147
+ });
142
148
  }
143
149
 
144
150
  // A card's "항상 허용" for a connector tool saves through this same writer.
@@ -186,11 +192,12 @@ export function createAgentConnectorsApi(deps, editor) {
186
192
  /** Replace the agent's connector policy (null removes it). With `options.noWiden`
187
193
  * the replacement may not give any tool more authority than the stored policy. */
188
194
  async function setAgentConnectors(agentId, connectors, options) {
189
- if (options?.noWiden) {
190
- const next = connectors == null ? null : parseConnectorPolicy(connectors);
191
- assertConnectorPolicyNotWidened(editor.getAgentConnectorPolicy(agentId), next);
192
- }
193
- return editor.setAgentConnectorPolicy(agentId, connectors);
195
+ return editor.updateAgentConnectorPolicy(agentId, (stored) => {
196
+ if (options?.noWiden) {
197
+ assertConnectorPolicyNotWidened(stored, connectors == null ? null : parseConnectorPolicy(connectors));
198
+ }
199
+ return connectors;
200
+ });
194
201
  }
195
202
 
196
203
  /** The registered Project at `projectPath` (its path is the policy key). */
@@ -369,12 +369,40 @@ function writeAgentFiles(dir, { name, description, body, extra = {}, manifest =
369
369
  writeDefinitionText(join(dir, 'AGENT.md'), serializeFrontmatterDoc({ ...meta, ...extra }, body));
370
370
  // loadAgentDefinition prefers the manifest for name/description.
371
371
  writeManifest(join(dir, 'agent.json'), { ...meta, ...manifest });
372
+ // A stray purge marker goes before the tombstone: a crash between the two
373
+ // must never leave a live definition under a marker.
374
+ rmSync(join(dir, PURGING_MARKER), { force: true });
372
375
  rmSync(join(dir, AGENT_DELETED_MARKER), { force: true });
373
376
  rmSync(join(dir, ARCHIVED_AGENT_FILE), { force: true });
374
377
  }
375
378
 
379
+ // Per id, the tail of the queue its lifecycle changes (save, archive, restore,
380
+ // purge, recovery) run in, one at a time. One process owns the store, so this
381
+ // is enough; each change rechecks its eligibility when its turn comes.
382
+ const lifecycleTails = new Map();
383
+ function withLifecycle(dataDir, id, run) {
384
+ const key = `${dataDir}\0${id}`;
385
+ const result = (lifecycleTails.get(key) ?? Promise.resolve()).then(run);
386
+ const tail = result.catch(() => {});
387
+ lifecycleTails.set(key, tail);
388
+ tail.then(() => {
389
+ if (lifecycleTails.get(key) === tail) lifecycleTails.delete(key);
390
+ });
391
+ return result;
392
+ }
393
+
394
+ // Written before a purge deletes the bot's routines, gone with its folder.
395
+ const PURGING_MARKER = '.purging';
396
+
376
397
  const isArchivedAgent = (dataDir, id) => existsSync(join(userDir(dataDir, id), AGENT_DELETED_MARKER));
377
398
 
399
+ // Whether a purge of `id` is under way or was cut short: its marker with the
400
+ // definition archived or already gone. A marker beside a live definition
401
+ // (AGENT.md in place, no tombstone) proves nothing and is stale.
402
+ const purgePending = (dataDir, id) =>
403
+ existsSync(join(userDir(dataDir, id), PURGING_MARKER)) &&
404
+ (isArchivedAgent(dataDir, id) || !hasUserAgentFile(dataDir, id));
405
+
378
406
  // A save's avatar and connectors applied to `manifest` (in place); returns the
379
407
  // avatar update (its image writes), null when the save gives no avatar.
380
408
  function applyManifestEdits(manifest, payload, dir, options) {
@@ -673,6 +701,8 @@ function createAgentArchiveApi({
673
701
  shippedDir,
674
702
  announceBotChange,
675
703
  getAgentDefinition,
704
+ deleteOwnedRoutines,
705
+ reloadRoutines,
676
706
  }) {
677
707
  // A removed custom agent must not leave a dangling route/preset or a
678
708
  // disabled-roster entry that would silently disable a later agent of the
@@ -687,7 +717,17 @@ function createAgentArchiveApi({
687
717
  saveConfigAndAdopt(canonicalizeAgentRouteStorage(nextConfig));
688
718
  }
689
719
 
690
- async function deleteAgentDefinition(agentId) {
720
+ // One id's archive, restore, purge and recovery run one at a time, each
721
+ // checking its eligibility on its turn (withLifecycle).
722
+ const locked = (agentId, run) => {
723
+ const id = agentEditorId(agentId);
724
+ return id ? withLifecycle(dataDirOf(), id, () => run(agentId)) : run(agentId);
725
+ };
726
+ const deleteAgentDefinition = (agentId) => locked(agentId, deleteUnlocked);
727
+ const restoreAgentDefinition = (agentId) => locked(agentId, restoreUnlocked);
728
+ const purgeAgentDefinition = (agentId) => locked(agentId, purgeUnlocked);
729
+
730
+ async function deleteUnlocked(agentId) {
691
731
  const id = agentEditorId(agentId);
692
732
  if (!id) throw new Error(`unknown agent "${agentId}"`);
693
733
  if (isHiddenAgent(id)) throw new Error(`agent "${id}" is internal and cannot be deleted`);
@@ -714,7 +754,9 @@ function createAgentArchiveApi({
714
754
  // tombstone keeps the packaged copy of a starter from coming back, and the
715
755
  // rest (agent.json: name and face, persona, memory, its model and on/off)
716
756
  // stays for its archived chat — until restoreAgentDefinition brings it back
717
- // or purgeAgentDefinition.
757
+ // or purgeAgentDefinition. Its schedules and webhooks are left exactly as
758
+ // they are: while it is archived they neither fire nor list
759
+ // (routine-owner.mjs), and a restore brings them back as they were.
718
760
  // AGENT.md always moves aside; an AGENT.md over an existing archive is
719
761
  // refused, since the move would overwrite it. Another selected entry
720
762
  // moves too when its own archive is free, and otherwise stays in place
@@ -726,6 +768,10 @@ function createAgentArchiveApi({
726
768
  }
727
769
  const entry = archivableEntry(dir, entryIn(dir));
728
770
  mkdirSync(dir, { recursive: true });
771
+ // A stray purge marker goes before any rename: a crash after one would
772
+ // leave the marker with no AGENT.md and no tombstone, which reads as a
773
+ // purge cut short.
774
+ rmSync(join(dir, PURGING_MARKER), { force: true });
729
775
  if (existsSync(agentFile)) renameSync(agentFile, agentArchive);
730
776
  if (entry !== agentFile && existsSync(entry) && !existsSync(archivedEntryPath(entry))) {
731
777
  renameSync(entry, archivedEntryPath(entry));
@@ -739,13 +785,18 @@ function createAgentArchiveApi({
739
785
 
740
786
  /** An archived agent back as it was, under its own id: its AGENT.md moved
741
787
  * back (a starter without a copy of its own returns to the packaged one)
742
- * and the tombstone gone. Its routines stay off (the host). */
743
- async function restoreAgentDefinition(agentId) {
788
+ * and the tombstone gone. Its routines, never touched by the archive, list
789
+ * and fire again as they were. */
790
+ async function restoreUnlocked(agentId) {
744
791
  const id = agentEditorId(agentId);
745
792
  if (!id || isHiddenAgent(id) || isFixedAgent(id)) throw new Error(`unknown agent "${agentId}"`);
746
793
  const dataDir = dataDirOf();
747
794
  if (!isArchivedAgent(dataDir, id)) throw new Error(`agent "${id}" is not deleted`);
748
795
  const dir = userDir(dataDir, id);
796
+ // Its routines may already be gone: only the purge can finish.
797
+ if (existsSync(join(dir, PURGING_MARKER))) {
798
+ throw new Error(`agent "${id}" is being deleted for good and cannot be restored; delete it again to finish`);
799
+ }
749
800
  // AGENT.md.archived back to AGENT.md, and the selected entry's archive back
750
801
  // to that entry. Nothing is overwritten: an archive whose file exists again
751
802
  // stays as it is, and when every kept archive collides the restore is refused.
@@ -766,18 +817,47 @@ function createAgentArchiveApi({
766
817
  clearAgentDefinitionCache(id);
767
818
  // Back in the roster of the Leads that list it, from their next turn.
768
819
  await announceBotChange(dataDir);
820
+ // A one-shot that came due while it was archived was skipped with no
821
+ // timer left: the reload re-arms it (overdue fires at once, as at start).
822
+ // The bot is back by now, so a failed reload is reported as such rather
823
+ // than as a restore that succeeded with its one-shots unarmed.
824
+ try {
825
+ await reloadRoutines();
826
+ } catch (error) {
827
+ throw new Error(
828
+ `agent "${id}" was restored, but its schedules could not be re-armed (${error?.message || error}); ` +
829
+ 'they are re-armed by the next schedule reload or restart'
830
+ );
831
+ }
769
832
  return getAgentDefinition(id);
770
833
  }
771
834
 
772
- /** Deleting an archived agent again: everything it left goes for good. A
773
- * starter keeps only its tombstone, so its packaged copy stays gone. */
774
- async function purgeAgentDefinition(agentId) {
835
+ /** Deleting an archived agent again: everything it left goes for good, its
836
+ * schedules and webhooks first (one statement, all or none): a purge that
837
+ * fails aborts this with the agent still archived and nothing lost, to be
838
+ * retried. A starter keeps only its tombstone, so its packaged copy stays
839
+ * gone. */
840
+ async function purgeUnlocked(agentId) {
775
841
  const id = agentEditorId(agentId);
776
842
  if (!id || isHiddenAgent(id) || isFixedAgent(id)) throw new Error(`unknown agent "${agentId}"`);
777
843
  const dataDir = dataDirOf();
778
- // Never a live agent; one deleted before archiving existed left nothing.
779
- if (!isArchivedAgent(dataDir, id)) return { id, purged: false };
780
844
  const dir = userDir(dataDir, id);
845
+ // Never a live agent; one deleted before archiving existed left nothing.
846
+ // A marker beside a live definition is only removed.
847
+ if (!purgePending(dataDir, id)) {
848
+ rmSync(join(dir, PURGING_MARKER), { force: true });
849
+ if (!isArchivedAgent(dataDir, id)) return { id, purged: false };
850
+ }
851
+ return purgeFiles(id, dataDir, dir);
852
+ }
853
+
854
+ /** The purge of `id` (archived, or one a crash cut short), routines first. */
855
+ async function purgeFiles(id, dataDir, dir) {
856
+ // Set before the first await and before the routines go: a restore from
857
+ // here on is refused (it checks in the same synchronous stretch), and a
858
+ // crash before the folder is removed is finished by finishUnfinishedPurges.
859
+ writeFileAtomicSync(join(dir, PURGING_MARKER), 'purging\n');
860
+ const routines = await deleteOwnedRoutines(id);
781
861
  rmSync(dir, { recursive: true, force: true });
782
862
  clearAgentDefinitionCache(id);
783
863
  dropAgentRoute(id);
@@ -786,10 +866,56 @@ function createAgentArchiveApi({
786
866
  writeFileAtomicSync(join(dir, AGENT_DELETED_MARKER), 'deleted\n');
787
867
  clearAgentDefinitionCache(id);
788
868
  }
789
- return { id, purged: true };
869
+ // A save that passed its owner check before the bot was archived (an
870
+ // archived owner is refused) can land after the first purge: swept again
871
+ // now that the bot is gone (a later one is refused by the save itself,
872
+ // channel-admin.mjs). A failure here leaves at most such a row, listed as
873
+ // its bot deleted, deletable.
874
+ const late = await deleteOwnedRoutines(id).catch((error) => error);
875
+ const names = (kind) => [...routines[kind], ...(late instanceof Error ? [] : late[kind])];
876
+ const removed = { schedules: names('schedules'), webhooks: names('webhooks') };
877
+ return {
878
+ id,
879
+ purged: true,
880
+ ...(removed.schedules.length + removed.webhooks.length > 0 ? { routines: removed } : {}),
881
+ ...(late instanceof Error ? { routinesError: late.message } : {}),
882
+ };
883
+ }
884
+
885
+ /** Run at start: every purge that stopped before its folder was removed
886
+ * (its marker is still there) is carried through; the ids finished. */
887
+ async function finishUnfinishedPurges() {
888
+ const dataDir = dataDirOf();
889
+ const ids = [join(dataDir, 'agents'), dirname(botDir(dataDir, '_'))].flatMap((root) =>
890
+ existsSync(root) ? readdirSync(root).filter((name) => existsSync(join(root, name, PURGING_MARKER))) : []
891
+ );
892
+ const finished = [];
893
+ for (const id of ids) if ((await resumePurge(id)).purged) finished.push(id);
894
+ return finished;
790
895
  }
791
896
 
792
- return { dropAgentRoute, deleteAgentDefinition, restoreAgentDefinition, purgeAgentDefinition };
897
+ /** Resumes only a marked purge that is still pending, checked on the id's
898
+ * turn: a bot archived normally meanwhile (marker gone), made live again,
899
+ * or already purged by another call is not a purge to finish. */
900
+ const resumePurge = (id) =>
901
+ withLifecycle(dataDirOf(), id, async () => {
902
+ const dataDir = dataDirOf();
903
+ const dir = userDir(dataDir, id);
904
+ if (!existsSync(join(dir, PURGING_MARKER))) return { id, purged: false };
905
+ if (!purgePending(dataDir, id)) {
906
+ rmSync(join(dir, PURGING_MARKER), { force: true });
907
+ return { id, purged: false };
908
+ }
909
+ return purgeFiles(id, dataDir, dir);
910
+ });
911
+
912
+ return {
913
+ dropAgentRoute,
914
+ deleteAgentDefinition,
915
+ restoreAgentDefinition,
916
+ purgeAgentDefinition,
917
+ finishUnfinishedPurges,
918
+ };
793
919
  }
794
920
 
795
921
  // Agent catalog + editor surface: fixed services stay built-in; starter and
@@ -897,7 +1023,16 @@ export function createAgentEditorApi(deps) {
897
1023
  const body = String(payload.body || '').trim();
898
1024
  if (!body) throw new Error('AGENT.md body must not be empty');
899
1025
  const dataDir = resolveDataDir(deps);
900
- const { id, name, description } = resolveSaveTarget(loadAgentDefinition, payload, dataDir);
1026
+ const target = resolveSaveTarget(loadAgentDefinition, payload, dataDir);
1027
+ return withLifecycle(dataDir, target.id, () => saveLocked(payload, options, body, dataDir, target));
1028
+ }
1029
+
1030
+ // Runs as the id's turn in its lifecycle queue (withLifecycle): a purge ahead
1031
+ // of it has finished, so the id it frees is reused, and one behind it sees a live bot.
1032
+ async function saveLocked(payload, options, body, dataDir, { id, name, description }) {
1033
+ if (purgePending(dataDir, id)) {
1034
+ throw new Error(`agent "${id}" is being deleted for good; its id cannot be reused until that finishes`);
1035
+ }
901
1036
  // Opt-in (the agent profile): without `expectedRevision` the last write
902
1037
  // wins, as for the Workflows editor and the setup tool.
903
1038
  if (hasOwn(payload, 'expectedRevision') && String(payload.expectedRevision) !== definitionRevision(dataDir, id)) {
@@ -963,7 +1098,13 @@ export function createAgentEditorApi(deps) {
963
1098
  return getAgentDefinition(id);
964
1099
  }
965
1100
 
966
- const { dropAgentRoute, deleteAgentDefinition, restoreAgentDefinition, purgeAgentDefinition } = createAgentArchiveApi(
1101
+ const {
1102
+ dropAgentRoute,
1103
+ deleteAgentDefinition,
1104
+ restoreAgentDefinition,
1105
+ purgeAgentDefinition,
1106
+ finishUnfinishedPurges,
1107
+ } = createAgentArchiveApi(
967
1108
  {
968
1109
  dataDirOf: () => resolveDataDir(deps),
969
1110
  getConfig,
@@ -972,6 +1113,10 @@ export function createAgentEditorApi(deps) {
972
1113
  shippedDir,
973
1114
  announceBotChange,
974
1115
  getAgentDefinition,
1116
+ // The runtime wires the store (boot/apis.mjs); a read-only editor (the
1117
+ // routine owner and delivery probes) never deletes an agent.
1118
+ deleteOwnedRoutines: deps.deleteOwnedRoutines ?? (async () => ({ schedules: [], webhooks: [] })),
1119
+ reloadRoutines: deps.reloadRoutines ?? (() => {}),
975
1120
  }
976
1121
  );
977
1122
 
@@ -1041,17 +1186,30 @@ export function createAgentEditorApi(deps) {
1041
1186
  }
1042
1187
  // Replaces the policy (null removes the field). Every other key — avatar,
1043
1188
  // persona, frontmatter — is kept; for Mixy only its agent.json is touched.
1044
- async function setAgentConnectorPolicy(agentId, connectors) {
1189
+ const setAgentConnectorPolicy = (agentId, connectors) => updateAgentConnectorPolicy(agentId, () => connectors);
1190
+
1191
+ // Read-modify-write of the policy as one turn of the id's lifecycle queue,
1192
+ // like every other writer of its definition: `derive(current)` sees the
1193
+ // policy as stored when that turn comes (not as it was when the call was
1194
+ // made) and may throw to refuse (the remote no-widen check); what it returns
1195
+ // is stored. Nothing awaits between `derive` and the write's start.
1196
+ function updateAgentConnectorPolicy(agentId, derive) {
1045
1197
  const id = agentEditorId(agentId);
1046
- const next = connectorPolicyInput(connectors);
1047
- getAgentConnectorPolicy(id);
1048
- assertManifestWritable(join(id === LEAD_AGENT_ID ? leadDir() : userDir(resolveDataDir(deps), id), 'agent.json'));
1049
- if (id === LEAD_AGENT_ID) setLeadConnectorPolicy(next);
1050
- else {
1051
- const { name, description, body } = loadAgentDefinition(resolveDataDir(deps), id);
1052
- await saveAgentDefinition({ id, name, description, body, connectors: next });
1053
- }
1054
- return getAgentConnectorPolicy(id);
1198
+ if (!id) return Promise.reject(new Error(`unknown agent "${agentId}"`));
1199
+ return withLifecycle(resolveDataDir(deps), id, async () => {
1200
+ const dataDir = resolveDataDir(deps);
1201
+ const next = connectorPolicyInput(derive(getAgentConnectorPolicy(id)));
1202
+ assertManifestWritable(join(id === LEAD_AGENT_ID ? leadDir() : userDir(dataDir, id), 'agent.json'));
1203
+ if (id === LEAD_AGENT_ID) setLeadConnectorPolicy(next);
1204
+ else {
1205
+ const { name, description, body } = loadAgentDefinition(dataDir, id);
1206
+ const payload = { id, name, description, body, connectors: next };
1207
+ const text = String(body || '').trim();
1208
+ if (!text) throw new Error('AGENT.md body must not be empty');
1209
+ await saveLocked(payload, undefined, text, dataDir, resolveSaveTarget(loadAgentDefinition, payload, dataDir));
1210
+ }
1211
+ return getAgentConnectorPolicy(id);
1212
+ });
1055
1213
  }
1056
1214
 
1057
1215
  return {
@@ -1059,6 +1217,7 @@ export function createAgentEditorApi(deps) {
1059
1217
  migrateBotStore: () => migrateBotStore(deps),
1060
1218
  getAgentConnectorPolicy,
1061
1219
  setAgentConnectorPolicy,
1220
+ updateAgentConnectorPolicy,
1062
1221
  listAgents,
1063
1222
  getAgentDefinition,
1064
1223
  getAgentAvatarImage,
@@ -1074,6 +1233,7 @@ export function createAgentEditorApi(deps) {
1074
1233
  deleteAgentDefinition,
1075
1234
  restoreAgentDefinition,
1076
1235
  purgeAgentDefinition,
1236
+ finishUnfinishedPurges,
1077
1237
  archivedAgentIdentities,
1078
1238
  agentDefinitionPresence,
1079
1239
  };