mixdog 0.9.18 → 0.9.20

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 (214) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +93 -29
  3. package/package.json +5 -3
  4. package/scripts/build-runtime-windows.ps1 +242 -242
  5. package/scripts/build-tui.mjs +6 -0
  6. package/scripts/hook-bus-test.mjs +8 -0
  7. package/scripts/log-writer-guard-smoke.mjs +131 -0
  8. package/scripts/output-style-smoke.mjs +2 -2
  9. package/scripts/reactive-compact-persist-smoke.mjs +22 -6
  10. package/scripts/recall-bench-cases.json +10 -0
  11. package/scripts/recall-bench.mjs +91 -2
  12. package/scripts/recall-quality-cases.json +1 -2
  13. package/scripts/recall-usecase-cases.json +1 -1
  14. package/scripts/session-ingest-compaction-smoke.mjs +241 -0
  15. package/scripts/smoke-runtime-negative.ps1 +106 -106
  16. package/scripts/tool-efficiency-diag.mjs +5 -2
  17. package/scripts/tool-smoke.mjs +251 -72
  18. package/src/agents/debugger/AGENT.md +3 -3
  19. package/src/agents/heavy-worker/AGENT.md +7 -10
  20. package/src/agents/maintainer/AGENT.md +1 -2
  21. package/src/agents/reviewer/AGENT.md +1 -2
  22. package/src/agents/worker/AGENT.md +5 -8
  23. package/src/defaults/agents.json +3 -0
  24. package/src/help.mjs +2 -5
  25. package/src/lib/mixdog-debug.cjs +13 -0
  26. package/src/mixdog-session-runtime.mjs +7 -3311
  27. package/src/rules/agent/00-core.md +4 -3
  28. package/src/rules/agent/30-explorer.md +53 -22
  29. package/src/rules/lead/02-channels.md +3 -3
  30. package/src/rules/lead/lead-tool.md +3 -2
  31. package/src/rules/shared/01-tool.md +24 -29
  32. package/src/runtime/agent/orchestrator/context/collect.mjs +33 -9
  33. package/src/runtime/agent/orchestrator/providers/anthropic-oauth.mjs +1 -1
  34. package/src/runtime/agent/orchestrator/providers/anthropic.mjs +1 -1
  35. package/src/runtime/agent/orchestrator/providers/oauth-usage.mjs +24 -3
  36. package/src/runtime/agent/orchestrator/providers/retry-classifier.mjs +3 -3
  37. package/src/runtime/agent/orchestrator/session/agent-loop.mjs +663 -0
  38. package/src/runtime/agent/orchestrator/session/compact/engine.mjs +6 -0
  39. package/src/runtime/agent/orchestrator/session/context-utils.mjs +2 -2
  40. package/src/runtime/agent/orchestrator/session/eager-dispatch.mjs +153 -0
  41. package/src/runtime/agent/orchestrator/session/loop/recall-fasttrack.mjs +49 -0
  42. package/src/runtime/agent/orchestrator/session/loop/steering-ladder.mjs +250 -35
  43. package/src/runtime/agent/orchestrator/session/loop/stored-tool-args.mjs +9 -1
  44. package/src/runtime/agent/orchestrator/session/loop.mjs +8 -1860
  45. package/src/runtime/agent/orchestrator/session/manager/agent-runtime-singleton.mjs +29 -0
  46. package/src/runtime/agent/orchestrator/session/manager/ask-session.mjs +686 -0
  47. package/src/runtime/agent/orchestrator/session/manager/compaction-runner.mjs +60 -12
  48. package/src/runtime/agent/orchestrator/session/manager/env-utils.mjs +8 -0
  49. package/src/runtime/agent/orchestrator/session/manager/idle-cleanup.mjs +159 -0
  50. package/src/runtime/agent/orchestrator/session/manager/message-sanitize.mjs +143 -0
  51. package/src/runtime/agent/orchestrator/session/manager/prefetch-bridge.mjs +268 -0
  52. package/src/runtime/agent/orchestrator/session/manager/provider-cache-key.mjs +22 -0
  53. package/src/runtime/agent/orchestrator/session/manager/runtime-loaders.mjs +26 -0
  54. package/src/runtime/agent/orchestrator/session/manager/session-close.mjs +124 -0
  55. package/src/runtime/agent/orchestrator/session/manager/session-crud.mjs +258 -0
  56. package/src/runtime/agent/orchestrator/session/manager/session-errors.mjs +20 -0
  57. package/src/runtime/agent/orchestrator/session/manager/session-id.mjs +9 -0
  58. package/src/runtime/agent/orchestrator/session/manager/session-lifecycle.mjs +475 -0
  59. package/src/runtime/agent/orchestrator/session/manager/session-lock.mjs +23 -0
  60. package/src/runtime/agent/orchestrator/session/manager/tool-resolution.mjs +6 -4
  61. package/src/runtime/agent/orchestrator/session/manager.mjs +88 -2285
  62. package/src/runtime/agent/orchestrator/session/pre-send-compact.mjs +440 -0
  63. package/src/runtime/agent/orchestrator/session/send-with-recovery.mjs +153 -0
  64. package/src/runtime/agent/orchestrator/session/store.mjs +4 -1
  65. package/src/runtime/agent/orchestrator/session/tool-batch.mjs +642 -0
  66. package/src/runtime/agent/orchestrator/tools/bash-session.mjs +23 -3
  67. package/src/runtime/agent/orchestrator/tools/builtin/arg-guard.mjs +198 -6
  68. package/src/runtime/agent/orchestrator/tools/builtin/bash-tool.mjs +10 -2
  69. package/src/runtime/agent/orchestrator/tools/builtin/builtin-tools.mjs +13 -15
  70. package/src/runtime/agent/orchestrator/tools/builtin/read-batch.mjs +6 -1
  71. package/src/runtime/agent/orchestrator/tools/builtin/read-single-tool.mjs +45 -3
  72. package/src/runtime/agent/orchestrator/tools/builtin/search-path-diagnostics.mjs +5 -2
  73. package/src/runtime/agent/orchestrator/tools/builtin/search-tool.mjs +195 -3
  74. package/src/runtime/agent/orchestrator/tools/builtin/shell-job-paths.mjs +108 -2
  75. package/src/runtime/agent/orchestrator/tools/builtin/shell-job-process.mjs +15 -3
  76. package/src/runtime/agent/orchestrator/tools/builtin/shell-jobs.mjs +7 -0
  77. package/src/runtime/agent/orchestrator/tools/builtin/shell-runtime.mjs +24 -2
  78. package/src/runtime/agent/orchestrator/tools/builtin.mjs +17 -1
  79. package/src/runtime/agent/orchestrator/tools/code-graph/dispatch.mjs +38 -0
  80. package/src/runtime/agent/orchestrator/tools/code-graph-tool-defs.mjs +4 -4
  81. package/src/runtime/agent/orchestrator/tools/patch/orchestrator.mjs +2 -2
  82. package/src/runtime/agent/orchestrator/tools/patch/parsing.mjs +72 -8
  83. package/src/runtime/agent/orchestrator/tools/shell-policy-danger-target.mjs +5 -1
  84. package/src/runtime/agent/orchestrator/tools/shell-state.mjs +1 -1
  85. package/src/runtime/channels/backends/discord-gateway.mjs +14 -1
  86. package/src/runtime/channels/backends/discord.mjs +43 -1
  87. package/src/runtime/channels/index.mjs +6 -2096
  88. package/src/runtime/channels/lib/inbound-handler.mjs +328 -0
  89. package/src/runtime/channels/lib/inbound-routing.mjs +19 -12
  90. package/src/runtime/channels/lib/interaction-handlers.mjs +260 -0
  91. package/src/runtime/channels/lib/memory-client.mjs +32 -14
  92. package/src/runtime/channels/lib/network-retry.mjs +23 -0
  93. package/src/runtime/channels/lib/output-forwarder.mjs +38 -7
  94. package/src/runtime/channels/lib/owned-runtime.mjs +547 -0
  95. package/src/runtime/channels/lib/owner-heartbeat.mjs +13 -4
  96. package/src/runtime/channels/lib/runtime-paths.mjs +35 -1
  97. package/src/runtime/channels/lib/tool-dispatch.mjs +17 -7
  98. package/src/runtime/channels/lib/transcript-binding.mjs +336 -0
  99. package/src/runtime/channels/lib/voice-runtime-fetcher.mjs +39 -2
  100. package/src/runtime/channels/lib/worker-bootstrap.mjs +97 -0
  101. package/src/runtime/channels/lib/worker-ipc.mjs +201 -0
  102. package/src/runtime/channels/lib/worker-main.mjs +771 -0
  103. package/src/runtime/memory/index.mjs +73 -1725
  104. package/src/runtime/memory/lib/embedding-provider.mjs +4 -2
  105. package/src/runtime/memory/lib/embedding-worker.mjs +47 -6
  106. package/src/runtime/memory/lib/http-router.mjs +772 -0
  107. package/src/runtime/memory/lib/memory-action-handlers.mjs +901 -0
  108. package/src/runtime/memory/lib/memory-embed.mjs +28 -7
  109. package/src/runtime/memory/lib/memory-recall-scope-filter.mjs +8 -2
  110. package/src/runtime/memory/lib/memory-recall-store.mjs +182 -9
  111. package/src/runtime/memory/lib/query-handlers.mjs +38 -6
  112. package/src/runtime/memory/lib/recall-format.mjs +106 -6
  113. package/src/runtime/memory/lib/session-ingest-runtime.mjs +401 -0
  114. package/src/runtime/memory/lib/session-ingest.mjs +1 -1
  115. package/src/runtime/shared/atomic-file.mjs +10 -4
  116. package/src/runtime/shared/background-tasks.mjs +4 -2
  117. package/src/runtime/shared/tool-execution-contract.mjs +1 -1
  118. package/src/runtime/shared/tool-result-summary.mjs +1 -1
  119. package/src/runtime/shared/tool-surface.mjs +30 -1
  120. package/src/session-runtime/boot-profile.mjs +36 -0
  121. package/src/session-runtime/channel-config-api.mjs +70 -0
  122. package/src/session-runtime/config-lifecycle.mjs +1 -1
  123. package/src/session-runtime/context-status.mjs +181 -0
  124. package/src/session-runtime/cwd-plugins.mjs +46 -3
  125. package/src/session-runtime/env.mjs +17 -0
  126. package/src/session-runtime/lifecycle-api.mjs +242 -0
  127. package/src/session-runtime/mcp-glue.mjs +24 -3
  128. package/src/session-runtime/model-route-api.mjs +198 -0
  129. package/src/session-runtime/output-styles.mjs +44 -10
  130. package/src/session-runtime/provider-auth-api.mjs +135 -0
  131. package/src/session-runtime/resource-api.mjs +282 -0
  132. package/src/session-runtime/runtime-core.mjs +2046 -0
  133. package/src/session-runtime/session-turn-api.mjs +274 -0
  134. package/src/session-runtime/tool-catalog.mjs +18 -264
  135. package/src/session-runtime/tool-defs.mjs +2 -2
  136. package/src/session-runtime/workflow-agents-api.mjs +238 -0
  137. package/src/session-runtime/workflow.mjs +16 -1
  138. package/src/standalone/agent-tool.mjs +2 -2
  139. package/src/standalone/channel-worker.mjs +78 -5
  140. package/src/standalone/explore-tool.mjs +1 -1
  141. package/src/standalone/memory-runtime-proxy.mjs +56 -6
  142. package/src/tui/App.jsx +88 -97
  143. package/src/tui/app/channel-pickers.mjs +45 -0
  144. package/src/tui/app/core-memory-picker.mjs +1 -1
  145. package/src/tui/app/slash-commands.mjs +0 -1
  146. package/src/tui/app/slash-dispatch.mjs +0 -16
  147. package/src/tui/app/transcript-window.mjs +44 -1
  148. package/src/tui/app/use-mouse-input.mjs +15 -2
  149. package/src/tui/app/use-prompt-handlers.mjs +7 -94
  150. package/src/tui/app/use-transcript-scroll.mjs +82 -4
  151. package/src/tui/app/use-transcript-window.mjs +65 -5
  152. package/src/tui/components/PromptInput.jsx +33 -64
  153. package/src/tui/components/ToolExecution.jsx +2 -2
  154. package/src/tui/dist/index.mjs +7908 -7558
  155. package/src/tui/engine/context-state.mjs +145 -0
  156. package/src/tui/engine/prompt-history.mjs +27 -0
  157. package/src/tui/engine/session-api-ext.mjs +478 -0
  158. package/src/tui/engine/session-api.mjs +545 -0
  159. package/src/tui/engine/session-flow.mjs +485 -0
  160. package/src/tui/engine/turn.mjs +1078 -0
  161. package/src/tui/engine.mjs +69 -2582
  162. package/src/tui/index.jsx +7 -0
  163. package/src/tui/lib/voice-setup.mjs +166 -0
  164. package/src/tui/paste-attachments.mjs +12 -5
  165. package/src/tui/prompt-history-store.mjs +125 -12
  166. package/vendor/ink/build/ink.js +16 -1
  167. package/vendor/ink/build/output.js +30 -4
  168. package/vendor/ink/build/render.js +5 -0
  169. package/scripts/bench/cache-probe-tasks.json +0 -8
  170. package/scripts/bench/lead-review-tasks-r3.json +0 -20
  171. package/scripts/bench/lead-review-tasks.json +0 -20
  172. package/scripts/bench/r4-mixed-tasks.json +0 -20
  173. package/scripts/bench/r5-orchestrated-task.json +0 -7
  174. package/scripts/bench/review-tasks.json +0 -20
  175. package/scripts/bench/round-codex.json +0 -114
  176. package/scripts/bench/round-mixdog-lead-r3.json +0 -269
  177. package/scripts/bench/round-mixdog-lead.json +0 -269
  178. package/scripts/bench/round-mixdog.json +0 -126
  179. package/scripts/bench/round-r10-bigsample.json +0 -679
  180. package/scripts/bench/round-r11-codexalign.json +0 -257
  181. package/scripts/bench/round-r13-clientmeta.json +0 -464
  182. package/scripts/bench/round-r14-betafeatures.json +0 -466
  183. package/scripts/bench/round-r15-fulldefault.json +0 -462
  184. package/scripts/bench/round-r16-sessionid.json +0 -466
  185. package/scripts/bench/round-r17-wirebytes.json +0 -456
  186. package/scripts/bench/round-r18-prewarm.json +0 -468
  187. package/scripts/bench/round-r19-clean.json +0 -472
  188. package/scripts/bench/round-r20-prewarm-clean.json +0 -475
  189. package/scripts/bench/round-r21-delta-retry.json +0 -473
  190. package/scripts/bench/round-r22-full-probe.json +0 -693
  191. package/scripts/bench/round-r23-itemprobe.json +0 -701
  192. package/scripts/bench/round-r24-shapefix.json +0 -677
  193. package/scripts/bench/round-r25-serial.json +0 -464
  194. package/scripts/bench/round-r26-parallel3.json +0 -671
  195. package/scripts/bench/round-r27-parallel10.json +0 -894
  196. package/scripts/bench/round-r28-parallel10-stagger.json +0 -882
  197. package/scripts/bench/round-r29-parallel10-stagger166.json +0 -886
  198. package/scripts/bench/round-r30-instid.json +0 -253
  199. package/scripts/bench/round-r31-upgradeprobe.json +0 -256
  200. package/scripts/bench/round-r32-vs-codex-lead.json +0 -254
  201. package/scripts/bench/round-r33-vs-codex-codex.json +0 -115
  202. package/scripts/bench/round-r34-orchestrated.json +0 -120
  203. package/scripts/bench/round-r35-orchestrated-codex.json +0 -61
  204. package/scripts/bench/round-r36-orchestrated-capped.json +0 -128
  205. package/scripts/bench/round-r4-codex.json +0 -114
  206. package/scripts/bench/round-r4-mixed.json +0 -225
  207. package/scripts/bench/round-r5-gpt-lead.json +0 -259
  208. package/scripts/bench/round-r6-codex.json +0 -114
  209. package/scripts/bench/round-r6-solo.json +0 -257
  210. package/scripts/bench/round-r7-full.json +0 -254
  211. package/scripts/bench/round-r8-fulldefault.json +0 -255
  212. package/src/tui/components/prompt-input/voice-indicator.mjs +0 -39
  213. package/src/tui/lib/voice-recorder.mjs +0 -469
  214. package/src/workflows/sequential/WORKFLOW.md +0 -51
