@gajae-code/coding-agent 0.19.3-nightly.20261030094347.41301593972.gf536b1010d4e → 0.19.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (273) hide show
  1. package/CHANGELOG.md +238 -0
  2. package/dist/types/async/job-manager.d.ts +56 -18
  3. package/dist/types/cli/auth-token-file.d.ts +9 -0
  4. package/dist/types/cli/doctor/install-repairs.d.ts +1 -0
  5. package/dist/types/cli/doctor/types.d.ts +1 -0
  6. package/dist/types/cli/install-activation.d.ts +10 -1
  7. package/dist/types/cli/malloc-env-guard.d.ts +8 -0
  8. package/dist/types/cli/update-cli.d.ts +4 -1
  9. package/dist/types/config/atomic-yaml-patch.d.ts +34 -1
  10. package/dist/types/config/model-profile-activation.d.ts +40 -13
  11. package/dist/types/config/model-registry.d.ts +3 -0
  12. package/dist/types/config/models-config-schema.d.ts +4 -0
  13. package/dist/types/config/settings-schema.d.ts +49 -8
  14. package/dist/types/config/settings.d.ts +39 -5
  15. package/dist/types/config/task-delegation.d.ts +2 -0
  16. package/dist/types/extensibility/extensions/runner.d.ts +2 -0
  17. package/dist/types/extensibility/slash-commands.d.ts +14 -1
  18. package/dist/types/gjc-runtime/managed-owner-admission.d.ts +4 -12
  19. package/dist/types/gjc-runtime/managed-owner-binding.d.ts +164 -0
  20. package/dist/types/gjc-runtime/managed-owner-supervisor.d.ts +26 -33
  21. package/dist/types/gjc-runtime/owner-lifecycle-path.d.ts +21 -0
  22. package/dist/types/gjc-runtime/owner-lifecycle-root.d.ts +7 -0
  23. package/dist/types/gjc-runtime/session-state-sidecar.d.ts +8 -1
  24. package/dist/types/gjc-runtime/tmux-common.d.ts +10 -0
  25. package/dist/types/gjc-runtime/tmux-owner-isolation.d.ts +131 -5
  26. package/dist/types/gjc-runtime/tmux-sessions.d.ts +46 -0
  27. package/dist/types/gjc-runtime/ultragoal-owner-loss-recovery.d.ts +1 -1
  28. package/dist/types/harness-control-plane/session-lease.d.ts +29 -2
  29. package/dist/types/harness-control-plane/storage.d.ts +8 -0
  30. package/dist/types/main.d.ts +12 -0
  31. package/dist/types/memories/index.d.ts +7 -1
  32. package/dist/types/memories/storage.d.ts +1 -0
  33. package/dist/types/memory-backend/types.d.ts +6 -1
  34. package/dist/types/modes/components/model-selector.d.ts +11 -4
  35. package/dist/types/modes/components/notifications-settings-editor.d.ts +2 -166
  36. package/dist/types/modes/components/settings-defs.d.ts +2 -1
  37. package/dist/types/modes/components/settings-selector.d.ts +5 -2
  38. package/dist/types/modes/components/smart-routing-panel.d.ts +19 -14
  39. package/dist/types/modes/components/tool-execution.d.ts +6 -0
  40. package/dist/types/modes/controllers/goal-mode-controller.d.ts +5 -0
  41. package/dist/types/modes/controllers/selector-controller.d.ts +7 -59
  42. package/dist/types/plan-mode/state.d.ts +7 -0
  43. package/dist/types/runtime-mcp/config.d.ts +8 -0
  44. package/dist/types/runtime-mcp/manager.d.ts +43 -0
  45. package/dist/types/runtime-mcp/session-controls-grant.d.ts +7 -0
  46. package/dist/types/sdk/broker/broker.d.ts +33 -7
  47. package/dist/types/sdk/broker/lifecycle.d.ts +1 -0
  48. package/dist/types/sdk/broker/session-index.d.ts +2 -0
  49. package/dist/types/sdk/broker/session-scope.d.ts +31 -1
  50. package/dist/types/sdk/broker/spawn-authority.d.ts +19 -0
  51. package/dist/types/sdk/broker/spawn-substrate.d.ts +12 -1
  52. package/dist/types/sdk/bus/index.d.ts +5 -0
  53. package/dist/types/sdk/bus/notification-orchestration.d.ts +21 -3
  54. package/dist/types/sdk/bus/notification-service.d.ts +2 -1
  55. package/dist/types/sdk/bus/telegram-daemon-contract.d.ts +1 -1
  56. package/dist/types/sdk/cli/rows.d.ts +7 -0
  57. package/dist/types/sdk/extension-interaction.d.ts +108 -0
  58. package/dist/types/sdk/host/control/btw-ask.d.ts +19 -0
  59. package/dist/types/sdk/host/control/dispatch.d.ts +2 -0
  60. package/dist/types/sdk/host/control/index.d.ts +1 -0
  61. package/dist/types/sdk/host/control/operations.d.ts +7 -0
  62. package/dist/types/sdk/host/external-permissions.d.ts +47 -0
  63. package/dist/types/sdk/host/host.d.ts +8 -2
  64. package/dist/types/sdk/host/query/handlers.d.ts +1 -0
  65. package/dist/types/sdk/host/session-runtime.d.ts +13 -1
  66. package/dist/types/sdk/host/surface-policy.d.ts +2 -1
  67. package/dist/types/sdk/index.d.ts +11 -0
  68. package/dist/types/sdk/job-observation.d.ts +51 -0
  69. package/dist/types/sdk/lifecycle/service.d.ts +6 -1
  70. package/dist/types/sdk/notification-setup-contract.d.ts +169 -0
  71. package/dist/types/sdk/notification-setup.d.ts +54 -0
  72. package/dist/types/sdk/protocol/adapter-validation.d.ts +2 -0
  73. package/dist/types/sdk/router/session-router.d.ts +5 -0
  74. package/dist/types/sdk/routing-settings.d.ts +57 -0
  75. package/dist/types/sdk/session-list.d.ts +5 -0
  76. package/dist/types/sdk/session-recap.d.ts +50 -0
  77. package/dist/types/sdk/session.d.ts +14 -0
  78. package/dist/types/sdk/settings-catalog.d.ts +52 -0
  79. package/dist/types/sdk/workflow-gates.d.ts +9 -0
  80. package/dist/types/session/agent-session.d.ts +129 -15
  81. package/dist/types/session/client-bridge.d.ts +1 -0
  82. package/dist/types/session/internal/managed-session-storage.d.ts +6 -0
  83. package/dist/types/session/recap.d.ts +104 -0
  84. package/dist/types/session/session-manager.d.ts +51 -1
  85. package/dist/types/session/streaming-output.d.ts +9 -1
  86. package/dist/types/session/workflow-recovery-field-fence.d.ts +4 -0
  87. package/dist/types/session/yield-queue.d.ts +16 -0
  88. package/dist/types/task/executor.d.ts +2 -0
  89. package/dist/types/tools/auto-generated-guard.d.ts +8 -1
  90. package/dist/types/tools/bash.d.ts +1 -1
  91. package/dist/types/tools/grouped-file-tree.d.ts +21 -0
  92. package/dist/types/tools/image-gen.d.ts +6 -1
  93. package/dist/types/tools/index.d.ts +7 -0
  94. package/dist/types/tui/file-list.d.ts +0 -3
  95. package/dist/types/utils/gh.d.ts +5 -0
  96. package/dist/types/utils/herdr-core-status.d.ts +31 -0
  97. package/dist/types/utils/herdr-pane.d.ts +7 -0
  98. package/dist/types/utils/recap-generator.d.ts +41 -0
  99. package/dist/types/web/hardened-http.d.ts +41 -0
  100. package/dist/types/web/insane/url-guard.d.ts +2 -0
  101. package/package.json +7 -7
  102. package/scripts/generate-sdk-operation-inventory.ts +28 -1
  103. package/src/async/job-manager.ts +381 -41
  104. package/src/cli/auth-broker-cli.ts +11 -53
  105. package/src/cli/auth-gateway-cli.ts +13 -56
  106. package/src/cli/auth-token-file.ts +56 -0
  107. package/src/cli/customize-doctor.ts +40 -27
  108. package/src/cli/doctor/install-repairs.ts +36 -2
  109. package/src/cli/doctor/repairs.ts +1 -0
  110. package/src/cli/doctor/report.ts +2 -0
  111. package/src/cli/doctor/types.ts +1 -0
  112. package/src/cli/install-activation.ts +58 -1
  113. package/src/cli/malloc-env-guard.ts +11 -0
  114. package/src/cli/session-picker.ts +8 -2
  115. package/src/cli/setup-cli.ts +2 -0
  116. package/src/cli/update-cli.ts +48 -3
  117. package/src/cli-main.ts +2 -2
  118. package/src/cli-ordinary.ts +2 -2
  119. package/src/commands/harness.ts +16 -3
  120. package/src/config/atomic-yaml-patch.ts +439 -141
  121. package/src/config/machine-identity.ts +6 -2
  122. package/src/config/mcp-schema.json +1 -1
  123. package/src/config/model-profile-activation.ts +505 -248
  124. package/src/config/model-registry.ts +54 -2
  125. package/src/config/models-config-schema.ts +2 -0
  126. package/src/config/settings-schema.ts +52 -8
  127. package/src/config/settings.ts +640 -237
  128. package/src/config/task-delegation.ts +4 -1
  129. package/src/coordinator-mcp/question-gate-codec.ts +17 -5
  130. package/src/coordinator-mcp/server.ts +2 -0
  131. package/src/extensibility/extensions/runner.ts +6 -0
  132. package/src/extensibility/gjc-plugins/installer.ts +2 -1
  133. package/src/extensibility/plugins/marketplace/fetcher.ts +28 -119
  134. package/src/extensibility/slash-commands.ts +90 -16
  135. package/src/gjc-runtime/launch-tmux.ts +79 -23
  136. package/src/gjc-runtime/launch-worktree.ts +15 -3
  137. package/src/gjc-runtime/managed-owner-admission.ts +298 -212
  138. package/src/gjc-runtime/managed-owner-binding.ts +410 -0
  139. package/src/gjc-runtime/managed-owner-supervisor.ts +265 -112
  140. package/src/gjc-runtime/owner-lifecycle-path.ts +82 -0
  141. package/src/gjc-runtime/owner-lifecycle-root.ts +26 -0
  142. package/src/gjc-runtime/ralplan-current-final.ts +35 -15
  143. package/src/gjc-runtime/ralplan-runtime.ts +3 -0
  144. package/src/gjc-runtime/session-state-sidecar.ts +61 -28
  145. package/src/gjc-runtime/tmux-common.ts +28 -0
  146. package/src/gjc-runtime/tmux-owner-isolation.ts +1100 -111
  147. package/src/gjc-runtime/tmux-sessions.ts +293 -58
  148. package/src/gjc-runtime/ultragoal-change-set.ts +8 -1
  149. package/src/gjc-runtime/ultragoal-owner-loss-recovery.ts +1 -1
  150. package/src/harness-control-plane/finalize.ts +2 -0
  151. package/src/harness-control-plane/owner.ts +23 -1
  152. package/src/harness-control-plane/preserve.ts +7 -1
  153. package/src/harness-control-plane/session-lease.ts +357 -3
  154. package/src/harness-control-plane/storage.ts +61 -10
  155. package/src/hashline/execute.ts +13 -1
  156. package/src/internal-urls/docs-index.generated.ts +12 -12
  157. package/src/lsp/lspmux.ts +4 -0
  158. package/src/main.ts +44 -3
  159. package/src/master-mode/snapshot.ts +13 -1
  160. package/src/memories/index.ts +8 -1
  161. package/src/memories/storage.ts +1 -0
  162. package/src/memory-backend/types.ts +6 -1
  163. package/src/modes/acp/acp-agent.ts +28 -4
  164. package/src/modes/components/gjc-bundle-settings.ts +56 -14
  165. package/src/modes/components/model-selector.ts +98 -18
  166. package/src/modes/components/notifications-settings-editor.ts +68 -188
  167. package/src/modes/components/session-selector.ts +27 -5
  168. package/src/modes/components/settings-defs.ts +4 -10
  169. package/src/modes/components/settings-selector.ts +93 -66
  170. package/src/modes/components/smart-routing-panel.ts +363 -48
  171. package/src/modes/components/tool-execution.ts +388 -9
  172. package/src/modes/controllers/event-controller.ts +2 -1
  173. package/src/modes/controllers/extension-ui-controller.ts +2 -1
  174. package/src/modes/controllers/goal-mode-controller.ts +24 -0
  175. package/src/modes/controllers/plan-mode-controller.ts +11 -3
  176. package/src/modes/controllers/selector-controller.ts +127 -1242
  177. package/src/modes/interactive-mode.ts +44 -3
  178. package/src/modes/runtime-init.ts +2 -1
  179. package/src/modes/shared/agent-wire/approval-gate.ts +13 -2
  180. package/src/modes/shared/agent-wire/deep-interview-gate.ts +2 -4
  181. package/src/plan-mode/state.ts +17 -0
  182. package/src/prompts/system/master-mode.md +2 -0
  183. package/src/prompts/system/recap-system.md +5 -0
  184. package/src/prompts/system/system-prompt.md +5 -1
  185. package/src/prompts/tools/ask.md +4 -3
  186. package/src/runtime-mcp/config.ts +20 -1
  187. package/src/runtime-mcp/manager.ts +588 -45
  188. package/src/runtime-mcp/session-controls-grant.ts +24 -0
  189. package/src/sdk/acp/adapter.ts +14 -3
  190. package/src/sdk/broker/broker.ts +237 -23
  191. package/src/sdk/broker/lifecycle.ts +2 -0
  192. package/src/sdk/broker/session-index.ts +93 -19
  193. package/src/sdk/broker/session-scope.ts +81 -2
  194. package/src/sdk/broker/spawn-authority.ts +34 -5
  195. package/src/sdk/broker/spawn-substrate.ts +117 -18
  196. package/src/sdk/bus/chat-daemon-control.ts +2 -2
  197. package/src/sdk/bus/index.ts +77 -11
  198. package/src/sdk/bus/notification-orchestration.ts +141 -59
  199. package/src/sdk/bus/notification-service.ts +25 -23
  200. package/src/sdk/bus/telegram-daemon-contract.ts +1 -1
  201. package/src/sdk/cli/master-cli.ts +2 -2
  202. package/src/sdk/cli/rows.ts +9 -0
  203. package/src/sdk/cli/session-cli.ts +29 -4
  204. package/src/sdk/extension-interaction.ts +533 -0
  205. package/src/sdk/host/control/btw-ask.ts +49 -0
  206. package/src/sdk/host/control/dispatch.ts +12 -0
  207. package/src/sdk/host/control/index.ts +1 -0
  208. package/src/sdk/host/control/operations.ts +7 -0
  209. package/src/sdk/host/external-permissions.ts +332 -0
  210. package/src/sdk/host/host.ts +8 -2
  211. package/src/sdk/host/query/handlers.ts +9 -0
  212. package/src/sdk/host/sdk-surface-parity.test.ts +55 -1
  213. package/src/sdk/host/session-runtime.test.ts +142 -1
  214. package/src/sdk/host/session-runtime.ts +108 -28
  215. package/src/sdk/host/surface-policy.ts +11 -0
  216. package/src/sdk/index.ts +15 -0
  217. package/src/sdk/job-observation.ts +157 -0
  218. package/src/sdk/lifecycle/service.ts +15 -2
  219. package/src/sdk/notification-setup-contract.ts +181 -0
  220. package/src/sdk/notification-setup.ts +1151 -0
  221. package/src/sdk/protocol/adapter-validation.ts +6 -1
  222. package/src/sdk/protocol/operation-inventory.generated.json +239 -6
  223. package/src/sdk/protocol/operation-registry.ts +21 -3
  224. package/src/sdk/router/session-router.ts +12 -1
  225. package/src/sdk/routing-settings.ts +395 -0
  226. package/src/sdk/session-list.ts +37 -0
  227. package/src/sdk/session-recap.ts +121 -0
  228. package/src/sdk/session.ts +335 -23
  229. package/src/sdk/settings-catalog.ts +119 -0
  230. package/src/sdk/workflow-gates.ts +30 -0
  231. package/src/session/agent-session.ts +1880 -238
  232. package/src/session/client-bridge.ts +1 -1
  233. package/src/session/contribution-prep.ts +8 -1
  234. package/src/session/internal/managed-session-storage.ts +17 -3
  235. package/src/session/recap.ts +298 -0
  236. package/src/session/session-manager.ts +776 -121
  237. package/src/session/streaming-output.ts +69 -9
  238. package/src/session/workflow-recovery-field-fence.ts +27 -0
  239. package/src/session/yield-queue.ts +52 -1
  240. package/src/setup/provider-presets.json +3 -1
  241. package/src/slash-commands/builtin-registry.ts +124 -4
  242. package/src/ssh/connection-manager.ts +3 -2
  243. package/src/ssh/ssh-executor.ts +3 -0
  244. package/src/ssh/sshfs-mount.ts +5 -4
  245. package/src/task/executor.ts +3 -0
  246. package/src/task/index.ts +48 -19
  247. package/src/tools/ast-edit.ts +10 -47
  248. package/src/tools/ast-grep.ts +10 -45
  249. package/src/tools/auto-generated-guard.ts +21 -1
  250. package/src/tools/bash-allowed-prefixes.ts +2 -0
  251. package/src/tools/bash.ts +10 -4
  252. package/src/tools/bisect.ts +5 -0
  253. package/src/tools/browser/launch.ts +7 -2
  254. package/src/tools/browser/registry.ts +5 -0
  255. package/src/tools/grouped-file-tree.ts +86 -0
  256. package/src/tools/image-gen.ts +180 -174
  257. package/src/tools/index.ts +7 -0
  258. package/src/tools/json-tree.ts +2 -2
  259. package/src/tools/recipe/runners/cargo.ts +3 -0
  260. package/src/tools/recipe/runners/just.ts +3 -0
  261. package/src/tools/recipe/runners/task.ts +3 -0
  262. package/src/tools/search.ts +9 -48
  263. package/src/tools/tool-catalog.generated.ts +1 -1
  264. package/src/tui/file-list.ts +14 -3
  265. package/src/utils/gh.ts +14 -1
  266. package/src/utils/git.ts +1 -8
  267. package/src/utils/herdr-core-status.ts +156 -0
  268. package/src/utils/herdr-pane.ts +38 -26
  269. package/src/utils/recap-generator.ts +191 -0
  270. package/src/web/hardened-http.ts +183 -0
  271. package/src/web/insane/bridge.ts +2 -1
  272. package/src/web/insane/url-guard.ts +7 -2
  273. package/src/web/scrapers/youtube.ts +3 -0
