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
@@ -0,0 +1,2046 @@
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-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 './effort.mjs';
119
+ import {
120
+ LAZY_SECRET_PROVIDERS,
121
+ routeFastKey,
122
+ fastCapableFor,
123
+ makeSearchCapableFor,
124
+ fastPreferenceFor,
125
+ saveModelSettings,
126
+ } from './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 './config-helpers.mjs';
153
+ import {
154
+ routeForStatusline,
155
+ writeStatuslineRoute,
156
+ } from './statusline-route.mjs';
157
+ import {
158
+ normalizeOutputStyleId,
159
+ listOutputStyleCatalog,
160
+ findOutputStyle,
161
+ outputStyleStatus as outputStyleStatusRaw,
162
+ } from './output-styles.mjs';
163
+ import { readJsonSafe, readTextSafe } from './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 './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 './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 './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 './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 './tool-defs.mjs';
227
+ import { ONBOARDING_VERSION, QUICK_SEARCH_MODELS } from './quick-search-models.mjs';
228
+ import {
229
+ sortProviderModels as sortProviderModelsRaw,
230
+ providerModelCacheRow as providerModelCacheRowRaw,
231
+ } from './model-recency.mjs';
232
+ import { createNativeSearch } from './native-search.mjs';
233
+ import { createConfigLifecycle } from './config-lifecycle.mjs';
234
+ import { attachSessionHooks } from './session-hooks.mjs';
235
+ import { createQuickModelRows } from './quick-model-rows.mjs';
236
+ import { createWarmupSchedulers } from './warmup-schedulers.mjs';
237
+ import { createPrewarmSchedulers } from './prewarm.mjs';
238
+ import { createMcpGlue } from './mcp-glue.mjs';
239
+ import { createCwdPlugins } from './cwd-plugins.mjs';
240
+ import { createSettingsApi } from './settings-api.mjs';
241
+ import { createProviderModels } from './provider-models.mjs';
242
+ import { createProviderUsage } from './provider-usage.mjs';
243
+ import { envFlag, envPresent, envDelayMs } from './env.mjs';
244
+ import { bootProfile, profiledImport } from './boot-profile.mjs';
245
+ import { createChannelConfigApi } from './channel-config-api.mjs';
246
+ import { createProviderAuthApi } from './provider-auth-api.mjs';
247
+ import { createContextStatus } from './context-status.mjs';
248
+ import { createLifecycleApi } from './lifecycle-api.mjs';
249
+ import { createResourceApi } from './resource-api.mjs';
250
+ import { createModelRouteApi } from './model-route-api.mjs';
251
+ import { createWorkflowAgentsApi } from './workflow-agents-api.mjs';
252
+ import { createSessionTurnApi } from './session-turn-api.mjs';
253
+ // Re-exported for external consumers (scripts/tool-smoke.mjs) that imported
254
+ // these from this module before the tool-defs extraction.
255
+ export { TOOL_SEARCH_TOOL, SKILL_TOOL };
256
+ // Back-compat test alias; delegates to the extracted helper.
257
+ export function __applyStandaloneToolDefaultsForTest(tool) {
258
+ return applyStandaloneToolDefaults(tool);
259
+ }
260
+
261
+ const RUNTIME = '../runtime/agent/orchestrator';
262
+ const SEARCH_RUNTIME = '../runtime/search/index.mjs';
263
+ const SEARCH_TOOL_DEFS = '../runtime/search/tool-defs.mjs';
264
+ const MEMORY_TOOL_DEFS = '../runtime/memory/tool-defs.mjs';
265
+ const MEMORY_RUNTIME = '../runtime/memory/index.mjs';
266
+ const CHANNEL_TOOL_DEFS = '../runtime/channels/tool-defs.mjs';
267
+ const CHANNEL_WORKER_ENTRY = '../runtime/channels/index.mjs';
268
+ const CODE_GRAPH_TOOL_DEFS = '../runtime/agent/orchestrator/tools/code-graph-tool-defs.mjs';
269
+ const CODE_GRAPH_RUNTIME = '../runtime/agent/orchestrator/tools/code-graph.mjs';
270
+ const STATUSLINE_SESSION_ROUTES = '../vendor/statusline/src/gateway/session-routes.mjs';
271
+ const __dirname = dirname(fileURLToPath(import.meta.url));
272
+ // This module lives in src/session-runtime/, but the resource root must remain
273
+ // src/ (defaults/, rules/, runtime/, vendor/ live there), so climb one level.
274
+ const STANDALONE_SOURCE_ROOT = dirname(__dirname);
275
+ // Resource root stays at src/ because defaults/, rules/, runtime/, vendor/ live
276
+ // there. User-owned standalone state lives under MIXDOG_HOME (~/.mixdog).
277
+ const STANDALONE_ROOT = STANDALONE_SOURCE_ROOT;
278
+ const MIXDOG_HOME = process.env.MIXDOG_HOME || join(homedir(), '.mixdog');
279
+ const STANDALONE_DATA_DIR = process.env.MIXDOG_DATA_DIR || join(MIXDOG_HOME, 'data');
280
+
281
+ const resolveDefaultProvider = makeResolveDefaultProvider(isKnownProvider);
282
+ const resolveRoute = makeResolveRoute(resolveDefaultProvider);
283
+ const searchCapableFor = makeSearchCapableFor(normalizeSearchProviderId, isSearchCapableProvider);
284
+
285
+ const outputStyleStatus = (dataDir = STANDALONE_DATA_DIR, opts = {}) => outputStyleStatusRaw(STANDALONE_ROOT, dataDir || STANDALONE_DATA_DIR, opts);
286
+ // Workflow/agent pack loaders bound to this runtime's root/data layout.
287
+ const {
288
+ listWorkflowPacks,
289
+ activeWorkflowId,
290
+ loadWorkflowPack,
291
+ workflowSummary,
292
+ activeWorkflowSummary,
293
+ loadAgentDefinition,
294
+ workflowContextBlock,
295
+ activeWorkflowContext,
296
+ } = createWorkflowHelpers({
297
+ rootDir: STANDALONE_ROOT,
298
+ dataDir: STANDALONE_DATA_DIR,
299
+ readMarkdownDocument,
300
+ normalizeAgentPermissionOrNone,
301
+ });
302
+ const {
303
+ summarizeWorkflowRoutes,
304
+ routeFromPreset,
305
+ agentRouteFromConfig,
306
+ } = createWorkflowRouteHelpers({ resolveDefaultProvider, findPreset });
307
+
308
+ export function __renderToolSearchForTest(args = {}, session = {}, mode = 'full') {
309
+ return renderToolSearch(args, session, mode);
310
+ }
311
+
312
+ export function __saveModelSettingsForTest(cfgMod, route, options = {}) {
313
+ return saveModelSettings(cfgMod, route, options);
314
+ }
315
+
316
+ export async function createMixdogSessionRuntime({
317
+ provider,
318
+ model,
319
+ cwd = process.cwd(),
320
+ toolMode = 'full',
321
+ remote = false,
322
+ } = {}) {
323
+ bootProfile('session-runtime:start', { provider, model, toolMode, cwd });
324
+ let remoteEnabled = remote === true;
325
+ // Remote-mode transcript writer (Discord outbound). Lazily created per
326
+ // session.id + cwd inside ask(); only active while remoteEnabled.
327
+ let _transcriptWriter = null;
328
+ let _twKey = '';
329
+ // Last assistant text handed to the transcript writer (via onAssistantText),
330
+ // so the post-turn final-content append can skip an exact duplicate.
331
+ let _lastAppendedAssistant = '';
332
+ process.env.MIXDOG_QUIET_SESSION_LOG ??= '1';
333
+ const standaloneStartedAt = performance.now();
334
+ ensureStandaloneEnvironment({
335
+ rootDir: STANDALONE_ROOT,
336
+ dataDir: STANDALONE_DATA_DIR,
337
+ });
338
+ bootProfile('standalone-env:ready', { ms: (performance.now() - standaloneStartedAt).toFixed(1) });
339
+
340
+ const importsStartedAt = performance.now();
341
+ const [
342
+ cfgMod,
343
+ sharedCfgMod,
344
+ reg,
345
+ mcpClient,
346
+ mgr,
347
+ contextMod,
348
+ internalTools,
349
+ statusRoutes,
350
+ searchToolDefs,
351
+ memoryToolDefs,
352
+ channelToolDefs,
353
+ codeGraphToolDefs,
354
+ ] = await Promise.all([
355
+ profiledImport('config', `${RUNTIME}/config.mjs`),
356
+ profiledImport('shared-config', `${RUNTIME}/../../shared/config.mjs`),
357
+ profiledImport('providers-registry', `${RUNTIME}/providers/registry.mjs`),
358
+ profiledImport('mcp-client', `${RUNTIME}/mcp/client.mjs`),
359
+ profiledImport('session-manager', `${RUNTIME}/session/manager.mjs`),
360
+ profiledImport('context-collect', `${RUNTIME}/context/collect.mjs`),
361
+ profiledImport('internal-tools', `${RUNTIME}/internal-tools.mjs`),
362
+ profiledImport('status-routes', STATUSLINE_SESSION_ROUTES, { optional: true }),
363
+ profiledImport('search-tool-defs', SEARCH_TOOL_DEFS, { optional: true }),
364
+ profiledImport('memory-tool-defs', MEMORY_TOOL_DEFS, { optional: true }),
365
+ profiledImport('channel-tool-defs', CHANNEL_TOOL_DEFS, { optional: true }),
366
+ profiledImport('code-graph-tool-defs', CODE_GRAPH_TOOL_DEFS, { optional: true }),
367
+ ]);
368
+ bootProfile('imports:ready', { ms: (performance.now() - importsStartedAt).toFixed(1) });
369
+ const pluginDataDir = cfgMod.getPluginData();
370
+ // Re-wire the idle/tombstone sweep. startIdleCleanup() lost its caller in a
371
+ // refactor, so closed-session tombstones were never deleted after their 24h
372
+ // grace — the store grew unbounded (observed: 1.8k files / 114MB), which
373
+ // made summary-index rebuilds and per-save index rewrites stall boot for
374
+ // seconds. Timer is unref'd and first fires after CLEANUP_INITIAL_DELAY_MS
375
+ // (5min), so this adds zero boot-path cost.
376
+ try { mgr.startIdleCleanup?.(); } catch { /* cleanup is best-effort */ }
377
+ const memoryRuntime = createStandaloneMemoryRuntime({
378
+ // Entry constants are module-relative ('../runtime/...'); resolve against
379
+ // this module's dir, not STANDALONE_ROOT, or the 'src/' segment is lost.
380
+ entry: join(__dirname, MEMORY_RUNTIME),
381
+ dataDir: pluginDataDir,
382
+ cwd,
383
+ });
384
+ let memoryModPromise = null;
385
+ let searchModPromise = null;
386
+ let codeGraphModPromise = null;
387
+
388
+ // Memory module is always-on. `memoryEnabled()` is kept as a thin alias that
389
+ // now always returns true (callers/compaction helpers still reference it);
390
+ // the user-facing toggle is `recap` (background cycles only), read via
391
+ // recapEnabled(config).
392
+ const memoryEnabled = () => true;
393
+ const recapEnabledFn = () => recapEnabled(config, true);
394
+ const channelsEnabled = () => moduleEnabled(config, 'channels', true);
395
+
396
+ async function getMemoryModule() {
397
+ const startedAt = performance.now();
398
+ memoryModPromise ??= Promise.resolve(memoryRuntime);
399
+ const mod = await memoryModPromise;
400
+ if (typeof mod?.init === 'function') {
401
+ await mod.init();
402
+ }
403
+ bootProfile('memory-runtime:ready', { ms: (performance.now() - startedAt).toFixed(1) });
404
+ return mod;
405
+ }
406
+
407
+ async function getSearchModule() {
408
+ const startedAt = performance.now();
409
+ searchModPromise ??= import(SEARCH_RUNTIME);
410
+ const mod = await searchModPromise;
411
+ bootProfile('search-runtime:ready', { ms: (performance.now() - startedAt).toFixed(1) });
412
+ return mod;
413
+ }
414
+
415
+ async function getCodeGraphModule() {
416
+ const startedAt = performance.now();
417
+ codeGraphModPromise ??= import(CODE_GRAPH_RUNTIME);
418
+ const mod = await codeGraphModPromise;
419
+ bootProfile('code-graph-runtime:ready', { ms: (performance.now() - startedAt).toFixed(1) });
420
+ return mod;
421
+ }
422
+
423
+ function persistLeadRoute(routeLike) {
424
+ const leadRoute = normalizeWorkflowRoute(routeLike);
425
+ if (!leadRoute) return null;
426
+
427
+ const nextConfig = { ...(config || {}) };
428
+ nextConfig.presets = upsertWorkflowPreset(nextConfig.presets, 'lead', leadRoute);
429
+ nextConfig.workflowRoutes = {
430
+ ...(nextConfig.workflowRoutes || {}),
431
+ lead: leadRoute,
432
+ };
433
+ nextConfig.default = workflowPresetId('lead');
434
+
435
+ saveConfigAndAdopt(nextConfig);
436
+ return leadRoute;
437
+ }
438
+
439
+ async function closePatchRuntimeIfLoaded(options = {}) {
440
+ const closer = globalThis.__mixdogCloseNativePatchServers;
441
+ if (typeof closer !== 'function' || globalThis.__mixdogNativePatchRuntimeTouched !== true) return;
442
+ bootProfile('patch-runtime:close:start');
443
+ const startedAt = performance.now();
444
+ try {
445
+ await closer(options);
446
+ } catch {
447
+ // Best-effort shutdown only; terminal restore must continue.
448
+ } finally {
449
+ bootProfile('patch-runtime:close:done', { ms: (performance.now() - startedAt).toFixed(1) });
450
+ }
451
+ }
452
+
453
+ const configStartedAt = performance.now();
454
+ let config = cfgMod.loadConfig({ secrets: false });
455
+ setConfiguredShell(normalizeSystemShellConfig(config.shell).command);
456
+ let configHasSecrets = false;
457
+ let route = resolveRoute(config, { provider, model });
458
+ let searchRoute = normalizeSearchRouteConfig(config.searchRoute);
459
+ bootProfile('config:ready', { ms: (performance.now() - configStartedAt).toFixed(1) });
460
+ let mode = normalizeToolMode(toolMode);
461
+ let session = null;
462
+ let sessionCreatePromise = null;
463
+ let currentCwd = cwd;
464
+ let sessionNeedsCwdRefresh = false;
465
+ // session_manage tool: reset request scheduled by the model mid-turn,
466
+ // consumed by the TUI engine at turn end ('clear' | 'compact_clear').
467
+ let pendingSessionReset = null;
468
+ let closeRequested = false;
469
+ const warmupTimers = {
470
+ providerSetupWarmupTimer: null,
471
+ providerWarmupTimer: null,
472
+ providerModelWarmupTimer: null,
473
+ modelCatalogWarmupTimer: null,
474
+ statuslineUsageWarmupTimer: null,
475
+ statuslineUsageRefreshTimer: null,
476
+ };
477
+ // Prewarm/channel-start timer handles + async state, owned here so the
478
+ // teardown clearTimeout sweep still sees them; the prewarm scheduler factory
479
+ // mutates these objects in place (see createPrewarmSchedulers).
480
+ const prewarmTimers = {
481
+ codeGraphPrewarmTimer: null,
482
+ channelStartTimer: null,
483
+ };
484
+ const prewarmState = {
485
+ codeGraphPrewarmInFlight: false,
486
+ codeGraphPrewarmQueuedCwd: '',
487
+ channelStartPromise: null,
488
+ };
489
+ let activeTurnCount = 0;
490
+ let firstTurnCompleted = false;
491
+ function hookTranscriptPath(sessionId) {
492
+ const id = clean(sessionId);
493
+ if (!id || !/^[A-Za-z0-9_-]+$/.test(id)) return null;
494
+ const dataDir = cfgMod.getPluginData?.() || STANDALONE_DATA_DIR;
495
+ return join(dataDir, 'sessions', `${id}.json`);
496
+ }
497
+ function hookEffortPayload() {
498
+ const level = clean(route.effectiveEffort || route.effort);
499
+ return level ? { level: level.toLowerCase() } : undefined;
500
+ }
501
+ function hookCommonPayload(extra = {}) {
502
+ const sid = clean(extra.session_id || extra.sessionId || session?.id);
503
+ return {
504
+ ...(sid ? { session_id: sid, transcript_path: hookTranscriptPath(sid) } : {}),
505
+ cwd: currentCwd,
506
+ permission_mode: session?.permissionMode || 'default',
507
+ ...(hookEffortPayload() ? { effort: hookEffortPayload() } : {}),
508
+ ...extra,
509
+ };
510
+ }
511
+ const sessionPrewarmDelayMs = envDelayMs('MIXDOG_SESSION_PREWARM_DELAY_MS', 50, { min: 0, max: 10_000 });
512
+ const providerSetupWarmupDelayMs = envDelayMs('MIXDOG_PROVIDER_SETUP_WARMUP_DELAY_MS', 300, { min: 0, max: 60_000 });
513
+ const modelCatalogWarmupDelayMs = envDelayMs('MIXDOG_MODEL_CATALOG_WARMUP_DELAY_MS', 200, { min: 0, max: 60_000 });
514
+ const providerWarmupDelayMs = envDelayMs('MIXDOG_PROVIDER_WARMUP_DELAY_MS', 1_500, { min: 0, max: 60_000 });
515
+ // Background model-catalog prefetch delay. Kept short so the first `/model`
516
+ // open finds a warm cache instead of paying a cold full network load. The
517
+ // work is async + unref'd, so short-lived detached runtimes still exit
518
+ // cleanly without waiting on it. Operators can raise it via env if a
519
+ // detached runtime must avoid the /models round-trip entirely.
520
+ const providerModelWarmupDelayMs = envDelayMs('MIXDOG_PROVIDER_MODEL_WARMUP_DELAY_MS', 2_000, { min: 0, max: 120_000 });
521
+ const codeGraphPrewarmDelayMs = envDelayMs('MIXDOG_CODE_GRAPH_PREWARM_DELAY_MS', 250, { min: 0, max: 60_000 });
522
+ const statuslineUsageWarmupDelayMs = envDelayMs('MIXDOG_STATUSLINE_USAGE_WARMUP_DELAY_MS', 800, { min: 0, max: 60_000 });
523
+ // Idle keep-alive: re-fetch usage before the statusline's 10-min staleness cut
524
+ // (LIVE_USAGE_SNAPSHOT_MAX_AGE_MS) so the usage segment does not disappear
525
+ // while the session sits idle with no turns to trigger a refresh.
526
+ const statuslineUsageRefreshDelayMs = envDelayMs('MIXDOG_STATUSLINE_USAGE_REFRESH_MS', 240_000, { min: 30_000, max: 540_000 });
527
+ const channelStartDelayMs = envDelayMs('MIXDOG_CHANNEL_START_DELAY_MS', 10_000, { min: 0, max: 120_000 });
528
+ const backgroundBusyRetryMs = envDelayMs('MIXDOG_BACKGROUND_BUSY_RETRY_MS', 1_000, { min: 50, max: 10_000 });
529
+ const sessionPrewarmEnabled = !envFlag('MIXDOG_DISABLE_SESSION_PREWARM')
530
+ && (envFlag('MIXDOG_ENABLE_SESSION_PREWARM') || envPresent('MIXDOG_SESSION_PREWARM_DELAY_MS'));
531
+ const providerWarmupEnabled = !envFlag('MIXDOG_DISABLE_PROVIDER_WARMUP')
532
+ && (
533
+ envFlag('MIXDOG_ENABLE_PROVIDER_WARMUP')
534
+ || envFlag('MIXDOG_PROVIDER_WARMUP_BEFORE_FIRST_TURN')
535
+ || envPresent('MIXDOG_PROVIDER_WARMUP_DELAY_MS')
536
+ || envPresent('MIXDOG_PROVIDER_MODEL_WARMUP_DELAY_MS')
537
+ );
538
+ // Boot-time model-catalog prefetch is intentionally decoupled from the
539
+ // heavier providerWarmupEnabled gate (which stays opt-in for provider
540
+ // *init* side effects). Fetching the model list in the background after a
541
+ // short delay is cheap, fire-and-forget, and unref'd, so it is ON by
542
+ // default — otherwise the FIRST `/model` open always paid a cold full
543
+ // network load. Operators can still disable it explicitly.
544
+ const modelPrefetchEnabled = !envFlag('MIXDOG_DISABLE_PROVIDER_WARMUP')
545
+ && !envFlag('MIXDOG_DISABLE_MODEL_PREFETCH');
546
+ const codeGraphPrewarmEnabled = !envFlag('MIXDOG_DISABLE_CODE_GRAPH_PREWARM');
547
+ const modelCatalogWarmupEnabled = !envFlag('MIXDOG_DISABLE_MODEL_CATALOG_WARMUP');
548
+ // Lazy code-graph prewarm (default ON): do NOT prewarm at startup / on cwd
549
+ // change — that fired ~250ms after the first frame and, in a large tree,
550
+ // burned a worker (and felt like a freeze) before the user did anything.
551
+ // Instead prewarm ONCE on the first real turn, when a code lookup is actually
552
+ // imminent. Operators who want the old eager behavior can set
553
+ // MIXDOG_CODE_GRAPH_PREWARM_EAGER=1.
554
+ const codeGraphPrewarmLazy = codeGraphPrewarmEnabled && !envFlag('MIXDOG_CODE_GRAPH_PREWARM_EAGER');
555
+ let codeGraphFirstTurnPrewarmDone = false;
556
+ const modelMetaByRoute = new Map();
557
+ const notificationListeners = new Set();
558
+ // Remote seat listeners (TUI): fired when remote mode flips outside a direct
559
+ // user action — currently only the superseded (seat stolen) path.
560
+ const remoteStateListeners = new Set();
561
+ function emitRemoteStateChange(enabled, reason = '') {
562
+ for (const listener of [...remoteStateListeners]) {
563
+ try { listener({ enabled: enabled === true, reason: String(reason || '') }); } catch {}
564
+ }
565
+ }
566
+ const providerModelCaches = {
567
+ providerModelsCache: { models: null, at: 0 },
568
+ providerModelsPromise: null,
569
+ providerModelsLoadSeq: 0,
570
+ searchProviderModelsCache: { models: null, at: 0 },
571
+ };
572
+ const providerUsageCaches = {
573
+ usageDashboardCache: { dashboard: null, at: 0 },
574
+ usageDashboardPromise: null,
575
+ providerSetupCache: { setup: null, at: 0 },
576
+ providerSetupQuickCache: { setup: null, at: 0 },
577
+ providerSetupPromise: null,
578
+ };
579
+ let providerInitPromise = null;
580
+ let lastProjectMcpKey = null;
581
+ // MCP connect state, owned here so teardown/reconnect paths still observe it;
582
+ // the mcp-glue factory mutates this object in place (see createMcpGlue).
583
+ const mcpState = {
584
+ mcpFailures: [],
585
+ mcpConnectGeneration: 0,
586
+ mcpConnectInFlight: null,
587
+ };
588
+ // MCP glue factory — config/currentCwd live-bound; connect state shared via
589
+ // the caller-owned mcpState object above.
590
+ const {
591
+ mcpTransportLabel,
592
+ resolveEffectiveMcpServers,
593
+ mcpStatus,
594
+ connectConfiguredMcp,
595
+ normalizeMcpServerInput,
596
+ } = createMcpGlue({
597
+ mcpClient,
598
+ getConfig: () => config,
599
+ getCurrentCwd: () => currentCwd,
600
+ state: mcpState,
601
+ });
602
+ let preSessionToolSurface = null;
603
+ const hooksStartedAt = performance.now();
604
+ const hooks = createStandaloneHookBus({ dataDir: cfgMod.getPluginData() });
605
+ hooks.emit('runtime:start', { cwd: currentCwd, provider: route.provider, model: route.model, toolMode: mode });
606
+ bootProfile('hooks:ready', { ms: (performance.now() - hooksStartedAt).toFixed(1) });
607
+
608
+ // ---------------------------------------------------------------------
609
+ // Self-update (npm registry version check + optional auto-install).
610
+ // updateCheckState mirrors the last-known checkLatestVersion() result;
611
+ // updateProcessState tracks the in-flight install lifecycle so the TUI can
612
+ // poll getUpdateStatus() instead of needing a push/event channel. Both are
613
+ // purely in-memory (per runtime instance) — the on-disk cache lives inside
614
+ // update-checker.mjs and is what actually enforces the 24h TTL.
615
+ let updateCheckState = {
616
+ currentVersion: null,
617
+ latestVersion: null,
618
+ updateAvailable: false,
619
+ lastCheckedAt: 0,
620
+ };
621
+ // phase: 'idle' | 'checking' | 'installing' | 'installed' | 'failed'
622
+ let updateProcessState = { phase: 'idle', version: null, error: null };
623
+
624
+ function autoUpdateEnabled() {
625
+ return config?.update?.auto !== false;
626
+ }
627
+
628
+ async function checkForUpdateInternal({ force = false } = {}) {
629
+ if (updateProcessState.phase !== 'installing') updateProcessState.phase = 'checking';
630
+ try {
631
+ const result = await checkLatestVersion({ force, dataDir: cfgMod.getPluginData?.() || STANDALONE_DATA_DIR });
632
+ updateCheckState = {
633
+ currentVersion: result.currentVersion,
634
+ latestVersion: result.latestVersion,
635
+ updateAvailable: result.updateAvailable,
636
+ lastCheckedAt: result.lastCheckedAt,
637
+ };
638
+ } catch {
639
+ // checkLatestVersion() is already silent-safe; this catch is belt-and-
640
+ // braces so a boot-time call can never crash the runtime.
641
+ } finally {
642
+ if (updateProcessState.phase === 'checking') updateProcessState.phase = 'idle';
643
+ }
644
+ return updateCheckState;
645
+ }
646
+
647
+ async function runUpdateNowInternal() {
648
+ if (updateProcessState.phase === 'installing') {
649
+ return { ...updateProcessState, alreadyInstalling: true, error: 'update already in progress' };
650
+ }
651
+ updateProcessState = { phase: 'installing', version: null, error: null };
652
+ try {
653
+ const result = await runGlobalUpdate();
654
+ if (result?.ok) {
655
+ updateProcessState = { phase: 'installed', version: result.version || null, error: null };
656
+ } else {
657
+ updateProcessState = { phase: 'failed', version: null, error: result?.error || 'update failed' };
658
+ }
659
+ } catch (err) {
660
+ updateProcessState = { phase: 'failed', version: null, error: err?.message || String(err) };
661
+ }
662
+ return updateProcessState;
663
+ }
664
+
665
+ // Non-blocking boot hook: fires after the runtime object below is fully
666
+ // constructed (setTimeout(0) defers past the synchronous return), so a
667
+ // slow/hanging registry request or npm install can never delay session
668
+ // boot. Auto-update defaults to ON unless config.update.auto is explicitly
669
+ // false; a failed check or install is
670
+ // swallowed — getUpdateStatus()/getUpdateSettings() are the only surfaces,
671
+ // there is no push notice channel from runtime -> TUI today.
672
+ // force:true — always hit the registry at boot (the 24h disk cache went
673
+ // stale-visible: it kept reporting an older "latest" than the installed
674
+ // version). checkLatestVersion() still falls back to the cache offline.
675
+ const updateBootTimer = setTimeout(() => {
676
+ void (async () => {
677
+ await checkForUpdateInternal({ force: true });
678
+ if (autoUpdateEnabled() && updateCheckState.updateAvailable) {
679
+ await runUpdateNowInternal();
680
+ }
681
+ })().catch(() => {});
682
+ }, 0);
683
+ updateBootTimer.unref?.();
684
+
685
+ function emitRuntimeNotification(content, meta = {}) {
686
+ const text = String(content || '').trim();
687
+ if (!text) return false;
688
+ const event = { content: text, meta: meta && typeof meta === 'object' ? meta : {} };
689
+ let handled = false;
690
+ for (const listener of [...notificationListeners]) {
691
+ try {
692
+ if (listener(event) === true) handled = true;
693
+ } catch {}
694
+ }
695
+ return handled;
696
+ }
697
+
698
+ function notifyFnForSession(callerSessionId) {
699
+ return (text, meta = {}) => {
700
+ const handledByRuntimeListener = emitRuntimeNotification(text, meta);
701
+ let enqueued = false;
702
+ // TUI sessions consume raw execution notifications for UI/task cards via
703
+ // onNotification, but those raw envelopes are internal-only in pending
704
+ // drain. Always mirror terminal completions with a model-visible wrapper
705
+ // while keeping the raw text for UI display.
706
+ if (callerSessionId && typeof mgr.enqueuePendingMessage === 'function'
707
+ && shouldPersistModelVisibleToolCompletion(text, meta)) {
708
+ try {
709
+ const visible = modelVisibleToolCompletionMessage(text, meta);
710
+ if (visible) enqueued = mgr.enqueuePendingMessage(callerSessionId, visible) > 0;
711
+ } catch {}
712
+ }
713
+ // Headless/API listeners may exist but not consume the event; preserve
714
+ // the old fallback for non-terminal notifications only when unhandled.
715
+ if (!enqueued && !handledByRuntimeListener && callerSessionId
716
+ && typeof mgr.enqueuePendingMessage === 'function') {
717
+ try {
718
+ const visible = modelVisibleToolCompletionMessage(text, meta);
719
+ if (visible) enqueued = mgr.enqueuePendingMessage(callerSessionId, visible) > 0;
720
+ } catch {}
721
+ }
722
+ return enqueued || handledByRuntimeListener;
723
+ };
724
+ }
725
+
726
+ function skillsStatus() {
727
+ const skills = typeof contextMod.collectSkillsCached === 'function'
728
+ ? contextMod.collectSkillsCached(currentCwd)
729
+ : [];
730
+ const norm = (value) => String(value || '').replace(/\\/g, '/').toLowerCase();
731
+ const cwdNorm = norm(currentCwd);
732
+ const sourceForSkill = (filePath) => {
733
+ const path = norm(filePath);
734
+ if (cwdNorm && path.startsWith(`${cwdNorm}/.mixdog/skills/`)) return 'project';
735
+ return 'skill';
736
+ };
737
+ return {
738
+ cwd: currentCwd,
739
+ count: skills.length,
740
+ skills: skills.map((skill) => ({
741
+ name: skill.name,
742
+ description: skill.description || '',
743
+ filePath: skill.filePath || null,
744
+ source: sourceForSkill(skill.filePath),
745
+ })),
746
+ };
747
+ }
748
+
749
+ // cwd resolution/apply + plugins-status + core-memory context. Extracted to
750
+ // session-runtime/cwd-plugins.mjs; the facade keeps ownership of the mutable
751
+ // currentCwd/session/config/lastProjectMcpKey locals via getter/setter
752
+ // injection and passes the later-defined callbacks (prewarm/tool-surface/
753
+ // memory) as closures.
754
+ const {
755
+ resolveCwdPath,
756
+ applyResolvedCwd,
757
+ refreshSessionForCwdIfNeeded,
758
+ pluginsStatus,
759
+ loadCoreMemoryContext,
760
+ } = createCwdPlugins({
761
+ getCurrentCwd: () => currentCwd,
762
+ setCurrentCwd: (next) => { currentCwd = next; },
763
+ getConfig: () => config,
764
+ getSession: () => session,
765
+ getRoute: () => route,
766
+ getLastProjectMcpKey: () => lastProjectMcpKey,
767
+ setLastProjectMcpKey: (next) => { lastProjectMcpKey = next; },
768
+ isCodeGraphPrewarmLazy: () => codeGraphPrewarmLazy,
769
+ isCodeGraphFirstTurnPrewarmDone: () => codeGraphFirstTurnPrewarmDone,
770
+ getCodeGraphPrewarmDelayMs: () => codeGraphPrewarmDelayMs,
771
+ setSessionNeedsCwdRefresh: (next) => { sessionNeedsCwdRefresh = next; },
772
+ connectConfiguredMcp,
773
+ invalidatePreSessionToolSurface: (...a) => invalidatePreSessionToolSurface(...a),
774
+ scheduleCodeGraphPrewarm: (...a) => scheduleCodeGraphPrewarm(...a),
775
+ hooks,
776
+ hookCommonPayload: (...a) => hookCommonPayload(...a),
777
+ bootProfile,
778
+ getMemoryModule: (...a) => getMemoryModule(...a),
779
+ listRegisteredPlugins,
780
+ pluginAdminStatus,
781
+ pluginManifest,
782
+ pluginMcpServerName,
783
+ mcpScriptForPlugin,
784
+ countSkillFiles,
785
+ readProjectMcpServers,
786
+ writeLastSessionCwd,
787
+ clean,
788
+ resolve,
789
+ statSync,
790
+ existsSync,
791
+ cfgMod,
792
+ STANDALONE_DATA_DIR,
793
+ });
794
+
795
+ function skillContent(name) {
796
+ const res = typeof contextMod.loadSkillResource === 'function'
797
+ ? contextMod.loadSkillResource(name, currentCwd)
798
+ : null;
799
+ if (!res) throw new Error(`skill not found: ${name}`);
800
+ return { name, content: res.content, dir: res.dir };
801
+ }
802
+
803
+ function skillToolContent(name) {
804
+ if (typeof contextMod.isSkillDisabled === 'function' && contextMod.isSkillDisabled(name)) {
805
+ const label = String(name || '').trim() || 'skill';
806
+ return `Error: skill "${label}" is disabled`;
807
+ }
808
+ const skill = skillContent(name);
809
+ // Return the general tool envelope so the main/Lead session behaves the
810
+ // same as agent-loop sessions: the model-visible tool_result is the short
811
+ // stub (`Loaded skill: <name>`) and the full SKILL.md body is delivered
812
+ // ONCE as a separate injected role:'user' message (newMessages). The
813
+ // envelope passes through internal-tools._normalize untouched (it preserves
814
+ // __toolEnvelope objects), and the agent loop's central normalizeToolEnvelope
815
+ // splits it into stub + injected user body.
816
+ return contextMod.buildSkillToolEnvelope(skill.name, skill.content, skill.dir);
817
+ }
818
+
819
+ function addProjectSkill(input = {}) {
820
+ const name = clean(input.name).replace(/[^a-zA-Z0-9_.-]+/g, '-').replace(/^-+|-+$/g, '');
821
+ if (!name) throw new Error('skill name is required');
822
+ const dir = join(currentCwd, '.mixdog', 'skills', name);
823
+ const filePath = join(dir, 'SKILL.md');
824
+ if (existsSync(filePath)) throw new Error(`skill already exists: ${name}`);
825
+ const description = clean(input.description) || 'Project skill.';
826
+ mkdirSync(dir, { recursive: true });
827
+ writeFileSync(filePath, [
828
+ '---',
829
+ `name: ${name}`,
830
+ `description: ${description}`,
831
+ '---',
832
+ '',
833
+ '# Instructions',
834
+ '',
835
+ 'Describe when and how to use this skill.',
836
+ '',
837
+ ].join('\n'), 'utf8');
838
+ return { name, filePath };
839
+ }
840
+
841
+ const agentToolStartedAt = performance.now();
842
+ const agentTool = createStandaloneAgent({
843
+ cfgMod,
844
+ reg,
845
+ mgr,
846
+ dataDir: cfgMod.getPluginData(),
847
+ cwd,
848
+ // SubagentStart/SubagentStop: bridge internal worker spawn/finish to the
849
+ // standard hook bus. agent_type is passed top-level via hookCommonPayload
850
+ // (added to hook-bus buildEventPayload passthrough). Best-effort.
851
+ onSubagentEvent: (phase, info = {}) => {
852
+ try {
853
+ const event = phase === 'stop' ? 'SubagentStop' : 'SubagentStart';
854
+ void hooks.dispatch(event, hookCommonPayload({
855
+ session_id: info?.session_id || null,
856
+ agent_type: info?.agent_type || null,
857
+ }));
858
+ } catch { /* best-effort: subagent hook must never affect worker lifecycle */ }
859
+ },
860
+ });
861
+ bootProfile('agent:ready', { ms: (performance.now() - agentToolStartedAt).toFixed(1) });
862
+ const agentStatusState = () => {
863
+ try {
864
+ const status = agentTool.getStatus?.({ clientHostPid: session?.clientHostPid || process.pid }) || {};
865
+ return {
866
+ agentWorkers: Array.isArray(status.workers) ? status.workers : [],
867
+ agentJobs: Array.isArray(status.jobs) ? status.jobs : [],
868
+ agentScope: status.scope || null,
869
+ };
870
+ } catch {
871
+ return { agentWorkers: [], agentJobs: [], agentScope: null };
872
+ }
873
+ };
874
+ const channelsStartedAt = performance.now();
875
+ const channels = createStandaloneChannelWorker({
876
+ entry: join(__dirname, CHANNEL_WORKER_ENTRY),
877
+ rootDir: STANDALONE_ROOT,
878
+ dataDir: cfgMod.getPluginData(),
879
+ cwd,
880
+ onNotify: (msg) => {
881
+ // Single-holder remote: the worker reports it lost the bridge seat to a
882
+ // newer remote session. Drop remote mode entirely on this session (no
883
+ // handover, no retry) and tell UI listeners so the indicator updates.
884
+ if (msg?.method === 'notifications/mixdog/remote') {
885
+ if (msg?.params?.state === 'superseded' && remoteEnabled) {
886
+ stopRemote('superseded-by-newer-remote-session');
887
+ emitRemoteStateChange(false, 'superseded');
888
+ }
889
+ // Symmetric acquire: the worker took the bridge seat (boot make-before-
890
+ // break or activate). Flip remote ON via the same side-state a user
891
+ // /remote toggles — remoteEnabled + transcript writer — but WITHOUT
892
+ // re-invoking channel start (the worker is already running; startRemote
893
+ // would re-fork/activate). Idempotent: no-op when already enabled.
894
+ if (msg?.params?.state === 'acquired' && !remoteEnabled) {
895
+ remoteEnabled = true;
896
+ ensureRemoteTranscriptWriter();
897
+ emitRemoteStateChange(true, 'acquired');
898
+ }
899
+ return;
900
+ }
901
+ if (msg?.method !== 'notifications/claude/channel') return;
902
+ const params = msg?.params && typeof msg.params === 'object' ? msg.params : {};
903
+ const meta = params.meta && typeof params.meta === 'object' ? params.meta : {};
904
+ const content = channelNotificationModelContent(params);
905
+ if (!content) return;
906
+ const handled = emitRuntimeNotification(content, meta);
907
+ if (!handled && session?.id && shouldMirrorChannelNotificationToPending(meta)) {
908
+ try { mgr.enqueuePendingMessage(session.id, content); } catch {}
909
+ }
910
+ },
911
+ });
912
+ bootProfile('channels:worker-ready', { ms: (performance.now() - channelsStartedAt).toFixed(1) });
913
+ const toolsStartedAt = performance.now();
914
+ const standaloneTools = [
915
+ TOOL_SEARCH_TOOL,
916
+ SKILL_TOOL,
917
+ CWD_TOOL,
918
+ SESSION_MANAGE_TOOL,
919
+ EXPLORE_TOOL,
920
+ ...(searchToolDefs?.TOOL_DEFS || []).filter((tool) => tool?.name === 'search' || tool?.name === 'web_fetch'),
921
+ ...(memoryToolDefs?.TOOL_DEFS || []).filter((tool) => tool?.name === 'recall' || tool?.name === 'memory'),
922
+ ...(channelToolDefs?.TOOL_DEFS || []).filter((tool) => channels.isChannelTool(tool?.name)),
923
+ ...(codeGraphToolDefs?.CODE_GRAPH_TOOL_DEFS || []).filter((tool) => tool?.name === 'code_graph'),
924
+ ...agentTool.tools,
925
+ ].map(applyStandaloneToolDefaults);
926
+ bootProfile('tools:ready', { ms: (performance.now() - toolsStartedAt).toFixed(1), count: standaloneTools.length });
927
+
928
+ function invalidatePreSessionToolSurface() {
929
+ preSessionToolSurface = null;
930
+ }
931
+
932
+ const { contextStatus: computeContextStatus, invalidateContextStatusCache } = createContextStatus({
933
+ getSession: () => session,
934
+ getRoute: () => route,
935
+ getCurrentCwd: () => currentCwd,
936
+ getMode: () => mode,
937
+ });
938
+
939
+ function buildPreSessionToolSurface() {
940
+ const previewTools = typeof mgr.previewSessionTools === 'function'
941
+ ? mgr.previewSessionTools(toolSpecForMode(mode), [])
942
+ : [];
943
+ const tools = filterDisallowedTools(previewTools, LEAD_DISALLOWED_TOOLS);
944
+ const surface = { tools: Array.isArray(tools) ? tools.slice() : [] };
945
+ applyDeferredToolSurface(surface, deferredSurfaceModeForLead(mode), standaloneTools, { provider: route.provider });
946
+ return surface;
947
+ }
948
+
949
+ function activeToolSurface() {
950
+ if (session) return session;
951
+ preSessionToolSurface ??= buildPreSessionToolSurface();
952
+ return preSessionToolSurface;
953
+ }
954
+
955
+ function applyPreSessionToolSelection() {
956
+ if (!session || !preSessionToolSurface) return;
957
+ const selected = Array.isArray(preSessionToolSurface.deferredSelectedTools)
958
+ ? preSessionToolSurface.deferredSelectedTools
959
+ : [];
960
+ const discovered = Array.isArray(preSessionToolSurface.deferredDiscoveredTools)
961
+ ? preSessionToolSurface.deferredDiscoveredTools
962
+ : [];
963
+ const replay = [...new Set([...selected, ...discovered])];
964
+ if (replay.length) selectDeferredTools(session, replay, deferredSurfaceModeForLead(mode));
965
+ }
966
+ internalTools.setInternalToolsProvider({
967
+ tools: standaloneTools,
968
+ executor: async (name, args, callerCtx = {}) => {
969
+ const callerCwd = callerCtx?.callerCwd || currentCwd;
970
+ if (name === 'search' || name === 'web_fetch') {
971
+ const callerSessionId = callerCtx?.callerSessionId || session?.id || null;
972
+ const searchMod = await getSearchModule();
973
+ if (!searchMod?.handleToolCall) throw new Error('search runtime is not available');
974
+ return await searchMod.handleToolCall(name, args || {}, {
975
+ callerCwd,
976
+ callerSessionId,
977
+ routingSessionId: callerSessionId,
978
+ clientHostPid: callerCtx?.clientHostPid || session?.clientHostPid || process.pid,
979
+ notifyFn: notifyFnForSession(callerSessionId),
980
+ nativeSearch: name === 'search'
981
+ ? async (searchArgs) => runNativeWebSearch(searchArgs, { signal: callerCtx?.signal || session?.controller?.signal })
982
+ : undefined,
983
+ });
984
+ }
985
+ if (name === 'recall' || name === 'memory' || name === 'search_memories') {
986
+ const memoryMod = await getMemoryModule();
987
+ if (!memoryMod?.handleToolCall) throw new Error('memory runtime is not available');
988
+ return await memoryMod.handleToolCall(name, args || {});
989
+ }
990
+ if (name === 'code_graph') {
991
+ const codeGraphMod = await getCodeGraphModule();
992
+ if (!codeGraphMod?.executeCodeGraphTool) throw new Error('code_graph runtime is not available');
993
+ return await codeGraphMod.executeCodeGraphTool(name, args || {}, args?.cwd || callerCwd);
994
+ }
995
+ if (name === 'tool_search') {
996
+ return renderToolSearch(args, activeToolSurface(), mode);
997
+ }
998
+ if (name === 'explore') {
999
+ const callerSessionId = callerCtx?.callerSessionId || session?.id || null;
1000
+ return await runExplore(args || {}, {
1001
+ callerCwd: args?.cwd ? resolveCwdPath(args.cwd) : callerCwd,
1002
+ callerSessionId,
1003
+ routingSessionId: callerSessionId,
1004
+ clientHostPid: callerCtx?.clientHostPid || session?.clientHostPid || process.pid,
1005
+ notifyFn: notifyFnForSession(callerSessionId),
1006
+ });
1007
+ }
1008
+ if (name === 'cwd') {
1009
+ const action = clean(args?.action || (args?.path ? 'set' : 'get')).toLowerCase();
1010
+ if (action === 'set') {
1011
+ applyResolvedCwd(resolveCwdPath(args?.path));
1012
+ } else if (action !== 'get') {
1013
+ throw new Error(`cwd: unknown action "${action}"`);
1014
+ }
1015
+ return JSON.stringify({ cwd: currentCwd, sessionId: session?.id || null }, null, 2);
1016
+ }
1017
+ if (name === 'session_manage') {
1018
+ // Lead/owner sessions only: an agent worker resetting its own
1019
+ // transcript mid-task would corrupt the delegation contract, and it
1020
+ // must never reach the owner conversation either.
1021
+ const callerSessionId = callerCtx?.callerSessionId || null;
1022
+ if (callerSessionId && session?.id && callerSessionId !== session.id) {
1023
+ throw new Error('session_manage: only the lead session may reset the conversation');
1024
+ }
1025
+ if (!session?.id) throw new Error('session_manage: no active session');
1026
+ const action = clean(args?.action).toLowerCase();
1027
+ if (action !== 'clear' && action !== 'compact_clear') {
1028
+ throw new Error(`session_manage: unknown action "${action}" (use clear | compact_clear)`);
1029
+ }
1030
+ // Never clear mid-turn — the loop is still reading the transcript.
1031
+ // Schedule and let the TUI engine consume it at turn end (same
1032
+ // boundary the idle auto-clear uses).
1033
+ // Pin to the current session id so a resume/new-session between
1034
+ // scheduling and consumption can never clear the wrong conversation.
1035
+ pendingSessionReset = { action, sessionId: session.id };
1036
+ return action === 'clear'
1037
+ ? 'Session reset scheduled: full clear will run when this turn ends. All prior context will be gone.'
1038
+ : 'Session reset scheduled: the conversation will be summarized (compact) and cleared when this turn ends; key context carries forward in the summary.';
1039
+ }
1040
+ if (name === 'Skill') {
1041
+ return skillToolContent(args?.name);
1042
+ }
1043
+ if (name === 'agent') {
1044
+ const callerSessionId = callerCtx?.callerSessionId || session?.id || null;
1045
+ return await agentTool.execute(args, {
1046
+ callerCwd,
1047
+ invocationSource: 'model-tool',
1048
+ callerSessionId,
1049
+ clientHostPid: callerCtx?.clientHostPid || session?.clientHostPid || process.pid,
1050
+ signal: callerCtx?.signal,
1051
+ notifyFn: notifyFnForSession(callerSessionId),
1052
+ });
1053
+ }
1054
+ if (channels.isChannelTool(name)) {
1055
+ if (!channelsEnabled()) throw new Error('channels are disabled in settings');
1056
+ return await channels.execute(name, args || {});
1057
+ }
1058
+ throw new Error(`unknown standalone internal tool: ${name}`);
1059
+ },
1060
+ });
1061
+ internalTools.markBootReady?.();
1062
+ try { lastProjectMcpKey = resolve(currentCwd) + '\u0000' + JSON.stringify(readProjectMcpServers(currentCwd)); } catch { lastProjectMcpKey = null; }
1063
+ void connectConfiguredMcp()
1064
+ .then((status) => bootProfile('mcp:ready', {
1065
+ connected: Number(status?.connectedCount || 0),
1066
+ failed: Number(status?.failedCount || 0),
1067
+ }))
1068
+ .catch((error) => bootProfile('mcp:failed', { error: error?.message || String(error) }));
1069
+
1070
+ function reloadChannelsSoon() {
1071
+ channels.execute('reload_config', {}).catch(() => {});
1072
+ }
1073
+
1074
+ function invalidateProviderCaches() {
1075
+ providerModelCaches.providerModelsCache = { models: null, at: 0 };
1076
+ providerModelCaches.providerModelsPromise = null;
1077
+ providerModelCaches.providerModelsLoadSeq += 1;
1078
+ providerModelCaches.searchProviderModelsCache = { models: null, at: 0 };
1079
+ providerUsageCaches.usageDashboardCache = { dashboard: null, at: 0 };
1080
+ providerUsageCaches.usageDashboardPromise = null;
1081
+ providerUsageCaches.providerSetupCache = { setup: null, at: 0 };
1082
+ providerUsageCaches.providerSetupQuickCache = { setup: null, at: 0 };
1083
+ providerUsageCaches.providerSetupPromise = null;
1084
+ providerInitPromise = null;
1085
+ modelMetaByRoute.clear();
1086
+ }
1087
+
1088
+ // Config reload/save/adopt family + output-style status cache. Extracted to
1089
+ // session-runtime/config-lifecycle.mjs; the facade retains ownership of the
1090
+ // config/searchRoute/configHasSecrets mutable locals via getter/setter
1091
+ // injection (the proven mutable-state pattern).
1092
+ const {
1093
+ getOutputStyleStatusCached,
1094
+ invalidateOutputStyleStatusCache,
1095
+ seedOutputStyleStatusCache,
1096
+ adoptConfig,
1097
+ saveConfigAndAdopt,
1098
+ flushConfigSave,
1099
+ flushBackendSave,
1100
+ scheduleBackendSave,
1101
+ flushOutputStyleSave,
1102
+ scheduleOutputStyleSave,
1103
+ reloadFullConfig,
1104
+ ensureFullConfig,
1105
+ displayConfig,
1106
+ ensureConfigForRouteProvider,
1107
+ } = createConfigLifecycle({
1108
+ getConfig: () => config,
1109
+ setConfig: (next) => { config = next; },
1110
+ getSearchRoute: () => searchRoute,
1111
+ setSearchRoute: (next) => { searchRoute = next; },
1112
+ getConfigHasSecrets: () => configHasSecrets,
1113
+ setConfigHasSecrets: (next) => { configHasSecrets = next; },
1114
+ getRoute: () => route,
1115
+ cfgMod,
1116
+ sharedCfgMod,
1117
+ setBackend,
1118
+ setConfiguredShell,
1119
+ normalizeSystemShellConfig,
1120
+ normalizeSearchRouteConfig,
1121
+ outputStyleStatus,
1122
+ LAZY_SECRET_PROVIDERS,
1123
+ clean,
1124
+ resolve,
1125
+ STANDALONE_DATA_DIR,
1126
+ });
1127
+
1128
+ async function ensureProvidersReady(providerConfig = config.providers || {}) {
1129
+ if (providerInitPromise) return await providerInitPromise;
1130
+ providerInitPromise = reg.initProviders(providerConfig)
1131
+ .finally(() => {
1132
+ providerInitPromise = null;
1133
+ });
1134
+ return await providerInitPromise;
1135
+ }
1136
+
1137
+ const {
1138
+ currentMainSearchModelMeta,
1139
+ runNativeWebSearch,
1140
+ } = createNativeSearch({
1141
+ getRoute: () => route,
1142
+ getSearchRoute: () => searchRoute,
1143
+ setSearchRoute: (next) => { searchRoute = next; },
1144
+ getConfig: () => config,
1145
+ getSession: () => session,
1146
+ getReg: () => reg,
1147
+ ensureFullConfig,
1148
+ ensureProvidersReady,
1149
+ ensureProviderEnabled,
1150
+ normalizeSearchProviderId,
1151
+ normalizeSearchRouteConfig,
1152
+ isDefaultSearchRouteConfig,
1153
+ isSearchCapableProvider,
1154
+ searchCapableFor,
1155
+ });
1156
+
1157
+ // Late-bound: createWarmupSchedulers is constructed after this factory, but
1158
+ // cachedProviderSetup(quick) may nudge scheduleProviderSetupWarmup on a cold
1159
+ // quick-cache fill. Thread it by reference so the scheduler is reachable once
1160
+ // it exists (a pre-scheduler quick fill simply skips the warmup nudge).
1161
+ let scheduleProviderSetupWarmupRef = () => {};
1162
+ const {
1163
+ refreshStatuslineUsageSnapshot,
1164
+ cachedProviderSetup,
1165
+ getUsageDashboard,
1166
+ } = createProviderUsage({
1167
+ caches: providerUsageCaches,
1168
+ getConfig: () => config,
1169
+ getReg: () => reg,
1170
+ displayConfig,
1171
+ providerSetup,
1172
+ createUsageDashboard,
1173
+ fetchOAuthUsageSnapshot,
1174
+ isCloseRequested: () => closeRequested,
1175
+ getProviderSetupWarmupTimer: () => warmupTimers.providerSetupWarmupTimer,
1176
+ scheduleProviderSetupWarmup: (delayMs) => scheduleProviderSetupWarmupRef(delayMs),
1177
+ });
1178
+
1179
+ // Holder filled after createQuickModelRows resolves; provider-models and
1180
+ // quick-model-rows are mutually dependent (rows need cache-row helpers, the
1181
+ // model factory needs quick fallbacks) so we thread the quick surface in by
1182
+ // reference after both are constructed.
1183
+ const providerModelQuickHelpers = {};
1184
+ // Late-bound: createWarmupSchedulers is constructed after this factory, but
1185
+ // lookupModelMeta may fire scheduleProviderModelWarmup on a cache miss. Thread
1186
+ // it by reference so the scheduler is called once it exists (miss handling is
1187
+ // best-effort; a pre-scheduler miss simply skips the warmup nudge).
1188
+ let scheduleProviderModelWarmupRef = () => {};
1189
+ const {
1190
+ modelMetaKey,
1191
+ lookupModelMeta,
1192
+ sortProviderModels,
1193
+ providerModelCacheRow,
1194
+ providerModelsFromCacheRows,
1195
+ collectSearchProviderModels,
1196
+ collectProviderModels,
1197
+ warmProviderModelCache,
1198
+ } = createProviderModels({
1199
+ caches: providerModelCaches,
1200
+ modelMetaByRoute,
1201
+ getRoute: () => route,
1202
+ getConfig: () => config,
1203
+ getReg: () => reg,
1204
+ searchCapableFor,
1205
+ sortProviderModelsRaw,
1206
+ providerModelCacheRowRaw,
1207
+ normalizeSearchProviderId,
1208
+ isSearchCapableProvider,
1209
+ ensureFullConfig,
1210
+ ensureProvidersReady,
1211
+ bootProfile,
1212
+ scheduleProviderModelWarmup: () => scheduleProviderModelWarmupRef(),
1213
+ quickHelpers: providerModelQuickHelpers,
1214
+ });
1215
+
1216
+ const {
1217
+ quickProviderModelRows,
1218
+ addDefaultSearchModel,
1219
+ quickSearchProviderModelRows,
1220
+ searchModelsFromRows,
1221
+ searchRowsWithDefault,
1222
+ } = createQuickModelRows({
1223
+ getRoute: () => route,
1224
+ getSearchRoute: () => searchRoute,
1225
+ displayConfig,
1226
+ providerModelCacheRow,
1227
+ providerModelsFromCacheRows,
1228
+ sortProviderModels,
1229
+ modelMetaByRoute,
1230
+ modelMetaKey,
1231
+ normalizeSearchProviderId,
1232
+ normalizeSearchRouteConfig,
1233
+ isSearchCapableProvider,
1234
+ searchCapableFor,
1235
+ currentMainSearchModelMeta,
1236
+ });
1237
+ Object.assign(providerModelQuickHelpers, {
1238
+ quickProviderModelRows,
1239
+ addDefaultSearchModel,
1240
+ quickSearchProviderModelRows,
1241
+ searchModelsFromRows,
1242
+ searchRowsWithDefault,
1243
+ });
1244
+
1245
+ async function resolveMissingRouteModelForFirstTurn() {
1246
+ if (routeHasModel()) return route;
1247
+ const models = await collectProviderModels();
1248
+ const picked = models[0] || null;
1249
+ if (!picked) {
1250
+ throw new Error('No provider models available. Open /providers to sign in, then /model to choose a model.');
1251
+ }
1252
+ route = {
1253
+ ...route,
1254
+ provider: picked.provider,
1255
+ model: picked.id,
1256
+ preset: null,
1257
+ };
1258
+ return route;
1259
+ }
1260
+
1261
+ async function refreshRouteEffort(modelMetaOverride = null) {
1262
+ await ensureProvidersReady(ensureProviderEnabled(config, route.provider));
1263
+ const modelMeta = modelMetaOverride || await lookupModelMeta(route.provider, route.model);
1264
+ const requested = hasOwn(route, 'effort') ? route.effort : (route.preset?.effort || null);
1265
+ const effectiveEffort = coerceEffortFor(route.provider, modelMeta, requested);
1266
+ const fastCapable = fastCapableFor(route.provider, modelMeta);
1267
+ // Carry the catalog display name onto the route so the statusline shows a
1268
+ // human label (e.g. "Claude Fable 5") for preset-less direct models instead
1269
+ // of the raw id. `name` is only trusted when it differs from the raw model
1270
+ // id (some providers echo the id as `name`), so it can't clobber a better
1271
+ // already-resolved label. Falls back to existing route.modelDisplay, then unset.
1272
+ const metaName = clean(modelMeta?.name);
1273
+ const modelDisplay = clean(modelMeta?.display) || clean(modelMeta?.displayName)
1274
+ || (metaName && metaName !== clean(route.model) ? metaName : '')
1275
+ || clean(route.modelDisplay);
1276
+ route = {
1277
+ ...route,
1278
+ fast: fastCapable ? route.fast === true : false,
1279
+ fastCapable,
1280
+ effectiveEffort,
1281
+ effortOptions: effortItemsFor(route.provider, modelMeta, effectiveEffort),
1282
+ ...(modelDisplay ? { modelDisplay } : {}),
1283
+ };
1284
+ return route;
1285
+ }
1286
+
1287
+ function routeHasModel() {
1288
+ return !!clean(route?.model);
1289
+ }
1290
+
1291
+ function requireModelRoute() {
1292
+ if (routeHasModel()) return;
1293
+ throw new Error('No model configured. Open /providers to sign in, then /model to choose a model.');
1294
+ }
1295
+
1296
+ async function recreateCurrentSessionIfReady() {
1297
+ if (!routeHasModel()) {
1298
+ session = null;
1299
+ return null;
1300
+ }
1301
+ return await createCurrentSession();
1302
+ }
1303
+
1304
+ async function createCurrentSession(reason = 'demand') {
1305
+ if (sessionCreatePromise) return await sessionCreatePromise;
1306
+ if (session?.id && !sessionNeedsCwdRefresh) {
1307
+ const liveSession = mgr.getSession(session.id);
1308
+ if (liveSession && liveSession.closed !== true && liveSession.status !== 'closed') {
1309
+ session = liveSession;
1310
+ return session;
1311
+ }
1312
+ session = null;
1313
+ }
1314
+
1315
+ const startedAt = performance.now();
1316
+ bootProfile('session:create:start', { mode, reason });
1317
+ const promise = (async () => {
1318
+ ensureConfigForRouteProvider();
1319
+ await resolveMissingRouteModelForFirstTurn();
1320
+ requireModelRoute();
1321
+ bootProfile('session:create:route-ready', { ms: (performance.now() - startedAt).toFixed(1) });
1322
+ // refreshRouteEffort (effort/model-meta) and loadCoreMemoryContext (memory
1323
+ // files) are independent — refreshRouteEffort only touches route effort/
1324
+ // display fields, never provider/model that the memory load reads — so run
1325
+ // them concurrently instead of serially on the boot path.
1326
+ const [, coreMemoryContext] = await Promise.all([
1327
+ refreshRouteEffort(),
1328
+ loadCoreMemoryContext(),
1329
+ ]);
1330
+ bootProfile('session:create:effort-ready', { ms: (performance.now() - startedAt).toFixed(1) });
1331
+ const providerImpl = reg.getProvider(route.provider);
1332
+ if (!providerImpl) {
1333
+ throw new Error(`Provider "${route.provider}" is not configured.`);
1334
+ }
1335
+ bootProfile('session:create:provider-ready', { ms: (performance.now() - startedAt).toFixed(1) });
1336
+ if (closeRequested) throw new Error('runtime is closing');
1337
+ const dataDir = cfgMod.getPluginData?.() || STANDALONE_DATA_DIR;
1338
+ // Load the active WORKFLOW.md pack once for both summary + context block.
1339
+ const { summary: workflow, context: workflowContext } = activeWorkflowContext(config, dataDir);
1340
+ const sessionOpts = {
1341
+ provider: route.provider,
1342
+ model: route.model,
1343
+ preset: route.preset || undefined,
1344
+ tools: toolSpecForMode(mode),
1345
+ owner: 'cli',
1346
+ agent: 'lead',
1347
+ lane: 'cli',
1348
+ sourceType: 'lead',
1349
+ sourceName: 'main',
1350
+ clientHostPid: process.pid,
1351
+ disallowedTools: LEAD_DISALLOWED_TOOLS,
1352
+ cwd: currentCwd,
1353
+ coreMemoryContext,
1354
+ workflow,
1355
+ workflowContext,
1356
+ fast: route.fast === true,
1357
+ compaction: config.compaction && typeof config.compaction === 'object'
1358
+ ? normalizeCompactionConfig(config.compaction, { memoryEnabled: memoryEnabled() })
1359
+ : undefined,
1360
+ };
1361
+ if (hasOwn(route, 'effort') || route.effectiveEffort) {
1362
+ sessionOpts.effort = route.effectiveEffort || null;
1363
+ }
1364
+ session = mgr.createSession(sessionOpts);
1365
+ sessionNeedsCwdRefresh = false;
1366
+ attachSessionHooks(session, { hooks, hookCommonPayload, getCwd: () => currentCwd });
1367
+ applyDeferredToolSurface(session, deferredSurfaceModeForLead(mode), standaloneTools, { provider: route.provider });
1368
+ applyPreSessionToolSelection();
1369
+ writeStatuslineRoute(statusRoutes, session, route);
1370
+ hooks.emit('session:create', { sessionId: session.id, provider: route.provider, model: route.model, toolMode: mode, cwd: currentCwd });
1371
+ // SessionStart: bridge to the standard project hook bus. Best-effort;
1372
+ // a hook error must never break session creation. additionalContext is
1373
+ // injected before the first user turn as a system-reminder context pair.
1374
+ try {
1375
+ const startSource = /resume/i.test(String(reason || ''))
1376
+ ? 'resume'
1377
+ : (/clear/i.test(String(reason || '')) ? 'clear' : 'startup');
1378
+ const startDispatch = await hooks.dispatch('SessionStart', hookCommonPayload({ session_id: session.id, source: startSource, model: route.model }));
1379
+ const startContext = Array.isArray(startDispatch?.additionalContext)
1380
+ ? startDispatch.additionalContext.join('\n\n')
1381
+ : String(startDispatch?.additionalContext || '');
1382
+ if (startContext.trim()) {
1383
+ session.messages.push({ role: 'user', content: `<system-reminder>\n# SessionStart Hook Context\n${startContext.trim()}\n</system-reminder>` });
1384
+ session.messages.push({ role: 'assistant', content: '.' });
1385
+ session.updatedAt = Date.now();
1386
+ }
1387
+ } catch { /* best-effort: never break session create */ }
1388
+ bootProfile('session:create:ready', {
1389
+ ms: (performance.now() - startedAt).toFixed(1),
1390
+ reason,
1391
+ tools: Array.isArray(session.tools) ? session.tools.length : 0,
1392
+ catalog: Array.isArray(session.deferredToolCatalog) ? session.deferredToolCatalog.length : 0,
1393
+ });
1394
+ return session;
1395
+ })();
1396
+
1397
+ sessionCreatePromise = promise;
1398
+ try {
1399
+ return await promise;
1400
+ } finally {
1401
+ if (sessionCreatePromise === promise) sessionCreatePromise = null;
1402
+ }
1403
+ }
1404
+
1405
+ const {
1406
+ scheduleProviderWarmup,
1407
+ scheduleProviderSetupWarmup,
1408
+ scheduleProviderModelWarmup,
1409
+ scheduleModelCatalogWarmup,
1410
+ scheduleStatuslineUsageWarmup,
1411
+ scheduleStatuslineUsageRefresh,
1412
+ } = createWarmupSchedulers({
1413
+ timers: warmupTimers,
1414
+ bootProfile,
1415
+ getRoute: () => route,
1416
+ getConfig: () => config,
1417
+ isCloseRequested: () => closeRequested,
1418
+ getActiveTurnCount: () => activeTurnCount,
1419
+ getSessionCreatePromise: () => sessionCreatePromise,
1420
+ getProviderModelsCache: () => providerModelCaches.providerModelsCache,
1421
+ getProviderModelsPromise: () => providerModelCaches.providerModelsPromise,
1422
+ reloadFullConfig,
1423
+ ensureConfigForRouteProvider,
1424
+ ensureProvidersReady,
1425
+ ensureProviderEnabled,
1426
+ refreshStatuslineUsageSnapshot,
1427
+ warmProviderModelCache,
1428
+ cachedProviderSetup,
1429
+ warmCatalogsInBackground,
1430
+ isFirstTurnCompleted: () => firstTurnCompleted,
1431
+ envFlag,
1432
+ delays: {
1433
+ providerWarmupDelayMs,
1434
+ providerSetupWarmupDelayMs,
1435
+ providerModelWarmupDelayMs,
1436
+ modelCatalogWarmupDelayMs,
1437
+ statuslineUsageWarmupDelayMs,
1438
+ statuslineUsageRefreshDelayMs,
1439
+ backgroundBusyRetryMs,
1440
+ },
1441
+ flags: {
1442
+ providerWarmupEnabled,
1443
+ modelPrefetchEnabled,
1444
+ modelCatalogWarmupEnabled,
1445
+ },
1446
+ });
1447
+ scheduleProviderModelWarmupRef = scheduleProviderModelWarmup;
1448
+ scheduleProviderSetupWarmupRef = scheduleProviderSetupWarmup;
1449
+
1450
+ const {
1451
+ scheduleCodeGraphPrewarm,
1452
+ scheduleLeadSessionPrewarm,
1453
+ invokeChannelStart,
1454
+ scheduleChannelStart,
1455
+ } = createPrewarmSchedulers({
1456
+ timers: prewarmTimers,
1457
+ bootProfile,
1458
+ getCurrentCwd: () => currentCwd,
1459
+ isCloseRequested: () => closeRequested,
1460
+ getActiveTurnCount: () => activeTurnCount,
1461
+ getSessionCreatePromise: () => sessionCreatePromise,
1462
+ getSession: () => session,
1463
+ isRemoteEnabled: () => remoteEnabled,
1464
+ channelsEnabled,
1465
+ getCodeGraphModule,
1466
+ createCurrentSession,
1467
+ channels,
1468
+ envFlag,
1469
+ delays: {
1470
+ codeGraphPrewarmDelayMs,
1471
+ channelStartDelayMs,
1472
+ sessionPrewarmDelayMs,
1473
+ backgroundBusyRetryMs,
1474
+ },
1475
+ flags: {
1476
+ codeGraphPrewarmEnabled,
1477
+ sessionPrewarmEnabled,
1478
+ },
1479
+ state: prewarmState,
1480
+ });
1481
+
1482
+ // Eagerly create/refresh the remote transcript writer for the CURRENT
1483
+ // session + cwd, publish the session record, and ensure the transcript
1484
+ // file exists on disk. Called from startRemote() (so the channel worker's
1485
+ // activate-time discovery finds THIS session immediately instead of
1486
+ // waiting for the first turn) and from ask() at turn start. Returns true
1487
+ // when a writer is bound.
1488
+ function ensureRemoteTranscriptWriter() {
1489
+ if (!remoteEnabled || !session?.id) return false;
1490
+ const twKey = `${session.id}\u0000${currentCwd}`;
1491
+ if (_twKey !== twKey) {
1492
+ try {
1493
+ _transcriptWriter = createTranscriptWriter({
1494
+ mixdogHome: mixdogHome(),
1495
+ sessionId: session.id,
1496
+ cwd: currentCwd,
1497
+ pid: process.pid,
1498
+ });
1499
+ _transcriptWriter.writeSessionRecord();
1500
+ _twKey = twKey;
1501
+ } catch (error) {
1502
+ process.stderr.write(`mixdog: transcript-writer: init failed: ${error?.message || error}\n`);
1503
+ _transcriptWriter = null;
1504
+ _twKey = '';
1505
+ return false;
1506
+ }
1507
+ } else {
1508
+ // Same binding — refresh updatedAt so worker-side discovery keeps
1509
+ // ranking this session as the live parent-chain candidate.
1510
+ try { _transcriptWriter?.writeSessionRecord(); } catch {}
1511
+ }
1512
+ try { _transcriptWriter?.ensureTranscriptFile(); }
1513
+ catch (error) { process.stderr.write(`mixdog: transcript-writer: ensureTranscriptFile failed: ${error?.message || error}\n`); }
1514
+ return _transcriptWriter != null;
1515
+ }
1516
+
1517
+ // Remote (Discord channel) mode is opt-in per session. Only a session that
1518
+ // explicitly enables remote — via `mixdog --remote` or the runtime toggle —
1519
+ // boots the channel worker and contends for channel ownership.
1520
+ // startRemote() is FORCE-TAKEOVER: it always (re)claims the bridge seat and
1521
+ // rebinds output forwarding to this session, even when the worker is
1522
+ // already running (e.g. `/remote` re-issued after another session took the
1523
+ // seat, or to re-pin forwarding onto the current transcript).
1524
+ function startRemote() {
1525
+ remoteEnabled = true;
1526
+ // Boot the memory daemon eagerly. The channels worker forwards
1527
+ // transcript ingests/entries to the memory HTTP service, whose port is
1528
+ // published to active-instance.json by getMemoryModule().init(). Without
1529
+ // this, memory only starts on the first turn's getMemoryModule() call —
1530
+ // so early channel traffic finds no memory_port and gets buffered (or,
1531
+ // pre-drainer, silently dropped). Runs BEFORE channel claim so the port is
1532
+ // racing to be live by the time the worker sends its first ingest.
1533
+ //
1534
+ // Not fire-and-forget: init() only resolves the module handle, so a bare
1535
+ // getMemoryModule() could return before /health reports ok — leaving early
1536
+ // ingests to hit a not-yet-listening port. Await the proxy start() and then
1537
+ // poll /health with a bounded retry so the daemon is provably reachable
1538
+ // (or logged failed) rather than assumed-up. Still non-blocking to the
1539
+ // caller: the whole probe is detached, but it internally awaits readiness.
1540
+ void (async () => {
1541
+ try {
1542
+ // Yield one event-loop tick before the heavy chain below (module
1543
+ // resolve, daemon fork/health-poll) starts, so Ink's next render
1544
+ // (scheduled via setImmediate/timers) and any queued keypress
1545
+ // events get a turn first instead of being starved by this
1546
+ // detached chain's synchronous setup work.
1547
+ await new Promise((r) => setImmediate(r));
1548
+ const mod = await getMemoryModule();
1549
+ const started = typeof mod?.start === 'function' ? await mod.start() : null;
1550
+ const port = started?.port;
1551
+ if (!port) { bootProfile('channels:memory-eager-init-failed', { error: 'no port from start()' }); return; }
1552
+ for (let i = 0; i < 30; i++) {
1553
+ try {
1554
+ const ok = await new Promise((res) => {
1555
+ const req = httpMod.request({ hostname: '127.0.0.1', port, path: '/health', timeout: 1500 }, (r) => {
1556
+ let d = ''; r.on('data', (c) => { d += c; }); r.on('end', () => {
1557
+ try { res(JSON.parse(d)?.status === 'ok'); } catch { res(false); }
1558
+ });
1559
+ });
1560
+ req.on('error', () => res(false));
1561
+ req.on('timeout', () => { req.destroy(); res(false); });
1562
+ req.end();
1563
+ });
1564
+ if (ok) { bootProfile('channels:memory-eager-init-ready', { port }); return; }
1565
+ } catch {}
1566
+ await new Promise((r) => setTimeout(r, 500));
1567
+ }
1568
+ bootProfile('channels:memory-eager-init-failed', { error: `health not ok after retries (port ${port})` });
1569
+ } catch (error) {
1570
+ bootProfile('channels:memory-eager-init-failed', { error: error?.message || String(error) });
1571
+ }
1572
+ })();
1573
+ // Publish this session's record + transcript file BEFORE the worker's
1574
+ // activate-time discovery polls, so output forwarding binds to this
1575
+ // terminal session immediately instead of waiting for the first turn.
1576
+ // No-op when the session has not been created yet (lazy mode); that
1577
+ // case is covered by the turn-start rebind in ask().
1578
+ ensureRemoteTranscriptWriter();
1579
+ // A backend switch may still be sitting in its debounce window; flush it
1580
+ // so the channel worker boots against the backend the user just chose,
1581
+ // not the previous on-disk value.
1582
+ try { flushBackendSave(); } catch {}
1583
+ if (envFlag('MIXDOG_DISABLE_CHANNEL_START')) {
1584
+ bootProfile('channels:start-skipped');
1585
+ return true;
1586
+ }
1587
+ if (!channelsEnabled()) {
1588
+ bootProfile('channels:start-disabled');
1589
+ return true;
1590
+ }
1591
+ if (closeRequested) return true;
1592
+ if (prewarmTimers.channelStartTimer) {
1593
+ clearTimeout(prewarmTimers.channelStartTimer);
1594
+ prewarmTimers.channelStartTimer = null;
1595
+ }
1596
+ bootProfile('channels:start-scheduled', { delayMs: 0, immediate: true });
1597
+ void (async () => {
1598
+ // Yield before the createCurrentSession/transcript/fork chain below —
1599
+ // same rationale as the memory-eager-init yield above: this detached
1600
+ // chain runs synchronous config/fs work (createCurrentSession, backend
1601
+ // flush, transcript writer) back-to-back, and without a tick break it
1602
+ // can run ahead of Ink's queued render/input handling.
1603
+ await new Promise((r) => setImmediate(r));
1604
+ // Immediate-occupancy guarantee: make sure a session + transcript
1605
+ // exist BEFORE the worker boots — a freshly-forked worker claims and
1606
+ // runs transcript discovery inside its own start(), so publishing the
1607
+ // session record/file first lets that very first discovery pass bind
1608
+ // output forwarding to THIS terminal instead of a persisted/stale
1609
+ // neighbour. Lazy mode means the session may not exist yet at /remote
1610
+ // time; create it here (idempotent — reuses a live session, joins an
1611
+ // in-flight create). On create failure we still claim: that matches
1612
+ // the pre-eager behavior (bind resolves on the first turn's rebind).
1613
+ try { await createCurrentSession('remote-start'); }
1614
+ catch (error) { bootProfile('channels:remote-session-create-failed', { error: error?.message || String(error) }); }
1615
+ ensureRemoteTranscriptWriter();
1616
+ // Re-check after the awaits above: stopRemote()/superseded or runtime
1617
+ // close may have landed mid-chain — do not boot/claim for a session
1618
+ // that already turned remote off.
1619
+ if (!remoteEnabled || closeRequested) return;
1620
+ await invokeChannelStart();
1621
+ if (!remoteEnabled || closeRequested) return;
1622
+ // Unconditional claim + forwarder rebind. A freshly-forked worker
1623
+ // already claims in its own start(), so this is idempotent there; the
1624
+ // already-running case is where it matters (last-wins seat overwrite +
1625
+ // transcript rebind onto this session).
1626
+ await channels.execute('activate_channel_bridge', { active: true });
1627
+ })().catch((error) => bootProfile('channels:claim-failed', { error: error?.message || String(error) }));
1628
+ return true;
1629
+ }
1630
+
1631
+ function stopRemote(reason) {
1632
+ remoteEnabled = false;
1633
+ // Cancel any pending deferred start so it can't fire after remote is off.
1634
+ if (prewarmTimers.channelStartTimer) { clearTimeout(prewarmTimers.channelStartTimer); prewarmTimers.channelStartTimer = null; }
1635
+ channels.stop(reason || 'remote-disabled', { waitForExit: false }).catch(() => {});
1636
+ return true;
1637
+ }
1638
+
1639
+ function isRemoteEnabled() {
1640
+ return remoteEnabled;
1641
+ }
1642
+
1643
+ function withTeardownDeadline(promise, ms, fallback = false) {
1644
+ let timer = null;
1645
+ return Promise.race([
1646
+ Promise.resolve(promise),
1647
+ new Promise((resolve) => {
1648
+ timer = setTimeout(() => resolve(fallback), ms);
1649
+ }),
1650
+ ]).finally(() => {
1651
+ if (timer) clearTimeout(timer);
1652
+ });
1653
+ }
1654
+
1655
+ bootProfile('session-runtime:ready', {
1656
+ lazySession: true,
1657
+ prewarmSession: sessionPrewarmEnabled,
1658
+ providerWarmup: providerWarmupEnabled,
1659
+ codeGraphPrewarm: codeGraphPrewarmEnabled,
1660
+ });
1661
+ scheduleLeadSessionPrewarm();
1662
+ // Lazy mode (default): skip the startup prewarm entirely; the first turn
1663
+ // triggers it instead (see ask()). Eager mode keeps the old startup schedule.
1664
+ if (!codeGraphPrewarmLazy) {
1665
+ scheduleCodeGraphPrewarm(codeGraphPrewarmDelayMs, 'startup');
1666
+ } else {
1667
+ bootProfile('code-graph:prewarm-lazy', { reason: 'startup-deferred-to-first-turn' });
1668
+ }
1669
+ scheduleProviderSetupWarmup();
1670
+ scheduleModelCatalogWarmup();
1671
+ scheduleProviderWarmup();
1672
+ // Warm the provider model catalog in the background, but keep it on its own
1673
+ // delay so short-lived detached runtimes can exit before /models I/O starts.
1674
+ // Operators that want earlier catalog warming can lower
1675
+ // MIXDOG_PROVIDER_MODEL_WARMUP_DELAY_MS explicitly.
1676
+ scheduleProviderModelWarmup();
1677
+ scheduleStatuslineUsageWarmup();
1678
+ // Channels are opt-in: only boot the worker when this session started in (or
1679
+ // was toggled into) remote mode. Non-remote sessions never contend for the
1680
+ // channel; see startRemote()/stopRemote() and the `/remote` toggle.
1681
+ // `remote.autoStart` in mixdog-config.json makes every session claim remote
1682
+ // at boot (same force-takeover semantics as `mixdog --remote` / `/remote`).
1683
+ // The flag lives in the TOP-LEVEL `remote` section of mixdog-config.json
1684
+ // (sibling of agent/ui/channels), not inside the agent section that
1685
+ // cfgMod.loadConfig returns — read it via the shared whole-file reader.
1686
+ // `config?.remote?.autoStart` is kept for back-compat with agent-section
1687
+ // placement.
1688
+ if (!remoteEnabled) {
1689
+ try {
1690
+ if (config?.remote?.autoStart === true
1691
+ || sharedCfgMod?.readSection?.('remote')?.autoStart === true) {
1692
+ remoteEnabled = true;
1693
+ }
1694
+ } catch { /* unreadable config never blocks boot */ }
1695
+ }
1696
+ // Boot-time remote start (autoStart or --remote) is DEFERRED past the TUI's
1697
+ // first frame. startRemote() front-loads heavy work — memory daemon fork
1698
+ // (PG + forced ONNX embed warmup in the child), eager session create, and
1699
+ // the channel-worker fork — and running it inline here interleaves that
1700
+ // CPU/disk load with engine boot, visibly delaying the first ink frame by
1701
+ // seconds. The deferred timer reuses prewarmTimers.channelStartTimer so an
1702
+ // early /remote (startRemote clears it), stopRemote(), and close() all
1703
+ // cancel it through the existing clearTimeout paths. Runtime /remote calls
1704
+ // still start immediately (user-initiated, UI already painted).
1705
+ if (remoteEnabled) {
1706
+ const remoteAutoStartDelayMs = envDelayMs('MIXDOG_REMOTE_AUTOSTART_DELAY_MS', 1_500, { min: 0, max: 60_000 });
1707
+ bootProfile('channels:autostart-deferred', { delayMs: remoteAutoStartDelayMs });
1708
+ prewarmTimers.channelStartTimer = setTimeout(() => {
1709
+ prewarmTimers.channelStartTimer = null;
1710
+ if (closeRequested || !remoteEnabled) return;
1711
+ startRemote();
1712
+ }, remoteAutoStartDelayMs);
1713
+ prewarmTimers.channelStartTimer.unref?.();
1714
+ }
1715
+
1716
+ // Pure settings-delegate methods (onboarding status/skip, autoClear, profile,
1717
+ // compaction, recap/memory, channels, systemShell, update settings, channel
1718
+ // token save/forget, setBackend). Extracted to session-runtime/settings-api.mjs
1719
+ // and SPREAD into the API object below so the external surface is unchanged.
1720
+ const settingsApi = createSettingsApi({
1721
+ getConfig: () => config,
1722
+ getRoute: () => route,
1723
+ getSession: () => session,
1724
+ getRemoteEnabled: () => remoteEnabled,
1725
+ adoptConfig,
1726
+ saveConfigAndAdopt,
1727
+ scheduleBackendSave,
1728
+ cfgMod,
1729
+ hasOwn,
1730
+ normalizeAutoClearConfig,
1731
+ autoClearIdleMsForProvider,
1732
+ autoClearProviderDefaults,
1733
+ normalizeCompactionConfig,
1734
+ normalizeCompactTypeSetting,
1735
+ normalizeSystemShellConfig,
1736
+ normalizeSystemShellCommand,
1737
+ setConfiguredShell,
1738
+ setRecapEnabledInConfig,
1739
+ setModuleEnabledInConfig,
1740
+ summarizeWorkflowRoutes,
1741
+ parseDurationMs,
1742
+ formatDurationMs,
1743
+ localPackageVersion,
1744
+ memoryEnabled,
1745
+ recapEnabledFn,
1746
+ channelsEnabled,
1747
+ autoUpdateEnabled,
1748
+ getUpdateCheckState: () => updateCheckState,
1749
+ getUpdateProcessState: () => updateProcessState,
1750
+ invalidateContextStatusCache: (...a) => invalidateContextStatusCache(...a),
1751
+ invalidatePreSessionToolSurface: (...a) => invalidatePreSessionToolSurface(...a),
1752
+ scheduleChannelStart: (...a) => scheduleChannelStart(...a),
1753
+ channels,
1754
+ clearChannelStartTimer: () => {
1755
+ if (prewarmTimers.channelStartTimer) {
1756
+ clearTimeout(prewarmTimers.channelStartTimer);
1757
+ prewarmTimers.channelStartTimer = null;
1758
+ }
1759
+ },
1760
+ checkForUpdateInternal: (...a) => checkForUpdateInternal(...a),
1761
+ runUpdateNowInternal: (...a) => runUpdateNowInternal(...a),
1762
+ reloadChannelsSoon: (...a) => reloadChannelsSoon(...a),
1763
+ ONBOARDING_VERSION,
1764
+ saveDiscordToken,
1765
+ forgetDiscordToken,
1766
+ saveTelegramToken,
1767
+ forgetTelegramToken,
1768
+ saveWebhookAuthtoken,
1769
+ forgetWebhookAuthtoken,
1770
+ setBackend,
1771
+ });
1772
+
1773
+ const channelConfigApi = createChannelConfigApi({ flushBackendSave, channels, reloadChannelsSoon });
1774
+ const providerAuthApi = createProviderAuthApi({
1775
+ cfgMod,
1776
+ getConfig: () => config,
1777
+ saveConfigAndAdopt,
1778
+ displayConfig,
1779
+ reloadFullConfig,
1780
+ invalidateProviderCaches,
1781
+ warmProviderModelCache,
1782
+ cachedProviderSetup,
1783
+ getUsageDashboard,
1784
+ collectProviderModels,
1785
+ });
1786
+ const lifecycleApi = createLifecycleApi({
1787
+ getSession: () => session,
1788
+ setSession: (v) => { session = v; },
1789
+ getRoute: () => route,
1790
+ setRoute: (v) => { route = v; },
1791
+ getConfig: () => config,
1792
+ getMode: () => mode,
1793
+ getCurrentCwd: () => currentCwd,
1794
+ setCloseRequested: (v) => { closeRequested = v; },
1795
+ getMemoryModPromise: () => memoryModPromise,
1796
+ setMemoryModPromise: (v) => { memoryModPromise = v; },
1797
+ setSessionNeedsCwdRefresh: (v) => { sessionNeedsCwdRefresh = v; },
1798
+ hooks,
1799
+ hookCommonPayload,
1800
+ mgr,
1801
+ statusRoutes,
1802
+ channels,
1803
+ agentTool,
1804
+ mcpClient,
1805
+ warmupTimers,
1806
+ prewarmTimers,
1807
+ flushConfigSave,
1808
+ flushBackendSave,
1809
+ flushOutputStyleSave,
1810
+ withTeardownDeadline,
1811
+ closePatchRuntimeIfLoaded,
1812
+ createCurrentSession,
1813
+ refreshRouteEffort,
1814
+ invalidateContextStatusCache,
1815
+ invalidatePreSessionToolSurface,
1816
+ applyResolvedCwd,
1817
+ resolveRoute,
1818
+ applyDeferredToolSurface,
1819
+ standaloneTools,
1820
+ });
1821
+ const resourceApi = createResourceApi({
1822
+ getConfig: () => config,
1823
+ getSession: () => session,
1824
+ getCurrentCwd: () => currentCwd,
1825
+ cfgMod,
1826
+ mgr,
1827
+ hooks,
1828
+ STANDALONE_DATA_DIR,
1829
+ saveConfigAndAdopt,
1830
+ connectConfiguredMcp,
1831
+ invalidatePreSessionToolSurface,
1832
+ recreateCurrentSessionIfReady,
1833
+ normalizeMcpServerInput,
1834
+ mcpStatus,
1835
+ skillsStatus,
1836
+ skillContent,
1837
+ addProjectSkill,
1838
+ pluginsStatus,
1839
+ getMemoryModule,
1840
+ reloadFullConfig,
1841
+ });
1842
+ const modelRouteApi = createModelRouteApi({
1843
+ getConfig: () => config,
1844
+ getRoute: () => route,
1845
+ setRouteState: (v) => { route = v; },
1846
+ getSession: () => session,
1847
+ setSession: (v) => { session = v; },
1848
+ getConfigHasSecrets: () => configHasSecrets,
1849
+ getSearchRouteState: () => searchRoute,
1850
+ setSearchRouteState: (v) => { searchRoute = v; },
1851
+ cfgMod,
1852
+ reg,
1853
+ mgr,
1854
+ statusRoutes,
1855
+ resolveRoute,
1856
+ searchCapableFor,
1857
+ lookupModelMeta,
1858
+ adoptConfig,
1859
+ saveConfigAndAdopt,
1860
+ ensureFullConfig,
1861
+ persistLeadRoute,
1862
+ refreshRouteEffort,
1863
+ refreshStatuslineUsageSnapshot,
1864
+ scheduleStatuslineUsageRefresh,
1865
+ invalidateContextStatusCache,
1866
+ invalidateProviderCaches,
1867
+ collectSearchProviderModels,
1868
+ });
1869
+ const workflowAgentsApi = createWorkflowAgentsApi({
1870
+ getConfig: () => config,
1871
+ getRoute: () => route,
1872
+ setRouteState: (v) => { route = v; },
1873
+ getSession: () => session,
1874
+ setSession: (v) => { session = v; },
1875
+ getConfigHasSecrets: () => configHasSecrets,
1876
+ cfgMod,
1877
+ reg,
1878
+ mgr,
1879
+ STANDALONE_DATA_DIR,
1880
+ resolveRoute,
1881
+ lookupModelMeta,
1882
+ adoptConfig,
1883
+ saveConfigAndAdopt,
1884
+ displayConfig,
1885
+ agentRouteFromConfig,
1886
+ loadAgentDefinition,
1887
+ activeWorkflowId,
1888
+ listWorkflowPacks,
1889
+ loadWorkflowPack,
1890
+ workflowSummary,
1891
+ getOutputStyleStatusCached,
1892
+ seedOutputStyleStatusCache,
1893
+ scheduleOutputStyleSave,
1894
+ recreateCurrentSessionIfReady,
1895
+ notifyFnForSession,
1896
+ invalidateContextStatusCache,
1897
+ });
1898
+ const sessionTurnApi = createSessionTurnApi({
1899
+ getSession: () => session,
1900
+ setSession: (v) => { session = v; },
1901
+ getCurrentCwd: () => currentCwd,
1902
+ getMode: () => mode,
1903
+ setMode: (v) => { mode = v; },
1904
+ getActiveTurnCount: () => activeTurnCount,
1905
+ setActiveTurnCount: (v) => { activeTurnCount = v; },
1906
+ isFirstTurnCompleted: () => firstTurnCompleted,
1907
+ setFirstTurnCompleted: (v) => { firstTurnCompleted = v; },
1908
+ getCodeGraphFirstTurnPrewarmDone: () => codeGraphFirstTurnPrewarmDone,
1909
+ setCodeGraphFirstTurnPrewarmDone: (v) => { codeGraphFirstTurnPrewarmDone = v; },
1910
+ codeGraphPrewarmLazy,
1911
+ getRemoteEnabled: () => remoteEnabled,
1912
+ getCloseRequested: () => closeRequested,
1913
+ getPendingSessionReset: () => pendingSessionReset,
1914
+ setPendingSessionReset: (v) => { pendingSessionReset = v; },
1915
+ getTranscriptWriter: () => _transcriptWriter,
1916
+ getTwKey: () => _twKey,
1917
+ getLastAppendedAssistant: () => _lastAppendedAssistant,
1918
+ setLastAppendedAssistant: (v) => { _lastAppendedAssistant = v; },
1919
+ scheduleCodeGraphPrewarm,
1920
+ refreshSessionForCwdIfNeeded,
1921
+ createCurrentSession,
1922
+ ensureRemoteTranscriptWriter,
1923
+ channelsEnabled,
1924
+ invokeChannelStart,
1925
+ channels,
1926
+ hooks,
1927
+ hookCommonPayload,
1928
+ mgr,
1929
+ notifyFnForSession,
1930
+ bootProfile,
1931
+ scheduleProviderWarmup,
1932
+ scheduleProviderModelWarmup,
1933
+ invalidateContextStatusCache,
1934
+ agentTool,
1935
+ recreateCurrentSessionIfReady,
1936
+ invalidatePreSessionToolSurface,
1937
+ activeToolSurface,
1938
+ applyResolvedCwd,
1939
+ resolveCwdPath,
1940
+ agentStatusState,
1941
+ notificationListeners,
1942
+ });
1943
+
1944
+ return {
1945
+ ...settingsApi,
1946
+ ...channelConfigApi,
1947
+ ...providerAuthApi,
1948
+ get id() {
1949
+ return session?.id || null;
1950
+ },
1951
+ get provider() {
1952
+ return route.provider;
1953
+ },
1954
+ get model() {
1955
+ return route.model;
1956
+ },
1957
+ get effort() {
1958
+ return route.effectiveEffort || route.effort || route.preset?.effort || null;
1959
+ },
1960
+ get fast() {
1961
+ return route.fast === true;
1962
+ },
1963
+ get fastCapable() {
1964
+ return route.fastCapable === true;
1965
+ },
1966
+ get effortOptions() {
1967
+ return route.effortOptions || [];
1968
+ },
1969
+ get contextWindow() {
1970
+ return session?.contextWindow || null;
1971
+ },
1972
+ get rawContextWindow() {
1973
+ return session?.rawContextWindow || session?.contextWindow || null;
1974
+ },
1975
+ get effectiveContextWindowPercent() {
1976
+ return session?.effectiveContextWindowPercent || null;
1977
+ },
1978
+ get toolMode() {
1979
+ return mode;
1980
+ },
1981
+ get autoClear() {
1982
+ return this.getAutoClear();
1983
+ },
1984
+ get systemShell() {
1985
+ return normalizeSystemShellConfig(config.shell);
1986
+ },
1987
+ get searchRoute() {
1988
+ searchRoute = normalizeSearchRouteConfig(config.searchRoute) || normalizeSearchRouteConfig(searchRoute);
1989
+ return searchRoute;
1990
+ },
1991
+ get workflow() {
1992
+ const dataDir = cfgMod.getPluginData?.() || STANDALONE_DATA_DIR;
1993
+ const active = activeWorkflowSummary(config, dataDir);
1994
+ if (session?.workflow && typeof session.workflow === 'object') {
1995
+ const current = workflowSummary(session.workflow);
1996
+ return current?.id && active?.id && current.id !== active.id
1997
+ ? { ...active, currentSession: current, appliedToCurrentSession: false }
1998
+ : active;
1999
+ }
2000
+ return active;
2001
+ },
2002
+ get outputStyle() {
2003
+ return getOutputStyleStatusCached().current;
2004
+ },
2005
+ get cwd() {
2006
+ return currentCwd;
2007
+ },
2008
+ get session() {
2009
+ return session;
2010
+ },
2011
+ contextStatus() {
2012
+ // Prefer the in-flight working transcript while a turn is running so the
2013
+ // context gauge reflects LIVE growth (user turn + tool calls/results) as
2014
+ // it accumulates, instead of freezing at the pre-turn committed snapshot.
2015
+ // askSession() sets session.liveTurnMessages for the turn duration and
2016
+ // clears it on commit/cancel/error, after which we fall back to the
2017
+ // authoritative committed transcript.
2018
+ return computeContextStatus();
2019
+ },
2020
+ startRemote() {
2021
+ return startRemote();
2022
+ },
2023
+ stopRemote(reason) {
2024
+ return stopRemote(reason);
2025
+ },
2026
+ isRemoteEnabled() {
2027
+ return isRemoteEnabled();
2028
+ },
2029
+ // Subscribe to non-user-initiated remote flips (seat superseded). Returns
2030
+ // an unsubscribe function. TUI uses this to sync its Remote indicator and
2031
+ // show a "remote taken over" notice.
2032
+ onRemoteStateChange(listener) {
2033
+ if (typeof listener !== 'function') return () => {};
2034
+ remoteStateListeners.add(listener);
2035
+ return () => remoteStateListeners.delete(listener);
2036
+ },
2037
+ get clientHostPid() {
2038
+ return session?.clientHostPid || process.pid;
2039
+ },
2040
+ ...lifecycleApi,
2041
+ ...resourceApi,
2042
+ ...modelRouteApi,
2043
+ ...workflowAgentsApi,
2044
+ ...sessionTurnApi,
2045
+ };
2046
+ }