@@ -1,3311 +1,7 @@
1
- import { existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from 'node:fs';
2
- import { homedir } from 'node:os';
3
- import { basename, dirname, isAbsolute, join, resolve } from 'node:path';
4
- import { fileURLToPath } from 'node:url';
5
- import { performance } from 'node:perf_hooks';
6
- import httpMod from 'node:http';
7
- import { ensureStandaloneEnvironment } from './standalone/seeds.mjs';
8
- import { createStandaloneAgent } from './standalone/agent-tool.mjs';
9
- import { isAgentOwner } from './runtime/agent/orchestrator/agent-owner.mjs';
10
- import { EXPLORE_TOOL, runExplore } from './standalone/explore-tool.mjs';
11
- import { createStandaloneChannelWorker } from './standalone/channel-worker.mjs';
12
- import { createStandaloneMemoryRuntime } from './standalone/memory-runtime-proxy.mjs';
13
- import { createStandaloneHookBus } from './standalone/hook-bus.mjs';
14
- import { writeLastSessionCwd } from './runtime/shared/user-cwd.mjs';
15
- import { cancelBackgroundTasks } from './runtime/shared/background-tasks.mjs';
16
- import { createTranscriptWriter } from './runtime/shared/transcript-writer.mjs';
17
- import { mixdogHome } from './runtime/shared/plugin-paths.mjs';
18
- import { checkLatestVersion, runGlobalUpdate, localPackageVersion } from './runtime/shared/update-checker.mjs';
19
- import {
20
- modelVisibleToolCompletionMessage,
21
- shouldPersistModelVisibleToolCompletion,
22
- } from './runtime/shared/tool-execution-contract.mjs';
23
- import {
24
- channelNotificationModelContent,
25
- shouldMirrorChannelNotificationToPending,
26
- } from './runtime/shared/channel-notification-routing.mjs';
27
- import {
28
- normalizeAgentPermissionOrNone,
29
- readMarkdownDocument,
30
- } from './runtime/shared/markdown-frontmatter.mjs';
31
- import { setConfiguredShell } from './runtime/agent/orchestrator/tools/builtin/shell-runtime.mjs';
32
- import { hasUserConversationMessage } from './runtime/agent/orchestrator/session/manager/prompt-utils.mjs';
33
- import {
34
- beginOAuthProviderLogin,
35
- forgetProviderAuth,
36
- isKnownProvider,
37
- loginOAuthProvider,
38
- providerSetup,
39
- renderProviderStatus,
40
- saveOpenAIUsageSessionKey,
41
- saveOpenCodeGoUsageAuth,
42
- loginOpenCodeGoUsage,
43
- saveProviderApiKey,
44
- setLocalProvider,
45
- } from './standalone/provider-admin.mjs';
46
- import { createUsageDashboard } from './standalone/usage-dashboard.mjs';
47
- import { fetchOAuthUsageSnapshot } from './runtime/agent/orchestrator/providers/oauth-usage.mjs';
48
- import {
49
- getModelMetadataSync,
50
- warmCatalogsInBackground,
51
- } from './runtime/agent/orchestrator/providers/model-catalog.mjs';
52
- import {
53
- isResponsesFreeformTool,
54
- toResponsesCustomTool,
55
- } from './runtime/agent/orchestrator/providers/custom-tool-wire.mjs';
56
- import {
57
- channelSetup,
58
- deleteSchedule,
59
- deleteWebhook,
60
- forgetDiscordToken,
61
- forgetTelegramToken,
62
- forgetWebhookAuthtoken,
63
- setChannel,
64
- saveDiscordToken,
65
- saveTelegramToken,
66
- saveSchedule,
67
- saveWebhook,
68
- saveWebhookAuthtoken,
69
- setBackend,
70
- setScheduleEnabled,
71
- setWebhookEnabled,
72
- setWebhookConfig,
73
- } from './standalone/channel-admin.mjs';
74
- import {
75
- addPlugin as registryAddPlugin,
76
- listRegisteredPlugins,
77
- pluginAdminStatus,
78
- removePlugin as registryRemovePlugin,
79
- updatePlugin as registryUpdatePlugin,
80
- } from './standalone/plugin-admin.mjs';
81
- import {
82
- estimateMessagesTokens,
83
- estimateRequestReserveTokens,
84
- estimateTranscriptContextUsage,
85
- estimateToolSchemaTokens,
86
- resolveCompactBufferTokens,
87
- resolveCompactTriggerTokens,
88
- summarizeContextMessages,
89
- } from './runtime/agent/orchestrator/session/context-utils.mjs';
90
-
91
- import {
92
- sessionMessageText,
93
- messageContextText,
94
- isSessionPreviewNoise,
95
- cleanSessionPreview,
96
- clean,
97
- hasOwn,
98
- toolResponseText,
99
- isEmptyRecallText,
100
- currentSessionRecallRows,
101
- sessionHasConversationMessages,
102
- } from './session-runtime/session-text.mjs';
103
- import {
104
- TOOL_MODES,
105
- ALL_EFFORT_LEVELS,
106
- EFFORT_LABELS,
107
- EFFORT_OPTIONS_BY_PROVIDER,
108
- EFFORT_BY_FAMILY,
109
- EFFORT_FALLBACKS,
110
- normalizeToolMode,
111
- normalizeEffortInput,
112
- effortOptionsFor,
113
- coerceEffortFor,
114
- normalizeSavedEffort,
115
- effortItemsFor,
116
- toolSpecForMode,
117
- deferredSurfaceModeForLead,
118
- } from './session-runtime/effort.mjs';
119
- import {
120
- LAZY_SECRET_PROVIDERS,
121
- routeFastKey,
122
- fastCapableFor,
123
- makeSearchCapableFor,
124
- fastPreferenceFor,
125
- saveModelSettings,
126
- } from './session-runtime/model-capabilities.mjs';
127
- import {
128
- DEFAULT_PROVIDER,
129
- DEFAULT_MODEL,
130
- makeResolveDefaultProvider,
131
- findPreset,
132
- makeResolveRoute,
133
- isLikelyRawModelId,
134
- validateRequestedModelSelector,
135
- ensureProviderEnabled,
136
- normalizeSystemShellConfig,
137
- normalizeSystemShellCommand,
138
- normalizeAutoClearConfig,
139
- resolveAutoClearIdleMs,
140
- autoClearIdleMsForProvider,
141
- autoClearProviderDefaults,
142
- normalizeCompactionConfig,
143
- moduleEnabled,
144
- setModuleEnabledInConfig,
145
- recapEnabled,
146
- setRecapEnabledInConfig,
147
- formatDurationMs,
148
- parseDurationMs,
149
- modelMetaLooksResolved,
150
- modelSettingsFor,
151
- normalizeCompactTypeSetting,
152
- } from './session-runtime/config-helpers.mjs';
153
- import {
154
- routeForStatusline,
155
- writeStatuslineRoute,
156
- } from './session-runtime/statusline-route.mjs';
157
- import {
158
- normalizeOutputStyleId,
159
- listOutputStyleCatalog,
160
- findOutputStyle,
161
- outputStyleStatus as outputStyleStatusRaw,
162
- } from './session-runtime/output-styles.mjs';
163
- import { readJsonSafe, readTextSafe } from './session-runtime/fs-utils.mjs';
164
- import {
165
- readProjectMcpServers,
166
- countSkillFiles,
167
- mcpScriptForPlugin,
168
- normalizePluginMcpServerConfig,
169
- pluginManifest,
170
- pluginMcpServerName,
171
- pluginRawMcpServers,
172
- pluginMcpEnableScript,
173
- resolveContainedPluginPath,
174
- } from './session-runtime/plugin-mcp.mjs';
175
- import {
176
- WORKFLOW_ROUTE_SLOTS,
177
- FIXED_AGENT_SLOTS,
178
- SEARCH_DEFAULT_PROVIDER,
179
- SEARCH_DEFAULT_MODEL,
180
- workflowPresetId,
181
- agentPresetSlot,
182
- normalizeAgentId,
183
- normalizeWorkflowId,
184
- DEFAULT_WORKFLOW_ID,
185
- createWorkflowHelpers,
186
- normalizeSearchProviderId,
187
- isDefaultSearchRouteConfig,
188
- isSearchCapableProvider,
189
- normalizeSearchRouteConfig,
190
- normalizeWorkflowRoute,
191
- upsertWorkflowPreset,
192
- createWorkflowRouteHelpers,
193
- } from './session-runtime/workflow.mjs';
194
- import {
195
- MEASURED_TOOL_USAGE,
196
- DEFERRED_DEFAULT_FULL_TOOLS,
197
- DEFERRED_DEFAULT_READONLY_TOOLS,
198
- DEFERRED_DEFAULT_LEAD_TOOLS,
199
- toolKind,
200
- toolSchemaBucket,
201
- estimateToolSchemaBreakdown,
202
- measuredToolUsage,
203
- parseToolSelection,
204
- parseToolSearchQuerySelection,
205
- sortedCatalogByMeasuredUsage,
206
- filterDisallowedTools,
207
- sortedNamesByMeasuredUsage,
208
- defaultDeferredToolNames,
209
- compactToolSearchDescription,
210
- toolRow,
211
- toolSearchMatches,
212
- applyDeferredToolSurface,
213
- selectDeferredTools,
214
- renderToolSearch,
215
- } from './session-runtime/tool-catalog.mjs';
216
- // Re-exported for external consumers (scripts/tool-smoke.mjs) that imported
217
- // these from this module before the tool-catalog extraction.
218
- export { defaultDeferredToolNames, compactToolSearchDescription } from './session-runtime/tool-catalog.mjs';
219
- import {
220
- TOOL_SEARCH_TOOL,
221
- CWD_TOOL,
222
- SKILL_TOOL,
223
- SESSION_MANAGE_TOOL,
224
- LEAD_DISALLOWED_TOOLS,
225
- applyStandaloneToolDefaults,
226
- } from './session-runtime/tool-defs.mjs';
227
- import { ONBOARDING_VERSION, QUICK_SEARCH_MODELS } from './session-runtime/quick-search-models.mjs';
228
- import {
229
- sortProviderModels as sortProviderModelsRaw,
230
- providerModelCacheRow as providerModelCacheRowRaw,
231
- } from './session-runtime/model-recency.mjs';
232
- import { createNativeSearch } from './session-runtime/native-search.mjs';
233
- import { createConfigLifecycle } from './session-runtime/config-lifecycle.mjs';
234
- import { attachSessionHooks } from './session-runtime/session-hooks.mjs';
235
- import { createQuickModelRows } from './session-runtime/quick-model-rows.mjs';
236
- import { createWarmupSchedulers } from './session-runtime/warmup-schedulers.mjs';
237
- import { createPrewarmSchedulers } from './session-runtime/prewarm.mjs';
238
- import { createMcpGlue } from './session-runtime/mcp-glue.mjs';
239
- import { createCwdPlugins } from './session-runtime/cwd-plugins.mjs';
240
- import { createSettingsApi } from './session-runtime/settings-api.mjs';
241
- import { createProviderModels } from './session-runtime/provider-models.mjs';
242
- import { createProviderUsage } from './session-runtime/provider-usage.mjs';
243
- // Re-exported for external consumers (scripts/tool-smoke.mjs) that imported
244
- // these from this module before the tool-defs extraction.
245
- export { TOOL_SEARCH_TOOL, SKILL_TOOL };
246
- // Back-compat test alias; delegates to the extracted helper.
247
- export function __applyStandaloneToolDefaultsForTest(tool) {
248
- return applyStandaloneToolDefaults(tool);
249
- }
250
-
251
- const RUNTIME = './runtime/agent/orchestrator';
252
- const SEARCH_RUNTIME = './runtime/search/index.mjs';
253
- const SEARCH_TOOL_DEFS = './runtime/search/tool-defs.mjs';
254
- const MEMORY_TOOL_DEFS = './runtime/memory/tool-defs.mjs';
255
- const MEMORY_RUNTIME = './runtime/memory/index.mjs';
256
- const CHANNEL_TOOL_DEFS = './runtime/channels/tool-defs.mjs';
257
- const CHANNEL_WORKER_ENTRY = './runtime/channels/index.mjs';
258
- const CODE_GRAPH_TOOL_DEFS = './runtime/agent/orchestrator/tools/code-graph-tool-defs.mjs';
259
- const CODE_GRAPH_RUNTIME = './runtime/agent/orchestrator/tools/code-graph.mjs';
260
- const STATUSLINE_SESSION_ROUTES = './vendor/statusline/src/gateway/session-routes.mjs';
261
- const __dirname = dirname(fileURLToPath(import.meta.url));
262
- const STANDALONE_SOURCE_ROOT = __dirname;
263
- // Resource root stays at src/ because defaults/, rules/, runtime/, vendor/ live
264
- // there. User-owned standalone state lives under MIXDOG_HOME (~/.mixdog).
265
- const STANDALONE_ROOT = STANDALONE_SOURCE_ROOT;
266
- const MIXDOG_HOME = process.env.MIXDOG_HOME || join(homedir(), '.mixdog');
267
- const STANDALONE_DATA_DIR = process.env.MIXDOG_DATA_DIR || join(MIXDOG_HOME, 'data');
268
-
269
- const resolveDefaultProvider = makeResolveDefaultProvider(isKnownProvider);
270
- const resolveRoute = makeResolveRoute(resolveDefaultProvider);
271
- const searchCapableFor = makeSearchCapableFor(normalizeSearchProviderId, isSearchCapableProvider);
272
-
273
- function envFlag(name) {
274
- return /^(1|true|yes|on)$/i.test(String(process.env[name] || ''));
275
- }
276
-
277
- function envPresent(name) {
278
- return process.env[name] !== undefined && process.env[name] !== '';
279
- }
280
-
281
- function envDelayMs(name, fallback, { min = 0, max = 60_000 } = {}) {
282
- const raw = process.env[name];
283
- if (raw === undefined || raw === '') return fallback;
284
- const n = Number(raw);
285
- if (!Number.isFinite(n)) return fallback;
286
- return Math.min(max, Math.max(min, Math.floor(n)));
287
- }
288
-
289
- const BOOT_PROFILE_ENABLED = envFlag('MIXDOG_BOOT_PROFILE');
290
- const BOOT_PROFILE_START = globalThis.__mixdogBootProfileStart || (globalThis.__mixdogBootProfileStart = performance.now());
291
-
292
- function bootProfile(event, fields = {}) {
293
- if (!BOOT_PROFILE_ENABLED) return;
294
- const elapsedMs = performance.now() - BOOT_PROFILE_START;
295
- const parts = [`[mixdog-boot] +${elapsedMs.toFixed(1)}ms`, event];
296
- for (const [key, value] of Object.entries(fields || {})) {
297
- if (value === undefined || value === null || value === '') continue;
298
- parts.push(`${key}=${String(value).replace(/\s+/g, '_')}`);
299
- }
300
- try { process.stderr.write(`${parts.join(' ')}\n`); } catch {}
301
- }
302
-
303
- async function profiledImport(label, spec, { optional = false } = {}) {
304
- const startedAt = performance.now();
305
- try {
306
- const mod = await import(spec);
307
- bootProfile(`import:${label}`, { ms: (performance.now() - startedAt).toFixed(1) });
308
- return mod;
309
- } catch (error) {
310
- bootProfile(`import:${label}:failed`, {
311
- ms: (performance.now() - startedAt).toFixed(1),
312
- error: error?.message || String(error),
313
- });
314
- if (optional) return null;
315
- throw error;
316
- }
317
- }
318
- const outputStyleStatus = (dataDir = STANDALONE_DATA_DIR) => outputStyleStatusRaw(STANDALONE_ROOT, dataDir || STANDALONE_DATA_DIR);
319
- // Workflow/agent pack loaders bound to this runtime's root/data layout.
320
- const {
321
- listWorkflowPacks,
322
- activeWorkflowId,
323
- loadWorkflowPack,
324
- workflowSummary,
325
- activeWorkflowSummary,
326
- loadAgentDefinition,
327
- workflowContextBlock,
328
- } = createWorkflowHelpers({
329
- rootDir: STANDALONE_ROOT,
330
- dataDir: STANDALONE_DATA_DIR,
331
- readMarkdownDocument,
332
- normalizeAgentPermissionOrNone,
333
- });
334
- const {
335
- summarizeWorkflowRoutes,
336
- routeFromPreset,
337
- agentRouteFromConfig,
338
- } = createWorkflowRouteHelpers({ resolveDefaultProvider, findPreset });
339
-
340
- export function __renderToolSearchForTest(args = {}, session = {}, mode = 'full') {
341
- return renderToolSearch(args, session, mode);
342
- }
343
-
344
- export function __saveModelSettingsForTest(cfgMod, route, options = {}) {
345
- return saveModelSettings(cfgMod, route, options);
346
- }
347
-
348
- export async function createMixdogSessionRuntime({
349
- provider,
350
- model,
351
- cwd = process.cwd(),
352
- toolMode = 'full',
353
- remote = false,
354
- } = {}) {
355
- bootProfile('session-runtime:start', { provider, model, toolMode, cwd });
356
- let remoteEnabled = remote === true;
357
- // Remote-mode transcript writer (Discord outbound). Lazily created per
358
- // session.id + cwd inside ask(); only active while remoteEnabled.
359
- let _transcriptWriter = null;
360
- let _twKey = '';
361
- // Last assistant text handed to the transcript writer (via onAssistantText),
362
- // so the post-turn final-content append can skip an exact duplicate.
363
- let _lastAppendedAssistant = '';
364
- process.env.MIXDOG_QUIET_SESSION_LOG ??= '1';
365
- const standaloneStartedAt = performance.now();
366
- ensureStandaloneEnvironment({
367
- rootDir: STANDALONE_ROOT,
368
- dataDir: STANDALONE_DATA_DIR,
369
- });
370
- bootProfile('standalone-env:ready', { ms: (performance.now() - standaloneStartedAt).toFixed(1) });
371
-
372
- const importsStartedAt = performance.now();
373
- const [
374
- cfgMod,
375
- sharedCfgMod,
376
- reg,
377
- mcpClient,
378
- mgr,
379
- contextMod,
380
- internalTools,
381
- statusRoutes,
382
- searchToolDefs,
383
- memoryToolDefs,
384
- channelToolDefs,
385
- codeGraphToolDefs,
386
- ] = await Promise.all([
387
- profiledImport('config', `${RUNTIME}/config.mjs`),
388
- profiledImport('shared-config', `${RUNTIME}/../../shared/config.mjs`),
389
- profiledImport('providers-registry', `${RUNTIME}/providers/registry.mjs`),
390
- profiledImport('mcp-client', `${RUNTIME}/mcp/client.mjs`),
391
- profiledImport('session-manager', `${RUNTIME}/session/manager.mjs`),
392
- profiledImport('context-collect', `${RUNTIME}/context/collect.mjs`),
393
- profiledImport('internal-tools', `${RUNTIME}/internal-tools.mjs`),
394
- profiledImport('status-routes', STATUSLINE_SESSION_ROUTES, { optional: true }),
395
- profiledImport('search-tool-defs', SEARCH_TOOL_DEFS, { optional: true }),
396
- profiledImport('memory-tool-defs', MEMORY_TOOL_DEFS, { optional: true }),
397
- profiledImport('channel-tool-defs', CHANNEL_TOOL_DEFS, { optional: true }),
398
- profiledImport('code-graph-tool-defs', CODE_GRAPH_TOOL_DEFS, { optional: true }),
399
- ]);
400
- bootProfile('imports:ready', { ms: (performance.now() - importsStartedAt).toFixed(1) });
401
- const pluginDataDir = cfgMod.getPluginData();
402
- // Re-wire the idle/tombstone sweep. startIdleCleanup() lost its caller in a
403
- // refactor, so closed-session tombstones were never deleted after their 24h
404
- // grace — the store grew unbounded (observed: 1.8k files / 114MB), which
405
- // made summary-index rebuilds and per-save index rewrites stall boot for
406
- // seconds. Timer is unref'd and first fires after CLEANUP_INITIAL_DELAY_MS
407
- // (5min), so this adds zero boot-path cost.
408
- try { mgr.startIdleCleanup?.(); } catch { /* cleanup is best-effort */ }
409
- const memoryRuntime = createStandaloneMemoryRuntime({
410
- entry: join(STANDALONE_ROOT, MEMORY_RUNTIME.replace(/^\.\//, '')),
411
- dataDir: pluginDataDir,
412
- cwd,
413
- });
414
- let memoryModPromise = null;
415
- let searchModPromise = null;
416
- let codeGraphModPromise = null;
417
-
418
- // Memory module is always-on. `memoryEnabled()` is kept as a thin alias that
419
- // now always returns true (callers/compaction helpers still reference it);
420
- // the user-facing toggle is `recap` (background cycles only), read via
421
- // recapEnabled(config).
422
- const memoryEnabled = () => true;
423
- const recapEnabledFn = () => recapEnabled(config, true);
424
- const channelsEnabled = () => moduleEnabled(config, 'channels', true);
425
-
426
- async function getMemoryModule() {
427
- const startedAt = performance.now();
428
- memoryModPromise ??= Promise.resolve(memoryRuntime);
429
- const mod = await memoryModPromise;
430
- if (typeof mod?.init === 'function') {
431
- await mod.init();
432
- }
433
- bootProfile('memory-runtime:ready', { ms: (performance.now() - startedAt).toFixed(1) });
434
- return mod;
435
- }
436
-
437
- async function getSearchModule() {
438
- const startedAt = performance.now();
439
- searchModPromise ??= import(SEARCH_RUNTIME);
440
- const mod = await searchModPromise;
441
- bootProfile('search-runtime:ready', { ms: (performance.now() - startedAt).toFixed(1) });
442
- return mod;
443
- }
444
-
445
- async function getCodeGraphModule() {
446
- const startedAt = performance.now();
447
- codeGraphModPromise ??= import(CODE_GRAPH_RUNTIME);
448
- const mod = await codeGraphModPromise;
449
- bootProfile('code-graph-runtime:ready', { ms: (performance.now() - startedAt).toFixed(1) });
450
- return mod;
451
- }
452
-
453
- function persistLeadRoute(routeLike) {
454
- const leadRoute = normalizeWorkflowRoute(routeLike);
455
- if (!leadRoute) return null;
456
-
457
- const nextConfig = { ...(config || {}) };
458
- nextConfig.presets = upsertWorkflowPreset(nextConfig.presets, 'lead', leadRoute);
459
- nextConfig.workflowRoutes = {
460
- ...(nextConfig.workflowRoutes || {}),
461
- lead: leadRoute,
462
- };
463
- nextConfig.default = workflowPresetId('lead');
464
-
465
- saveConfigAndAdopt(nextConfig);
466
- return leadRoute;
467
- }
468
-
469
- async function closePatchRuntimeIfLoaded(options = {}) {
470
- const closer = globalThis.__mixdogCloseNativePatchServers;
471
- if (typeof closer !== 'function' || globalThis.__mixdogNativePatchRuntimeTouched !== true) return;
472
- bootProfile('patch-runtime:close:start');
473
- const startedAt = performance.now();
474
- try {
475
- await closer(options);
476
- } catch {
477
- // Best-effort shutdown only; terminal restore must continue.
478
- } finally {
479
- bootProfile('patch-runtime:close:done', { ms: (performance.now() - startedAt).toFixed(1) });
480
- }
481
- }
482
-
483
- const configStartedAt = performance.now();
484
- let config = cfgMod.loadConfig({ secrets: false });
485
- setConfiguredShell(normalizeSystemShellConfig(config.shell).command);
486
- let configHasSecrets = false;
487
- let route = resolveRoute(config, { provider, model });
488
- let searchRoute = normalizeSearchRouteConfig(config.searchRoute);
489
- bootProfile('config:ready', { ms: (performance.now() - configStartedAt).toFixed(1) });
490
- let mode = normalizeToolMode(toolMode);
491
- let session = null;
492
- let sessionCreatePromise = null;
493
- let currentCwd = cwd;
494
- let sessionNeedsCwdRefresh = false;
495
- // session_manage tool: reset request scheduled by the model mid-turn,
496
- // consumed by the TUI engine at turn end ('clear' | 'compact_clear').
497
- let pendingSessionReset = null;
498
- let closeRequested = false;
499
- const warmupTimers = {
500
- providerSetupWarmupTimer: null,
501
- providerWarmupTimer: null,
502
- providerModelWarmupTimer: null,
503
- modelCatalogWarmupTimer: null,
504
- statuslineUsageWarmupTimer: null,
505
- statuslineUsageRefreshTimer: null,
506
- };
507
- // Prewarm/channel-start timer handles + async state, owned here so the
508
- // teardown clearTimeout sweep still sees them; the prewarm scheduler factory
509
- // mutates these objects in place (see createPrewarmSchedulers).
510
- const prewarmTimers = {
511
- codeGraphPrewarmTimer: null,
512
- channelStartTimer: null,
513
- };
514
- const prewarmState = {
515
- codeGraphPrewarmInFlight: false,
516
- codeGraphPrewarmQueuedCwd: '',
517
- channelStartPromise: null,
518
- };
519
- let activeTurnCount = 0;
520
- let firstTurnCompleted = false;
521
- function hookTranscriptPath(sessionId) {
522
- const id = clean(sessionId);
523
- if (!id || !/^[A-Za-z0-9_-]+$/.test(id)) return null;
524
- const dataDir = cfgMod.getPluginData?.() || STANDALONE_DATA_DIR;
525
- return join(dataDir, 'sessions', `${id}.json`);
526
- }
527
- function hookEffortPayload() {
528
- const level = clean(route.effectiveEffort || route.effort);
529
- return level ? { level: level.toLowerCase() } : undefined;
530
- }
531
- function hookCommonPayload(extra = {}) {
532
- const sid = clean(extra.session_id || extra.sessionId || session?.id);
533
- return {
534
- ...(sid ? { session_id: sid, transcript_path: hookTranscriptPath(sid) } : {}),
535
- cwd: currentCwd,
536
- permission_mode: session?.permissionMode || 'default',
537
- ...(hookEffortPayload() ? { effort: hookEffortPayload() } : {}),
538
- ...extra,
539
- };
540
- }
541
- const sessionPrewarmDelayMs = envDelayMs('MIXDOG_SESSION_PREWARM_DELAY_MS', 50, { min: 0, max: 10_000 });
542
- const providerSetupWarmupDelayMs = envDelayMs('MIXDOG_PROVIDER_SETUP_WARMUP_DELAY_MS', 300, { min: 0, max: 60_000 });
543
- const modelCatalogWarmupDelayMs = envDelayMs('MIXDOG_MODEL_CATALOG_WARMUP_DELAY_MS', 200, { min: 0, max: 60_000 });
544
- const providerWarmupDelayMs = envDelayMs('MIXDOG_PROVIDER_WARMUP_DELAY_MS', 1_500, { min: 0, max: 60_000 });
545
- // Background model-catalog prefetch delay. Kept short so the first `/model`
546
- // open finds a warm cache instead of paying a cold full network load. The
547
- // work is async + unref'd, so short-lived detached runtimes still exit
548
- // cleanly without waiting on it. Operators can raise it via env if a
549
- // detached runtime must avoid the /models round-trip entirely.
550
- const providerModelWarmupDelayMs = envDelayMs('MIXDOG_PROVIDER_MODEL_WARMUP_DELAY_MS', 2_000, { min: 0, max: 120_000 });
551
- const codeGraphPrewarmDelayMs = envDelayMs('MIXDOG_CODE_GRAPH_PREWARM_DELAY_MS', 250, { min: 0, max: 60_000 });
552
- const statuslineUsageWarmupDelayMs = envDelayMs('MIXDOG_STATUSLINE_USAGE_WARMUP_DELAY_MS', 800, { min: 0, max: 60_000 });
553
- // Idle keep-alive: re-fetch usage before the statusline's 10-min staleness cut
554
- // (LIVE_USAGE_SNAPSHOT_MAX_AGE_MS) so the usage segment does not disappear
555
- // while the session sits idle with no turns to trigger a refresh.
556
- const statuslineUsageRefreshDelayMs = envDelayMs('MIXDOG_STATUSLINE_USAGE_REFRESH_MS', 240_000, { min: 30_000, max: 540_000 });
557
- const channelStartDelayMs = envDelayMs('MIXDOG_CHANNEL_START_DELAY_MS', 10_000, { min: 0, max: 120_000 });
558
- const backgroundBusyRetryMs = envDelayMs('MIXDOG_BACKGROUND_BUSY_RETRY_MS', 1_000, { min: 50, max: 10_000 });
559
- const sessionPrewarmEnabled = !envFlag('MIXDOG_DISABLE_SESSION_PREWARM')
560
- && (envFlag('MIXDOG_ENABLE_SESSION_PREWARM') || envPresent('MIXDOG_SESSION_PREWARM_DELAY_MS'));
561
- const providerWarmupEnabled = !envFlag('MIXDOG_DISABLE_PROVIDER_WARMUP')
562
- && (
563
- envFlag('MIXDOG_ENABLE_PROVIDER_WARMUP')
564
- || envFlag('MIXDOG_PROVIDER_WARMUP_BEFORE_FIRST_TURN')
565
- || envPresent('MIXDOG_PROVIDER_WARMUP_DELAY_MS')
566
- || envPresent('MIXDOG_PROVIDER_MODEL_WARMUP_DELAY_MS')
567
- );
568
- // Boot-time model-catalog prefetch is intentionally decoupled from the
569
- // heavier providerWarmupEnabled gate (which stays opt-in for provider
570
- // *init* side effects). Fetching the model list in the background after a
571
- // short delay is cheap, fire-and-forget, and unref'd, so it is ON by
572
- // default — otherwise the FIRST `/model` open always paid a cold full
573
- // network load. Operators can still disable it explicitly.
574
- const modelPrefetchEnabled = !envFlag('MIXDOG_DISABLE_PROVIDER_WARMUP')
575
- && !envFlag('MIXDOG_DISABLE_MODEL_PREFETCH');
576
- const codeGraphPrewarmEnabled = !envFlag('MIXDOG_DISABLE_CODE_GRAPH_PREWARM');
577
- const modelCatalogWarmupEnabled = !envFlag('MIXDOG_DISABLE_MODEL_CATALOG_WARMUP');
578
- // Lazy code-graph prewarm (default ON): do NOT prewarm at startup / on cwd
579
- // change — that fired ~250ms after the first frame and, in a large tree,
580
- // burned a worker (and felt like a freeze) before the user did anything.
581
- // Instead prewarm ONCE on the first real turn, when a code lookup is actually
582
- // imminent. Operators who want the old eager behavior can set
583
- // MIXDOG_CODE_GRAPH_PREWARM_EAGER=1.
584
- const codeGraphPrewarmLazy = codeGraphPrewarmEnabled && !envFlag('MIXDOG_CODE_GRAPH_PREWARM_EAGER');
585
- let codeGraphFirstTurnPrewarmDone = false;
586
- const modelMetaByRoute = new Map();
587
- const notificationListeners = new Set();
588
- // Remote seat listeners (TUI): fired when remote mode flips outside a direct
589
- // user action — currently only the superseded (seat stolen) path.
590
- const remoteStateListeners = new Set();
591
- function emitRemoteStateChange(enabled, reason = '') {
592
- for (const listener of [...remoteStateListeners]) {
593
- try { listener({ enabled: enabled === true, reason: String(reason || '') }); } catch {}
594
- }
595
- }
596
- const providerModelCaches = {
597
- providerModelsCache: { models: null, at: 0 },
598
- providerModelsPromise: null,
599
- providerModelsLoadSeq: 0,
600
- searchProviderModelsCache: { models: null, at: 0 },
601
- };
602
- const providerUsageCaches = {
603
- usageDashboardCache: { dashboard: null, at: 0 },
604
- usageDashboardPromise: null,
605
- providerSetupCache: { setup: null, at: 0 },
606
- providerSetupQuickCache: { setup: null, at: 0 },
607
- providerSetupPromise: null,
608
- };
609
- let providerInitPromise = null;
610
- let lastProjectMcpKey = null;
611
- // MCP connect state, owned here so teardown/reconnect paths still observe it;
612
- // the mcp-glue factory mutates this object in place (see createMcpGlue).
613
- const mcpState = {
614
- mcpFailures: [],
615
- mcpConnectGeneration: 0,
616
- mcpConnectInFlight: null,
617
- };
618
- // MCP glue factory — config/currentCwd live-bound; connect state shared via
619
- // the caller-owned mcpState object above.
620
- const {
621
- mcpTransportLabel,
622
- resolveEffectiveMcpServers,
623
- mcpStatus,
624
- connectConfiguredMcp,
625
- normalizeMcpServerInput,
626
- } = createMcpGlue({
627
- mcpClient,
628
- getConfig: () => config,
629
- getCurrentCwd: () => currentCwd,
630
- state: mcpState,
631
- });
632
- let preSessionToolSurface = null;
633
- let contextStatusCacheKey = null;
634
- let contextStatusCacheValue = null;
635
- const hooksStartedAt = performance.now();
636
- const hooks = createStandaloneHookBus({ dataDir: cfgMod.getPluginData() });
637
- hooks.emit('runtime:start', { cwd: currentCwd, provider: route.provider, model: route.model, toolMode: mode });
638
- bootProfile('hooks:ready', { ms: (performance.now() - hooksStartedAt).toFixed(1) });
639
-
640
- // ---------------------------------------------------------------------
641
- // Self-update (npm registry version check + optional auto-install).
642
- // updateCheckState mirrors the last-known checkLatestVersion() result;
643
- // updateProcessState tracks the in-flight install lifecycle so the TUI can
644
- // poll getUpdateStatus() instead of needing a push/event channel. Both are
645
- // purely in-memory (per runtime instance) — the on-disk cache lives inside
646
- // update-checker.mjs and is what actually enforces the 24h TTL.
647
- let updateCheckState = {
648
- currentVersion: null,
649
- latestVersion: null,
650
- updateAvailable: false,
651
- lastCheckedAt: 0,
652
- };
653
- // phase: 'idle' | 'checking' | 'installing' | 'installed' | 'failed'
654
- let updateProcessState = { phase: 'idle', version: null, error: null };
655
-
656
- function autoUpdateEnabled() {
657
- return config?.update?.auto !== false;
658
- }
659
-
660
- async function checkForUpdateInternal({ force = false } = {}) {
661
- if (updateProcessState.phase !== 'installing') updateProcessState.phase = 'checking';
662
- try {
663
- const result = await checkLatestVersion({ force, dataDir: cfgMod.getPluginData?.() || STANDALONE_DATA_DIR });
664
- updateCheckState = {
665
- currentVersion: result.currentVersion,
666
- latestVersion: result.latestVersion,
667
- updateAvailable: result.updateAvailable,
668
- lastCheckedAt: result.lastCheckedAt,
669
- };
670
- } catch {
671
- // checkLatestVersion() is already silent-safe; this catch is belt-and-
672
- // braces so a boot-time call can never crash the runtime.
673
- } finally {
674
- if (updateProcessState.phase === 'checking') updateProcessState.phase = 'idle';
675
- }
676
- return updateCheckState;
677
- }
678
-
679
- async function runUpdateNowInternal() {
680
- if (updateProcessState.phase === 'installing') {
681
- return { ...updateProcessState, alreadyInstalling: true, error: 'update already in progress' };
682
- }
683
- updateProcessState = { phase: 'installing', version: null, error: null };
684
- try {
685
- const result = await runGlobalUpdate();
686
- if (result?.ok) {
687
- updateProcessState = { phase: 'installed', version: result.version || null, error: null };
688
- } else {
689
- updateProcessState = { phase: 'failed', version: null, error: result?.error || 'update failed' };
690
- }
691
- } catch (err) {
692
- updateProcessState = { phase: 'failed', version: null, error: err?.message || String(err) };
693
- }
694
- return updateProcessState;
695
- }
696
-
697
- // Non-blocking boot hook: fires after the runtime object below is fully
698
- // constructed (setTimeout(0) defers past the synchronous return), so a
699
- // slow/hanging registry request or npm install can never delay session
700
- // boot. Auto-update defaults to ON unless config.update.auto is explicitly
701
- // false; a failed check or install is
702
- // swallowed — getUpdateStatus()/getUpdateSettings() are the only surfaces,
703
- // there is no push notice channel from runtime -> TUI today.
704
- // force:true — always hit the registry at boot (the 24h disk cache went
705
- // stale-visible: it kept reporting an older "latest" than the installed
706
- // version). checkLatestVersion() still falls back to the cache offline.
707
- const updateBootTimer = setTimeout(() => {
708
- void (async () => {
709
- await checkForUpdateInternal({ force: true });
710
- if (autoUpdateEnabled() && updateCheckState.updateAvailable) {
711
- await runUpdateNowInternal();
712
- }
713
- })().catch(() => {});
714
- }, 0);
715
- updateBootTimer.unref?.();
716
-
717
- function emitRuntimeNotification(content, meta = {}) {
718
- const text = String(content || '').trim();
719
- if (!text) return false;
720
- const event = { content: text, meta: meta && typeof meta === 'object' ? meta : {} };
721
- let handled = false;
722
- for (const listener of [...notificationListeners]) {
723
- try {
724
- if (listener(event) === true) handled = true;
725
- } catch {}
726
- }
727
- return handled;
728
- }
729
-
730
- function notifyFnForSession(callerSessionId) {
731
- return (text, meta = {}) => {
732
- const handledByRuntimeListener = emitRuntimeNotification(text, meta);
733
- let enqueued = false;
734
- // TUI sessions consume raw execution notifications for UI/task cards via
735
- // onNotification, but those raw envelopes are internal-only in pending
736
- // drain. Always mirror terminal completions with a model-visible wrapper
737
- // while keeping the raw text for UI display.
738
- if (callerSessionId && typeof mgr.enqueuePendingMessage === 'function'
739
- && shouldPersistModelVisibleToolCompletion(text, meta)) {
740
- try {
741
- const visible = modelVisibleToolCompletionMessage(text, meta);
742
- if (visible) enqueued = mgr.enqueuePendingMessage(callerSessionId, visible) > 0;
743
- } catch {}
744
- }
745
- // Headless/API listeners may exist but not consume the event; preserve
746
- // the old fallback for non-terminal notifications only when unhandled.
747
- if (!enqueued && !handledByRuntimeListener && callerSessionId
748
- && typeof mgr.enqueuePendingMessage === 'function') {
749
- try {
750
- const visible = modelVisibleToolCompletionMessage(text, meta);
751
- if (visible) enqueued = mgr.enqueuePendingMessage(callerSessionId, visible) > 0;
752
- } catch {}
753
- }
754
- return enqueued || handledByRuntimeListener;
755
- };
756
- }
757
-
758
- function skillsStatus() {
759
- const skills = typeof contextMod.collectSkillsCached === 'function'
760
- ? contextMod.collectSkillsCached(currentCwd)
761
- : [];
762
- const norm = (value) => String(value || '').replace(/\\/g, '/').toLowerCase();
763
- const cwdNorm = norm(currentCwd);
764
- const sourceForSkill = (filePath) => {
765
- const path = norm(filePath);
766
- if (cwdNorm && path.startsWith(`${cwdNorm}/.mixdog/skills/`)) return 'project';
767
- return 'skill';
768
- };
769
- return {
770
- cwd: currentCwd,
771
- count: skills.length,
772
- skills: skills.map((skill) => ({
773
- name: skill.name,
774
- description: skill.description || '',
775
- filePath: skill.filePath || null,
776
- source: sourceForSkill(skill.filePath),
777
- })),
778
- };
779
- }
780
-
781
- // cwd resolution/apply + plugins-status + core-memory context. Extracted to
782
- // session-runtime/cwd-plugins.mjs; the facade keeps ownership of the mutable
783
- // currentCwd/session/config/lastProjectMcpKey locals via getter/setter
784
- // injection and passes the later-defined callbacks (prewarm/tool-surface/
785
- // memory) as closures.
786
- const {
787
- resolveCwdPath,
788
- applyResolvedCwd,
789
- refreshSessionForCwdIfNeeded,
790
- pluginsStatus,
791
- loadCoreMemoryContext,
792
- } = createCwdPlugins({
793
- getCurrentCwd: () => currentCwd,
794
- setCurrentCwd: (next) => { currentCwd = next; },
795
- getConfig: () => config,
796
- getSession: () => session,
797
- getRoute: () => route,
798
- getLastProjectMcpKey: () => lastProjectMcpKey,
799
- setLastProjectMcpKey: (next) => { lastProjectMcpKey = next; },
800
- isCodeGraphPrewarmLazy: () => codeGraphPrewarmLazy,
801
- isCodeGraphFirstTurnPrewarmDone: () => codeGraphFirstTurnPrewarmDone,
802
- getCodeGraphPrewarmDelayMs: () => codeGraphPrewarmDelayMs,
803
- setSessionNeedsCwdRefresh: (next) => { sessionNeedsCwdRefresh = next; },
804
- connectConfiguredMcp,
805
- invalidatePreSessionToolSurface: (...a) => invalidatePreSessionToolSurface(...a),
806
- scheduleCodeGraphPrewarm: (...a) => scheduleCodeGraphPrewarm(...a),
807
- hooks,
808
- hookCommonPayload: (...a) => hookCommonPayload(...a),
809
- bootProfile,
810
- getMemoryModule: (...a) => getMemoryModule(...a),
811
- listRegisteredPlugins,
812
- pluginAdminStatus,
813
- pluginManifest,
814
- pluginMcpServerName,
815
- mcpScriptForPlugin,
816
- countSkillFiles,
817
- readProjectMcpServers,
818
- writeLastSessionCwd,
819
- clean,
820
- resolve,
821
- statSync,
822
- existsSync,
823
- cfgMod,
824
- STANDALONE_DATA_DIR,
825
- });
826
-
827
- function skillContent(name) {
828
- const res = typeof contextMod.loadSkillResource === 'function'
829
- ? contextMod.loadSkillResource(name, currentCwd)
830
- : null;
831
- if (!res) throw new Error(`skill not found: ${name}`);
832
- return { name, content: res.content, dir: res.dir };
833
- }
834
-
835
- function skillToolContent(name) {
836
- if (typeof contextMod.isSkillDisabled === 'function' && contextMod.isSkillDisabled(name)) {
837
- const label = String(name || '').trim() || 'skill';
838
- return `Error: skill "${label}" is disabled`;
839
- }
840
- const skill = skillContent(name);
841
- // Return the general tool envelope so the main/Lead session behaves the
842
- // same as agent-loop sessions: the model-visible tool_result is the short
843
- // stub (`Loaded skill: <name>`) and the full SKILL.md body is delivered
844
- // ONCE as a separate injected role:'user' message (newMessages). The
845
- // envelope passes through internal-tools._normalize untouched (it preserves
846
- // __toolEnvelope objects), and the agent loop's central normalizeToolEnvelope
847
- // splits it into stub + injected user body.
848
- return contextMod.buildSkillToolEnvelope(skill.name, skill.content, skill.dir);
849
- }
850
-
851
- function addProjectSkill(input = {}) {
852
- const name = clean(input.name).replace(/[^a-zA-Z0-9_.-]+/g, '-').replace(/^-+|-+$/g, '');
853
- if (!name) throw new Error('skill name is required');
854
- const dir = join(currentCwd, '.mixdog', 'skills', name);
855
- const filePath = join(dir, 'SKILL.md');
856
- if (existsSync(filePath)) throw new Error(`skill already exists: ${name}`);
857
- const description = clean(input.description) || 'Project skill.';
858
- mkdirSync(dir, { recursive: true });
859
- writeFileSync(filePath, [
860
- '---',
861
- `name: ${name}`,
862
- `description: ${description}`,
863
- '---',
864
- '',
865
- '# Instructions',
866
- '',
867
- 'Describe when and how to use this skill.',
868
- '',
869
- ].join('\n'), 'utf8');
870
- return { name, filePath };
871
- }
872
-
873
- const agentToolStartedAt = performance.now();
874
- const agentTool = createStandaloneAgent({
875
- cfgMod,
876
- reg,
877
- mgr,
878
- dataDir: cfgMod.getPluginData(),
879
- cwd,
880
- // SubagentStart/SubagentStop: bridge internal worker spawn/finish to the
881
- // standard hook bus. agent_type is passed top-level via hookCommonPayload
882
- // (added to hook-bus buildEventPayload passthrough). Best-effort.
883
- onSubagentEvent: (phase, info = {}) => {
884
- try {
885
- const event = phase === 'stop' ? 'SubagentStop' : 'SubagentStart';
886
- void hooks.dispatch(event, hookCommonPayload({
887
- session_id: info?.session_id || null,
888
- agent_type: info?.agent_type || null,
889
- }));
890
- } catch { /* best-effort: subagent hook must never affect worker lifecycle */ }
891
- },
892
- });
893
- bootProfile('agent:ready', { ms: (performance.now() - agentToolStartedAt).toFixed(1) });
894
- const agentStatusState = () => {
895
- try {
896
- const status = agentTool.getStatus?.({ clientHostPid: session?.clientHostPid || process.pid }) || {};
897
- return {
898
- agentWorkers: Array.isArray(status.workers) ? status.workers : [],
899
- agentJobs: Array.isArray(status.jobs) ? status.jobs : [],
900
- agentScope: status.scope || null,
901
- };
902
- } catch {
903
- return { agentWorkers: [], agentJobs: [], agentScope: null };
904
- }
905
- };
906
- const channelsStartedAt = performance.now();
907
- const channels = createStandaloneChannelWorker({
908
- entry: join(STANDALONE_ROOT, CHANNEL_WORKER_ENTRY.replace(/^\.\//, '')),
909
- rootDir: STANDALONE_ROOT,
910
- dataDir: cfgMod.getPluginData(),
911
- cwd,
912
- onNotify: (msg) => {
913
- // Single-holder remote: the worker reports it lost the bridge seat to a
914
- // newer remote session. Drop remote mode entirely on this session (no
915
- // handover, no retry) and tell UI listeners so the indicator updates.
916
- if (msg?.method === 'notifications/mixdog/remote') {
917
- if (msg?.params?.state === 'superseded' && remoteEnabled) {
918
- stopRemote('superseded-by-newer-remote-session');
919
- emitRemoteStateChange(false, 'superseded');
920
- }
921
- return;
922
- }
923
- if (msg?.method !== 'notifications/claude/channel') return;
924
- const params = msg?.params && typeof msg.params === 'object' ? msg.params : {};
925
- const meta = params.meta && typeof params.meta === 'object' ? params.meta : {};
926
- const content = channelNotificationModelContent(params);
927
- if (!content) return;
928
- const handled = emitRuntimeNotification(content, meta);
929
- if (!handled && session?.id && shouldMirrorChannelNotificationToPending(meta)) {
930
- try { mgr.enqueuePendingMessage(session.id, content); } catch {}
931
- }
932
- },
933
- });
934
- bootProfile('channels:worker-ready', { ms: (performance.now() - channelsStartedAt).toFixed(1) });
935
- const toolsStartedAt = performance.now();
936
- const standaloneTools = [
937
- TOOL_SEARCH_TOOL,
938
- SKILL_TOOL,
939
- CWD_TOOL,
940
- SESSION_MANAGE_TOOL,
941
- EXPLORE_TOOL,
942
- ...(searchToolDefs?.TOOL_DEFS || []).filter((tool) => tool?.name === 'search' || tool?.name === 'web_fetch'),
943
- ...(memoryToolDefs?.TOOL_DEFS || []).filter((tool) => tool?.name === 'recall' || tool?.name === 'memory'),
944
- ...(channelToolDefs?.TOOL_DEFS || []).filter((tool) => channels.isChannelTool(tool?.name)),
945
- ...(codeGraphToolDefs?.CODE_GRAPH_TOOL_DEFS || []).filter((tool) => tool?.name === 'code_graph'),
946
- ...agentTool.tools,
947
- ].map(applyStandaloneToolDefaults);
948
- bootProfile('tools:ready', { ms: (performance.now() - toolsStartedAt).toFixed(1), count: standaloneTools.length });
949
-
950
- function invalidatePreSessionToolSurface() {
951
- preSessionToolSurface = null;
952
- }
953
-
954
- function invalidateContextStatusCache() {
955
- contextStatusCacheKey = null;
956
- contextStatusCacheValue = null;
957
- }
958
-
959
- function buildPreSessionToolSurface() {
960
- const previewTools = typeof mgr.previewSessionTools === 'function'
961
- ? mgr.previewSessionTools(toolSpecForMode(mode), [])
962
- : [];
963
- const tools = filterDisallowedTools(previewTools, LEAD_DISALLOWED_TOOLS);
964
- const surface = { tools: Array.isArray(tools) ? tools.slice() : [] };
965
- applyDeferredToolSurface(surface, deferredSurfaceModeForLead(mode), standaloneTools, { provider: route.provider });
966
- return surface;
967
- }
968
-
969
- function activeToolSurface() {
970
- if (session) return session;
971
- preSessionToolSurface ??= buildPreSessionToolSurface();
972
- return preSessionToolSurface;
973
- }
974
-
975
- function applyPreSessionToolSelection() {
976
- if (!session || !preSessionToolSurface) return;
977
- const selected = Array.isArray(preSessionToolSurface.deferredSelectedTools)
978
- ? preSessionToolSurface.deferredSelectedTools
979
- : [];
980
- const discovered = Array.isArray(preSessionToolSurface.deferredDiscoveredTools)
981
- ? preSessionToolSurface.deferredDiscoveredTools
982
- : [];
983
- const replay = [...new Set([...selected, ...discovered])];
984
- if (replay.length) selectDeferredTools(session, replay, deferredSurfaceModeForLead(mode));
985
- }
986
- internalTools.setInternalToolsProvider({
987
- tools: standaloneTools,
988
- executor: async (name, args, callerCtx = {}) => {
989
- const callerCwd = callerCtx?.callerCwd || currentCwd;
990
- if (name === 'search' || name === 'web_fetch') {
991
- const callerSessionId = callerCtx?.callerSessionId || session?.id || null;
992
- const searchMod = await getSearchModule();
993
- if (!searchMod?.handleToolCall) throw new Error('search runtime is not available');
994
- return await searchMod.handleToolCall(name, args || {}, {
995
- callerCwd,
996
- callerSessionId,
997
- routingSessionId: callerSessionId,
998
- clientHostPid: callerCtx?.clientHostPid || session?.clientHostPid || process.pid,
999
- notifyFn: notifyFnForSession(callerSessionId),
1000
- nativeSearch: name === 'search'
1001
- ? async (searchArgs) => runNativeWebSearch(searchArgs, { signal: callerCtx?.signal || session?.controller?.signal })
1002
- : undefined,
1003
- });
1004
- }
1005
- if (name === 'recall' || name === 'memory' || name === 'search_memories') {
1006
- const memoryMod = await getMemoryModule();
1007
- if (!memoryMod?.handleToolCall) throw new Error('memory runtime is not available');
1008
- return await memoryMod.handleToolCall(name, args || {});
1009
- }
1010
- if (name === 'code_graph') {
1011
- const codeGraphMod = await getCodeGraphModule();
1012
- if (!codeGraphMod?.executeCodeGraphTool) throw new Error('code_graph runtime is not available');
1013
- return await codeGraphMod.executeCodeGraphTool(name, args || {}, args?.cwd || callerCwd);
1014
- }
1015
- if (name === 'tool_search') {
1016
- return renderToolSearch(args, activeToolSurface(), mode);
1017
- }
1018
- if (name === 'explore') {
1019
- const callerSessionId = callerCtx?.callerSessionId || session?.id || null;
1020
- return await runExplore(args || {}, {
1021
- callerCwd: args?.cwd ? resolveCwdPath(args.cwd) : callerCwd,
1022
- callerSessionId,
1023
- routingSessionId: callerSessionId,
1024
- clientHostPid: callerCtx?.clientHostPid || session?.clientHostPid || process.pid,
1025
- notifyFn: notifyFnForSession(callerSessionId),
1026
- });
1027
- }
1028
- if (name === 'cwd') {
1029
- const action = clean(args?.action || (args?.path ? 'set' : 'get')).toLowerCase();
1030
- if (action === 'set') {
1031
- applyResolvedCwd(resolveCwdPath(args?.path));
1032
- } else if (action !== 'get') {
1033
- throw new Error(`cwd: unknown action "${action}"`);
1034
- }
1035
- return JSON.stringify({ cwd: currentCwd, sessionId: session?.id || null }, null, 2);
1036
- }
1037
- if (name === 'session_manage') {
1038
- // Lead/owner sessions only: an agent worker resetting its own
1039
- // transcript mid-task would corrupt the delegation contract, and it
1040
- // must never reach the owner conversation either.
1041
- const callerSessionId = callerCtx?.callerSessionId || null;
1042
- if (callerSessionId && session?.id && callerSessionId !== session.id) {
1043
- throw new Error('session_manage: only the lead session may reset the conversation');
1044
- }
1045
- if (!session?.id) throw new Error('session_manage: no active session');
1046
- const action = clean(args?.action).toLowerCase();
1047
- if (action !== 'clear' && action !== 'compact_clear') {
1048
- throw new Error(`session_manage: unknown action "${action}" (use clear | compact_clear)`);
1049
- }
1050
- // Never clear mid-turn — the loop is still reading the transcript.
1051
- // Schedule and let the TUI engine consume it at turn end (same
1052
- // boundary the idle auto-clear uses).
1053
- // Pin to the current session id so a resume/new-session between
1054
- // scheduling and consumption can never clear the wrong conversation.
1055
- pendingSessionReset = { action, sessionId: session.id };
1056
- return action === 'clear'
1057
- ? 'Session reset scheduled: full clear will run when this turn ends. All prior context will be gone.'
1058
- : 'Session reset scheduled: the conversation will be summarized (compact) and cleared when this turn ends; key context carries forward in the summary.';
1059
- }
1060
- if (name === 'Skill') {
1061
- return skillToolContent(args?.name);
1062
- }
1063
- if (name === 'agent') {
1064
- const callerSessionId = callerCtx?.callerSessionId || session?.id || null;
1065
- return await agentTool.execute(args, {
1066
- callerCwd,
1067
- invocationSource: 'model-tool',
1068
- callerSessionId,
1069
- clientHostPid: callerCtx?.clientHostPid || session?.clientHostPid || process.pid,
1070
- signal: callerCtx?.signal,
1071
- notifyFn: notifyFnForSession(callerSessionId),
1072
- });
1073
- }
1074
- if (channels.isChannelTool(name)) {
1075
- if (!channelsEnabled()) throw new Error('channels are disabled in settings');
1076
- return await channels.execute(name, args || {});
1077
- }
1078
- throw new Error(`unknown standalone internal tool: ${name}`);
1079
- },
1080
- });
1081
- internalTools.markBootReady?.();
1082
- try { lastProjectMcpKey = resolve(currentCwd) + '\u0000' + JSON.stringify(readProjectMcpServers(currentCwd)); } catch { lastProjectMcpKey = null; }
1083
- void connectConfiguredMcp()
1084
- .then((status) => bootProfile('mcp:ready', {
1085
- connected: Number(status?.connectedCount || 0),
1086
- failed: Number(status?.failedCount || 0),
1087
- }))
1088
- .catch((error) => bootProfile('mcp:failed', { error: error?.message || String(error) }));
1089
-
1090
- function reloadChannelsSoon() {
1091
- channels.execute('reload_config', {}).catch(() => {});
1092
- }
1093
-
1094
- function invalidateProviderCaches() {
1095
- providerModelCaches.providerModelsCache = { models: null, at: 0 };
1096
- providerModelCaches.providerModelsPromise = null;
1097
- providerModelCaches.providerModelsLoadSeq += 1;
1098
- providerModelCaches.searchProviderModelsCache = { models: null, at: 0 };
1099
- providerUsageCaches.usageDashboardCache = { dashboard: null, at: 0 };
1100
- providerUsageCaches.usageDashboardPromise = null;
1101
- providerUsageCaches.providerSetupCache = { setup: null, at: 0 };
1102
- providerUsageCaches.providerSetupQuickCache = { setup: null, at: 0 };
1103
- providerUsageCaches.providerSetupPromise = null;
1104
- providerInitPromise = null;
1105
- modelMetaByRoute.clear();
1106
- }
1107
-
1108
- // Config reload/save/adopt family + output-style status cache. Extracted to
1109
- // session-runtime/config-lifecycle.mjs; the facade retains ownership of the
1110
- // config/searchRoute/configHasSecrets mutable locals via getter/setter
1111
- // injection (the proven mutable-state pattern).
1112
- const {
1113
- getOutputStyleStatusCached,
1114
- invalidateOutputStyleStatusCache,
1115
- seedOutputStyleStatusCache,
1116
- adoptConfig,
1117
- saveConfigAndAdopt,
1118
- flushConfigSave,
1119
- flushBackendSave,
1120
- scheduleBackendSave,
1121
- flushOutputStyleSave,
1122
- scheduleOutputStyleSave,
1123
- reloadFullConfig,
1124
- ensureFullConfig,
1125
- displayConfig,
1126
- ensureConfigForRouteProvider,
1127
- } = createConfigLifecycle({
1128
- getConfig: () => config,
1129
- setConfig: (next) => { config = next; },
1130
- getSearchRoute: () => searchRoute,
1131
- setSearchRoute: (next) => { searchRoute = next; },
1132
- getConfigHasSecrets: () => configHasSecrets,
1133
- setConfigHasSecrets: (next) => { configHasSecrets = next; },
1134
- getRoute: () => route,
1135
- cfgMod,
1136
- sharedCfgMod,
1137
- setBackend,
1138
- setConfiguredShell,
1139
- normalizeSystemShellConfig,
1140
- normalizeSearchRouteConfig,
1141
- outputStyleStatus,
1142
- LAZY_SECRET_PROVIDERS,
1143
- clean,
1144
- resolve,
1145
- STANDALONE_DATA_DIR,
1146
- });
1147
-
1148
- async function ensureProvidersReady(providerConfig = config.providers || {}) {
1149
- if (providerInitPromise) return await providerInitPromise;
1150
- providerInitPromise = reg.initProviders(providerConfig)
1151
- .finally(() => {
1152
- providerInitPromise = null;
1153
- });
1154
- return await providerInitPromise;
1155
- }
1156
-
1157
- const {
1158
- currentMainSearchModelMeta,
1159
- runNativeWebSearch,
1160
- } = createNativeSearch({
1161
- getRoute: () => route,
1162
- getSearchRoute: () => searchRoute,
1163
- setSearchRoute: (next) => { searchRoute = next; },
1164
- getConfig: () => config,
1165
- getSession: () => session,
1166
- getReg: () => reg,
1167
- ensureFullConfig,
1168
- ensureProvidersReady,
1169
- ensureProviderEnabled,
1170
- normalizeSearchProviderId,
1171
- normalizeSearchRouteConfig,
1172
- isDefaultSearchRouteConfig,
1173
- isSearchCapableProvider,
1174
- searchCapableFor,
1175
- });
1176
-
1177
- // Late-bound: createWarmupSchedulers is constructed after this factory, but
1178
- // cachedProviderSetup(quick) may nudge scheduleProviderSetupWarmup on a cold
1179
- // quick-cache fill. Thread it by reference so the scheduler is reachable once
1180
- // it exists (a pre-scheduler quick fill simply skips the warmup nudge).
1181
- let scheduleProviderSetupWarmupRef = () => {};
1182
- const {
1183
- refreshStatuslineUsageSnapshot,
1184
- cachedProviderSetup,
1185
- getUsageDashboard,
1186
- } = createProviderUsage({
1187
- caches: providerUsageCaches,
1188
- getConfig: () => config,
1189
- getReg: () => reg,
1190
- displayConfig,
1191
- providerSetup,
1192
- createUsageDashboard,
1193
- fetchOAuthUsageSnapshot,
1194
- isCloseRequested: () => closeRequested,
1195
- getProviderSetupWarmupTimer: () => warmupTimers.providerSetupWarmupTimer,
1196
- scheduleProviderSetupWarmup: (delayMs) => scheduleProviderSetupWarmupRef(delayMs),
1197
- });
1198
-
1199
- // Holder filled after createQuickModelRows resolves; provider-models and
1200
- // quick-model-rows are mutually dependent (rows need cache-row helpers, the
1201
- // model factory needs quick fallbacks) so we thread the quick surface in by
1202
- // reference after both are constructed.
1203
- const providerModelQuickHelpers = {};
1204
- // Late-bound: createWarmupSchedulers is constructed after this factory, but
1205
- // lookupModelMeta may fire scheduleProviderModelWarmup on a cache miss. Thread
1206
- // it by reference so the scheduler is called once it exists (miss handling is
1207
- // best-effort; a pre-scheduler miss simply skips the warmup nudge).
1208
- let scheduleProviderModelWarmupRef = () => {};
1209
- const {
1210
- modelMetaKey,
1211
- lookupModelMeta,
1212
- sortProviderModels,
1213
- providerModelCacheRow,
1214
- providerModelsFromCacheRows,
1215
- collectSearchProviderModels,
1216
- collectProviderModels,
1217
- warmProviderModelCache,
1218
- } = createProviderModels({
1219
- caches: providerModelCaches,
1220
- modelMetaByRoute,
1221
- getRoute: () => route,
1222
- getConfig: () => config,
1223
- getReg: () => reg,
1224
- searchCapableFor,
1225
- sortProviderModelsRaw,
1226
- providerModelCacheRowRaw,
1227
- normalizeSearchProviderId,
1228
- isSearchCapableProvider,
1229
- ensureFullConfig,
1230
- ensureProvidersReady,
1231
- bootProfile,
1232
- scheduleProviderModelWarmup: () => scheduleProviderModelWarmupRef(),
1233
- quickHelpers: providerModelQuickHelpers,
1234
- });
1235
-
1236
- const {
1237
- quickProviderModelRows,
1238
- addDefaultSearchModel,
1239
- quickSearchProviderModelRows,
1240
- searchModelsFromRows,
1241
- searchRowsWithDefault,
1242
- } = createQuickModelRows({
1243
- getRoute: () => route,
1244
- getSearchRoute: () => searchRoute,
1245
- displayConfig,
1246
- providerModelCacheRow,
1247
- providerModelsFromCacheRows,
1248
- sortProviderModels,
1249
- modelMetaByRoute,
1250
- modelMetaKey,
1251
- normalizeSearchProviderId,
1252
- normalizeSearchRouteConfig,
1253
- isSearchCapableProvider,
1254
- searchCapableFor,
1255
- currentMainSearchModelMeta,
1256
- });
1257
- Object.assign(providerModelQuickHelpers, {
1258
- quickProviderModelRows,
1259
- addDefaultSearchModel,
1260
- quickSearchProviderModelRows,
1261
- searchModelsFromRows,
1262
- searchRowsWithDefault,
1263
- });
1264
-
1265
- async function resolveMissingRouteModelForFirstTurn() {
1266
- if (routeHasModel()) return route;
1267
- const models = await collectProviderModels();
1268
- const picked = models[0] || null;
1269
- if (!picked) {
1270
- throw new Error('No provider models available. Open /providers to sign in, then /model to choose a model.');
1271
- }
1272
- route = {
1273
- ...route,
1274
- provider: picked.provider,
1275
- model: picked.id,
1276
- preset: null,
1277
- };
1278
- return route;
1279
- }
1280
-
1281
- async function refreshRouteEffort(modelMetaOverride = null) {
1282
- await ensureProvidersReady(ensureProviderEnabled(config, route.provider));
1283
- const modelMeta = modelMetaOverride || await lookupModelMeta(route.provider, route.model);
1284
- const requested = hasOwn(route, 'effort') ? route.effort : (route.preset?.effort || null);
1285
- const effectiveEffort = coerceEffortFor(route.provider, modelMeta, requested);
1286
- const fastCapable = fastCapableFor(route.provider, modelMeta);
1287
- // Carry the catalog display name onto the route so the statusline shows a
1288
- // human label (e.g. "Claude Fable 5") for preset-less direct models instead
1289
- // of the raw id. `name` is only trusted when it differs from the raw model
1290
- // id (some providers echo the id as `name`), so it can't clobber a better
1291
- // already-resolved label. Falls back to existing route.modelDisplay, then unset.
1292
- const metaName = clean(modelMeta?.name);
1293
- const modelDisplay = clean(modelMeta?.display) || clean(modelMeta?.displayName)
1294
- || (metaName && metaName !== clean(route.model) ? metaName : '')
1295
- || clean(route.modelDisplay);
1296
- route = {
1297
- ...route,
1298
- fast: fastCapable ? route.fast === true : false,
1299
- fastCapable,
1300
- effectiveEffort,
1301
- effortOptions: effortItemsFor(route.provider, modelMeta, effectiveEffort),
1302
- ...(modelDisplay ? { modelDisplay } : {}),
1303
- };
1304
- return route;
1305
- }
1306
-
1307
- function routeHasModel() {
1308
- return !!clean(route?.model);
1309
- }
1310
-
1311
- function requireModelRoute() {
1312
- if (routeHasModel()) return;
1313
- throw new Error('No model configured. Open /providers to sign in, then /model to choose a model.');
1314
- }
1315
-
1316
- async function recreateCurrentSessionIfReady() {
1317
- if (!routeHasModel()) {
1318
- session = null;
1319
- return null;
1320
- }
1321
- return await createCurrentSession();
1322
- }
1323
-
1324
- async function createCurrentSession(reason = 'demand') {
1325
- if (sessionCreatePromise) return await sessionCreatePromise;
1326
- if (session?.id && !sessionNeedsCwdRefresh) {
1327
- const liveSession = mgr.getSession(session.id);
1328
- if (liveSession && liveSession.closed !== true && liveSession.status !== 'closed') {
1329
- session = liveSession;
1330
- return session;
1331
- }
1332
- session = null;
1333
- }
1334
-
1335
- const startedAt = performance.now();
1336
- bootProfile('session:create:start', { mode, reason });
1337
- const promise = (async () => {
1338
- ensureConfigForRouteProvider();
1339
- await resolveMissingRouteModelForFirstTurn();
1340
- requireModelRoute();
1341
- bootProfile('session:create:route-ready', { ms: (performance.now() - startedAt).toFixed(1) });
1342
- await refreshRouteEffort();
1343
- bootProfile('session:create:effort-ready', { ms: (performance.now() - startedAt).toFixed(1) });
1344
- const providerImpl = reg.getProvider(route.provider);
1345
- if (!providerImpl) {
1346
- throw new Error(`Provider "${route.provider}" is not configured.`);
1347
- }
1348
- bootProfile('session:create:provider-ready', { ms: (performance.now() - startedAt).toFixed(1) });
1349
- const coreMemoryContext = await loadCoreMemoryContext();
1350
- if (closeRequested) throw new Error('runtime is closing');
1351
- const dataDir = cfgMod.getPluginData?.() || STANDALONE_DATA_DIR;
1352
- const workflow = activeWorkflowSummary(config, dataDir);
1353
- const workflowContext = workflowContextBlock(config, dataDir);
1354
- const sessionOpts = {
1355
- provider: route.provider,
1356
- model: route.model,
1357
- preset: route.preset || undefined,
1358
- tools: toolSpecForMode(mode),
1359
- owner: 'cli',
1360
- agent: 'lead',
1361
- lane: 'cli',
1362
- sourceType: 'lead',
1363
- sourceName: 'main',
1364
- clientHostPid: process.pid,
1365
- disallowedTools: LEAD_DISALLOWED_TOOLS,
1366
- cwd: currentCwd,
1367
- coreMemoryContext,
1368
- workflow,
1369
- workflowContext,
1370
- fast: route.fast === true,
1371
- compaction: config.compaction && typeof config.compaction === 'object'
1372
- ? normalizeCompactionConfig(config.compaction, { memoryEnabled: memoryEnabled() })
1373
- : undefined,
1374
- };
1375
- if (hasOwn(route, 'effort') || route.effectiveEffort) {
1376
- sessionOpts.effort = route.effectiveEffort || null;
1377
- }
1378
- session = mgr.createSession(sessionOpts);
1379
- sessionNeedsCwdRefresh = false;
1380
- attachSessionHooks(session, { hooks, hookCommonPayload, getCwd: () => currentCwd });
1381
- applyDeferredToolSurface(session, deferredSurfaceModeForLead(mode), standaloneTools, { provider: route.provider });
1382
- applyPreSessionToolSelection();
1383
- writeStatuslineRoute(statusRoutes, session, route);
1384
- hooks.emit('session:create', { sessionId: session.id, provider: route.provider, model: route.model, toolMode: mode, cwd: currentCwd });
1385
- // SessionStart: bridge to the standard project hook bus. Best-effort;
1386
- // a hook error must never break session creation. additionalContext is
1387
- // injected before the first user turn as a system-reminder context pair.
1388
- try {
1389
- const startSource = /resume/i.test(String(reason || ''))
1390
- ? 'resume'
1391
- : (/clear/i.test(String(reason || '')) ? 'clear' : 'startup');
1392
- const startDispatch = await hooks.dispatch('SessionStart', hookCommonPayload({ session_id: session.id, source: startSource, model: route.model }));
1393
- const startContext = Array.isArray(startDispatch?.additionalContext)
1394
- ? startDispatch.additionalContext.join('\n\n')
1395
- : String(startDispatch?.additionalContext || '');
1396
- if (startContext.trim()) {
1397
- session.messages.push({ role: 'user', content: `<system-reminder>\n# SessionStart Hook Context\n${startContext.trim()}\n</system-reminder>` });
1398
- session.messages.push({ role: 'assistant', content: '.' });
1399
- session.updatedAt = Date.now();
1400
- }
1401
- } catch { /* best-effort: never break session create */ }
1402
- bootProfile('session:create:ready', {
1403
- ms: (performance.now() - startedAt).toFixed(1),
1404
- reason,
1405
- tools: Array.isArray(session.tools) ? session.tools.length : 0,
1406
- catalog: Array.isArray(session.deferredToolCatalog) ? session.deferredToolCatalog.length : 0,
1407
- });
1408
- return session;
1409
- })();
1410
-
1411
- sessionCreatePromise = promise;
1412
- try {
1413
- return await promise;
1414
- } finally {
1415
- if (sessionCreatePromise === promise) sessionCreatePromise = null;
1416
- }
1417
- }
1418
-
1419
- const {
1420
- scheduleProviderWarmup,
1421
- scheduleProviderSetupWarmup,
1422
- scheduleProviderModelWarmup,
1423
- scheduleModelCatalogWarmup,
1424
- scheduleStatuslineUsageWarmup,
1425
- scheduleStatuslineUsageRefresh,
1426
- } = createWarmupSchedulers({
1427
- timers: warmupTimers,
1428
- bootProfile,
1429
- getRoute: () => route,
1430
- getConfig: () => config,
1431
- isCloseRequested: () => closeRequested,
1432
- getActiveTurnCount: () => activeTurnCount,
1433
- getSessionCreatePromise: () => sessionCreatePromise,
1434
- getProviderModelsCache: () => providerModelCaches.providerModelsCache,
1435
- getProviderModelsPromise: () => providerModelCaches.providerModelsPromise,
1436
- reloadFullConfig,
1437
- ensureConfigForRouteProvider,
1438
- ensureProvidersReady,
1439
- ensureProviderEnabled,
1440
- refreshStatuslineUsageSnapshot,
1441
- warmProviderModelCache,
1442
- cachedProviderSetup,
1443
- warmCatalogsInBackground,
1444
- isFirstTurnCompleted: () => firstTurnCompleted,
1445
- envFlag,
1446
- delays: {
1447
- providerWarmupDelayMs,
1448
- providerSetupWarmupDelayMs,
1449
- providerModelWarmupDelayMs,
1450
- modelCatalogWarmupDelayMs,
1451
- statuslineUsageWarmupDelayMs,
1452
- statuslineUsageRefreshDelayMs,
1453
- backgroundBusyRetryMs,
1454
- },
1455
- flags: {
1456
- providerWarmupEnabled,
1457
- modelPrefetchEnabled,
1458
- modelCatalogWarmupEnabled,
1459
- },
1460
- });
1461
- scheduleProviderModelWarmupRef = scheduleProviderModelWarmup;
1462
- scheduleProviderSetupWarmupRef = scheduleProviderSetupWarmup;
1463
-
1464
- const {
1465
- scheduleCodeGraphPrewarm,
1466
- scheduleLeadSessionPrewarm,
1467
- invokeChannelStart,
1468
- scheduleChannelStart,
1469
- } = createPrewarmSchedulers({
1470
- timers: prewarmTimers,
1471
- bootProfile,
1472
- getCurrentCwd: () => currentCwd,
1473
- isCloseRequested: () => closeRequested,
1474
- getActiveTurnCount: () => activeTurnCount,
1475
- getSessionCreatePromise: () => sessionCreatePromise,
1476
- getSession: () => session,
1477
- isRemoteEnabled: () => remoteEnabled,
1478
- channelsEnabled,
1479
- getCodeGraphModule,
1480
- createCurrentSession,
1481
- channels,
1482
- envFlag,
1483
- delays: {
1484
- codeGraphPrewarmDelayMs,
1485
- channelStartDelayMs,
1486
- sessionPrewarmDelayMs,
1487
- backgroundBusyRetryMs,
1488
- },
1489
- flags: {
1490
- codeGraphPrewarmEnabled,
1491
- sessionPrewarmEnabled,
1492
- },
1493
- state: prewarmState,
1494
- });
1495
-
1496
- // Eagerly create/refresh the remote transcript writer for the CURRENT
1497
- // session + cwd, publish the session record, and ensure the transcript
1498
- // file exists on disk. Called from startRemote() (so the channel worker's
1499
- // activate-time discovery finds THIS session immediately instead of
1500
- // waiting for the first turn) and from ask() at turn start. Returns true
1501
- // when a writer is bound.
1502
- function ensureRemoteTranscriptWriter() {
1503
- if (!remoteEnabled || !session?.id) return false;
1504
- const twKey = `${session.id}\u0000${currentCwd}`;
1505
- if (_twKey !== twKey) {
1506
- try {
1507
- _transcriptWriter = createTranscriptWriter({
1508
- mixdogHome: mixdogHome(),
1509
- sessionId: session.id,
1510
- cwd: currentCwd,
1511
- pid: process.pid,
1512
- });
1513
- _transcriptWriter.writeSessionRecord();
1514
- _twKey = twKey;
1515
- } catch (error) {
1516
- process.stderr.write(`mixdog: transcript-writer: init failed: ${error?.message || error}\n`);
1517
- _transcriptWriter = null;
1518
- _twKey = '';
1519
- return false;
1520
- }
1521
- } else {
1522
- // Same binding — refresh updatedAt so worker-side discovery keeps
1523
- // ranking this session as the live parent-chain candidate.
1524
- try { _transcriptWriter?.writeSessionRecord(); } catch {}
1525
- }
1526
- try { _transcriptWriter?.ensureTranscriptFile(); }
1527
- catch (error) { process.stderr.write(`mixdog: transcript-writer: ensureTranscriptFile failed: ${error?.message || error}\n`); }
1528
- return _transcriptWriter != null;
1529
- }
1530
-
1531
- // Remote (Discord channel) mode is opt-in per session. Only a session that
1532
- // explicitly enables remote — via `mixdog --remote` or the runtime toggle —
1533
- // boots the channel worker and contends for channel ownership.
1534
- // startRemote() is FORCE-TAKEOVER: it always (re)claims the bridge seat and
1535
- // rebinds output forwarding to this session, even when the worker is
1536
- // already running (e.g. `/remote` re-issued after another session took the
1537
- // seat, or to re-pin forwarding onto the current transcript).
1538
- function startRemote() {
1539
- remoteEnabled = true;
1540
- // Boot the memory daemon eagerly. The channels worker forwards
1541
- // transcript ingests/entries to the memory HTTP service, whose port is
1542
- // published to active-instance.json by getMemoryModule().init(). Without
1543
- // this, memory only starts on the first turn's getMemoryModule() call —
1544
- // so early channel traffic finds no memory_port and gets buffered (or,
1545
- // pre-drainer, silently dropped). Runs BEFORE channel claim so the port is
1546
- // racing to be live by the time the worker sends its first ingest.
1547
- //
1548
- // Not fire-and-forget: init() only resolves the module handle, so a bare
1549
- // getMemoryModule() could return before /health reports ok — leaving early
1550
- // ingests to hit a not-yet-listening port. Await the proxy start() and then
1551
- // poll /health with a bounded retry so the daemon is provably reachable
1552
- // (or logged failed) rather than assumed-up. Still non-blocking to the
1553
- // caller: the whole probe is detached, but it internally awaits readiness.
1554
- void (async () => {
1555
- try {
1556
- // Yield one event-loop tick before the heavy chain below (module
1557
- // resolve, daemon fork/health-poll) starts, so Ink's next render
1558
- // (scheduled via setImmediate/timers) and any queued keypress
1559
- // events get a turn first instead of being starved by this
1560
- // detached chain's synchronous setup work.
1561
- await new Promise((r) => setImmediate(r));
1562
- const mod = await getMemoryModule();
1563
- const started = typeof mod?.start === 'function' ? await mod.start() : null;
1564
- const port = started?.port;
1565
- if (!port) { bootProfile('channels:memory-eager-init-failed', { error: 'no port from start()' }); return; }
1566
- for (let i = 0; i < 30; i++) {
1567
- try {
1568
- const ok = await new Promise((res) => {
1569
- const req = httpMod.request({ hostname: '127.0.0.1', port, path: '/health', timeout: 1500 }, (r) => {
1570
- let d = ''; r.on('data', (c) => { d += c; }); r.on('end', () => {
1571
- try { res(JSON.parse(d)?.status === 'ok'); } catch { res(false); }
1572
- });
1573
- });
1574
- req.on('error', () => res(false));
1575
- req.on('timeout', () => { req.destroy(); res(false); });
1576
- req.end();
1577
- });
1578
- if (ok) { bootProfile('channels:memory-eager-init-ready', { port }); return; }
1579
- } catch {}
1580
- await new Promise((r) => setTimeout(r, 500));
1581
- }
1582
- bootProfile('channels:memory-eager-init-failed', { error: `health not ok after retries (port ${port})` });
1583
- } catch (error) {
1584
- bootProfile('channels:memory-eager-init-failed', { error: error?.message || String(error) });
1585
- }
1586
- })();
1587
- // Publish this session's record + transcript file BEFORE the worker's
1588
- // activate-time discovery polls, so output forwarding binds to this
1589
- // terminal session immediately instead of waiting for the first turn.
1590
- // No-op when the session has not been created yet (lazy mode); that
1591
- // case is covered by the turn-start rebind in ask().
1592
- ensureRemoteTranscriptWriter();
1593
- // A backend switch may still be sitting in its debounce window; flush it
1594
- // so the channel worker boots against the backend the user just chose,
1595
- // not the previous on-disk value.
1596
- try { flushBackendSave(); } catch {}
1597
- if (envFlag('MIXDOG_DISABLE_CHANNEL_START')) {
1598
- bootProfile('channels:start-skipped');
1599
- return true;
1600
- }
1601
- if (!channelsEnabled()) {
1602
- bootProfile('channels:start-disabled');
1603
- return true;
1604
- }
1605
- if (closeRequested) return true;
1606
- if (prewarmTimers.channelStartTimer) {
1607
- clearTimeout(prewarmTimers.channelStartTimer);
1608
- prewarmTimers.channelStartTimer = null;
1609
- }
1610
- bootProfile('channels:start-scheduled', { delayMs: 0, immediate: true });
1611
- void (async () => {
1612
- // Yield before the createCurrentSession/transcript/fork chain below —
1613
- // same rationale as the memory-eager-init yield above: this detached
1614
- // chain runs synchronous config/fs work (createCurrentSession, backend
1615
- // flush, transcript writer) back-to-back, and without a tick break it
1616
- // can run ahead of Ink's queued render/input handling.
1617
- await new Promise((r) => setImmediate(r));
1618
- // Immediate-occupancy guarantee: make sure a session + transcript
1619
- // exist BEFORE the worker boots — a freshly-forked worker claims and
1620
- // runs transcript discovery inside its own start(), so publishing the
1621
- // session record/file first lets that very first discovery pass bind
1622
- // output forwarding to THIS terminal instead of a persisted/stale
1623
- // neighbour. Lazy mode means the session may not exist yet at /remote
1624
- // time; create it here (idempotent — reuses a live session, joins an
1625
- // in-flight create). On create failure we still claim: that matches
1626
- // the pre-eager behavior (bind resolves on the first turn's rebind).
1627
- try { await createCurrentSession('remote-start'); }
1628
- catch (error) { bootProfile('channels:remote-session-create-failed', { error: error?.message || String(error) }); }
1629
- ensureRemoteTranscriptWriter();
1630
- // Re-check after the awaits above: stopRemote()/superseded or runtime
1631
- // close may have landed mid-chain — do not boot/claim for a session
1632
- // that already turned remote off.
1633
- if (!remoteEnabled || closeRequested) return;
1634
- await invokeChannelStart();
1635
- if (!remoteEnabled || closeRequested) return;
1636
- // Unconditional claim + forwarder rebind. A freshly-forked worker
1637
- // already claims in its own start(), so this is idempotent there; the
1638
- // already-running case is where it matters (last-wins seat overwrite +
1639
- // transcript rebind onto this session).
1640
- await channels.execute('activate_channel_bridge', { active: true });
1641
- })().catch((error) => bootProfile('channels:claim-failed', { error: error?.message || String(error) }));
1642
- return true;
1643
- }
1644
-
1645
- function stopRemote(reason) {
1646
- remoteEnabled = false;
1647
- // Cancel any pending deferred start so it can't fire after remote is off.
1648
- if (prewarmTimers.channelStartTimer) { clearTimeout(prewarmTimers.channelStartTimer); prewarmTimers.channelStartTimer = null; }
1649
- channels.stop(reason || 'remote-disabled', { waitForExit: false }).catch(() => {});
1650
- return true;
1651
- }
1652
-
1653
- function isRemoteEnabled() {
1654
- return remoteEnabled;
1655
- }
1656
-
1657
- function withTeardownDeadline(promise, ms, fallback = false) {
1658
- let timer = null;
1659
- return Promise.race([
1660
- Promise.resolve(promise),
1661
- new Promise((resolve) => {
1662
- timer = setTimeout(() => resolve(fallback), ms);
1663
- }),
1664
- ]).finally(() => {
1665
- if (timer) clearTimeout(timer);
1666
- });
1667
- }
1668
-
1669
- bootProfile('session-runtime:ready', {
1670
- lazySession: true,
1671
- prewarmSession: sessionPrewarmEnabled,
1672
- providerWarmup: providerWarmupEnabled,
1673
- codeGraphPrewarm: codeGraphPrewarmEnabled,
1674
- });
1675
- scheduleLeadSessionPrewarm();
1676
- // Lazy mode (default): skip the startup prewarm entirely; the first turn
1677
- // triggers it instead (see ask()). Eager mode keeps the old startup schedule.
1678
- if (!codeGraphPrewarmLazy) {
1679
- scheduleCodeGraphPrewarm(codeGraphPrewarmDelayMs, 'startup');
1680
- } else {
1681
- bootProfile('code-graph:prewarm-lazy', { reason: 'startup-deferred-to-first-turn' });
1682
- }
1683
- scheduleProviderSetupWarmup();
1684
- scheduleModelCatalogWarmup();
1685
- scheduleProviderWarmup();
1686
- // Warm the provider model catalog in the background, but keep it on its own
1687
- // delay so short-lived detached runtimes can exit before /models I/O starts.
1688
- // Operators that want earlier catalog warming can lower
1689
- // MIXDOG_PROVIDER_MODEL_WARMUP_DELAY_MS explicitly.
1690
- scheduleProviderModelWarmup();
1691
- scheduleStatuslineUsageWarmup();
1692
- // Channels are opt-in: only boot the worker when this session started in (or
1693
- // was toggled into) remote mode. Non-remote sessions never contend for the
1694
- // channel; see startRemote()/stopRemote() and the `/remote` toggle.
1695
- // `remote.autoStart` in mixdog-config.json makes every session claim remote
1696
- // at boot (same force-takeover semantics as `mixdog --remote` / `/remote`).
1697
- // The flag lives in the TOP-LEVEL `remote` section of mixdog-config.json
1698
- // (sibling of agent/ui/channels), not inside the agent section that
1699
- // cfgMod.loadConfig returns — read it via the shared whole-file reader.
1700
- // `config?.remote?.autoStart` is kept for back-compat with agent-section
1701
- // placement.
1702
- if (!remoteEnabled) {
1703
- try {
1704
- if (config?.remote?.autoStart === true
1705
- || sharedCfgMod?.readSection?.('remote')?.autoStart === true) {
1706
- remoteEnabled = true;
1707
- }
1708
- } catch { /* unreadable config never blocks boot */ }
1709
- }
1710
- // Boot-time remote start (autoStart or --remote) is DEFERRED past the TUI's
1711
- // first frame. startRemote() front-loads heavy work — memory daemon fork
1712
- // (PG + forced ONNX embed warmup in the child), eager session create, and
1713
- // the channel-worker fork — and running it inline here interleaves that
1714
- // CPU/disk load with engine boot, visibly delaying the first ink frame by
1715
- // seconds. The deferred timer reuses prewarmTimers.channelStartTimer so an
1716
- // early /remote (startRemote clears it), stopRemote(), and close() all
1717
- // cancel it through the existing clearTimeout paths. Runtime /remote calls
1718
- // still start immediately (user-initiated, UI already painted).
1719
- if (remoteEnabled) {
1720
- const remoteAutoStartDelayMs = envDelayMs('MIXDOG_REMOTE_AUTOSTART_DELAY_MS', 1_500, { min: 0, max: 60_000 });
1721
- bootProfile('channels:autostart-deferred', { delayMs: remoteAutoStartDelayMs });
1722
- prewarmTimers.channelStartTimer = setTimeout(() => {
1723
- prewarmTimers.channelStartTimer = null;
1724
- if (closeRequested || !remoteEnabled) return;
1725
- startRemote();
1726
- }, remoteAutoStartDelayMs);
1727
- prewarmTimers.channelStartTimer.unref?.();
1728
- }
1729
-
1730
- function contextStatusCacheKeyFor({ messages, tools }) {
1731
- const compaction = session?.compaction || {};
1732
- const lastMessage = messages[messages.length - 1] || null;
1733
- return {
1734
- session,
1735
- sessionId: session?.id || null,
1736
- provider: route.provider,
1737
- model: route.model,
1738
- cwd: currentCwd,
1739
- mode,
1740
- messages,
1741
- messageCount: messages.length,
1742
- lastMessage,
1743
- lastMessageRole: lastMessage?.role || null,
1744
- lastMessageContent: lastMessage?.content || null,
1745
- tools,
1746
- toolCount: tools.length,
1747
- contextWindow: session?.contextWindow || null,
1748
- rawContextWindow: session?.rawContextWindow || null,
1749
- effectiveContextWindowPercent: session?.effectiveContextWindowPercent || null,
1750
- autoCompactTokenLimit: Number(session?.autoCompactTokenLimit || 0),
1751
- lastContextTokens: Number(session?.lastContextTokens || 0),
1752
- lastContextTokensUpdatedAt: Number(session?.lastContextTokensUpdatedAt || 0),
1753
- lastContextTokensStaleAfterCompact: session?.lastContextTokensStaleAfterCompact === true,
1754
- lastInputTokens: Number(session?.lastInputTokens || 0),
1755
- lastUncachedInputTokens: Number(session?.lastUncachedInputTokens || 0),
1756
- lastOutputTokens: Number(session?.lastOutputTokens || 0),
1757
- lastCachedReadTokens: Number(session?.lastCachedReadTokens || 0),
1758
- lastCacheWriteTokens: Number(session?.lastCacheWriteTokens || 0),
1759
- totalInputTokens: Number(session?.totalInputTokens || 0),
1760
- totalUncachedInputTokens: Number(session?.totalUncachedInputTokens || 0),
1761
- totalOutputTokens: Number(session?.totalOutputTokens || 0),
1762
- totalCachedReadTokens: Number(session?.totalCachedReadTokens || 0),
1763
- totalCacheWriteTokens: Number(session?.totalCacheWriteTokens || 0),
1764
- compactBoundaryTokens: Number(session?.compactBoundaryTokens || 0),
1765
- compactionBoundaryTokens: Number(compaction.boundaryTokens || 0),
1766
- compactionTriggerTokens: Number(compaction.triggerTokens || 0),
1767
- compactionLastChangedAt: Number(compaction.lastChangedAt || 0),
1768
- compactionLastCompactAt: Number(compaction.lastCompactAt || 0),
1769
- };
1770
- }
1771
-
1772
- function sameContextStatusCacheKey(a, b) {
1773
- if (!a || !b) return false;
1774
- for (const key of Object.keys(a)) {
1775
- if (!Object.is(a[key], b[key])) return false;
1776
- }
1777
- return true;
1778
- }
1779
-
1780
- // Pure settings-delegate methods (onboarding status/skip, autoClear, profile,
1781
- // compaction, recap/memory, channels, systemShell, update settings, channel
1782
- // token save/forget, setBackend). Extracted to session-runtime/settings-api.mjs
1783
- // and SPREAD into the API object below so the external surface is unchanged.
1784
- const settingsApi = createSettingsApi({
1785
- getConfig: () => config,
1786
- getRoute: () => route,
1787
- getSession: () => session,
1788
- getRemoteEnabled: () => remoteEnabled,
1789
- adoptConfig,
1790
- saveConfigAndAdopt,
1791
- scheduleBackendSave,
1792
- cfgMod,
1793
- hasOwn,
1794
- normalizeAutoClearConfig,
1795
- autoClearIdleMsForProvider,
1796
- autoClearProviderDefaults,
1797
- normalizeCompactionConfig,
1798
- normalizeCompactTypeSetting,
1799
- normalizeSystemShellConfig,
1800
- normalizeSystemShellCommand,
1801
- setConfiguredShell,
1802
- setRecapEnabledInConfig,
1803
- setModuleEnabledInConfig,
1804
- summarizeWorkflowRoutes,
1805
- parseDurationMs,
1806
- formatDurationMs,
1807
- localPackageVersion,
1808
- memoryEnabled,
1809
- recapEnabledFn,
1810
- channelsEnabled,
1811
- autoUpdateEnabled,
1812
- getUpdateCheckState: () => updateCheckState,
1813
- getUpdateProcessState: () => updateProcessState,
1814
- invalidateContextStatusCache: (...a) => invalidateContextStatusCache(...a),
1815
- invalidatePreSessionToolSurface: (...a) => invalidatePreSessionToolSurface(...a),
1816
- scheduleChannelStart: (...a) => scheduleChannelStart(...a),
1817
- channels,
1818
- clearChannelStartTimer: () => {
1819
- if (prewarmTimers.channelStartTimer) {
1820
- clearTimeout(prewarmTimers.channelStartTimer);
1821
- prewarmTimers.channelStartTimer = null;
1822
- }
1823
- },
1824
- checkForUpdateInternal: (...a) => checkForUpdateInternal(...a),
1825
- runUpdateNowInternal: (...a) => runUpdateNowInternal(...a),
1826
- reloadChannelsSoon: (...a) => reloadChannelsSoon(...a),
1827
- ONBOARDING_VERSION,
1828
- saveDiscordToken,
1829
- forgetDiscordToken,
1830
- saveTelegramToken,
1831
- forgetTelegramToken,
1832
- saveWebhookAuthtoken,
1833
- forgetWebhookAuthtoken,
1834
- setBackend,
1835
- });
1836
-
1837
- return {
1838
- ...settingsApi,
1839
- get id() {
1840
- return session?.id || null;
1841
- },
1842
- get provider() {
1843
- return route.provider;
1844
- },
1845
- get model() {
1846
- return route.model;
1847
- },
1848
- get effort() {
1849
- return route.effectiveEffort || route.effort || route.preset?.effort || null;
1850
- },
1851
- get fast() {
1852
- return route.fast === true;
1853
- },
1854
- get fastCapable() {
1855
- return route.fastCapable === true;
1856
- },
1857
- get effortOptions() {
1858
- return route.effortOptions || [];
1859
- },
1860
- get contextWindow() {
1861
- return session?.contextWindow || null;
1862
- },
1863
- get rawContextWindow() {
1864
- return session?.rawContextWindow || session?.contextWindow || null;
1865
- },
1866
- get effectiveContextWindowPercent() {
1867
- return session?.effectiveContextWindowPercent || null;
1868
- },
1869
- get toolMode() {
1870
- return mode;
1871
- },
1872
- get autoClear() {
1873
- return this.getAutoClear();
1874
- },
1875
- get systemShell() {
1876
- return normalizeSystemShellConfig(config.shell);
1877
- },
1878
- get searchRoute() {
1879
- searchRoute = normalizeSearchRouteConfig(config.searchRoute) || normalizeSearchRouteConfig(searchRoute);
1880
- return searchRoute;
1881
- },
1882
- get workflow() {
1883
- const dataDir = cfgMod.getPluginData?.() || STANDALONE_DATA_DIR;
1884
- const active = activeWorkflowSummary(config, dataDir);
1885
- if (session?.workflow && typeof session.workflow === 'object') {
1886
- const current = workflowSummary(session.workflow);
1887
- return current?.id && active?.id && current.id !== active.id
1888
- ? { ...active, currentSession: current, appliedToCurrentSession: false }
1889
- : active;
1890
- }
1891
- return active;
1892
- },
1893
- get outputStyle() {
1894
- return getOutputStyleStatusCached().current;
1895
- },
1896
- get cwd() {
1897
- return currentCwd;
1898
- },
1899
- get session() {
1900
- return session;
1901
- },
1902
- contextStatus() {
1903
- // Prefer the in-flight working transcript while a turn is running so the
1904
- // context gauge reflects LIVE growth (user turn + tool calls/results) as
1905
- // it accumulates, instead of freezing at the pre-turn committed snapshot.
1906
- // askSession() sets session.liveTurnMessages for the turn duration and
1907
- // clears it on commit/cancel/error, after which we fall back to the
1908
- // authoritative committed transcript.
1909
- const liveTurnMessages = Array.isArray(session?.liveTurnMessages) ? session.liveTurnMessages : null;
1910
- const messages = liveTurnMessages || (Array.isArray(session?.messages) ? session.messages : []);
1911
- const tools = Array.isArray(session?.tools) ? session.tools : [];
1912
- const cacheKey = contextStatusCacheKeyFor({ messages, tools });
1913
- if (contextStatusCacheValue && sameContextStatusCacheKey(cacheKey, contextStatusCacheKey)) {
1914
- return contextStatusCacheValue;
1915
- }
1916
-
1917
- const messageSummary = summarizeContextMessages(messages);
1918
- const toolSchemaTokens = estimateToolSchemaTokens(tools);
1919
- const toolSchemaBreakdown = estimateToolSchemaBreakdown(tools);
1920
- const requestReserveTokens = estimateRequestReserveTokens(tools);
1921
- const requestOverheadTokens = Math.max(0, requestReserveTokens - toolSchemaTokens);
1922
- const rawWindow = Number(session?.rawContextWindow || session?.contextWindow || 0);
1923
- const effectiveWindow = Number(session?.contextWindow || rawWindow || 0);
1924
- const lastContextTokens = Number(session?.lastContextTokens || 0);
1925
- const estimatedContextTokens = estimateTranscriptContextUsage(messages, tools, {
1926
- messageCount: messageSummary.count,
1927
- });
1928
- const compactAt = Number(session?.compaction?.lastChangedAt || session?.compaction?.lastCompactAt || 0);
1929
- const usageAt = Number(session?.lastContextTokensUpdatedAt || 0);
1930
- const lastUsageStale = !!lastContextTokens && (
1931
- session?.lastContextTokensStaleAfterCompact === true
1932
- || (compactAt > 0 && usageAt > 0 && usageAt <= compactAt)
1933
- || (compactAt > 0 && usageAt <= 0)
1934
- );
1935
- const compactBoundaryTokens = Number(session?.compactBoundaryTokens || session?.compaction?.boundaryTokens || 0);
1936
- const displayWindow = compactBoundaryTokens || effectiveWindow;
1937
- // The transcript estimate is the single source of truth for the displayed
1938
- // context footprint. Provider-reported input_tokens (lastContextTokens)
1939
- // swing non-monotonically and are not window-bounded on some providers
1940
- // (e.g. OpenAI gpt-5.5 Responses API), so they are kept only as secondary
1941
- // metadata (lastApiRequestTokens / usage.lastContextTokens) and never feed
1942
- // the gauge numerator.
1943
- const usedTokens = estimatedContextTokens;
1944
- const freeTokens = displayWindow ? Math.max(0, displayWindow - usedTokens) : 0;
1945
- // Use the same shared compact-policy math as manager/loop. Do not trust
1946
- // persisted trigger telemetry as an independent policy input: it is an
1947
- // output snapshot and was the source of repeated /context false positives.
1948
- const compactTriggerTokens = resolveCompactTriggerTokens(session || {}, compactBoundaryTokens) || 0;
1949
- const compactBufferTokens = compactBoundaryTokens
1950
- ? Math.max(0, compactBoundaryTokens - compactTriggerTokens)
1951
- : resolveCompactBufferTokens(compactBoundaryTokens, session?.compaction || {});
1952
- const value = {
1953
- sessionId: session?.id || null,
1954
- provider: route.provider,
1955
- model: route.model,
1956
- cwd: currentCwd,
1957
- toolMode: mode,
1958
- contextWindow: displayWindow || effectiveWindow || null,
1959
- effectiveContextWindow: effectiveWindow || null,
1960
- rawContextWindow: rawWindow || null,
1961
- effectiveContextWindowPercent: session?.effectiveContextWindowPercent || null,
1962
- usedTokens,
1963
- usedSource: 'estimated',
1964
- currentEstimatedTokens: estimatedContextTokens,
1965
- lastApiRequestTokens: lastContextTokens || 0,
1966
- lastApiRequestStale: lastUsageStale,
1967
- freeTokens,
1968
- compaction: {
1969
- ...(session?.compaction || {}),
1970
- boundaryTokens: compactBoundaryTokens || null,
1971
- triggerTokens: compactTriggerTokens || null,
1972
- bufferTokens: compactBufferTokens || null,
1973
- currentEstimatedTokens: estimatedContextTokens,
1974
- lastApiRequestTokens: lastContextTokens || 0,
1975
- lastApiRequestStale: lastUsageStale,
1976
- },
1977
- messages: messageSummary,
1978
- request: {
1979
- toolSchemaTokens,
1980
- toolSchemaBreakdown,
1981
- requestOverheadTokens,
1982
- reserveTokens: requestReserveTokens,
1983
- },
1984
- usage: {
1985
- lastInputTokens: Number(session?.lastInputTokens || 0),
1986
- lastUncachedInputTokens: Number(session?.lastUncachedInputTokens || 0),
1987
- lastOutputTokens: Number(session?.lastOutputTokens || 0),
1988
- lastCachedReadTokens: Number(session?.lastCachedReadTokens || 0),
1989
- lastCacheWriteTokens: Number(session?.lastCacheWriteTokens || 0),
1990
- lastContextTokens,
1991
- totalInputTokens: Number(session?.totalInputTokens || 0),
1992
- totalUncachedInputTokens: Number(session?.totalUncachedInputTokens || 0),
1993
- totalOutputTokens: Number(session?.totalOutputTokens || 0),
1994
- totalCachedReadTokens: Number(session?.totalCachedReadTokens || 0),
1995
- totalCacheWriteTokens: Number(session?.totalCacheWriteTokens || 0),
1996
- },
1997
- };
1998
- contextStatusCacheKey = cacheKey;
1999
- contextStatusCacheValue = value;
2000
- return value;
2001
- },
2002
- listProviders() {
2003
- return renderProviderStatus(displayConfig());
2004
- },
2005
- async getProviderSetup() {
2006
- return await cachedProviderSetup();
2007
- },
2008
- async getUsageDashboard(options = {}) {
2009
- return await getUsageDashboard(options);
2010
- },
2011
- async completeOnboarding(payload = {}) {
2012
- // Only fall back to the live runtime route when the caller actually sent a
2013
- // defaultRoute. The onboarding "partial save" path (Main left unset, only
2014
- // Search/agent picks) omits defaultRoute entirely and must NOT persist the
2015
- // current route as Main or recreate the session.
2016
- const defaultRoute = hasOwn(payload, 'defaultRoute')
2017
- ? normalizeWorkflowRoute(payload.defaultRoute, route)
2018
- : null;
2019
- const workflowInput = payload.workflowRoutes && typeof payload.workflowRoutes === 'object'
2020
- ? payload.workflowRoutes
2021
- : {};
2022
- const nextConfig = { ...config };
2023
- if (hasOwn(payload, 'defaultProvider')) {
2024
- const requested = clean(payload.defaultProvider);
2025
- if (requested) {
2026
- if (!isKnownProvider(requested)) throw new Error(`unknown provider "${payload.defaultProvider}"`);
2027
- nextConfig.defaultProvider = requested;
2028
- }
2029
- }
2030
- let presets = Array.isArray(nextConfig.presets) ? nextConfig.presets.slice() : [];
2031
- const workflowRoutes = { ...(nextConfig.workflowRoutes || {}) };
2032
- // Track slots actually written THIS call so maintenance mirroring never
2033
- // clobbers an existing slot the payload did not touch.
2034
- const touchedWorkflowSlots = new Set();
2035
-
2036
- if (defaultRoute) {
2037
- presets = upsertWorkflowPreset(presets, 'lead', defaultRoute);
2038
- workflowRoutes.lead = defaultRoute;
2039
- nextConfig.default = workflowPresetId('lead');
2040
- }
2041
-
2042
- for (const slot of WORKFLOW_ROUTE_SLOTS) {
2043
- const normalized = normalizeWorkflowRoute(workflowInput[slot]);
2044
- if (!normalized) continue;
2045
- workflowRoutes[slot] = normalized;
2046
- presets = upsertWorkflowPreset(presets, slot, normalized);
2047
- touchedWorkflowSlots.add(slot);
2048
- }
2049
-
2050
- nextConfig.presets = presets;
2051
- nextConfig.workflowRoutes = workflowRoutes;
2052
- // Maintenance slots store a direct {provider, model} route. Only mirror a
2053
- // slot that was actually written this call (touchedWorkflowSlots); an
2054
- // untouched slot keeps its existing maintenance value.
2055
- nextConfig.maintenance = {
2056
- ...(nextConfig.maintenance || {}),
2057
- ...(touchedWorkflowSlots.has('explorer') ? { explore: normalizeWorkflowRoute(workflowRoutes.explorer) } : {}),
2058
- ...(touchedWorkflowSlots.has('memory') ? { memory: normalizeWorkflowRoute(workflowRoutes.memory) } : {}),
2059
- };
2060
- // Per-agent onboarding routes (id → route) for the full FIXED_AGENT_SLOTS
2061
- // roster. Mirrors setAgentRoute persistence: config.agents[id], an
2062
- // agent-<id> preset, and (for workflow-backed agents) the workflowRoute +
2063
- // maintenance slot. Agents omitted from the payload inherit defaultRoute.
2064
- const agentInput = payload.agentRoutes && typeof payload.agentRoutes === 'object'
2065
- ? payload.agentRoutes
2066
- : null;
2067
- if (agentInput) {
2068
- const nextAgents = { ...(nextConfig.agents || {}) };
2069
- const nextMaintenance = { ...(nextConfig.maintenance || {}) };
2070
- for (const agent of FIXED_AGENT_SLOTS) {
2071
- // Persist ONLY agents with an explicit override in the payload. An
2072
- // omitted agent is left untouched (existing value preserved, or
2073
- // unwritten so the runtime dynamically follows the Main Model). Never
2074
- // fall back to defaultRoute here — that would overwrite an agent the
2075
- // user did not choose.
2076
- const routeToSave = normalizeWorkflowRoute(agentInput[agent.id]);
2077
- if (!routeToSave) continue;
2078
- nextAgents[agent.id] = routeToSave;
2079
- presets = upsertWorkflowPreset(presets, agentPresetSlot(agent.id), routeToSave);
2080
- if (agent.workflowSlot) {
2081
- workflowRoutes[agent.workflowSlot] = routeToSave;
2082
- presets = upsertWorkflowPreset(presets, agent.workflowSlot, routeToSave);
2083
- if (agent.id === 'explore') nextMaintenance.explore = routeToSave;
2084
- if (agent.id === 'maintainer') nextMaintenance.memory = routeToSave;
2085
- }
2086
- }
2087
- nextConfig.agents = nextAgents;
2088
- nextConfig.presets = presets;
2089
- nextConfig.workflowRoutes = workflowRoutes;
2090
- nextConfig.maintenance = nextMaintenance;
2091
- }
2092
- nextConfig.onboarding = {
2093
- ...(nextConfig.onboarding || {}),
2094
- completed: true,
2095
- version: ONBOARDING_VERSION,
2096
- completedAt: new Date().toISOString(),
2097
- };
2098
-
2099
- // Optional native web-search route. Only persisted when provided; mirrors
2100
- // setSearchRoute's config write (skip provider capability validation here
2101
- // since onboarding routes come from the vetted provider model list).
2102
- if (payload.searchRoute) {
2103
- const searchToSave = normalizeSearchRouteConfig(payload.searchRoute);
2104
- if (searchToSave) nextConfig.searchRoute = searchToSave;
2105
- }
2106
-
2107
- saveConfigAndAdopt(nextConfig);
2108
- if (defaultRoute) {
2109
- route = resolveRoute(config, { provider: defaultRoute.provider, model: defaultRoute.model, effort: defaultRoute.effort });
2110
- if (session?.id) mgr.closeSession(session.id, 'cli-onboarding-complete');
2111
- await recreateCurrentSessionIfReady();
2112
- }
2113
- return this.getOnboardingStatus();
2114
- },
2115
- getChannelSetup() {
2116
- // Flush a pending debounced backend switch first so setup readers
2117
- // (Settings → Channel Setting, remote toggles) never observe the
2118
- // previous backend during the 150ms debounce window.
2119
- try { flushBackendSave(); } catch {}
2120
- return channelSetup();
2121
- },
2122
- getChannelWorkerStatus() {
2123
- return channels.status();
2124
- },
2125
- startRemote() {
2126
- return startRemote();
2127
- },
2128
- stopRemote(reason) {
2129
- return stopRemote(reason);
2130
- },
2131
- isRemoteEnabled() {
2132
- return isRemoteEnabled();
2133
- },
2134
- // Subscribe to non-user-initiated remote flips (seat superseded). Returns
2135
- // an unsubscribe function. TUI uses this to sync its Remote indicator and
2136
- // show a "remote taken over" notice.
2137
- onRemoteStateChange(listener) {
2138
- if (typeof listener !== 'function') return () => {};
2139
- remoteStateListeners.add(listener);
2140
- return () => remoteStateListeners.delete(listener);
2141
- },
2142
- setChannel(entry) {
2143
- const result = setChannel(entry);
2144
- reloadChannelsSoon();
2145
- return result;
2146
- },
2147
- setWebhookConfig(patch) {
2148
- const result = setWebhookConfig(patch);
2149
- reloadChannelsSoon();
2150
- return result;
2151
- },
2152
- saveSchedule(entry) {
2153
- const result = saveSchedule(entry);
2154
- reloadChannelsSoon();
2155
- return result;
2156
- },
2157
- deleteSchedule(name) {
2158
- const result = deleteSchedule(name);
2159
- reloadChannelsSoon();
2160
- return result;
2161
- },
2162
- setScheduleEnabled(name, enabled) {
2163
- const result = setScheduleEnabled(name, enabled);
2164
- reloadChannelsSoon();
2165
- return result;
2166
- },
2167
- saveWebhook(entry) {
2168
- const result = saveWebhook(entry);
2169
- reloadChannelsSoon();
2170
- return result;
2171
- },
2172
- deleteWebhook(name) {
2173
- const result = deleteWebhook(name);
2174
- reloadChannelsSoon();
2175
- return result;
2176
- },
2177
- setWebhookEnabled(name, enabled) {
2178
- const result = setWebhookEnabled(name, enabled);
2179
- reloadChannelsSoon();
2180
- return result;
2181
- },
2182
- async authenticateProvider(providerId, secret) {
2183
- const result = String(secret || '').trim()
2184
- ? saveProviderApiKey(cfgMod, providerId, secret)
2185
- : await loginOAuthProvider(cfgMod, providerId);
2186
- reloadFullConfig();
2187
- invalidateProviderCaches();
2188
- warmProviderModelCache();
2189
- return result;
2190
- },
2191
- async loginOAuthProvider(providerId) {
2192
- const result = await loginOAuthProvider(cfgMod, providerId);
2193
- reloadFullConfig();
2194
- invalidateProviderCaches();
2195
- warmProviderModelCache();
2196
- return result;
2197
- },
2198
- async beginOAuthProviderLogin(providerId) {
2199
- const result = await beginOAuthProviderLogin(cfgMod, providerId);
2200
- reloadFullConfig();
2201
- return {
2202
- ...result,
2203
- waitForCallback: result.waitForCallback?.then((completed) => {
2204
- reloadFullConfig();
2205
- if (completed) {
2206
- invalidateProviderCaches();
2207
- warmProviderModelCache();
2208
- }
2209
- return completed;
2210
- }),
2211
- completeCode: async (code) => {
2212
- const completed = await result.completeCode(code);
2213
- reloadFullConfig();
2214
- invalidateProviderCaches();
2215
- warmProviderModelCache();
2216
- return completed;
2217
- },
2218
- };
2219
- },
2220
- saveProviderApiKey(providerId, secret) {
2221
- const result = saveProviderApiKey(cfgMod, providerId, secret);
2222
- reloadFullConfig();
2223
- invalidateProviderCaches();
2224
- warmProviderModelCache();
2225
- return result;
2226
- },
2227
- saveOpenAIUsageSessionKey(secret) {
2228
- const result = saveOpenAIUsageSessionKey(cfgMod, secret);
2229
- reloadFullConfig();
2230
- invalidateProviderCaches();
2231
- return result;
2232
- },
2233
- saveOpenCodeGoUsageAuth(opts) {
2234
- const result = saveOpenCodeGoUsageAuth(cfgMod, opts);
2235
- reloadFullConfig();
2236
- invalidateProviderCaches();
2237
- return result;
2238
- },
2239
- async loginOpenCodeGoUsage() {
2240
- const result = await loginOpenCodeGoUsage(cfgMod);
2241
- reloadFullConfig();
2242
- invalidateProviderCaches();
2243
- return result;
2244
- },
2245
- setLocalProvider(providerId, opts) {
2246
- const result = setLocalProvider(cfgMod, providerId, opts);
2247
- reloadFullConfig();
2248
- invalidateProviderCaches();
2249
- warmProviderModelCache();
2250
- return result;
2251
- },
2252
- forgetProviderAuth(providerId) {
2253
- const result = forgetProviderAuth(cfgMod, providerId);
2254
- reloadFullConfig();
2255
- invalidateProviderCaches();
2256
- warmProviderModelCache();
2257
- return result;
2258
- },
2259
- listPresets() {
2260
- return cfgMod.listPresets(displayConfig());
2261
- },
2262
- async listProviderModels(options = {}) {
2263
- return await collectProviderModels({
2264
- force: options.force === true || options.refresh === true,
2265
- quick: options.quick === true,
2266
- });
2267
- },
2268
- getSearchRoute() {
2269
- searchRoute = normalizeSearchRouteConfig(config.searchRoute) || normalizeSearchRouteConfig(searchRoute);
2270
- return searchRoute;
2271
- },
2272
- async listSearchModels(options = {}) {
2273
- return await collectSearchProviderModels({ force: options.force === true || options.refresh === true });
2274
- },
2275
- async setSearchRoute(next) {
2276
- let selectedRoute = normalizeSearchRouteConfig(next);
2277
- if (!selectedRoute && next?.model && searchRoute?.provider) {
2278
- selectedRoute = normalizeSearchRouteConfig({ ...next, provider: searchRoute.provider });
2279
- }
2280
- if (!selectedRoute) throw new Error('search route requires provider and model');
2281
- if (isDefaultSearchRouteConfig(selectedRoute)) {
2282
- ensureFullConfig();
2283
- const routeToSave = normalizeSearchRouteConfig({
2284
- provider: SEARCH_DEFAULT_PROVIDER,
2285
- model: SEARCH_DEFAULT_MODEL,
2286
- ...(selectedRoute.toolType ? { toolType: selectedRoute.toolType } : {}),
2287
- });
2288
- const nextConfig = { ...config };
2289
- nextConfig.searchRoute = routeToSave;
2290
- saveConfigAndAdopt(nextConfig);
2291
- searchRoute = normalizeSearchRouteConfig(config.searchRoute);
2292
- invalidateProviderCaches();
2293
- return searchRoute;
2294
- }
2295
- if (!isSearchCapableProvider(selectedRoute.provider)) {
2296
- throw new Error(`provider "${selectedRoute.provider}" does not support Mixdog native search`);
2297
- }
2298
- ensureFullConfig();
2299
- await reg.initProviders(ensureProviderEnabled(config, selectedRoute.provider));
2300
- const modelMeta = await lookupModelMeta(selectedRoute.provider, selectedRoute.model);
2301
- if (!searchCapableFor(selectedRoute.provider, modelMeta)) {
2302
- throw new Error(`model "${selectedRoute.model}" is not marked as web-search capable`);
2303
- }
2304
- const fastCapable = fastCapableFor(selectedRoute.provider, modelMeta);
2305
- const effort = coerceEffortFor(selectedRoute.provider, modelMeta, selectedRoute.effort);
2306
- selectedRoute = {
2307
- ...selectedRoute,
2308
- ...(effort ? { effort } : {}),
2309
- fast: fastCapable ? selectedRoute.fast === true : false,
2310
- };
2311
- adoptConfig(saveModelSettings(cfgMod, selectedRoute, { fastCapable, baseConfig: config }), { hasSecrets: configHasSecrets });
2312
- const routeToSave = normalizeSearchRouteConfig(selectedRoute);
2313
- const nextConfig = { ...config };
2314
- nextConfig.searchRoute = routeToSave;
2315
- saveConfigAndAdopt(nextConfig);
2316
- searchRoute = normalizeSearchRouteConfig(config.searchRoute);
2317
- invalidateProviderCaches();
2318
- return searchRoute;
2319
- },
2320
- listAgents() {
2321
- const dataDir = cfgMod.getPluginData?.() || STANDALONE_DATA_DIR;
2322
- return FIXED_AGENT_SLOTS.map((agent) => ({
2323
- ...agent,
2324
- locked: true,
2325
- route: agentRouteFromConfig(config, agent.id, dataDir),
2326
- definition: loadAgentDefinition(dataDir, agent.id),
2327
- }));
2328
- },
2329
- listWorkflows() {
2330
- const currentConfig = displayConfig();
2331
- const dataDir = cfgMod.getPluginData?.() || STANDALONE_DATA_DIR;
2332
- const active = activeWorkflowId(currentConfig);
2333
- return listWorkflowPacks(dataDir).map((workflow) => ({
2334
- id: workflow.id,
2335
- name: workflow.name,
2336
- description: workflow.description,
2337
- source: workflow.source,
2338
- active: workflow.id === active,
2339
- agents: workflow.agents,
2340
- }));
2341
- },
2342
- getOutputStyle() {
2343
- return getOutputStyleStatusCached();
2344
- },
2345
- listOutputStyles() {
2346
- return getOutputStyleStatusCached();
2347
- },
2348
- async setOutputStyle(value) {
2349
- const before = getOutputStyleStatusCached({ fresh: true });
2350
- const selected = findOutputStyle(value, before.styles);
2351
- if (!selected) {
2352
- const names = before.styles.map((style) => style.label || style.id).join(', ') || 'Default';
2353
- throw new Error(`output style must be one of ${names}`);
2354
- }
2355
- // Adopt in-memory immediately so same-tick readers see the new style;
2356
- // persist off the key-handler tick. NOTE: the disk write goes through
2357
- // the dedicated flushOutputStyleSave debounce (sharedCfgMod whole-root
2358
- // RMW) — cfgMod.saveConfig only serializes agent-section fields and
2359
- // would drop the top-level outputStyle key.
2360
- const nextConfig = { ...config, outputStyle: selected.id };
2361
- if (nextConfig.agent && typeof nextConfig.agent === 'object' && !Array.isArray(nextConfig.agent)) {
2362
- const agent = { ...nextConfig.agent };
2363
- delete agent.outputStyle;
2364
- nextConfig.agent = agent;
2365
- }
2366
- adoptConfig(nextConfig);
2367
- scheduleOutputStyleSave(selected.id);
2368
- // Reuse the catalog already scanned above for `before` instead of a
2369
- // second forced-fresh filesystem scan; refresh the status cache
2370
- // in-memory (short TTL, same as getOutputStyleStatusCached) so reads
2371
- // during the debounce window see the just-selected style.
2372
- const freshStatus = { configured: selected.id, current: selected, styles: before.styles };
2373
- seedOutputStyleStatusCache(freshStatus);
2374
- const hasConversation = sessionHasConversationMessages(session);
2375
- let appliedToCurrentSession = !hasConversation;
2376
- if (session?.id && !hasConversation) {
2377
- const closedSessionId = session.id;
2378
- mgr.closeSession(closedSessionId, 'cli-output-style-switch');
2379
- session = null;
2380
- // Defer the recreate so the output-style picker can repaint first;
2381
- // any failure still surfaces via the existing notice path.
2382
- setTimeout(() => {
2383
- recreateCurrentSessionIfReady().catch((err) => {
2384
- try {
2385
- notifyFnForSession(closedSessionId)(
2386
- `Failed to start a new session after output style change: ${err?.message || err}`,
2387
- { level: 'error' },
2388
- );
2389
- } catch {}
2390
- });
2391
- }, 0);
2392
- }
2393
- invalidateContextStatusCache();
2394
- return { ...freshStatus, appliedToCurrentSession };
2395
- },
2396
- async setWorkflow(workflowId) {
2397
- const id = normalizeWorkflowId(workflowId, DEFAULT_WORKFLOW_ID);
2398
- const dataDir = cfgMod.getPluginData?.() || STANDALONE_DATA_DIR;
2399
- const pack = loadWorkflowPack(dataDir, id);
2400
- if (!pack || pack.id !== id) throw new Error(`workflow "${workflowId}" not found`);
2401
- const nextConfig = { ...config };
2402
- nextConfig.workflow = { ...(nextConfig.workflow || {}), active: id };
2403
- saveConfigAndAdopt(nextConfig);
2404
- return workflowSummary(pack);
2405
- },
2406
- async setAgentRoute(agentId, next) {
2407
- const id = normalizeAgentId(agentId);
2408
- if (!id) throw new Error(`unknown agent "${agentId}"`);
2409
- let selectedRoute = resolveRoute(config, { ...(next || {}) });
2410
- await reg.initProviders(ensureProviderEnabled(config, selectedRoute.provider));
2411
- const modelMeta = await lookupModelMeta(selectedRoute.provider, selectedRoute.model);
2412
- const fastCapable = fastCapableFor(selectedRoute.provider, modelMeta);
2413
- selectedRoute = { ...selectedRoute, fast: fastCapable ? selectedRoute.fast === true : false };
2414
- adoptConfig(saveModelSettings(cfgMod, selectedRoute, { fastCapable, baseConfig: config }), { hasSecrets: configHasSecrets });
2415
-
2416
- const routeToSave = normalizeWorkflowRoute(selectedRoute);
2417
- if (!routeToSave) throw new Error('agent route requires provider and model');
2418
- const agent = FIXED_AGENT_SLOTS.find((item) => item.id === id);
2419
- const nextConfig = { ...config };
2420
- nextConfig.agents = {
2421
- ...(nextConfig.agents || {}),
2422
- [id]: routeToSave,
2423
- };
2424
- nextConfig.presets = upsertWorkflowPreset(nextConfig.presets, agentPresetSlot(id), routeToSave);
2425
- if (agent?.workflowSlot) {
2426
- nextConfig.workflowRoutes = {
2427
- ...(nextConfig.workflowRoutes || {}),
2428
- [agent.workflowSlot]: routeToSave,
2429
- };
2430
- nextConfig.presets = upsertWorkflowPreset(nextConfig.presets, agent.workflowSlot, routeToSave);
2431
- // Maintenance slots store a direct {provider, model} route now, so
2432
- // mirror the agent route straight in instead of a preset-id string.
2433
- nextConfig.maintenance = {
2434
- ...(nextConfig.maintenance || {}),
2435
- ...(id === 'explore' ? { explore: routeToSave } : {}),
2436
- ...(id === 'maintainer' ? { memory: routeToSave } : {}),
2437
- };
2438
- }
2439
- saveConfigAndAdopt(nextConfig);
2440
- return routeToSave;
2441
- },
2442
- async setDefaultProvider(provider) {
2443
- const requested = clean(provider);
2444
- if (!requested) throw new Error('provider is required');
2445
- if (!isKnownProvider(requested)) throw new Error(`unknown provider "${provider}"`);
2446
- saveConfigAndAdopt({ ...config, defaultProvider: requested });
2447
- return requested;
2448
- },
2449
- async ask(prompt, options = {}) {
2450
- activeTurnCount += 1;
2451
- // Lazy code-graph prewarm: kick off the build ONCE, on the first real
2452
- // turn, so a likely code lookup hits a warm cache — without paying the
2453
- // post-first-frame prewarm freeze on idle startup. The schedule is async
2454
- // + unref'd (worker thread), so it never blocks this turn.
2455
- if (codeGraphPrewarmLazy && !codeGraphFirstTurnPrewarmDone) {
2456
- codeGraphFirstTurnPrewarmDone = true;
2457
- scheduleCodeGraphPrewarm(0, 'first-turn');
2458
- }
2459
- const startedAt = Date.now();
2460
- try {
2461
- await refreshSessionForCwdIfNeeded('cwd-change');
2462
- if (!session?.id) await createCurrentSession('turn');
2463
- // Remote outbound: ensure a transcript writer bound to the current
2464
- // session.id + cwd. The channel worker's OutputForwarder tails this
2465
- // JSONL and pushes the surface view to Discord. Gated on remoteEnabled
2466
- // so non-remote sessions write nothing.
2467
- if (remoteEnabled) {
2468
- // Reset per-turn dedup tracker so an identical answer in a later turn
2469
- // is still written (the guard only prevents same-turn double-write).
2470
- _lastAppendedAssistant = '';
2471
- const prevKey = _twKey;
2472
- ensureRemoteTranscriptWriter();
2473
- // The writer moved to a NEW session/cwd (e.g. lazy first-turn
2474
- // session create after /remote, or /new mid-remote). Re-pin the
2475
- // channel worker's output forwarder onto the fresh transcript NOW —
2476
- // otherwise it keeps tailing the previous binding until an inbound
2477
- // Discord message triggers the steal path, so terminal-initiated
2478
- // turns would never forward. activate_channel_bridge is idempotent
2479
- // force-takeover (claim + rebind); fire-and-forget so the turn is
2480
- // never blocked on worker IPC.
2481
- if (_twKey && _twKey !== prevKey && channelsEnabled() && !envFlag('MIXDOG_DISABLE_CHANNEL_START')) {
2482
- void invokeChannelStart()
2483
- .then(() => {
2484
- // stopRemote()/superseded/close may have landed while the
2485
- // worker was starting — never re-claim for a turned-off session.
2486
- if (!remoteEnabled || closeRequested) return undefined;
2487
- return channels.execute('activate_channel_bridge', { active: true });
2488
- })
2489
- .catch((error) => bootProfile('channels:turn-rebind-failed', { error: error?.message || String(error) }));
2490
- }
2491
- }
2492
- hooks.emit('turn:start', { sessionId: session.id, prompt, cwd: currentCwd });
2493
- // UserPromptSubmit: bridge to the standard hook bus. A hook FAILURE
2494
- // must not block the turn, but a genuine blocked===true MUST throw.
2495
- let promptDispatch = null;
2496
- try {
2497
- promptDispatch = await hooks.dispatch('UserPromptSubmit', hookCommonPayload({ session_id: session.id, prompt }));
2498
- } catch { /* hook failure never blocks the turn */ }
2499
- if (promptDispatch?.blocked === true) {
2500
- throw new Error(`prompt blocked by hook: ${promptDispatch.reason || ''}`);
2501
- }
2502
- const hookContext = Array.isArray(promptDispatch?.additionalContext)
2503
- ? promptDispatch.additionalContext.join('\n\n')
2504
- : String(promptDispatch?.additionalContext || '');
2505
- const turnContext = [options.context || '', hookContext]
2506
- .map((part) => String(part || '').trim())
2507
- .filter(Boolean)
2508
- .join('\n\n');
2509
- const result = await mgr.askSession(
2510
- session.id,
2511
- prompt,
2512
- turnContext || null,
2513
- async (iter, calls) => {
2514
- for (const call of calls || []) {
2515
- hooks.emit('tool:planned', {
2516
- sessionId: session.id,
2517
- name: call?.name || 'tool',
2518
- callId: call?.id || null,
2519
- });
2520
- // Mirror each tool card the TUI shows into the transcript so the
2521
- // forwarder renders the same one-line tool summary on Discord.
2522
- // calls carry { name, arguments, id } (loop.mjs response.toolCalls);
2523
- // some providers use `input` — accept either.
2524
- if (remoteEnabled && _transcriptWriter) {
2525
- try { _transcriptWriter.appendToolUse(call?.name, call?.input ?? call?.arguments); }
2526
- catch (error) { process.stderr.write(`mixdog: transcript-writer: onToolCall failed: ${error?.message || error}\n`); }
2527
- }
2528
- }
2529
- if (typeof options.onToolCall === 'function') {
2530
- return await options.onToolCall(iter, calls);
2531
- }
2532
- return undefined;
2533
- },
2534
- currentCwd,
2535
- options.prefetch || null,
2536
- {
2537
- onTextDelta: options.onTextDelta,
2538
- onReasoningDelta: options.onReasoningDelta,
2539
- onAssistantText: (text) => {
2540
- // Capture the same assistant text the TUI renders (final answer +
2541
- // mid-turn preamble). Feed the writer, then ALWAYS call through to
2542
- // the caller's hook so terminal rendering is never affected.
2543
- if (remoteEnabled && _transcriptWriter) {
2544
- try {
2545
- const value = typeof text === 'string' ? text : (text == null ? '' : String(text));
2546
- if (value.trim()) {
2547
- _transcriptWriter.appendAssistant(value);
2548
- // Track the last line we wrote so the post-turn final
2549
- // append below can skip an identical re-write (buffered
2550
- // providers surface the final answer here AND in result).
2551
- _lastAppendedAssistant = value;
2552
- }
2553
- }
2554
- catch (error) { process.stderr.write(`mixdog: transcript-writer: onAssistantText failed: ${error?.message || error}\n`); }
2555
- }
2556
- return options.onAssistantText?.(text);
2557
- },
2558
- onUsageDelta: options.onUsageDelta,
2559
- onToolResult: (message) => {
2560
- // Surface Edit diffs only: the forwarder reads toolUseResult
2561
- // {oldString,newString}. Other tool results carry no diff payload,
2562
- // so we append only when those fields are present.
2563
- if (remoteEnabled && _transcriptWriter) {
2564
- try {
2565
- const tur = message?.toolUseResult;
2566
- if (tur && (tur.oldString != null || tur.newString != null)) {
2567
- _transcriptWriter.appendToolResult({ oldString: tur.oldString ?? '', newString: tur.newString ?? '' });
2568
- }
2569
- } catch (error) { process.stderr.write(`mixdog: transcript-writer: onToolResult failed: ${error?.message || error}\n`); }
2570
- }
2571
- return options.onToolResult?.(message);
2572
- },
2573
- onToolApproval: options.onToolApproval,
2574
- onCompactEvent: options.onCompactEvent,
2575
- onStageChange: options.onStageChange,
2576
- onStreamDelta: options.onStreamDelta,
2577
- drainSteering: options.drainSteering,
2578
- onSteerMessage: options.onSteerMessage,
2579
- notifyFn: notifyFnForSession(session.id),
2580
- },
2581
- );
2582
- session = mgr.getSession(session.id) || session;
2583
- // Final assistant text: onAssistantText fires only for buffered
2584
- // (non-streaming) providers and for mid-turn preamble. Streaming
2585
- // providers deliver the final answer via onTextDelta (which we do NOT
2586
- // tap, to avoid per-delta spam), so append the authoritative final
2587
- // content here from result.content. To avoid double-writing the
2588
- // buffered case, only append when it differs from the last assistant
2589
- // line onAssistantText already wrote.
2590
- if (remoteEnabled && _transcriptWriter) {
2591
- try {
2592
- const finalText = result?.content != null ? String(result.content) : '';
2593
- if (finalText.trim() && finalText !== _lastAppendedAssistant) {
2594
- _transcriptWriter.appendAssistant(finalText);
2595
- _lastAppendedAssistant = finalText;
2596
- }
2597
- } catch (error) {
2598
- process.stderr.write(`mixdog: transcript-writer: final append failed: ${error?.message || error}\n`);
2599
- }
2600
- }
2601
- hooks.emit('turn:end', { sessionId: session.id, elapsedMs: Date.now() - startedAt });
2602
- // Stop: bridge to the standard hook bus. Best-effort; ignore result,
2603
- // never throw.
2604
- try {
2605
- await hooks.dispatch('Stop', hookCommonPayload({ session_id: session.id }));
2606
- } catch { /* best-effort: Stop hook must never break the turn */ }
2607
- return { result, session };
2608
- } catch (error) {
2609
- hooks.emit('turn:error', { sessionId: session?.id || null, elapsedMs: Date.now() - startedAt, error: error?.message || String(error) });
2610
- // StopFailure: bridge a turn error to the standard hook bus. Spec:
2611
- // output + exit code ignored, so pure fire-and-forget. error_type is a
2612
- // simple regex mapping from the error message (default 'unknown').
2613
- try {
2614
- const msg = String(error?.message || error || '').toLowerCase();
2615
- const errorType = /rate.?limit|429|too many requests/.test(msg) ? 'rate_limit'
2616
- : /overloaded|529/.test(msg) ? 'overloaded'
2617
- : /authenticat|unauthorized|401|invalid.*api.?key/.test(msg) ? 'authentication_failed'
2618
- : /server.?error|5\d\d|internal error/.test(msg) ? 'server_error'
2619
- : 'unknown';
2620
- void hooks.dispatch('StopFailure', hookCommonPayload({ session_id: session?.id || null, error_type: errorType }));
2621
- } catch { /* best-effort: StopFailure hook must never break teardown */ }
2622
- throw error;
2623
- } finally {
2624
- activeTurnCount = Math.max(0, activeTurnCount - 1);
2625
- if (!firstTurnCompleted) {
2626
- firstTurnCompleted = true;
2627
- scheduleProviderWarmup();
2628
- scheduleProviderModelWarmup();
2629
- }
2630
- }
2631
- },
2632
- async clear(options = {}) {
2633
- if (!session?.id) return false;
2634
- const cleared = await mgr.clearSessionMessages(session.id, options);
2635
- if (!cleared) return false;
2636
- session = typeof cleared === 'object' ? cleared : (mgr.getSession(session.id) || session);
2637
- if (options.recoverAgent === true) {
2638
- try { agentTool.recoverWorkers?.({ clientHostPid: session?.clientHostPid || process.pid }); } catch {}
2639
- }
2640
- invalidateContextStatusCache();
2641
- return true;
2642
- },
2643
- // session_manage tool handoff: the engine polls this at turn end and, if
2644
- // set, runs the same clear path the idle auto-clear uses. One-shot read.
2645
- consumePendingSessionReset() {
2646
- const pending = pendingSessionReset;
2647
- pendingSessionReset = null;
2648
- if (!pending) return null;
2649
- // Session changed since scheduling (resume / new session) — drop it.
2650
- if (!session?.id || pending.sessionId !== session.id) return null;
2651
- return pending.action;
2652
- },
2653
- async compact(options = {}) {
2654
- if (!session?.id) return null;
2655
- if (activeTurnCount > 0) {
2656
- return { changed: false, reason: 'compact skipped: turn in progress' };
2657
- }
2658
- // Manual compact bypasses loop.mjs, so its PreCompact/PostCompact never
2659
- // fire here — dispatch them explicitly via the session-property hooks
2660
- // (wired at session create). Best-effort; a hook must not block compaction.
2661
- try { await session.preCompactHook?.({ trigger: 'manual' }); }
2662
- catch { /* best-effort: PreCompact hook must never break manual compact */ }
2663
- const result = await mgr.compactSessionMessages(session.id);
2664
- try { await session.postCompactHook?.({ trigger: 'manual' }); }
2665
- catch { /* best-effort: PostCompact hook must never break manual compact */ }
2666
- session = mgr.getSession(session.id) || session;
2667
- if (options.recoverAgent === true) {
2668
- try { agentTool.recoverWorkers?.({ clientHostPid: session?.clientHostPid || process.pid }); } catch {}
2669
- }
2670
- invalidateContextStatusCache();
2671
- return result;
2672
- },
2673
- async setToolMode(nextMode) {
2674
- mode = normalizeToolMode(nextMode);
2675
- invalidatePreSessionToolSurface();
2676
- if (session?.id) mgr.closeSession(session.id, 'cli-mode-switch');
2677
- await recreateCurrentSessionIfReady();
2678
- return mode;
2679
- },
2680
- agentStatus() {
2681
- return agentStatusState();
2682
- },
2683
- get clientHostPid() {
2684
- return session?.clientHostPid || process.pid;
2685
- },
2686
- agentControl(args = {}) {
2687
- const callerSessionId = session?.id || null;
2688
- return agentTool.execute(args, {
2689
- callerCwd: currentCwd,
2690
- invocationSource: 'user-command',
2691
- callerSessionId,
2692
- clientHostPid: session?.clientHostPid || process.pid,
2693
- notifyFn: notifyFnForSession(callerSessionId),
2694
- });
2695
- },
2696
- onNotification(listener) {
2697
- if (typeof listener !== 'function') return () => {};
2698
- notificationListeners.add(listener);
2699
- return () => notificationListeners.delete(listener);
2700
- },
2701
- toolsStatus(query = '') {
2702
- const surface = activeToolSurface();
2703
- const catalog = Array.isArray(surface?.deferredToolCatalog)
2704
- ? surface.deferredToolCatalog
2705
- : (Array.isArray(surface?.tools) ? surface.tools : []);
2706
- const activeNames = new Set((surface?.tools || []).map((tool) => tool?.name).filter(Boolean));
2707
- const needle = clean(query).toLowerCase();
2708
- const rows = catalog.map((tool) => toolRow(tool, activeNames)).filter((row) => row.name);
2709
- const tools = needle
2710
- ? rows.filter((row) => toolSearchMatches(row, needle))
2711
- : rows;
2712
- return {
2713
- mode,
2714
- count: rows.length,
2715
- activeCount: rows.filter((row) => row.active).length,
2716
- tools,
2717
- activeTools: sortedNamesByMeasuredUsage(activeNames),
2718
- discoveredTools: sortedNamesByMeasuredUsage(surface?.deferredDiscoveredTools || []),
2719
- };
2720
- },
2721
- selectTools(names) {
2722
- const list = Array.isArray(names) ? names : String(names || '').split(/[,\s]+/);
2723
- const result = selectDeferredTools(activeToolSurface(), list, mode);
2724
- return { ...result, status: this.toolsStatus() };
2725
- },
2726
- setCwd(path) {
2727
- applyResolvedCwd(resolveCwdPath(path));
2728
- return currentCwd;
2729
- },
2730
- mcpStatus() {
2731
- return mcpStatus();
2732
- },
2733
- async reconnectMcp() {
2734
- reloadFullConfig();
2735
- const status = await connectConfiguredMcp({ reset: true });
2736
- invalidatePreSessionToolSurface();
2737
- if (session?.id) mgr.closeSession(session.id, 'cli-mcp-reconnect');
2738
- await recreateCurrentSessionIfReady();
2739
- return status;
2740
- },
2741
- async addMcpServer(input = {}) {
2742
- const { name, config: serverConfig } = normalizeMcpServerInput(input);
2743
- const nextConfig = { ...config };
2744
- nextConfig.mcpServers = {
2745
- ...(nextConfig.mcpServers || {}),
2746
- [name]: serverConfig,
2747
- };
2748
- saveConfigAndAdopt(nextConfig);
2749
- const status = await connectConfiguredMcp({ reset: true });
2750
- invalidatePreSessionToolSurface();
2751
- if (session?.id) mgr.closeSession(session.id, 'cli-mcp-add');
2752
- await recreateCurrentSessionIfReady();
2753
- return { name, status };
2754
- },
2755
- async removeMcpServer(name) {
2756
- const serverName = clean(name);
2757
- if (!serverName) throw new Error('MCP server name is required');
2758
- const nextConfig = { ...config };
2759
- const current = nextConfig.mcpServers && typeof nextConfig.mcpServers === 'object'
2760
- ? { ...nextConfig.mcpServers }
2761
- : {};
2762
- if (!Object.prototype.hasOwnProperty.call(current, serverName)) {
2763
- throw new Error(`MCP server not configured: ${serverName}`);
2764
- }
2765
- delete current[serverName];
2766
- saveConfigAndAdopt({ ...nextConfig, mcpServers: current });
2767
- const status = await connectConfiguredMcp({ reset: true });
2768
- invalidatePreSessionToolSurface();
2769
- if (session?.id) mgr.closeSession(session.id, 'cli-mcp-remove');
2770
- await recreateCurrentSessionIfReady();
2771
- return status;
2772
- },
2773
- async setMcpServerEnabled(name, enabled) {
2774
- const serverName = clean(name);
2775
- if (!serverName) throw new Error('MCP server name is required');
2776
- const nextConfig = { ...config };
2777
- const current = nextConfig.mcpServers && typeof nextConfig.mcpServers === 'object'
2778
- ? { ...nextConfig.mcpServers }
2779
- : {};
2780
- if (!Object.prototype.hasOwnProperty.call(current, serverName)) {
2781
- throw new Error(`MCP server not configured: ${serverName}`);
2782
- }
2783
- current[serverName] = { ...(current[serverName] || {}), enabled: enabled !== false };
2784
- saveConfigAndAdopt({ ...nextConfig, mcpServers: current });
2785
- const status = await connectConfiguredMcp({ reset: true });
2786
- invalidatePreSessionToolSurface();
2787
- if (session?.id) mgr.closeSession(session.id, 'cli-mcp-toggle');
2788
- await recreateCurrentSessionIfReady();
2789
- return status;
2790
- },
2791
- skillsStatus() {
2792
- return skillsStatus();
2793
- },
2794
- skillContent(name) {
2795
- return skillContent(name);
2796
- },
2797
- async addSkill(input = {}) {
2798
- const skill = addProjectSkill(input);
2799
- if (session?.id) mgr.closeSession(session.id, 'cli-skill-add');
2800
- await recreateCurrentSessionIfReady();
2801
- return { skill, status: skillsStatus() };
2802
- },
2803
- async reloadSkills() {
2804
- if (session?.id) mgr.closeSession(session.id, 'cli-skills-reload');
2805
- await recreateCurrentSessionIfReady();
2806
- return skillsStatus();
2807
- },
2808
- pluginsStatus() {
2809
- return pluginsStatus();
2810
- },
2811
- async reloadPlugins() {
2812
- if (session?.id) mgr.closeSession(session.id, 'cli-plugins-reload');
2813
- await recreateCurrentSessionIfReady();
2814
- return pluginsStatus();
2815
- },
2816
- async addPlugin(source) {
2817
- const dataDir = cfgMod.getPluginData?.();
2818
- const plugin = registryAddPlugin(source, { dataDir });
2819
- if (session?.id) mgr.closeSession(session.id, 'cli-plugin-add');
2820
- await recreateCurrentSessionIfReady();
2821
- return { plugin, status: pluginsStatus() };
2822
- },
2823
- async updatePlugin(plugin = {}) {
2824
- const key = clean(plugin.id || plugin.name || plugin);
2825
- const dataDir = cfgMod.getPluginData?.();
2826
- const updated = registryUpdatePlugin(key, { dataDir });
2827
- if (session?.id) mgr.closeSession(session.id, 'cli-plugin-update');
2828
- await recreateCurrentSessionIfReady();
2829
- return { plugin: updated, status: pluginsStatus() };
2830
- },
2831
- async removePlugin(plugin = {}) {
2832
- const key = clean(plugin.id || plugin.name || plugin);
2833
- const dataDir = cfgMod.getPluginData?.();
2834
- const removed = registryRemovePlugin(key, { dataDir });
2835
- const nextConfig = { ...config };
2836
- const serverName = pluginMcpServerName(plugin);
2837
- const prefix = `${serverName}--`;
2838
- const hasMatch = nextConfig.mcpServers && Object.keys(nextConfig.mcpServers).some(
2839
- (k) => k === serverName || k.startsWith(prefix)
2840
- );
2841
- if (hasMatch) {
2842
- const current = { ...nextConfig.mcpServers };
2843
- for (const k of Object.keys(current)) {
2844
- if (k === serverName || k.startsWith(prefix)) delete current[k];
2845
- }
2846
- saveConfigAndAdopt({ ...nextConfig, mcpServers: current });
2847
- await connectConfiguredMcp({ reset: true });
2848
- invalidatePreSessionToolSurface();
2849
- }
2850
- if (session?.id) mgr.closeSession(session.id, 'cli-plugin-remove');
2851
- await recreateCurrentSessionIfReady();
2852
- return { plugin: removed, status: pluginsStatus() };
2853
- },
2854
- async enablePluginMcp(plugin = {}) {
2855
- const root = clean(plugin.root);
2856
- const script = pluginMcpEnableScript(root, plugin);
2857
- if (!root || !script) throw new Error('plugin has no MCP script');
2858
- const serverName = pluginMcpServerName(plugin);
2859
- const nextConfig = { ...config };
2860
- const manifestMcp = pluginRawMcpServers(root, script);
2861
- if (manifestMcp) {
2862
- const { rawServers, mcpRoot } = manifestMcp;
2863
- const keys = Object.keys(rawServers).filter((k) => {
2864
- const v = rawServers[k];
2865
- return v !== null && typeof v === 'object' && !Array.isArray(v);
2866
- });
2867
- const ownedPrefix = `${serverName}--`;
2868
- const nextServers = {};
2869
- for (const [k, v] of Object.entries(nextConfig.mcpServers || {})) {
2870
- if (k === serverName || k.startsWith(ownedPrefix)) continue;
2871
- nextServers[k] = v;
2872
- }
2873
- for (const serverKey of keys) {
2874
- const cfg = normalizePluginMcpServerConfig(rawServers[serverKey], mcpRoot);
2875
- cfg.env = {
2876
- ...(cfg.env || {}),
2877
- MIXDOG_PLUGIN_ROOT: root,
2878
- MIXDOG_PLUGIN_DATA: join(cfgMod.getPluginData?.() || STANDALONE_DATA_DIR, 'plugins', 'data', clean(plugin.id || plugin.name || serverName)),
2879
- };
2880
- const key = keys.length === 1 ? serverName : `${serverName}--${serverKey}`;
2881
- nextServers[key] = cfg;
2882
- }
2883
- nextConfig.mcpServers = nextServers;
2884
- } else {
2885
- const scriptPath = resolveContainedPluginPath(root, script);
2886
- if (!scriptPath || !existsSync(scriptPath)) throw new Error(`plugin MCP script not found: ${join(root, script)}`);
2887
- nextConfig.mcpServers = {
2888
- ...(nextConfig.mcpServers || {}),
2889
- [serverName]: {
2890
- command: 'node',
2891
- args: [scriptPath],
2892
- cwd: root,
2893
- env: {
2894
- MIXDOG_PLUGIN_ROOT: root,
2895
- MIXDOG_PLUGIN_DATA: join(cfgMod.getPluginData?.() || STANDALONE_DATA_DIR, 'plugins', 'data', clean(plugin.id || plugin.name || serverName)),
2896
- },
2897
- },
2898
- };
2899
- }
2900
- saveConfigAndAdopt(nextConfig);
2901
- const status = await connectConfiguredMcp({ reset: true });
2902
- invalidatePreSessionToolSurface();
2903
- if (session?.id) mgr.closeSession(session.id, 'cli-plugin-mcp-enable');
2904
- await recreateCurrentSessionIfReady();
2905
- return { serverName, status };
2906
- },
2907
- hooksStatus() {
2908
- return hooks.status();
2909
- },
2910
- addHookRule(rule) {
2911
- return hooks.addRule(rule);
2912
- },
2913
- setHookRuleEnabled(index, enabled) {
2914
- return hooks.setRuleEnabled(index, enabled);
2915
- },
2916
- deleteHookRule(index) {
2917
- return hooks.deleteRule(index);
2918
- },
2919
- async memoryControl(args = {}) {
2920
- const memoryMod = await getMemoryModule();
2921
- if (!memoryMod?.handleToolCall) throw new Error('memory runtime is not available');
2922
- return toolResponseText(await memoryMod.handleToolCall('memory', args || {}));
2923
- },
2924
- async recall(query, args = {}) {
2925
- const baseQuery = query || args?.query || '';
2926
- if (args?.currentSession !== false && session?.id) {
2927
- const currentText = currentSessionRecallRows(session, baseQuery, { limit: args?.limit });
2928
- if (!isEmptyRecallText(currentText)) return currentText;
2929
- }
2930
- const memoryMod = await getMemoryModule();
2931
- if (!memoryMod?.handleToolCall) throw new Error('memory runtime is not available');
2932
- const baseArgs = {
2933
- ...(args || {}),
2934
- query: baseQuery,
2935
- cwd: args?.cwd || currentCwd,
2936
- // Grouping hint for multi-session browse output: lets the memory
2937
- // service mark THIS session's group as "(current)". Not a filter.
2938
- ...(session?.id ? { currentSessionId: session.id } : {}),
2939
- };
2940
- let result = '(no results)';
2941
- if (session?.id && args?.currentSession !== false && args?.forceCycleOnEmpty !== false) {
2942
- // Empty-fallback: hydrate the current transcript into the memory DB
2943
- // (no LLM — ingest only) and re-search session-scoped with the raw
2944
- // leg on. The old path also ran a synchronous cycle1 (LLM chunking)
2945
- // here, which made an empty recall the slowest possible recall and
2946
- // called the LLM even with recap/memory off; the raw rows are
2947
- // searchable directly (FTS/trgm + post-ingest raw embeddings), so
2948
- // chunking is left to the background cycle.
2949
- const messages = Array.isArray(session.messages) ? session.messages : [];
2950
- if (messages.length > 0) {
2951
- await memoryMod.handleToolCall('memory', {
2952
- action: 'ingest_session',
2953
- sessionId: session.id,
2954
- cwd: currentCwd,
2955
- messages,
2956
- });
2957
- result = toolResponseText(await memoryMod.handleToolCall('recall', {
2958
- ...baseArgs,
2959
- sessionId: session.id,
2960
- currentSession: true,
2961
- projectScope: baseArgs.projectScope || 'all',
2962
- includeRaw: baseArgs.includeRaw !== false,
2963
- includeArchived: baseArgs.includeArchived !== false,
2964
- }));
2965
- }
2966
- }
2967
- if (isEmptyRecallText(result)) {
2968
- result = toolResponseText(await memoryMod.handleToolCall('recall', baseArgs));
2969
- }
2970
- return result;
2971
- },
2972
- async setRoute(next, options = {}) {
2973
- // Model/provider changes take effect on the NEXT session only — never
2974
- // rewrite a running session's provider/model in place. A live turn's
2975
- // prompt cache (Anthropic/OpenAI/etc.) is provider-keyed; flipping
2976
- // session.provider mid-conversation forces a full cache-miss rewrite
2977
- // of the entire history on the very next turn (seen as a promptΔ
2978
- // spike + cache_ratio=0% in session-bench). `route` (this closure
2979
- // variable) still updates immediately so the NEXT createCurrentSession()
2980
- // picks it up; only the currently-open session is left untouched.
2981
- const applyToCurrentSession = options?.applyToCurrentSession === true;
2982
- const requested = { ...(next || {}) };
2983
- validateRequestedModelSelector(config, requested);
2984
- const providerExplicitlyRequested = clean(next?.provider) !== '';
2985
- if (requested.effort === undefined && !requested.provider && !requested.model && hasOwn(route, 'effort')) {
2986
- requested.effort = route.effort;
2987
- }
2988
- if (!requested.provider && requested.model && !findPreset(config, requested.model)) {
2989
- requested.provider = route.provider;
2990
- }
2991
- let selectedRoute = resolveRoute(config, requested);
2992
- await reg.initProviders(ensureProviderEnabled(config, selectedRoute.provider));
2993
- const modelMeta = await lookupModelMeta(selectedRoute.provider, selectedRoute.model);
2994
- // Guard (A안 / strict reject): a free-text string must never become the
2995
- // lead model. When the caller did not pin a provider, the route did not
2996
- // match a preset, and the model is unknown to both the live provider
2997
- // catalog (modelMeta is still the {id,provider} placeholder) and the
2998
- // offline catalog, refuse BEFORE any config write so a partial save
2999
- // (saveModelSettings/adoptConfig/persistLeadRoute) can never land.
3000
- if (!providerExplicitlyRequested
3001
- && !selectedRoute.preset
3002
- && !modelMetaLooksResolved(modelMeta)
3003
- && !getModelMetadataSync(selectedRoute.model, selectedRoute.provider)) {
3004
- throw new Error(`unknown model: ${selectedRoute.provider}/${selectedRoute.model}`);
3005
- }
3006
- const fastCapable = fastCapableFor(selectedRoute.provider, modelMeta);
3007
- selectedRoute = { ...selectedRoute, fast: fastCapable ? selectedRoute.fast === true : false };
3008
- adoptConfig(saveModelSettings(cfgMod, selectedRoute, { fastCapable, baseConfig: config }), { hasSecrets: configHasSecrets });
3009
- const leadRoute = persistLeadRoute(selectedRoute);
3010
- route = resolveRoute(config, leadRoute
3011
- ? { model: workflowPresetId('lead') }
3012
- : selectedRoute);
3013
- await refreshRouteEffort(modelMeta);
3014
- refreshStatuslineUsageSnapshot(route);
3015
- scheduleStatuslineUsageRefresh();
3016
- if (!applyToCurrentSession) {
3017
- // `route` is updated for the next session; the open session (and its
3018
- // live provider/model/cache chain) is left alone on purpose.
3019
- return route;
3020
- }
3021
- if (session) {
3022
- const updated = mgr.updateSessionRoute?.(session.id, {
3023
- provider: route.provider,
3024
- model: route.model,
3025
- fast: route.fast === true,
3026
- effort: route.effectiveEffort || null,
3027
- });
3028
- if (updated) session = updated;
3029
- else {
3030
- session.provider = route.provider;
3031
- session.model = route.model;
3032
- session.fast = route.fast === true;
3033
- session.effort = route.effectiveEffort || null;
3034
- }
3035
- writeStatuslineRoute(statusRoutes, session, route);
3036
- invalidateContextStatusCache();
3037
- }
3038
- return route;
3039
- },
3040
-
3041
- async setFast(value) {
3042
- const enabled = value === true;
3043
- const modelMeta = await lookupModelMeta(route.provider, route.model);
3044
- const fastCapable = fastCapableFor(route.provider, modelMeta);
3045
- if (enabled && !fastCapable) {
3046
- throw new Error(`fast mode is not available for ${route.provider}/${route.model}`);
3047
- }
3048
- route = resolveRoute(config, { provider: route.provider, model: route.model, effort: route.effort, fast: fastCapable ? enabled : false });
3049
- adoptConfig(saveModelSettings(cfgMod, route, { fastCapable, baseConfig: config }), { hasSecrets: configHasSecrets });
3050
- const leadRoute = persistLeadRoute(route);
3051
- if (leadRoute) route = resolveRoute(config, { model: workflowPresetId('lead') });
3052
- await refreshRouteEffort(modelMeta);
3053
- if (session) {
3054
- session.fast = route.fast === true;
3055
- session.effort = route.effectiveEffort || null;
3056
- writeStatuslineRoute(statusRoutes, session, route);
3057
- invalidateContextStatusCache();
3058
- }
3059
- return route.fast === true;
3060
- },
3061
-
3062
- async toggleFast() {
3063
- return await this.setFast(!(route.fast === true));
3064
- },
3065
-
3066
- async setEffort(value) {
3067
- const normalized = normalizeEffortInput(value);
3068
- route = { ...route, effort: normalized };
3069
- const modelMeta = await lookupModelMeta(route.provider, route.model);
3070
- const fastCapable = fastCapableFor(route.provider, modelMeta);
3071
- adoptConfig(saveModelSettings(cfgMod, route, { fastCapable, baseConfig: config }), { hasSecrets: configHasSecrets });
3072
- const leadRoute = persistLeadRoute(route);
3073
- if (leadRoute) {
3074
- route = resolveRoute(config, { model: workflowPresetId('lead') });
3075
- }
3076
- await refreshRouteEffort(modelMeta);
3077
- if (session) {
3078
- session.effort = route.effectiveEffort || null;
3079
- writeStatuslineRoute(statusRoutes, session, route);
3080
- invalidateContextStatusCache();
3081
- }
3082
- return route;
3083
- },
3084
- async close(reason = 'cli-exit', options = {}) {
3085
- const detach = options?.detach === true || options?.wait === false || options?.waitForExit === false;
3086
- closeRequested = true;
3087
- // SessionEnd: bridge teardown to the standard hook bus. reason mapped to
3088
- // standard values ('clear'/'exit' where applicable, else 'other'). Short
3089
- // await guard so a slow hook cannot wedge teardown; best-effort.
3090
- try {
3091
- const rl = String(reason || '').toLowerCase();
3092
- const endReason = /clear/.test(rl) ? 'clear'
3093
- : /exit|quit|cli-exit|shutdown|sigint|sigterm/.test(rl) ? 'exit'
3094
- : 'other';
3095
- if (session?.id) {
3096
- await withTeardownDeadline(
3097
- Promise.resolve(hooks.dispatch('SessionEnd', hookCommonPayload({ session_id: session.id, reason: endReason }))).catch(() => {}),
3098
- 300,
3099
- undefined,
3100
- );
3101
- }
3102
- } catch { /* best-effort: SessionEnd hook must never wedge teardown */ }
3103
- // Persist any change that is still sitting in the debounce window so a
3104
- // toggle made right before exit is not lost. Synchronous + best-effort:
3105
- // teardown must continue even if the final write fails.
3106
- try { flushConfigSave(); } catch {}
3107
- try { flushBackendSave(); } catch {}
3108
- try { flushOutputStyleSave(); } catch {}
3109
- if (prewarmTimers.channelStartTimer) {
3110
- clearTimeout(prewarmTimers.channelStartTimer);
3111
- prewarmTimers.channelStartTimer = null;
3112
- }
3113
- for (const timerKey of [
3114
- 'providerSetupWarmupTimer',
3115
- 'providerWarmupTimer',
3116
- 'providerModelWarmupTimer',
3117
- 'modelCatalogWarmupTimer',
3118
- ]) {
3119
- if (warmupTimers[timerKey]) {
3120
- clearTimeout(warmupTimers[timerKey]);
3121
- warmupTimers[timerKey] = null;
3122
- }
3123
- }
3124
- if (prewarmTimers.codeGraphPrewarmTimer) {
3125
- clearTimeout(prewarmTimers.codeGraphPrewarmTimer);
3126
- prewarmTimers.codeGraphPrewarmTimer = null;
3127
- }
3128
- for (const timerKey of ['statuslineUsageWarmupTimer', 'statuslineUsageRefreshTimer']) {
3129
- if (warmupTimers[timerKey]) {
3130
- clearTimeout(warmupTimers[timerKey]);
3131
- warmupTimers[timerKey] = null;
3132
- }
3133
- }
3134
- try { cancelBackgroundTasks({ reason, notify: false }); } catch {}
3135
- const channelStop = channels.stop(reason, detach ? { waitForExit: false } : undefined);
3136
- try { agentTool.closeAll(reason); } catch {}
3137
- let mcpStop = null;
3138
- try { mcpStop = mcpClient.disconnectAll?.(); } catch {}
3139
- const openaiWsStop = globalThis.__mixdogOpenaiWsRuntimeLoaded === true
3140
- ? import('./runtime/agent/orchestrator/providers/openai-oauth-ws.mjs')
3141
- .then((mod) => mod?.drainOpenaiWsPool?.(reason))
3142
- .catch(() => {})
3143
- : null;
3144
- const patchStop = closePatchRuntimeIfLoaded(detach ? { waitForExit: false } : undefined);
3145
- const memoryStop = memoryModPromise
3146
- ? memoryModPromise
3147
- .then((mod) => (typeof mod?.stop === 'function' ? mod.stop() : null))
3148
- .catch(() => {})
3149
- .finally(() => {
3150
- memoryModPromise = null;
3151
- })
3152
- : null;
3153
- let ok = false;
3154
- if (session?.id) {
3155
- statusRoutes?.clearGatewaySessionRoute?.(session.id);
3156
- // Bug fix: runtime stop/exit (TUI Ctrl-C, process exit) previously
3157
- // always tombstoned the current session, so a session you were
3158
- // mid-conversation in vanished from the Resume list the instant you
3159
- // quit and was hard-deleted by the 24h tombstone sweep. Only
3160
- // tombstone truly-empty scratch sessions; non-empty sessions must
3161
- // survive exit resumable.
3162
- // liveTurnMessages holds the in-flight user prompt until turn
3163
- // commit — an active first-turn ask has its user message there,
3164
- // not yet in session.messages, so it must also be checked or a
3165
- // first-turn exit could still burn a real session.
3166
- const tombstone = !hasUserConversationMessage(session.messages)
3167
- && !hasUserConversationMessage(session.liveTurnMessages);
3168
- ok = mgr.closeSession(session.id, reason, { tombstone });
3169
- session = null;
3170
- }
3171
- const shellJobsStop = globalThis.__mixdogShellJobsRuntimeLoaded === true
3172
- ? import('./runtime/agent/orchestrator/tools/builtin/shell-jobs.mjs')
3173
- .then((mod) => mod?.shutdownShellJobs?.(reason, { sync: !detach }))
3174
- .catch(() => {})
3175
- : null;
3176
- const bashSessionsStop = globalThis.__mixdogBashSessionRuntimeLoaded === true
3177
- ? import('./runtime/agent/orchestrator/tools/bash-session.mjs')
3178
- .then((mod) => mod?.shutdownBashSessions?.(reason))
3179
- .catch(() => {})
3180
- : null;
3181
- if (detach) {
3182
- try { await withTeardownDeadline(channelStop, 300, false); } catch {}
3183
- try { await withTeardownDeadline(shellJobsStop, 300, false); } catch {}
3184
- try { await withTeardownDeadline(bashSessionsStop, 300, false); } catch {}
3185
- try { await withTeardownDeadline(memoryStop, 1500, false); } catch {}
3186
- for (const stop of [mcpStop, openaiWsStop, patchStop]) {
3187
- Promise.resolve(stop).catch(() => {});
3188
- }
3189
- return ok;
3190
- }
3191
- await Promise.allSettled([
3192
- withTeardownDeadline(channelStop, 5500, false),
3193
- withTeardownDeadline(mcpStop, 1500, false),
3194
- withTeardownDeadline(openaiWsStop, 1500, false),
3195
- withTeardownDeadline(patchStop, 1500, false),
3196
- withTeardownDeadline(memoryStop, 5500, false),
3197
- withTeardownDeadline(shellJobsStop, 1500, false),
3198
- withTeardownDeadline(bashSessionsStop, 1500, false),
3199
- ]);
3200
- return ok;
3201
- },
3202
- abort(reason = 'cli-abort') {
3203
- if (!session?.id) return false;
3204
- return mgr.abortSessionTurn(session.id, reason);
3205
- },
3206
- listSessions() {
3207
- return mgr.listSessions({}).map(s => {
3208
- const owner = clean(s.owner || 'user').toLowerCase();
3209
- if (owner && !['cli', 'user', 'mixdog', 'legacy'].includes(owner)) return null;
3210
- const sourceType = clean(s.sourceType || '').toLowerCase();
3211
- const sourceName = clean(s.sourceName || '').toLowerCase();
3212
- const agent = clean(s.agent || '').toLowerCase();
3213
- const leadish = agent === 'lead'
3214
- || sourceType === 'lead'
3215
- // Bug fix: side-terminal cli sessions have a non-empty/non-'main' sourceName
3216
- // (e.g. terminal id) and were being hidden from resume even though they are
3217
- // legitimate user sessions, not agent-owned. Any sourceName is fine for cli.
3218
- || (sourceType === 'cli')
3219
- || (!sourceType && !sourceName && !isAgentOwner(owner));
3220
- if (!leadish) return null;
3221
- let preview = cleanSessionPreview(s.preview || '');
3222
- let messageCount = Math.max(0, Number(s.messageCount) || 0);
3223
- if (!preview && Array.isArray(s.messages)) {
3224
- const msgs = s.messages || [];
3225
- const userPreviews = msgs
3226
- .filter(m => m && m.role === 'user')
3227
- .map(m => cleanSessionPreview(sessionMessageText(m.content)))
3228
- .filter(text => !isSessionPreviewNoise(text));
3229
- preview = userPreviews[userPreviews.length - 1] || userPreviews[0] || '';
3230
- messageCount = msgs.filter(m => m && (m.role === 'user' || m.role === 'assistant')).length;
3231
- }
3232
- // Bug fix: sessions whose preview couldn't be derived (e.g. noise-only user
3233
- // turns) were silently dropped from the resume list even when they had real
3234
- // messages. Keep the row and let preview fall back to '' (TUI renders
3235
- // '(no message)' for empty preview); only drop truly-empty scratch sessions
3236
- // with zero visible messages.
3237
- if (!preview && messageCount === 0) return null;
3238
- return {
3239
- id: s.id,
3240
- updatedAt: s.updatedAt,
3241
- cwd: s.cwd || '',
3242
- model: s.model,
3243
- provider: s.provider,
3244
- messageCount,
3245
- preview,
3246
- };
3247
- }).filter(Boolean);
3248
- },
3249
- async newSession() {
3250
- if (session?.id) {
3251
- // Bug fix: /new used to unconditionally tombstone the outgoing
3252
- // session, so switching to a fresh session burned whatever you'd
3253
- // been working on — it dropped off the Resume list immediately and
3254
- // was hard-deleted after the 24h tombstone sweep. Only tombstone
3255
- // truly-empty scratch sessions; keep non-empty ones resumable.
3256
- const tombstone = !hasUserConversationMessage(session.messages)
3257
- && !hasUserConversationMessage(session.liveTurnMessages);
3258
- mgr.closeSession(session.id, 'cli-new', { tombstone });
3259
- // Bug fix: closeSession({tombstone:false}) keeps the outgoing
3260
- // session file intact so it stays resumable — but that meant
3261
- // createCurrentSession()'s live-session reuse check (session?.id →
3262
- // mgr.getSession(...) not closed) happily reloaded the SAME session,
3263
- // so /new never actually reset the transcript and the context gauge
3264
- // never returned to 0. Drop the in-memory reference so a fresh
3265
- // session is always created.
3266
- session = null;
3267
- }
3268
- invalidateContextStatusCache();
3269
- await createCurrentSession();
3270
- return session.id;
3271
- },
3272
- async resume(id) {
3273
- const previousId = session?.id || null;
3274
- const previousMessages = session?.messages || null;
3275
- const previousLive = session?.liveTurnMessages || null;
3276
- const resumed = await mgr.resumeSession(id, toolSpecForMode(mode));
3277
- if (!resumed) return null;
3278
- if (previousId && previousId !== resumed.id) {
3279
- statusRoutes?.clearGatewaySessionRoute?.(previousId);
3280
- // Bug fix: /resume used to unconditionally tombstone the session
3281
- // you were switching away from, so it vanished from the Resume
3282
- // list right away and was hard-deleted after the 24h sweep — the
3283
- // exact "burn a resumable session" bug this fix targets. Only
3284
- // tombstone truly-empty scratch sessions.
3285
- const tombstone = !hasUserConversationMessage(previousMessages)
3286
- && !hasUserConversationMessage(previousLive);
3287
- mgr.closeSession(previousId, 'cli-resume', { tombstone });
3288
- }
3289
- session = resumed;
3290
- currentCwd = resumed.cwd || currentCwd;
3291
- applyResolvedCwd(currentCwd, { markRefresh: false });
3292
- const resumeEffort = hasOwn(route, 'effort') ? route.effort : resumed.effort;
3293
- route = resolveRoute(config, { provider: resumed.provider, model: resumed.model, effort: resumeEffort });
3294
- await refreshRouteEffort();
3295
- session.effort = route.effectiveEffort || null;
3296
- session.cwd = currentCwd;
3297
- applyDeferredToolSurface(session, deferredSurfaceModeForLead(mode), standaloneTools, { provider: route.provider });
3298
- invalidatePreSessionToolSurface();
3299
- invalidateContextStatusCache();
3300
- sessionNeedsCwdRefresh = false;
3301
- writeStatuslineRoute(statusRoutes, session, route);
3302
- return {
3303
- id: resumed.id,
3304
- messages: resumed.messages || [],
3305
- cwd: currentCwd,
3306
- provider: resumed.provider,
3307
- model: resumed.model,
3308
- };
3309
- },
3310
- };
3311
- }
1
+ // Thin facade. The former ~3.3k-line implementation was split into cohesive
2
+ // modules under src/session-runtime/ (runtime-core.mjs holds the orchestrator
3
+ // createMixdogSessionRuntime plus the module-level wiring; env.mjs and
4
+ // boot-profile.mjs hold the extracted env/boot helpers). This file re-exports
5
+ // the exact same public API so existing importers (TUI engine,
6
+ // scripts/tool-smoke.mjs, tests) keep their import paths unchanged.
7
+ export * from './session-runtime/runtime-core.mjs';