@@ -1,4 +1,3 @@
1
- import * as path from "node:path";
2
1
  import { ThinkingLevel } from "@gajae-code/agent-core";
3
2
  import {
4
3
  type Api,
@@ -16,16 +15,7 @@ import type { OAuthProvider } from "@gajae-code/ai/utils/oauth/types";
16
15
  import type { Component, OverlayHandle, SlashCommand } from "@gajae-code/tui";
17
16
  import { Input, Loader, resolvePetMode, Spacer, Text } from "@gajae-code/tui";
18
17
  import { getAgentDbPath, getProjectDir, logger, VERSION } from "@gajae-code/utils";
19
- import {
20
- type AutoroutingProvenance,
21
- type AutoroutingSetup,
22
- buildAutoroutingEnabledPatch,
23
- buildAutoroutingSettingsBatch,
24
- evaluateAutoroutingProvenanceState,
25
- validateAutoroutingSetup,
26
- } from "../../config/autorouting-contract";
27
- import { canonicalJsonBytes, generateTierChains } from "../../config/autorouting-generator";
28
- import { CURATED_TIER_MAP } from "../../config/autorouting-tier-map";
18
+ import type { AutoroutingSetup } from "../../config/autorouting-contract";
29
19
  import type { AppKeybinding } from "../../config/keybindings";
30
20
  import {
31
21
  activateModelProfile,
@@ -38,7 +28,7 @@ import { GJC_MODEL_ASSIGNMENT_TARGETS, type GjcModelAssignmentTargetId } from ".
38
28
  import { formatModelSelectorValue } from "../../config/model-resolver";
39
29
  import { selectorHead } from "../../config/model-selector-value";
40
30
  import type { ModelProfileConfig } from "../../config/models-config-schema";
41
- import { type RawSettings, type Settings, type SettingsAtomicReceipt, settings } from "../../config/settings";
31
+ import { type Settings, settings } from "../../config/settings";
42
32
  import type { SettingValue } from "../../config/settings-schema";
43
33
  import { DebugSelectorComponent } from "../../debug";
44
34
  import { disableProvider, enableProvider } from "../../discovery";
@@ -71,41 +61,14 @@ import {
71
61
  suspendInteractiveActivityIndicator,
72
62
  } from "../../modes/types";
73
63
  import { configureSttFromSettings } from "../../runtime/stt-settings-setup";
74
- import { ChatDaemonController } from "../../sdk/bus/chat-daemon-control";
75
- import {
76
- getCurrentTelegramActivationMarker,
77
- getNotificationConfig,
78
- isProviderEffectivelyEnabled,
79
- isTelegramComplete,
80
- maskToken,
81
- type NotificationProvider,
82
- } from "../../sdk/bus/config";
83
- import {
84
- clearTelegramActivationMarker,
85
- createTelegramActivationMarker,
86
- mutateNotificationProvider,
87
- type NotificationProviderConfigurationMutation,
88
- type NotificationProviderRuntimeAuthority,
89
- observedTelegramActivationMarker,
90
- persistTelegramActivationMarker,
91
- proposedTelegramIdentity,
92
- reconcileCommittedTelegramConfiguration,
93
- removeNotificationProvider,
94
- removeTelegramConfiguration,
95
- saveTelegramInactive,
96
- setGlobalNotificationsEnabled,
97
- } from "../../sdk/bus/notification-orchestration";
64
+ import { createNotificationsEditorOperations } from "../../sdk/notification-setup";
98
65
  import {
99
- buildNotificationStatusReport,
100
- checkNotificationHealth,
101
- recoverNotifications,
102
- sanitizeDiagnostic,
103
- sendNotificationTest,
104
- } from "../../sdk/bus/notification-service";
105
- import type { NotificationSessionStatus } from "../../sdk/bus/session-control";
106
- import { ensureTelegramDaemonRunningDetailed, resolveTelegramSetupPreflight } from "../../sdk/bus/telegram-daemon";
107
- import { TelegramDaemonController } from "../../sdk/bus/telegram-daemon-control";
108
- import { runTelegramSetup, type TelegramSetupPreflight } from "../../sdk/bus/telegram-setup";
66
+ createRoutingSettingsService,
67
+ RoutingSettingsActivationError,
68
+ type RoutingSettingsOutcome,
69
+ type RoutingSettingsPreview,
70
+ type RoutingSettingsService,
71
+ } from "../../sdk/routing-settings";
109
72
  import { clearPersistentPinForRemovedRows } from "../../session/account-inventory";
110
73
  import type {
111
74
  AgentSessionProfileInstalledOverrideState,
@@ -197,11 +160,6 @@ import { HistorySearchComponent } from "../components/history-search";
197
160
  import { HookSelectorComponent } from "../components/hook-selector";
198
161
  import { JobsOverlayComponent } from "../components/jobs-overlay";
199
162
  import { ModelSelectorComponent } from "../components/model-selector";
200
- import type {
201
- NotificationsEditorOperations,
202
- PreparedNotificationProviderConfiguration,
203
- PreparedTelegramConfiguration,
204
- } from "../components/notifications-settings-editor";
205
163
  import { OAuthSelectorComponent } from "../components/oauth-selector";
206
164
  import { isPetAvailable } from "../components/pet-capability";
207
165
  import { PetSelectorComponent } from "../components/pet-selector";
@@ -221,7 +179,6 @@ import { SessionObserverOverlayComponent } from "../components/session-observer-
221
179
  import { SessionSelectorComponent } from "../components/session-selector";
222
180
  import { dashboardSessions, SessionsDashboardComponent } from "../components/sessions-dashboard";
223
181
  import { SettingsSelectorComponent } from "../components/settings-selector";
224
- import type { SmartRoutingPreview } from "../components/smart-routing-panel";
225
182
  import { TasksPaneComponent } from "../components/tasks-pane";
226
183
  import { ThemeSelectorComponent } from "../components/theme-selector";
227
184
  import { ThinkingSelectorComponent } from "../components/thinking-selector";
@@ -287,925 +244,6 @@ function formatProviderOnboardingCommandGuide(): string {
287
244
  ].join("\n");
288
245
  }
289
246
 
290
- export interface NotificationsEditorAdapterContext {
291
- settings: Settings;
292
- session: Pick<InteractiveModeContext["session"], "notificationSessionController">;
293
- sessionManager: Pick<InteractiveModeContext["sessionManager"], "getCwd" | "getSessionId">;
294
- notifyConfigChanged?: () => Promise<void> | void;
295
- }
296
-
297
- type TelegramDaemonStopResult = {
298
- ok: boolean;
299
- message: string;
300
- before?: { health?: string };
301
- };
302
-
303
- export interface NotificationsEditorOperationDependencies {
304
- getNotificationConfig: typeof getNotificationConfig;
305
- getCurrentTelegramActivationMarker: typeof getCurrentTelegramActivationMarker;
306
- maskToken: typeof maskToken;
307
- buildNotificationStatusReport: typeof buildNotificationStatusReport;
308
- checkNotificationHealth: typeof checkNotificationHealth;
309
- sendNotificationTest: typeof sendNotificationTest;
310
- recoverNotifications: typeof recoverNotifications;
311
- sanitizeDiagnostic: typeof sanitizeDiagnostic;
312
- ensureTelegramDaemonRunningDetailed: typeof ensureTelegramDaemonRunningDetailed;
313
- runTelegramSetup: typeof runTelegramSetup;
314
- resolveTelegramSetupPreflight: typeof resolveTelegramSetupPreflight;
315
- proposedTelegramIdentity: typeof proposedTelegramIdentity;
316
- reconcileCommittedTelegramConfiguration: typeof reconcileCommittedTelegramConfiguration;
317
- saveTelegramInactive: typeof saveTelegramInactive;
318
- removeTelegramConfiguration: typeof removeTelegramConfiguration;
319
-
320
- reloadTelegramDaemon(settings: Settings): Promise<{ ok: boolean; message: string }>;
321
- restartTelegramDaemon(settings: Settings): Promise<{ ok: boolean; message: string }>;
322
- stopTelegramDaemon(settings: Settings): Promise<TelegramDaemonStopResult>;
323
- providerRuntime?: NotificationProviderRuntimeAuthority;
324
- }
325
-
326
- const notificationEditorOperationDependencies: NotificationsEditorOperationDependencies = {
327
- getNotificationConfig,
328
- getCurrentTelegramActivationMarker,
329
- maskToken,
330
- buildNotificationStatusReport,
331
- checkNotificationHealth,
332
- sendNotificationTest,
333
- recoverNotifications,
334
- sanitizeDiagnostic,
335
- ensureTelegramDaemonRunningDetailed,
336
- runTelegramSetup,
337
- resolveTelegramSetupPreflight,
338
- proposedTelegramIdentity,
339
- reconcileCommittedTelegramConfiguration,
340
- saveTelegramInactive,
341
- removeTelegramConfiguration,
342
-
343
- reloadTelegramDaemon: async settings =>
344
- await new TelegramDaemonController(settings).reload({ spawnIfStopped: false }),
345
- restartTelegramDaemon: async settings =>
346
- await new TelegramDaemonController(settings).reload({ spawnIfStopped: true }),
347
- stopTelegramDaemon: async settings => await new TelegramDaemonController(settings).stop(),
348
- };
349
-
350
- function unavailableNotificationSessionStatus(): NotificationSessionStatus {
351
- return {
352
- eligible: false,
353
- locallyEnabled: true,
354
- genericSessionEnabled: false,
355
- genericEligibilitySource: "none",
356
- running: false,
357
- };
358
- }
359
-
360
- function unavailableNotificationSessionResult() {
361
- return { outcome: "disabled" as const, status: unavailableNotificationSessionStatus() };
362
- }
363
-
364
- function notificationOperationError(
365
- services: NotificationsEditorOperationDependencies,
366
- error: unknown,
367
- token?: string,
368
- ): Error {
369
- return new Error(
370
- services.sanitizeDiagnostic(error instanceof Error ? error.message : "Notification operation failed.", token),
371
- );
372
- }
373
-
374
- /**
375
- * Concrete service adapter for the direct Notifications settings tab. Secrets remain in this closure's
376
- * WeakMap and are never exposed through the editor's safe draft contract.
377
- */
378
- export function createNotificationsEditorOperations(
379
- ctx: NotificationsEditorAdapterContext,
380
- overrides: Partial<NotificationsEditorOperationDependencies> = {},
381
- ): NotificationsEditorOperations {
382
- const services = { ...notificationEditorOperationDependencies, ...overrides };
383
- const drafts = new WeakMap<PreparedTelegramConfiguration, string>();
384
- const providerDrafts = new WeakMap<
385
- PreparedNotificationProviderConfiguration,
386
- { botToken?: string; appToken?: string }
387
- >();
388
- const sessionContext = () => ({ sessionManager: ctx.sessionManager });
389
- const notifyAfterDurableCommit = async (): Promise<void> => {
390
- await ctx.notifyConfigChanged?.();
391
- };
392
- const reconnect = async () => await services.ensureTelegramDaemonRunningDetailed({ settings: ctx.settings });
393
- const telegramSetupPreflight = async (): Promise<TelegramSetupPreflight> =>
394
- await services.resolveTelegramSetupPreflight(ctx.settings);
395
- const providerRuntime: NotificationProviderRuntimeAuthority = services.providerRuntime ?? {
396
- activate: async provider => {
397
- if (provider === "telegram") {
398
- const result = await reconnect();
399
- if (result === "blocked_identity" || result === "disabled") {
400
- throw new Error("Telegram activation failed after the durable save.");
401
- }
402
- await ctx.session.notificationSessionController?.reconcileCurrentSession(sessionContext());
403
- return;
404
- }
405
- const result = await new ChatDaemonController(ctx.settings, provider).ensure();
406
- if (result === "disabled") throw new Error(`${provider} activation failed after the durable save.`);
407
- },
408
- deactivate: async provider => {
409
- if (provider === "telegram") {
410
- const result = await services.stopTelegramDaemon(ctx.settings);
411
- if (!result.ok) throw new Error(result.message);
412
- await ctx.session.notificationSessionController?.reconcileCurrentSession(sessionContext());
413
- return;
414
- }
415
- const result = await new ChatDaemonController(ctx.settings, provider).stop();
416
- if (!result.ok) throw new Error(result.message);
417
- },
418
- };
419
-
420
- return {
421
- loadState: async () => {
422
- const config = services.getNotificationConfig(ctx.settings);
423
- const status = services.buildNotificationStatusReport(ctx.settings);
424
- const runtime = async (provider: NotificationProvider) => {
425
- const daemon =
426
- provider === "telegram"
427
- ? await new TelegramDaemonController(ctx.settings).status()
428
- : await new ChatDaemonController(ctx.settings, provider).status();
429
- return daemon.health === "running" ? "ready" : daemon.health === "not_configured" ? "inactive" : "failed";
430
- };
431
- const [telegramRuntime, discordRuntime, slackRuntime] = await Promise.all([
432
- runtime("telegram"),
433
- runtime("discord"),
434
- runtime("slack"),
435
- ]);
436
- status.telegram.runtime = telegramRuntime;
437
- status.discord.runtime = discordRuntime;
438
- status.slack.runtime = slackRuntime;
439
- return {
440
- status,
441
- session:
442
- ctx.session.notificationSessionController?.query(sessionContext()) ??
443
- unavailableNotificationSessionStatus(),
444
- preferences: {
445
- redact: config.redact,
446
- verbosity: config.verbosity,
447
- sessionScope: config.sessionScope,
448
- richEnabled: config.rich.enabled,
449
- richDraftEnabled: config.richDraft.enabled,
450
- toolActivityEnabled: config.toolActivity.enabled,
451
- streamingEnabled: config.streaming.enabled,
452
- sound: config.sound,
453
- },
454
- };
455
- },
456
-
457
- refreshHealth: async ({ probe, provider, signal }) => {
458
- if (signal?.aborted) throw new Error("Notification health refresh cancelled.");
459
- try {
460
- const input: Parameters<typeof checkNotificationHealth>[0] & { signal?: AbortSignal } = {
461
- settings: ctx.settings,
462
- stateRoot: path.join(ctx.sessionManager.getCwd(), ".gjc", "state"),
463
- probe,
464
- provider,
465
- signal,
466
- };
467
- const report = await services.checkNotificationHealth(input);
468
- if (signal?.aborted) throw new Error("Notification health refresh cancelled.");
469
- const token = services.getNotificationConfig(ctx.settings).botToken;
470
- return {
471
- ...report,
472
- checks: report.checks.map(check => ({
473
- ...check,
474
- detail: services.sanitizeDiagnostic(check.detail, token),
475
- })),
476
- reachability: {
477
- ...report.reachability,
478
- detail: services.sanitizeDiagnostic(report.reachability.detail, token),
479
- },
480
- };
481
- } catch (error) {
482
- throw notificationOperationError(services, error, services.getNotificationConfig(ctx.settings).botToken);
483
- }
484
- },
485
-
486
- sendTest: async provider => {
487
- try {
488
- const result = await services.sendNotificationTest({
489
- settings: ctx.settings,
490
- provider,
491
- deps: {
492
- providerRuntimeStatus: async selected => {
493
- const status =
494
- selected === "telegram"
495
- ? await new TelegramDaemonController(ctx.settings).status()
496
- : await new ChatDaemonController(ctx.settings, selected).status();
497
- return status.health === "running" ? "ready" : "inactive";
498
- },
499
- },
500
- });
501
- return {
502
- ...result,
503
- detail: services.sanitizeDiagnostic(
504
- result.detail,
505
- services.getNotificationConfig(ctx.settings).botToken,
506
- ),
507
- };
508
- } catch (error) {
509
- throw notificationOperationError(services, error, services.getNotificationConfig(ctx.settings).botToken);
510
- }
511
- },
512
-
513
- recover: async () => {
514
- try {
515
- const result = await services.recoverNotifications({
516
- settings: ctx.settings,
517
- stateRoot: path.join(ctx.sessionManager.getCwd(), ".gjc", "state"),
518
- });
519
- return {
520
- ...result,
521
- daemon: {
522
- ...result.daemon,
523
- detail: services.sanitizeDiagnostic(
524
- result.daemon.detail,
525
- services.getNotificationConfig(ctx.settings).botToken,
526
- ),
527
- },
528
- };
529
- } catch (error) {
530
- throw notificationOperationError(services, error, services.getNotificationConfig(ctx.settings).botToken);
531
- }
532
- },
533
-
534
- reconnect: async () => {
535
- try {
536
- const result = await reconnect();
537
- const controller = ctx.session.notificationSessionController;
538
- if (result === "blocked_identity") {
539
- await controller?.enterBlockedRuntime(sessionContext());
540
- } else if (result === "spawned" || result === "reloaded" || result === "attached") {
541
- await controller?.clearBlockedRuntime(sessionContext());
542
- await controller?.reconcileCurrentSession(sessionContext());
543
- }
544
- return result;
545
- } catch (error) {
546
- throw notificationOperationError(services, error, services.getNotificationConfig(ctx.settings).botToken);
547
- }
548
- },
549
-
550
- preflightProposedIdentity: async (input, signal) => {
551
- const token = input.token.consume();
552
- const unknownIdentity = { status: "unknown" as const };
553
- if (!token.trim()) {
554
- return {
555
- status: "error",
556
- identity: unknownIdentity,
557
- message: "Telegram bot token is required.",
558
- };
559
- }
560
- try {
561
- const setup = await services.runTelegramSetup({
562
- token,
563
- chatId: input.chatId,
564
- preflight: await telegramSetupPreflight(),
565
- revalidatePreflight: async () => await telegramSetupPreflight(),
566
- interactive: false,
567
- signal,
568
- deps: { fetchImpl: globalThis.fetch },
569
- });
570
- if (!setup.ok) {
571
- return {
572
- status: setup.status === "aborted" ? "aborted" : setup.status === "cancelled" ? "cancelled" : "error",
573
- identity: unknownIdentity,
574
- message: services.sanitizeDiagnostic(setup.detail, token),
575
- };
576
- }
577
- if (signal.aborted) {
578
- return {
579
- status: "aborted",
580
- identity: unknownIdentity,
581
- message: "Telegram setup cancelled.",
582
- };
583
- }
584
- const identity = await services.proposedTelegramIdentity({
585
- settings: ctx.settings,
586
- botToken: token,
587
- chatId: setup.chatId,
588
- chatDisplay: setup.chatId,
589
- });
590
- if (signal.aborted) {
591
- return {
592
- status: "aborted",
593
- identity,
594
- message: "Telegram setup cancelled.",
595
- };
596
- }
597
- const draft: PreparedTelegramConfiguration = {
598
- chatId: setup.chatId,
599
- tokenMask: services.maskToken(token),
600
- tokenFingerprint: setup.tokenFingerprint,
601
- richEnabled: input.richEnabled,
602
- richDraftEnabled: input.richDraftEnabled,
603
- streamingEnabled: input.streamingEnabled,
604
- };
605
- drafts.set(draft, token);
606
- const pairingMessage =
607
- setup.pairingSource === "discovered"
608
- ? "Telegram private chat discovered and validated."
609
- : setup.pairingSource === "reused"
610
- ? "Stored Telegram private chat validated without polling."
611
- : "Supplied Telegram private chat validated.";
612
- return {
613
- status: "ready",
614
- identity,
615
- draft,
616
- pairingSource: setup.pairingSource,
617
- message:
618
- identity.status === "foreign" || identity.status === "unknown"
619
- ? `${pairingMessage} Activation is blocked by the current daemon identity.`
620
- : pairingMessage,
621
- };
622
- } catch (error) {
623
- return {
624
- status: signal.aborted ? "aborted" : "error",
625
- identity: unknownIdentity,
626
- message: signal.aborted
627
- ? "Telegram setup cancelled."
628
- : services.sanitizeDiagnostic(
629
- error instanceof Error ? error.message : "Telegram setup failed.",
630
- token,
631
- ),
632
- };
633
- }
634
- },
635
-
636
- commitConfigure: async draft => {
637
- const token = drafts.get(draft);
638
- if (!token) throw new Error("The Telegram setup draft expired. Re-enter the masked bot token.");
639
- let receipt: SettingsAtomicReceipt | undefined;
640
- try {
641
- const inactiveMarkerToClear = observedTelegramActivationMarker(ctx.settings, token, draft.chatId);
642
- receipt = await ctx.settings.commitAtomicBatch([
643
- { path: "notifications.enabled", op: "set", value: true },
644
- { path: "notifications.telegram.botToken", op: "set", value: token },
645
- { path: "notifications.telegram.chatId", op: "set", value: draft.chatId },
646
- { path: "notifications.telegram.enabled", op: "set", value: true },
647
- { path: "notifications.telegram.rich.enabled", op: "set", value: draft.richEnabled },
648
- { path: "notifications.telegram.richDraft.enabled", op: "set", value: draft.richDraftEnabled },
649
- { path: "notifications.telegram.streaming.enabled", op: "set", value: draft.streamingEnabled },
650
- ]);
651
- drafts.delete(draft);
652
- const activationMarker = createTelegramActivationMarker({
653
- botToken: token,
654
- chatId: draft.chatId,
655
- state: "blocked",
656
- reason: "identity_mismatch",
657
- });
658
- const controller = ctx.session.notificationSessionController;
659
- const activation = await services.reconcileCommittedTelegramConfiguration({
660
- receipt,
661
- inactiveMarkerToClear,
662
- activation: {
663
- controller: controller
664
- ? {
665
- enterBlockedRuntime: async () => await controller.enterBlockedRuntime(sessionContext()),
666
- clearBlockedRuntime: async () => await controller.clearBlockedRuntime(sessionContext()),
667
- reconcileCurrentSession: async () =>
668
- await controller.reconcileCurrentSession(sessionContext()),
669
- }
670
- : {
671
- enterBlockedRuntime: async () => undefined,
672
- clearBlockedRuntime: async () => undefined,
673
- reconcileCurrentSession: async () => undefined,
674
- },
675
- reconnect,
676
- persistInactive: async marker => await persistTelegramActivationMarker(ctx.settings, marker),
677
- clearInactive: async marker => await clearTelegramActivationMarker(ctx.settings, marker),
678
- marker: activationMarker,
679
- },
680
- });
681
- let observerFailed = false;
682
- try {
683
- await notifyAfterDurableCommit();
684
- } catch {
685
- observerFailed = true;
686
- }
687
- if (activation.status === "blocked_identity") {
688
- return {
689
- status: "blocked_identity" as const,
690
- receipt,
691
- message: services.sanitizeDiagnostic(
692
- `${activation.message}${observerFailed ? " The settings observer also failed after the durable commit." : ""}`,
693
- token,
694
- ),
695
- restore: async () => {
696
- const restored = await activation.restore();
697
- if (restored.status === "restored" || restored.status === "still_blocked") {
698
- await notifyAfterDurableCommit();
699
- }
700
- return restored;
701
- },
702
- retainCommitted: () => activation.retainCommitted(),
703
- };
704
- }
705
- if (activation.status === "activation_failed") {
706
- return {
707
- status: "activation_failed" as const,
708
- receipt,
709
- message: services.sanitizeDiagnostic(
710
- `${activation.message}${observerFailed ? " The settings observer also failed after the durable commit." : ""}`,
711
- token,
712
- ),
713
- };
714
- }
715
- if (observerFailed) {
716
- return {
717
- status: "observer_failed" as const,
718
- receipt,
719
- message: "Telegram configuration was saved and activated, but the settings observer failed.",
720
- };
721
- }
722
- return {
723
- status: "saved" as const,
724
- receipt,
725
- message: services.sanitizeDiagnostic("Telegram configuration saved and reconciled.", token),
726
- };
727
- } catch (error) {
728
- if (receipt) {
729
- return {
730
- status: "activation_failed" as const,
731
- receipt,
732
- message: "Telegram configuration was saved, but post-commit activation failed.",
733
- };
734
- }
735
- throw notificationOperationError(services, error, token);
736
- }
737
- },
738
-
739
- saveInactive: async draft => {
740
- const token = drafts.get(draft);
741
- if (!token) throw new Error("The Telegram setup draft expired. Re-enter the masked bot token.");
742
- try {
743
- const result = await services.saveTelegramInactive({
744
- settings: ctx.settings,
745
- botToken: token,
746
- chatId: draft.chatId,
747
- });
748
- drafts.delete(draft);
749
- try {
750
- await notifyAfterDurableCommit();
751
- } catch {
752
- return {
753
- status: "observer_failed" as const,
754
- receipt: result.receipt,
755
- message: "Telegram configuration was saved inactive, but the settings observer failed.",
756
- };
757
- }
758
- return {
759
- status: "saved_inactive" as const,
760
- receipt: result.receipt,
761
- message: "Telegram configuration saved inactive; no runtime activation was requested.",
762
- };
763
- } catch (error) {
764
- throw notificationOperationError(services, error, token);
765
- }
766
- },
767
-
768
- discardConfigureDraft: draft => {
769
- drafts.delete(draft);
770
- },
771
-
772
- prepareProviderConfiguration: async input => {
773
- const cfg = services.getNotificationConfig(ctx.settings);
774
- const consumeSecret = (action: typeof input.botToken): string | undefined => {
775
- if (!action.value) return undefined;
776
- const value = action.value.consume();
777
- return action.action === "replace" ? value : undefined;
778
- };
779
- const botToken = consumeSecret(input.botToken);
780
- const appToken = input.appToken ? consumeSecret(input.appToken) : undefined;
781
- if (input.botToken.action === "replace" && !botToken?.trim()) {
782
- throw new Error("A non-blank bot token replacement is required.");
783
- }
784
- if (input.provider === "slack" && input.appToken?.action === "replace" && !appToken?.trim()) {
785
- throw new Error("A non-blank Slack app token replacement is required.");
786
- }
787
- if (input.provider === "discord") {
788
- const applicationId = input.applicationId?.trim() || undefined;
789
- const guildId = input.guildId?.trim() || undefined;
790
- const parentChannelId = input.parentChannelId?.trim() || undefined;
791
- const resolvedApplicationId = applicationId ?? cfg.discord.applicationId;
792
- const resolvedGuildId = guildId ?? cfg.discord.guildId;
793
- const resolvedParentChannelId = parentChannelId ?? cfg.discord.parentChannelId;
794
- const removesSecret = input.botToken.action === "remove";
795
- if (!removesSecret && (!resolvedApplicationId || !resolvedGuildId || !resolvedParentChannelId)) {
796
- throw new Error("Discord application, guild, and parent channel IDs are required.");
797
- }
798
- if (!removesSecret && input.botToken.action === "keep" && !cfg.discord.botToken) {
799
- throw new Error("Discord has no stored bot token to keep.");
800
- }
801
- const draft: PreparedNotificationProviderConfiguration = {
802
- provider: "discord",
803
- botTokenDisposition: input.botToken.action,
804
- botTokenMask: maskToken(botToken ?? cfg.discord.botToken),
805
- ...(applicationId === undefined ? {} : { applicationId }),
806
- ...(guildId === undefined ? {} : { guildId }),
807
- ...(parentChannelId === undefined ? {} : { parentChannelId }),
808
- applicationIdDisplay: resolvedApplicationId,
809
- guildIdDisplay: resolvedGuildId,
810
- parentChannelIdDisplay: resolvedParentChannelId,
811
- };
812
- providerDrafts.set(draft, { ...(botToken === undefined ? {} : { botToken }) });
813
- return draft;
814
- }
815
- const workspaceId = input.workspaceId?.trim() || undefined;
816
- const channelId = input.channelId?.trim() || undefined;
817
- const authorizedUserId = input.authorizedUserId?.trim() || undefined;
818
- const resolvedWorkspaceId = workspaceId ?? cfg.slack.workspaceId;
819
- const resolvedChannelId = channelId ?? cfg.slack.channelId;
820
- const resolvedAuthorizedUserId = authorizedUserId ?? cfg.slack.authorizedUserId;
821
- const appDisposition = input.appToken?.action ?? "keep";
822
- const removesSecret = input.botToken.action === "remove" || appDisposition === "remove";
823
- if (!removesSecret && (!resolvedWorkspaceId || !resolvedChannelId)) {
824
- throw new Error("Slack workspace and channel IDs are required.");
825
- }
826
- if (!removesSecret && input.botToken.action === "keep" && !cfg.slack.botToken) {
827
- throw new Error("Slack has no stored bot token to keep.");
828
- }
829
- if (!removesSecret && appDisposition === "keep" && !cfg.slack.appToken) {
830
- throw new Error("Slack has no stored app token to keep.");
831
- }
832
- const draft: PreparedNotificationProviderConfiguration = {
833
- provider: "slack",
834
- botTokenDisposition: input.botToken.action,
835
- botTokenMask: maskToken(botToken ?? cfg.slack.botToken),
836
- appTokenDisposition: appDisposition,
837
- appTokenMask: maskToken(appToken ?? cfg.slack.appToken),
838
- ...(workspaceId === undefined ? {} : { workspaceId }),
839
- ...(channelId === undefined ? {} : { channelId }),
840
- ...(authorizedUserId === undefined ? {} : { authorizedUserId }),
841
- workspaceIdDisplay: resolvedWorkspaceId,
842
- channelIdDisplay: resolvedChannelId,
843
- authorizedUserIdDisplay: resolvedAuthorizedUserId,
844
- };
845
- providerDrafts.set(draft, {
846
- ...(botToken === undefined ? {} : { botToken }),
847
- ...(appToken === undefined ? {} : { appToken }),
848
- });
849
- return draft;
850
- },
851
-
852
- commitProviderConfiguration: async draft => {
853
- const secrets = providerDrafts.get(draft) ?? {};
854
- try {
855
- let mutation: NotificationProviderConfigurationMutation;
856
- if (draft.provider === "discord") {
857
- mutation = {
858
- provider: "discord",
859
- botToken:
860
- draft.botTokenDisposition === "replace"
861
- ? { action: "replace", value: secrets.botToken ?? "" }
862
- : { action: draft.botTokenDisposition },
863
- applicationId: draft.applicationId,
864
- guildId: draft.guildId,
865
- parentChannelId: draft.parentChannelId,
866
- };
867
- } else {
868
- const appDisposition = draft.appTokenDisposition ?? "keep";
869
- mutation = {
870
- provider: "slack",
871
- botToken:
872
- draft.botTokenDisposition === "replace"
873
- ? { action: "replace", value: secrets.botToken ?? "" }
874
- : { action: draft.botTokenDisposition },
875
- appToken:
876
- appDisposition === "replace"
877
- ? { action: "replace", value: secrets.appToken ?? "" }
878
- : { action: appDisposition },
879
- workspaceId: draft.workspaceId,
880
- channelId: draft.channelId,
881
- authorizedUserId: draft.authorizedUserId,
882
- };
883
- }
884
- const removesSecret = draft.botTokenDisposition === "remove" || draft.appTokenDisposition === "remove";
885
- const result = await mutateNotificationProvider({
886
- settings: ctx.settings,
887
- mutation,
888
- configureAndActivate: !removesSecret,
889
- ...(removesSecret ? { desiredEnabled: false } : {}),
890
- notifyConfigChanged: notifyAfterDurableCommit,
891
- runtime: providerRuntime,
892
- });
893
- const outcome =
894
- result.status === "commit_failed"
895
- ? "failed"
896
- : result.status === "activation_failed" ||
897
- result.status === "deactivation_failed" ||
898
- result.observerFailed
899
- ? "degraded"
900
- : "success";
901
- const observerSuffix =
902
- result.status !== "commit_failed" && result.observerFailed
903
- ? " The settings observer also failed after the durable commit."
904
- : "";
905
- return {
906
- ...(result.status === "commit_failed" ? {} : { receipt: result.receipt }),
907
- outcome,
908
- message:
909
- (result.status === "activated"
910
- ? `${draft.provider} configuration saved and activated.`
911
- : result.status === "activation_failed"
912
- ? `${draft.provider} configuration and desired intent were saved, but runtime activation failed.`
913
- : result.status === "deactivation_failed"
914
- ? `${draft.provider} desired-off configuration was saved, but runtime deactivation failed.`
915
- : result.status === "commit_failed"
916
- ? `${draft.provider} configuration was not saved because the CAS commit failed.`
917
- : `${draft.provider} configuration saved.`) + observerSuffix,
918
- };
919
- } finally {
920
- providerDrafts.delete(draft);
921
- }
922
- },
923
-
924
- discardProviderConfiguration: draft => {
925
- providerDrafts.delete(draft);
926
- },
927
-
928
- setProviderDesired: async (provider, enabled) => {
929
- if (provider === "telegram" && enabled) {
930
- const config = services.getNotificationConfig(ctx.settings);
931
- if (services.getCurrentTelegramActivationMarker(config)) {
932
- return {
933
- outcome: "failed",
934
- message:
935
- "Telegram remains inactive because its exact activation marker must be restored or cleared after safe owner readiness.",
936
- };
937
- }
938
- }
939
- const mutation: NotificationProviderConfigurationMutation =
940
- provider === "telegram"
941
- ? { provider, botToken: { action: "keep" } }
942
- : provider === "discord"
943
- ? { provider, botToken: { action: "keep" } }
944
- : { provider, botToken: { action: "keep" }, appToken: { action: "keep" } };
945
- const result = await mutateNotificationProvider({
946
- settings: ctx.settings,
947
- mutation,
948
- desiredEnabled: enabled,
949
- notifyConfigChanged: notifyAfterDurableCommit,
950
- runtime: providerRuntime,
951
- });
952
- const outcome =
953
- result.status === "commit_failed"
954
- ? "failed"
955
- : result.status === "activation_failed" ||
956
- result.status === "deactivation_failed" ||
957
- result.observerFailed
958
- ? "degraded"
959
- : "success";
960
- return {
961
- ...(result.status === "commit_failed" ? {} : { receipt: result.receipt }),
962
- outcome,
963
- message:
964
- (result.status === "activation_failed"
965
- ? `${provider} desired intent was saved, but activation failed.`
966
- : result.status === "deactivation_failed"
967
- ? `${provider} desired-off intent was saved, but deactivation failed.`
968
- : result.status === "commit_failed"
969
- ? `${provider} desired intent was not saved because the CAS commit failed.`
970
- : `${provider} desired intent ${enabled ? "enabled" : "disabled"}.`) +
971
- (result.status !== "commit_failed" && result.observerFailed
972
- ? " The settings observer also failed after the durable commit."
973
- : ""),
974
- };
975
- },
976
-
977
- removeProvider: async provider => {
978
- if (provider === "telegram") {
979
- return { message: "Use the Telegram removal action to preserve root-registration fencing." };
980
- }
981
- const result = await removeNotificationProvider({
982
- settings: ctx.settings,
983
- provider,
984
- runtime: providerRuntime,
985
- notifyConfigChanged: notifyAfterDurableCommit,
986
- });
987
- const degraded =
988
- result.status === "deactivation_failed" || ("observerFailed" in result && result.observerFailed);
989
- return {
990
- ...("receipt" in result && result.receipt ? { receipt: result.receipt } : {}),
991
- outcome:
992
- result.status === "commit_failed" || result.status === "commit_failed_after_teardown"
993
- ? "failed"
994
- : degraded
995
- ? "degraded"
996
- : "success",
997
- message:
998
- (result.status === "removed"
999
- ? `${provider} configuration removed.`
1000
- : result.status === "deactivation_failed"
1001
- ? `${provider} configuration was removed, but runtime deactivation failed.`
1002
- : `${provider} configuration removal failed.`) +
1003
- ("observerFailed" in result && result.observerFailed
1004
- ? " The settings observer also failed after the durable commit."
1005
- : ""),
1006
- };
1007
- },
1008
-
1009
- enableGlobally: async () => {
1010
- const result = await setGlobalNotificationsEnabled({
1011
- settings: ctx.settings,
1012
- enabled: true,
1013
- notifyConfigChanged: notifyAfterDurableCommit,
1014
- runtime: providerRuntime,
1015
- });
1016
- const degraded =
1017
- result.status === "global_activation_partial" || ("observerFailed" in result && result.observerFailed);
1018
- return {
1019
- ...(result.status === "commit_failed" ? {} : { receipt: result.receipt }),
1020
- outcome: result.status === "commit_failed" ? "failed" : degraded ? "degraded" : "success",
1021
- message:
1022
- (result.status === "global_activation_partial"
1023
- ? `Global notifications were enabled, but activation failed for ${result.failed.join(", ")}.`
1024
- : result.status === "commit_failed"
1025
- ? "Global notifications were not enabled because the CAS commit failed."
1026
- : "Global notifications enabled using stored provider intent.") +
1027
- (result.status !== "commit_failed" && result.observerFailed
1028
- ? " The settings observer also failed after the durable commit."
1029
- : ""),
1030
- };
1031
- },
1032
-
1033
- disableGlobally: async () => {
1034
- const result = await setGlobalNotificationsEnabled({
1035
- settings: ctx.settings,
1036
- enabled: false,
1037
- notifyConfigChanged: notifyAfterDurableCommit,
1038
- runtime: providerRuntime,
1039
- });
1040
- const degraded =
1041
- result.status === "global_deactivation_partial" || ("observerFailed" in result && result.observerFailed);
1042
- return {
1043
- ...(result.status === "commit_failed" ? {} : { receipt: result.receipt }),
1044
- outcome: result.status === "commit_failed" ? "failed" : degraded ? "degraded" : "success",
1045
- message:
1046
- (result.status === "global_deactivation_partial"
1047
- ? `Global notifications were disabled, but teardown failed for ${result.failed.join(", ")}.`
1048
- : result.status === "commit_failed"
1049
- ? "Global notifications were not disabled because the CAS commit failed."
1050
- : "Global notifications disabled; provider configuration and desired intent were preserved.") +
1051
- (result.status !== "commit_failed" && result.observerFailed
1052
- ? " The settings observer also failed after the durable commit."
1053
- : ""),
1054
- };
1055
- },
1056
-
1057
- removeTelegram: async () => {
1058
- const controller = ctx.session.notificationSessionController;
1059
- let runtimePrepared = false;
1060
- try {
1061
- const result = await services.removeTelegramConfiguration({
1062
- settings: ctx.settings,
1063
- removal: {
1064
- stopAndUnregister: async () => {
1065
- if (controller) await controller.enterBlockedRuntime(sessionContext());
1066
- runtimePrepared = true;
1067
- const stopped = await services.stopTelegramDaemon(ctx.settings);
1068
- if (!stopped.ok) throw new Error(stopped.message);
1069
- },
1070
- },
1071
- });
1072
- const postCommitFailures: string[] = [];
1073
- if (runtimePrepared && controller) {
1074
- try {
1075
- await controller.clearBlockedRuntime(sessionContext());
1076
- await controller.reconcileCurrentSession(sessionContext());
1077
- } catch {
1078
- postCommitFailures.push("current-session reconciliation failed");
1079
- }
1080
- }
1081
- try {
1082
- await notifyAfterDurableCommit();
1083
- } catch {
1084
- postCommitFailures.push("settings observer failed");
1085
- }
1086
- return {
1087
- receipt: result.receipt,
1088
- outcome: postCommitFailures.length === 0 ? "success" : "degraded",
1089
- globallyDisabled: result.globallyDisabled,
1090
- message: `Telegram configuration removed without changing the global master.${
1091
- postCommitFailures.length === 0 ? "" : ` Post-commit ${postCommitFailures.join(" and ")}.`
1092
- }`,
1093
- };
1094
- } catch (error) {
1095
- if (runtimePrepared) {
1096
- const restored = await reconnect();
1097
- if (restored !== "blocked_identity" && controller) {
1098
- await controller.clearBlockedRuntime(sessionContext());
1099
- await controller.reconcileCurrentSession(sessionContext());
1100
- }
1101
- }
1102
- throw notificationOperationError(services, error, services.getNotificationConfig(ctx.settings).botToken);
1103
- }
1104
- },
1105
-
1106
- setSessionLocal: async enabled => {
1107
- const controller = ctx.session.notificationSessionController;
1108
- if (!controller) return unavailableNotificationSessionResult();
1109
- try {
1110
- return await controller.setLocalEnabled(sessionContext(), enabled);
1111
- } catch (error) {
1112
- throw notificationOperationError(services, error, services.getNotificationConfig(ctx.settings).botToken);
1113
- }
1114
- },
1115
-
1116
- commitPreferences: async preferences => {
1117
- let daemonWasRunningForDisable = false;
1118
- try {
1119
- const before = services.getNotificationConfig(ctx.settings);
1120
- const disablingToolActivity =
1121
- isProviderEffectivelyEnabled(before, "telegram") &&
1122
- isTelegramComplete(before) &&
1123
- before.toolActivity.enabled &&
1124
- !preferences.toolActivityEnabled;
1125
- if (disablingToolActivity) {
1126
- const stopped = await services.stopTelegramDaemon(ctx.settings);
1127
- if (!stopped.ok)
1128
- throw new Error(
1129
- `Notification preferences were not saved because daemon stop failed: ${stopped.message}`,
1130
- );
1131
- daemonWasRunningForDisable = stopped.before?.health === "running";
1132
- }
1133
-
1134
- let receipt: SettingsAtomicReceipt;
1135
- try {
1136
- receipt = await ctx.settings.commitAtomicBatch([
1137
- { path: "notifications.redact", op: "set", value: preferences.redact },
1138
- { path: "notifications.verbosity", op: "set", value: preferences.verbosity },
1139
- { path: "notifications.sessionScope", op: "set", value: preferences.sessionScope },
1140
- { path: "notifications.telegram.sound", op: "set", value: preferences.sound },
1141
- { path: "notifications.telegram.rich.enabled", op: "set", value: preferences.richEnabled },
1142
- { path: "notifications.telegram.richDraft.enabled", op: "set", value: preferences.richDraftEnabled },
1143
- { path: "notifications.telegram.streaming.enabled", op: "set", value: preferences.streamingEnabled },
1144
- {
1145
- path: "notifications.telegram.toolActivity.enabled",
1146
- op: "set",
1147
- value: preferences.toolActivityEnabled,
1148
- },
1149
- ]);
1150
- } catch (error) {
1151
- if (daemonWasRunningForDisable) {
1152
- try {
1153
- const restarted = await services.restartTelegramDaemon(ctx.settings);
1154
- if (!restarted.ok) throw new Error(restarted.message);
1155
- } catch (restartError) {
1156
- const commitMessage = error instanceof Error ? error.message : String(error);
1157
- const restartMessage = restartError instanceof Error ? restartError.message : String(restartError);
1158
- throw new Error(
1159
- `Notification preference commit failed (${commitMessage}) and daemon restart failed (${restartMessage}).`,
1160
- { cause: new AggregateError([error, restartError]) },
1161
- );
1162
- }
1163
- }
1164
- throw error;
1165
- }
1166
-
1167
- const postCommitFailures: string[] = [];
1168
- const config = services.getNotificationConfig(ctx.settings);
1169
- if (isProviderEffectivelyEnabled(config, "telegram") && isTelegramComplete(config)) {
1170
- try {
1171
- const reload = daemonWasRunningForDisable
1172
- ? await services.restartTelegramDaemon(ctx.settings)
1173
- : await services.reloadTelegramDaemon(ctx.settings);
1174
- if (!reload.ok) postCommitFailures.push(`daemon reload failed: ${reload.message}`);
1175
- } catch {
1176
- postCommitFailures.push("daemon reload failed");
1177
- }
1178
- }
1179
- try {
1180
- await notifyAfterDurableCommit();
1181
- } catch {
1182
- postCommitFailures.push("settings observer failed");
1183
- }
1184
- return {
1185
- receipt,
1186
- outcome: postCommitFailures.length === 0 ? "success" : "degraded",
1187
- message:
1188
- postCommitFailures.length === 0
1189
- ? "Notification preferences saved atomically."
1190
- : `Notification preferences were saved, but post-commit ${postCommitFailures.join(" and ")}.`,
1191
- };
1192
- } catch (error) {
1193
- throw notificationOperationError(services, error, services.getNotificationConfig(ctx.settings).botToken);
1194
- }
1195
- },
1196
-
1197
- reconcileCurrentSession: async () => {
1198
- const controller = ctx.session.notificationSessionController;
1199
- if (!controller) return unavailableNotificationSessionResult();
1200
- try {
1201
- return await controller.reconcileCurrentSession(sessionContext());
1202
- } catch (error) {
1203
- throw notificationOperationError(services, error, services.getNotificationConfig(ctx.settings).botToken);
1204
- }
1205
- },
1206
- };
1207
- }
1208
-
1209
247
  interface DefaultAssignmentRollbackSnapshot {
1210
248
  model: Model<Api> | undefined;
1211
249
  thinkingLevel: ThinkingLevel | undefined;
@@ -1223,35 +261,8 @@ interface DefaultAssignmentRollbackSnapshot {
1223
261
  fallbackRuntimeState: DefaultFallbackRuntimeState;
1224
262
  }
1225
263
 
1226
- function sameCanonicalAutoroutingValue(left: unknown, right: unknown): boolean {
1227
- const leftBytes = canonicalJsonBytes(left);
1228
- const rightBytes = canonicalJsonBytes(right);
1229
- if (leftBytes.length !== rightBytes.length) return false;
1230
- for (let index = 0; index < leftBytes.length; index++) {
1231
- if (leftBytes[index] !== rightBytes[index]) return false;
1232
- }
1233
- return true;
1234
- }
1235
-
1236
- function rawAutoroutingState(current: RawSettings): {
1237
- provenance?: AutoroutingProvenance;
1238
- setup?: AutoroutingSetup;
1239
- tiers?: unknown;
1240
- } {
1241
- const task = current.task;
1242
- if (!task || typeof task !== "object" || Array.isArray(task)) return {};
1243
- const autorouting = (task as Record<string, unknown>).autorouting;
1244
- if (!autorouting || typeof autorouting !== "object" || Array.isArray(autorouting)) return {};
1245
- const record = autorouting as Record<string, unknown>;
1246
- return {
1247
- provenance: record.provenance as AutoroutingProvenance | undefined,
1248
- setup: record.setup as AutoroutingSetup | undefined,
1249
- tiers: record.tiers,
1250
- };
1251
- }
1252
-
1253
264
  export class SelectorController {
1254
- #smartRoutingInFlight?: Promise<unknown>;
265
+ #smartRouting: RoutingSettingsService;
1255
266
  #modelSelector?: ModelSelectorComponent;
1256
267
  #settingsSelector?: SettingsSelectorComponent;
1257
268
  #statusLinePreview?: Partial<StatusLineSettings>;
@@ -1271,6 +282,13 @@ export class SelectorController {
1271
282
  private readonly clipboard: (text: string) => void = copyToClipboard,
1272
283
  ) {
1273
284
  this.#credentialAutoImportStateStore = credentialAutoImportStateStore;
285
+ this.#smartRouting = createRoutingSettingsService({
286
+ settings: ctx.settings,
287
+ getCatalog: () => ctx.session.modelRegistry.getAll(ctx.session.credentialSessionId),
288
+ getProviderOrder: () => ctx.session.modelRegistry.autoroutingProviderOrder(),
289
+ isScoped: () => (ctx.session.scopedModels?.length ?? 0) > 0,
290
+ activate: ctx.notifyConfigChanged ? () => ctx.notifyConfigChanged!() : undefined,
291
+ });
1274
292
  }
1275
293
 
1276
294
  #captureDefaultAssignmentRollback(): DefaultAssignmentRollbackSnapshot {
@@ -1463,7 +481,7 @@ export class SelectorController {
1463
481
 
1464
482
  #applyStatusLineSettings(): void {
1465
483
  this.ctx.statusLine.updateSettings({
1466
- ...buildStatusLineSettings(this.ctx.settings),
484
+ ...buildStatusLineSettings(this.ctx.session.settings),
1467
485
  ...(this.#statusLinePreviewActive ? this.#statusLinePreview : undefined),
1468
486
  });
1469
487
  }
@@ -1972,6 +990,7 @@ export class SelectorController {
1972
990
 
1973
991
  const selector = new SettingsSelectorComponent(
1974
992
  {
993
+ settings: this.ctx.session.settings,
1975
994
  availableThinkingLevels: [...this.ctx.session.getAvailableThinkingLevels()],
1976
995
  thinkingLevel: this.ctx.session.thinkingLevel,
1977
996
  availableThemes,
@@ -2000,7 +1019,7 @@ export class SelectorController {
2000
1019
  });
2001
1020
  },
2002
1021
  onThemeCommit: async (path, themeName, previousTheme) => {
2003
- if (!settings.canWriteDurableConfig()) {
1022
+ if (!this.ctx.session.settings.canWriteDurableConfig()) {
2004
1023
  this.ctx.showError(
2005
1024
  "Cannot change settings while config.yml has invalid YAML syntax. Repair config.yml and reload settings.",
2006
1025
  );
@@ -2019,7 +1038,7 @@ export class SelectorController {
2019
1038
  return false;
2020
1039
  }
2021
1040
  try {
2022
- settings.set(path, themeName);
1041
+ this.ctx.session.settings.set(path, themeName);
2023
1042
  } catch (error) {
2024
1043
  await restoreThemePreview(previousTheme);
2025
1044
  this.ctx.showError(error instanceof Error ? error.message : String(error));
@@ -2060,7 +1079,7 @@ export class SelectorController {
2060
1079
  const availableWidth =
2061
1080
  width ?? this.ctx.editor.getTopBorderAvailableWidth(this.ctx.ui.terminal.columns);
2062
1081
  return this.ctx.statusLine.getPreviewContentForSettings(availableWidth, {
2063
- ...buildStatusLineSettings(settings),
1082
+ ...buildStatusLineSettings(this.ctx.session.settings),
2064
1083
  ...previewSettings,
2065
1084
  });
2066
1085
  },
@@ -2068,7 +1087,7 @@ export class SelectorController {
2068
1087
  const availableWidth =
2069
1088
  width ?? this.ctx.editor.getTopBorderAvailableWidth(this.ctx.ui.terminal.columns);
2070
1089
  return this.ctx.statusLine.getPreviewPartsForSettings(availableWidth, {
2071
- ...buildStatusLineSettings(settings),
1090
+ ...buildStatusLineSettings(this.ctx.session.settings),
2072
1091
  ...previewSettings,
2073
1092
  });
2074
1093
  },
@@ -2083,7 +1102,7 @@ export class SelectorController {
2083
1102
  let editor: ProviderOrderEditorComponent | undefined;
2084
1103
  const context = new ProviderOrderContext(
2085
1104
  this.ctx.session.modelRegistry,
2086
- this.ctx.settings,
1105
+ this.ctx.session.settings,
2087
1106
  () => {
2088
1107
  editor?.refresh();
2089
1108
  this.ctx.ui.requestRender();
@@ -2113,7 +1132,7 @@ export class SelectorController {
2113
1132
  onCancel: () => {
2114
1133
  done();
2115
1134
  // Restore status line to saved settings
2116
- this.ctx.statusLine.updateSettings(buildStatusLineSettings(settings));
1135
+ this.ctx.statusLine.updateSettings(buildStatusLineSettings(this.ctx.session.settings));
2117
1136
  this.ctx.updateEditorTopBorder();
2118
1137
  this.ctx.ui.requestRender();
2119
1138
  },
@@ -2375,9 +1394,9 @@ export class SelectorController {
2375
1394
  case "stt.enabled":
2376
1395
  if (value === true) {
2377
1396
  void configureSttFromSettings({
2378
- modelName: settings.get("stt.modelName"),
2379
- setEnabled: enabled => settings.set("stt.enabled", enabled),
2380
- flush: () => settings.flushOrThrow(),
1397
+ modelName: this.ctx.session.settings.get("stt.modelName"),
1398
+ setEnabled: enabled => this.ctx.session.settings.set("stt.enabled", enabled),
1399
+ flush: () => this.ctx.session.settings.flushOrThrow(),
2381
1400
  showStatus: message => this.ctx.showStatus(message),
2382
1401
  showError: message => this.ctx.showError(message),
2383
1402
  });
@@ -2445,36 +1464,6 @@ export class SelectorController {
2445
1464
  });
2446
1465
  break;
2447
1466
  }
2448
- case "temperature": {
2449
- const temp = typeof value === "number" ? value : Number(value);
2450
- this.ctx.session.agent.temperature = temp >= 0 ? temp : undefined;
2451
- break;
2452
- }
2453
- case "topP": {
2454
- const topP = typeof value === "number" ? value : Number(value);
2455
- this.ctx.session.agent.topP = topP >= 0 ? topP : undefined;
2456
- break;
2457
- }
2458
- case "topK": {
2459
- const topK = typeof value === "number" ? value : Number(value);
2460
- this.ctx.session.agent.topK = topK >= 0 ? topK : undefined;
2461
- break;
2462
- }
2463
- case "minP": {
2464
- const minP = typeof value === "number" ? value : Number(value);
2465
- this.ctx.session.agent.minP = minP >= 0 ? minP : undefined;
2466
- break;
2467
- }
2468
- case "presencePenalty": {
2469
- const presencePenalty = typeof value === "number" ? value : Number(value);
2470
- this.ctx.session.agent.presencePenalty = presencePenalty >= 0 ? presencePenalty : undefined;
2471
- break;
2472
- }
2473
- case "repetitionPenalty": {
2474
- const repetitionPenalty = typeof value === "number" ? value : Number(value);
2475
- this.ctx.session.agent.repetitionPenalty = repetitionPenalty >= 0 ? repetitionPenalty : undefined;
2476
- break;
2477
- }
2478
1467
  case "statusLine.showActionHints": {
2479
1468
  this.ctx.updateEditorChrome();
2480
1469
  break;
@@ -2501,7 +1490,7 @@ export class SelectorController {
2501
1490
  case "statusLineGitShowUntracked":
2502
1491
  case "statusLineTimeFormat":
2503
1492
  case "statusLineTimeShowSeconds": {
2504
- this.ctx.statusLine.updateSettings(buildStatusLineSettings(settings));
1493
+ this.ctx.statusLine.updateSettings(buildStatusLineSettings(this.ctx.session.settings));
2505
1494
  this.ctx.updateEditorTopBorder();
2506
1495
  this.ctx.ui.requestRender();
2507
1496
  break;
@@ -2509,7 +1498,8 @@ export class SelectorController {
2509
1498
  case "irc.enabled":
2510
1499
  case "irc.sidebar.enabled":
2511
1500
  this.ctx.applyIrcSidebarAvailability(
2512
- this.ctx.settings.get("irc.enabled") === true && this.ctx.settings.get("irc.sidebar.enabled") === true,
1501
+ this.ctx.session.settings.get("irc.enabled") === true &&
1502
+ this.ctx.session.settings.get("irc.sidebar.enabled") === true,
2513
1503
  );
2514
1504
  break;
2515
1505
 
@@ -2556,7 +1546,7 @@ export class SelectorController {
2556
1546
  {
2557
1547
  session: this.ctx.session,
2558
1548
  modelRegistry: this.ctx.session.modelRegistry,
2559
- settings: this.ctx.settings,
1549
+ settings: this.ctx.session.settings,
2560
1550
  profileName,
2561
1551
  },
2562
1552
  { persistDefault },
@@ -2567,207 +1557,70 @@ export class SelectorController {
2567
1557
  this.ctx.showStatus(persistDefault ? `Default model profile: ${profileLabel}` : `Model profile: ${profileLabel}`);
2568
1558
  }
2569
1559
 
2570
- /** Generate the immutable preview used by the smart-routing panel. */
2571
- previewSmartRouting(draft: AutoroutingSetup): SmartRoutingPreview {
2572
- const issues = validateAutoroutingSetup(draft);
2573
- if (issues.length > 0)
2574
- throw new Error(issues.map(issue => `${issue.path || "setup"}: ${issue.detail}`).join("; "));
2575
- const setup = structuredClone(draft);
2576
- const generated = generateTierChains(setup, CURATED_TIER_MAP, [
2577
- ...this.ctx.session.modelRegistry.getAll(this.ctx.session.credentialSessionId),
2578
- ]);
2579
- const provenance: AutoroutingProvenance = {
2580
- schema: 1,
2581
- source: structuredClone(generated.sourceIdentity),
2582
- declarationFingerprint: generated.declarationFingerprint,
2583
- tiersFingerprint: generated.tiersFingerprint,
2584
- };
2585
- return {
2586
- setup,
2587
- tiers: structuredClone(generated.tiers),
2588
- provenance,
2589
- sourceIdentity: structuredClone(generated.sourceIdentity),
2590
- };
1560
+ previewSmartRouting(draft: AutoroutingSetup): RoutingSettingsPreview {
1561
+ return this.#smartRouting.previewSmartRouting(draft);
2591
1562
  }
2592
1563
 
2593
- #assertSmartRoutingWritable(): void {
2594
- if ((this.ctx.session.scopedModels?.length ?? 0) > 0) {
2595
- throw new Error("Smart-routing settings are read-only in a --models-scoped session.");
2596
- }
2597
- if (!this.ctx.settings.canWriteDurableConfig()) {
2598
- throw new Error("Cannot change smart-routing settings while durable config is unavailable.");
1564
+ async #runSmartRoutingIntent<T extends RoutingSettingsOutcome>(
1565
+ label: string,
1566
+ operation: () => Promise<T>,
1567
+ ): Promise<T> {
1568
+ this.ctx.showStatus(`${label} smart-routing settings…`);
1569
+ let result: T;
1570
+ try {
1571
+ result = await operation();
1572
+ } catch (error) {
1573
+ this.#updateSmartRoutingUi(() => this.ctx.showError(error instanceof Error ? error.message : String(error)));
1574
+ this.#updateSmartRoutingUi(() => this.ctx.ui.requestRender());
1575
+ throw error;
2599
1576
  }
2600
- }
2601
-
2602
- #assertSmartRoutingNotHandEdited(
2603
- preview: SmartRoutingPreview,
2604
- allowHandEdit: boolean,
2605
- current?: { provenance?: AutoroutingProvenance; tiers?: unknown },
2606
- ): void {
2607
- if (allowHandEdit) return;
2608
- const provenance = current?.provenance ?? this.ctx.settings.get("task.autorouting.provenance");
2609
- const currentTiers = current?.tiers ?? this.ctx.settings.get("task.autorouting.tiers");
2610
- if (!provenance || currentTiers === undefined) return;
2611
- const state = evaluateAutoroutingProvenanceState(provenance, {
2612
- catalogFingerprint: preview.sourceIdentity.catalogFingerprint,
2613
- mapFingerprint: preview.sourceIdentity.mapFingerprint,
2614
- tiers: currentTiers,
2615
- });
2616
- if (!state.handEdited) return;
2617
- throw Object.assign(
2618
- new Error("Generated autorouting tiers were hand-edited; explicit confirmation is required."),
2619
- { code: "autorouting-hand-edited" },
1577
+ this.#updateSmartRoutingUi(() =>
1578
+ this.ctx.showStatus(
1579
+ `${label} smart-routing settings ${result.durability === "persisted" ? "saved" : "updated in memory"}.`,
1580
+ ),
2620
1581
  );
1582
+ this.#updateSmartRoutingUi(() => this.ctx.ui.requestRender());
1583
+ return result;
2621
1584
  }
2622
1585
 
2623
- async #runSmartRoutingIntent<T>(label: string, operation: () => Promise<T>): Promise<T> {
2624
- if (this.#smartRoutingInFlight) throw new Error("Another smart-routing operation is already in progress.");
2625
- const task = (async () => {
2626
- this.ctx.showStatus(`${label} smart-routing settings…`);
2627
- try {
2628
- const result = await operation();
2629
- await this.ctx.notifyConfigChanged?.();
2630
- this.ctx.showStatus(`${label} smart-routing settings saved.`);
2631
- this.ctx.ui.requestRender();
2632
- return result;
2633
- } catch (error) {
2634
- this.ctx.showError(error instanceof Error ? error.message : String(error));
2635
- this.ctx.ui.requestRender();
2636
- throw error;
2637
- } finally {
2638
- this.#smartRoutingInFlight = undefined;
2639
- }
2640
- })();
2641
- this.#smartRoutingInFlight = task;
2642
- return task;
2643
- }
2644
- #reportSmartRoutingValidationError(error: unknown): never {
2645
- this.ctx.showError(error instanceof Error ? error.message : String(error));
2646
- this.ctx.ui.requestRender();
2647
- throw error;
1586
+ #updateSmartRoutingUi(update: () => void): void {
1587
+ try {
1588
+ update();
1589
+ } catch {
1590
+ logger.warn("Smart-routing UI update failed", { classification: "smart-routing-ui-update-failed" });
1591
+ }
2648
1592
  }
2649
1593
 
2650
- async applySmartRouting(
2651
- draft: AutoroutingSetup,
2652
- options?: { preview?: SmartRoutingPreview; confirmHandEdit?: boolean },
2653
- ): Promise<SmartRoutingPreview> {
2654
- let preview: SmartRoutingPreview;
1594
+ #refreshSmartRoutingUi(selector: ModelSelectorComponent, preview?: RoutingSettingsPreview): void {
2655
1595
  try {
2656
- this.#assertSmartRoutingWritable();
2657
- const issues = validateAutoroutingSetup(draft);
2658
- if (issues.length > 0) {
2659
- throw new Error(issues.map(issue => `${issue.path || "setup"}: ${issue.detail}`).join("; "));
2660
- }
2661
- preview = options?.preview ?? this.previewSmartRouting(draft);
2662
- const regenerated = this.previewSmartRouting(draft);
2663
- if (!sameCanonicalAutoroutingValue(preview.setup, regenerated.setup)) {
2664
- throw new Error("Smart-routing preview does not match the draft being applied.");
2665
- }
2666
- if (
2667
- !sameCanonicalAutoroutingValue(preview.tiers, regenerated.tiers) ||
2668
- !sameCanonicalAutoroutingValue(preview.provenance, regenerated.provenance)
2669
- ) {
2670
- // Never persist caller-supplied tier/provenance bytes that diverge from
2671
- // the declaration. Continue with the fresh canonical payload so Apply
2672
- // remains exactly the generated preview for legitimate callers.
2673
- preview = regenerated;
2674
- }
2675
- this.#assertSmartRoutingNotHandEdited(preview, options?.confirmHandEdit === true);
2676
- } catch (error) {
2677
- return this.#reportSmartRoutingValidationError(error);
1596
+ selector.refreshSmartRoutingState(preview);
1597
+ } catch {
1598
+ this.#updateSmartRoutingUi(() => selector.markSmartRoutingEffectiveStateUnknown());
2678
1599
  }
2679
- return this.#runSmartRoutingIntent("Apply", async () => {
2680
- await this.ctx.settings.commitAtomicBatchWithCurrent(current => {
2681
- this.#assertSmartRoutingNotHandEdited(
2682
- preview,
2683
- options?.confirmHandEdit === true,
2684
- rawAutoroutingState(current),
2685
- );
2686
- return buildAutoroutingSettingsBatch({
2687
- tiers: preview.tiers,
2688
- setup: preview.setup,
2689
- provenance: preview.provenance,
2690
- });
2691
- });
2692
- return preview;
2693
- });
2694
1600
  }
2695
1601
 
2696
- /**
2697
- * Reorder a recorded declaration into current provider priority and drop entries
2698
- * the catalog no longer offers. Comparison uses normalized ids while the result
2699
- * keeps the catalog's spelling, because the generator matches provider prefixes
2700
- * case-sensitively.
2701
- */
2702
- #reseedProvidersFromPolicy(setup: AutoroutingSetup): AutoroutingSetup {
2703
- const order = this.ctx.session.modelRegistry.autoroutingProviderOrder();
2704
- const declared = new Set(setup.providers.map(provider => provider.trim().toLowerCase()));
2705
- const providers = order.filter(provider => declared.has(provider.trim().toLowerCase()));
2706
- return { ...structuredClone(setup), providers };
1602
+ async applySmartRouting(
1603
+ draft: AutoroutingSetup,
1604
+ options?: { preview?: RoutingSettingsPreview; confirmHandEdit?: boolean },
1605
+ ): Promise<RoutingSettingsPreview> {
1606
+ return (await this.#runSmartRoutingIntent("Apply", () => this.#smartRouting.applySmartRouting(draft, options)))
1607
+ .preview;
2707
1608
  }
2708
1609
 
2709
- async refreshSmartRouting(options?: { confirmHandEdit?: boolean }): Promise<SmartRoutingPreview> {
2710
- let preview: SmartRoutingPreview;
2711
- let expectedSetup: AutoroutingSetup;
2712
- try {
2713
- this.#assertSmartRoutingWritable();
2714
- const setup = this.ctx.settings.get("task.autorouting.setup");
2715
- const issues = validateAutoroutingSetup(setup);
2716
- if (issues.length > 0 || setup === undefined) {
2717
- throw new Error("Cannot refresh smart routing without a valid recorded setup.");
2718
- }
2719
- expectedSetup = setup;
2720
- // Reseed the recorded declaration against the current provider priority:
2721
- // reorder to policy order and drop providers the catalog no longer offers.
2722
- // Refusing an empty result keeps a dead declaration from being persisted.
2723
- const reseeded = this.#reseedProvidersFromPolicy(setup);
2724
- if (reseeded.providers.length === 0) {
2725
- throw new Error("No declared providers remain in the catalog; smart routing was not updated.");
2726
- }
2727
- preview = this.previewSmartRouting(reseeded);
2728
- this.#assertSmartRoutingNotHandEdited(preview, options?.confirmHandEdit === true);
2729
- } catch (error) {
2730
- return this.#reportSmartRoutingValidationError(error);
2731
- }
2732
- return this.#runSmartRoutingIntent("Refresh", async () => {
2733
- await this.ctx.settings.commitAtomicBatchWithCurrent(current => {
2734
- const currentState = rawAutoroutingState(current);
2735
- if (!sameCanonicalAutoroutingValue(currentState.setup, expectedSetup)) {
2736
- throw new Error(
2737
- "Smart-routing setup changed while refresh was preparing; refresh again to use current settings.",
2738
- );
2739
- }
2740
- this.#assertSmartRoutingNotHandEdited(preview, options?.confirmHandEdit === true, currentState);
2741
- return buildAutoroutingSettingsBatch({
2742
- tiers: preview.tiers,
2743
- setup: preview.setup,
2744
- provenance: preview.provenance,
2745
- });
2746
- });
2747
- return preview;
2748
- });
1610
+ async refreshSmartRouting(options?: {
1611
+ preview?: RoutingSettingsPreview;
1612
+ confirmHandEdit?: boolean;
1613
+ }): Promise<RoutingSettingsPreview> {
1614
+ return (await this.#runSmartRoutingIntent("Refresh", () => this.#smartRouting.refreshSmartRouting(options)))
1615
+ .preview;
2749
1616
  }
2750
1617
 
2751
1618
  async clearGeneratedSetup(): Promise<void> {
2752
- try {
2753
- this.#assertSmartRoutingWritable();
2754
- } catch (error) {
2755
- return this.#reportSmartRoutingValidationError(error);
2756
- }
2757
- return this.#runSmartRoutingIntent("Clear", async () => {
2758
- await this.ctx.settings.commitAtomicBatchWithCurrent(() => buildAutoroutingSettingsBatch({ clear: true }));
2759
- });
1619
+ await this.#runSmartRoutingIntent("Clear", () => this.#smartRouting.clearGeneratedSetup());
2760
1620
  }
2761
1621
 
2762
1622
  async setAutoroutingEnabled(enabled: boolean): Promise<void> {
2763
- try {
2764
- this.#assertSmartRoutingWritable();
2765
- } catch (error) {
2766
- return this.#reportSmartRoutingValidationError(error);
2767
- }
2768
- return this.#runSmartRoutingIntent("Toggle", async () => {
2769
- await this.ctx.settings.commitAtomicBatchWithCurrent(() => [buildAutoroutingEnabledPatch(enabled)]);
2770
- });
1623
+ await this.#runSmartRoutingIntent("Toggle", () => this.#smartRouting.setAutoroutingEnabled(enabled));
2771
1624
  }
2772
1625
 
2773
1626
  showModelSelector(options?: { temporaryOnly?: boolean; smartRoutingOnly?: boolean }): void {
@@ -2789,25 +1642,48 @@ export class SelectorController {
2789
1642
  this.ctx.session.scopedModels,
2790
1643
  async selection => {
2791
1644
  if (selection.kind === "smartRouting") {
2792
- switch (selection.intent.kind) {
2793
- case "apply":
2794
- await this.applySmartRouting(selection.intent.draft, {
2795
- preview: selection.intent.preview,
2796
- confirmHandEdit: selection.intent.confirmHandEdit,
2797
- });
2798
- break;
2799
- case "refresh":
2800
- await this.refreshSmartRouting({ confirmHandEdit: selection.intent.confirmHandEdit });
2801
- break;
2802
- case "clear":
2803
- await this.clearGeneratedSetup();
2804
- break;
2805
- case "toggle":
2806
- await this.setAutoroutingEnabled(selection.intent.enabled);
2807
- break;
1645
+ try {
1646
+ switch (selection.intent.kind) {
1647
+ case "apply": {
1648
+ const preview = await this.applySmartRouting(selection.intent.draft, {
1649
+ preview: selection.intent.preview,
1650
+ confirmHandEdit: selection.intent.confirmHandEdit,
1651
+ });
1652
+ this.#refreshSmartRoutingUi(modelSelector, preview);
1653
+ return preview;
1654
+ }
1655
+ case "refresh": {
1656
+ const preview = await this.refreshSmartRouting({
1657
+ preview: selection.intent.preview,
1658
+ confirmHandEdit: selection.intent.confirmHandEdit,
1659
+ });
1660
+ this.#refreshSmartRoutingUi(modelSelector, preview);
1661
+ return preview;
1662
+ }
1663
+ case "clear":
1664
+ await this.clearGeneratedSetup();
1665
+ break;
1666
+ case "toggle":
1667
+ await this.setAutoroutingEnabled(selection.intent.enabled);
1668
+ break;
1669
+ }
1670
+ this.#refreshSmartRoutingUi(modelSelector);
1671
+ return;
1672
+ } catch (error) {
1673
+ if (
1674
+ error instanceof RoutingSettingsActivationError &&
1675
+ (error.rollback === "conflict" ||
1676
+ error.rollback === "failed" ||
1677
+ error.rollback === "not-restorable")
1678
+ ) {
1679
+ if (error.durability === "persisted") {
1680
+ this.#updateSmartRoutingUi(() => modelSelector.invalidateSmartRoutingState());
1681
+ } else {
1682
+ this.#refreshSmartRoutingUi(modelSelector);
1683
+ }
1684
+ }
1685
+ throw error;
2808
1686
  }
2809
- modelSelector.refreshSmartRoutingState();
2810
- return;
2811
1687
  }
2812
1688
  const isTrackedSingleAssignment =
2813
1689
  selection.kind === "assignment" && selection.role !== null && selection.roles === undefined;
@@ -2826,8 +1702,15 @@ export class SelectorController {
2826
1702
  return;
2827
1703
  }
2828
1704
  if (selection.kind === "profile") {
2829
- await this.#applyModelProfile(selection.profileName, selection.setDefault);
1705
+ // Activation waits for the session to go idle before it takes the
1706
+ // selection admission. Close the selector first so Enter is not a
1707
+ // silent no-op that leaves the menu mounted until the session settles.
2830
1708
  done();
1709
+ if (this.ctx.session.isAwaitingIdle) {
1710
+ this.ctx.showStatus("Model profile change queued until the agent is idle.");
1711
+ }
1712
+ this.ctx.ui.requestRender();
1713
+ await this.#applyModelProfile(selection.profileName, selection.setDefault);
2831
1714
  this.ctx.ui.requestRender();
2832
1715
  return;
2833
1716
  }
@@ -3065,6 +1948,8 @@ export class SelectorController {
3065
1948
  this.ctx.session.isFastForSubagentProvider(provider, supportsServiceTier),
3066
1949
  isCurrentModelFastModeActive: () => this.ctx.session.isFastModeActive(),
3067
1950
  smartRoutingPreview: draft => this.previewSmartRouting(draft),
1951
+ smartRoutingDiscardPreview: preview => this.#smartRouting.discardPreview(preview),
1952
+ smartRoutingStateUnknown: () => this.#smartRouting.stateUnknown,
3068
1953
  smartRoutingOnly: options?.smartRoutingOnly,
3069
1954
  },
3070
1955
  );