@chroxy/server 0.10.0

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 (275) hide show
  1. package/CONFIG.md +695 -0
  2. package/README.md +105 -0
  3. package/hooks/permission-hook.sh +285 -0
  4. package/package.json +69 -0
  5. package/scripts/fix-node-pty-helper.js +44 -0
  6. package/sidecar/Dockerfile +40 -0
  7. package/sidecar/PROTOCOL.md +691 -0
  8. package/sidecar/agent.js +1290 -0
  9. package/sidecar/package-lock.json +43 -0
  10. package/sidecar/package.json +17 -0
  11. package/src/activity-registry.js +491 -0
  12. package/src/anthropic-compatible-config.js +534 -0
  13. package/src/anthropic-compatible-session.js +579 -0
  14. package/src/anthropic-openai-shim.js +109 -0
  15. package/src/anthropic-openai-translate.js +377 -0
  16. package/src/auth-probes.js +296 -0
  17. package/src/background-shell-tracker.js +320 -0
  18. package/src/background-shells.js +125 -0
  19. package/src/base-session.js +1518 -0
  20. package/src/billing-budget.js +191 -0
  21. package/src/billing-canary-monitor.js +203 -0
  22. package/src/billing-class.js +149 -0
  23. package/src/bind-host.js +82 -0
  24. package/src/built-in-tools/bash-exec.js +167 -0
  25. package/src/built-in-tools/file-ops.js +198 -0
  26. package/src/built-in-tools/tool-transforms.js +179 -0
  27. package/src/builtin-commands.js +107 -0
  28. package/src/byok-compose-state-shared.js +31 -0
  29. package/src/byok-compose-state.js +234 -0
  30. package/src/byok-credentials.js +127 -0
  31. package/src/byok-event-translator.js +136 -0
  32. package/src/byok-mcp-client.js +404 -0
  33. package/src/byok-mcp-config.js +159 -0
  34. package/src/byok-mcp-fleet.js +214 -0
  35. package/src/byok-mcp-trust.js +175 -0
  36. package/src/byok-session.js +2019 -0
  37. package/src/byok-subagent-profiles.js +101 -0
  38. package/src/byok-tool-executor.js +813 -0
  39. package/src/byok-tools.js +271 -0
  40. package/src/channels/PACKAGING.md +181 -0
  41. package/src/channels/README.md +99 -0
  42. package/src/channels/chroxy-channel-server.js +248 -0
  43. package/src/checkpoint-manager.js +515 -0
  44. package/src/child-stream-guard.js +38 -0
  45. package/src/claude-channel-session.js +185 -0
  46. package/src/claude-model-catalog.js +266 -0
  47. package/src/claude-stream-parser.js +106 -0
  48. package/src/claude-tui/form-driver.js +874 -0
  49. package/src/claude-tui/pty-driver.js +520 -0
  50. package/src/claude-tui/tested-cli-version.js +22 -0
  51. package/src/claude-tui-attachments.js +342 -0
  52. package/src/claude-tui-session.js +4029 -0
  53. package/src/cli/config-cmd.js +34 -0
  54. package/src/cli/credentials-cmd.js +59 -0
  55. package/src/cli/deploy-cmd.js +167 -0
  56. package/src/cli/doctor-cmd.js +52 -0
  57. package/src/cli/identity-cmd.js +82 -0
  58. package/src/cli/init-cmd.js +209 -0
  59. package/src/cli/pages-cmd.js +167 -0
  60. package/src/cli/pair-code-cmd.js +108 -0
  61. package/src/cli/pair-discord-cmd.js +100 -0
  62. package/src/cli/providers-cmd.js +168 -0
  63. package/src/cli/server-cmd.js +94 -0
  64. package/src/cli/service-cmd.js +237 -0
  65. package/src/cli/session-cmd.js +143 -0
  66. package/src/cli/shared.js +194 -0
  67. package/src/cli/shell-cmd.js +130 -0
  68. package/src/cli/status-cmd.js +204 -0
  69. package/src/cli/tunnel-cmd.js +101 -0
  70. package/src/cli/update-cmd.js +45 -0
  71. package/src/cli/worktree-gc-cmd.js +195 -0
  72. package/src/cli-session.js +1820 -0
  73. package/src/cli.js +60 -0
  74. package/src/codex-app-server-client.js +156 -0
  75. package/src/codex-app-server-session.js +572 -0
  76. package/src/codex-session.js +604 -0
  77. package/src/config.js +1757 -0
  78. package/src/connection-info.js +42 -0
  79. package/src/connection-locality.js +55 -0
  80. package/src/content-blocks.js +42 -0
  81. package/src/control-room/byok-pool.js +130 -0
  82. package/src/control-room/constants.js +26 -0
  83. package/src/control-room/containers.js +258 -0
  84. package/src/control-room/emulators.js +279 -0
  85. package/src/control-room/handler-factory.js +142 -0
  86. package/src/control-room/host-prune.js +387 -0
  87. package/src/control-room/integrations.js +929 -0
  88. package/src/control-room/repo-runtime-config.js +239 -0
  89. package/src/control-room/repo-set.js +162 -0
  90. package/src/control-room/runners.js +479 -0
  91. package/src/control-room/simulators.js +223 -0
  92. package/src/control-room/skills-inventory.js +303 -0
  93. package/src/control-room/survey.js +685 -0
  94. package/src/control-room/wsl.js +182 -0
  95. package/src/conversation-scanner.js +270 -0
  96. package/src/conversation-scope.js +52 -0
  97. package/src/conversation-search.js +216 -0
  98. package/src/cost-budget-manager.js +190 -0
  99. package/src/credential-cipher.js +179 -0
  100. package/src/credential-store.js +786 -0
  101. package/src/credential-test.js +145 -0
  102. package/src/credentials-file.js +58 -0
  103. package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +111 -0
  104. package/src/dashboard-next/dist/assets/index-DM-_dISG.css +1 -0
  105. package/src/dashboard-next/dist/index.html +13 -0
  106. package/src/deepseek-credentials.js +58 -0
  107. package/src/deepseek-session.js +192 -0
  108. package/src/detect-thinking-keyword.js +67 -0
  109. package/src/dev-preview.js +227 -0
  110. package/src/devcontainer-config.js +269 -0
  111. package/src/device-preferences.js +267 -0
  112. package/src/diagnostics.js +187 -0
  113. package/src/diff-parser.js +157 -0
  114. package/src/discord-credentials.js +188 -0
  115. package/src/discord-pair-delivery.js +113 -0
  116. package/src/docker-byok-pool-stats.js +221 -0
  117. package/src/docker-byok-pool.js +841 -0
  118. package/src/docker-byok-session.js +2172 -0
  119. package/src/docker-image-allowlist.js +99 -0
  120. package/src/docker-sdk-session.js +396 -0
  121. package/src/docker-session.js +382 -0
  122. package/src/doctor-billing.js +179 -0
  123. package/src/doctor.js +667 -0
  124. package/src/duration.js +77 -0
  125. package/src/environment-manager.js +753 -0
  126. package/src/environment-statuses.js +20 -0
  127. package/src/environments/backends/docker.js +931 -0
  128. package/src/environments/backends/k8s.js +3030 -0
  129. package/src/environments/backends/rancher.js +326 -0
  130. package/src/environments/backends/types.js +332 -0
  131. package/src/event-ingest.js +546 -0
  132. package/src/event-normalizer.js +1083 -0
  133. package/src/external-session-registry.js +0 -0
  134. package/src/file-store.js +52 -0
  135. package/src/gemini-session.js +498 -0
  136. package/src/get-public-ip.js +52 -0
  137. package/src/git.js +15 -0
  138. package/src/github-webhook.js +256 -0
  139. package/src/handler-utils.js +663 -0
  140. package/src/handlers/checkpoint-handlers.js +202 -0
  141. package/src/handlers/control-room-handlers.js +1945 -0
  142. package/src/handlers/conversation-handlers.js +201 -0
  143. package/src/handlers/credential-handlers.js +247 -0
  144. package/src/handlers/evaluator-handlers.js +94 -0
  145. package/src/handlers/feature-handlers.js +332 -0
  146. package/src/handlers/file-handlers.js +142 -0
  147. package/src/handlers/ide-handlers.js +238 -0
  148. package/src/handlers/input-handlers.js +1048 -0
  149. package/src/handlers/pairing-handlers.js +94 -0
  150. package/src/handlers/repo-handlers.js +295 -0
  151. package/src/handlers/session-handlers.js +660 -0
  152. package/src/handlers/settings-handlers.js +818 -0
  153. package/src/handlers/skills-handlers.js +682 -0
  154. package/src/handlers/summarize-handlers.js +172 -0
  155. package/src/handlers/token-handlers.js +57 -0
  156. package/src/http-oversize.js +51 -0
  157. package/src/http-routes.js +1158 -0
  158. package/src/ide/search.js +268 -0
  159. package/src/ide/symbols.js +423 -0
  160. package/src/ip-utils.js +85 -0
  161. package/src/json-state-file.js +169 -0
  162. package/src/jsonl-reader.js +187 -0
  163. package/src/jsonl-subprocess-session.js +441 -0
  164. package/src/keychain.js +458 -0
  165. package/src/lan-ip.js +38 -0
  166. package/src/logger.js +388 -0
  167. package/src/mailbox-route.js +252 -0
  168. package/src/mcp-tools.js +46 -0
  169. package/src/message-transform.js +102 -0
  170. package/src/metrics.js +67 -0
  171. package/src/model-discovery.js +288 -0
  172. package/src/models.js +1426 -0
  173. package/src/notification-prefs.js +544 -0
  174. package/src/notifications/discord-billing-sink.js +323 -0
  175. package/src/notifications/discord-webhook-client.js +187 -0
  176. package/src/notifications/discord-webhook-sink.js +768 -0
  177. package/src/notifications/expo-push-sink.js +414 -0
  178. package/src/notifications/ready-body.js +177 -0
  179. package/src/notifications/sink-registry.js +98 -0
  180. package/src/notifications/sink.js +82 -0
  181. package/src/ollama-session.js +221 -0
  182. package/src/ollama-tags.js +238 -0
  183. package/src/openai-compatible-session.js +118 -0
  184. package/src/pages-store.js +255 -0
  185. package/src/pairing.js +836 -0
  186. package/src/path-hash-trust-ledger.js +311 -0
  187. package/src/per-session-settings.js +366 -0
  188. package/src/permission-audit.js +120 -0
  189. package/src/permission-hook.js +257 -0
  190. package/src/permission-manager.js +829 -0
  191. package/src/permission-resolver.js +144 -0
  192. package/src/platform.js +139 -0
  193. package/src/prompt-evaluator.js +386 -0
  194. package/src/providers.js +436 -0
  195. package/src/push.js +565 -0
  196. package/src/rate-limiter.js +433 -0
  197. package/src/redaction.js +206 -0
  198. package/src/sdk-session.js +1773 -0
  199. package/src/semver.js +92 -0
  200. package/src/server-cli/push-notification-handler.js +240 -0
  201. package/src/server-cli/server-orchestrator.js +168 -0
  202. package/src/server-cli/startup-display.js +146 -0
  203. package/src/server-cli/tunnel-lifecycle-handler.js +219 -0
  204. package/src/server-cli-child.js +207 -0
  205. package/src/server-cli.js +1223 -0
  206. package/src/server-identity.js +383 -0
  207. package/src/service.js +835 -0
  208. package/src/session-context.js +49 -0
  209. package/src/session-lock.js +60 -0
  210. package/src/session-manager.js +3257 -0
  211. package/src/session-message-history.js +511 -0
  212. package/src/session-preset-trust.js +78 -0
  213. package/src/session-preset.js +458 -0
  214. package/src/session-state-persistence.js +307 -0
  215. package/src/session-timeout-manager.js +166 -0
  216. package/src/session-token-store.js +83 -0
  217. package/src/shell-approval-info.js +45 -0
  218. package/src/shell-approval-store.js +163 -0
  219. package/src/shell-audit.js +63 -0
  220. package/src/skills-budget.js +181 -0
  221. package/src/skills-content-validator.js +106 -0
  222. package/src/skills-frontmatter.js +422 -0
  223. package/src/skills-loader.js +1893 -0
  224. package/src/skills-manager.js +256 -0
  225. package/src/skills-trust.js +532 -0
  226. package/src/skills-usage.js +335 -0
  227. package/src/snapshots-store.js +345 -0
  228. package/src/ssrf-guard.js +130 -0
  229. package/src/subagent-counter.js +149 -0
  230. package/src/summarize-session.js +268 -0
  231. package/src/supervisor.js +929 -0
  232. package/src/test-client.js +131 -0
  233. package/src/token-compare.js +28 -0
  234. package/src/token-manager.js +220 -0
  235. package/src/tool-result.js +87 -0
  236. package/src/transcript-tasks.js +334 -0
  237. package/src/tunnel/base.js +294 -0
  238. package/src/tunnel/cloudflare.js +281 -0
  239. package/src/tunnel/index.js +54 -0
  240. package/src/tunnel-check.js +84 -0
  241. package/src/turn-tracker.js +0 -0
  242. package/src/user-shell-registry.js +218 -0
  243. package/src/user-shell-session.js +411 -0
  244. package/src/utils/check-dependencies.js +70 -0
  245. package/src/utils/concurrency.js +24 -0
  246. package/src/utils/context-window-learn.js +148 -0
  247. package/src/utils/error-message.js +25 -0
  248. package/src/utils/format-bytes.js +35 -0
  249. package/src/utils/preflight.js +143 -0
  250. package/src/utils/resolve-binary.js +91 -0
  251. package/src/utils/respawn-rate-limiter.js +59 -0
  252. package/src/utils/sleep.js +58 -0
  253. package/src/utils/spawn-env.js +193 -0
  254. package/src/utils/validation-patterns.js +23 -0
  255. package/src/utils/win-spawn.js +98 -0
  256. package/src/version-check.js +16 -0
  257. package/src/web-task-manager.js +383 -0
  258. package/src/worktree-gc.js +418 -0
  259. package/src/worktree-reaper.js +168 -0
  260. package/src/ws-auth.js +645 -0
  261. package/src/ws-broadcaster.js +385 -0
  262. package/src/ws-client-manager.js +476 -0
  263. package/src/ws-client-sender.js +115 -0
  264. package/src/ws-file-ops/browser.js +594 -0
  265. package/src/ws-file-ops/common.js +163 -0
  266. package/src/ws-file-ops/git.js +298 -0
  267. package/src/ws-file-ops/index.js +52 -0
  268. package/src/ws-file-ops/reader.js +595 -0
  269. package/src/ws-forwarding.js +543 -0
  270. package/src/ws-handler-context.js +196 -0
  271. package/src/ws-history.js +1251 -0
  272. package/src/ws-message-handlers.js +165 -0
  273. package/src/ws-permissions.js +676 -0
  274. package/src/ws-schemas.js +119 -0
  275. package/src/ws-server.js +2866 -0
package/src/push.js ADDED
@@ -0,0 +1,565 @@
1
+ /**
2
+ * PushManager — the shared notification pipeline (#5413 Phase 1).
3
+ *
4
+ * Owns everything that must behave identically for every delivery channel:
5
+ * notification preferences (#4541/#4544), the per-category RATE_LIMITS
6
+ * throttle, and the fan-out to configured sinks via SinkRegistry. The
7
+ * Expo-specific delivery (token registry, exp.host POST, ticket pruning,
8
+ * Live Activity) lives in ExpoPushSink (notifications/expo-push-sink.js) —
9
+ * extracted from this file so #5413 Phase 2 can register a
10
+ * DiscordWebhookSink alongside it with no pipeline changes. See
11
+ * notifications/sink.js for the sink contract.
12
+ *
13
+ * For now PushManager keeps its full pre-extraction public surface
14
+ * (registerToken, releaseTokenOwner, Live Activity registration, the
15
+ * `tokens` set, ...) by delegating to the Expo sink, so callers
16
+ * (server-cli.js, supervisor.js, ws handlers) and existing tests are
17
+ * untouched. Per-sink wiring/config is a Phase 2 concern.
18
+ *
19
+ * Wired into server-cli.js via SessionManager event listeners.
20
+ */
21
+
22
+ import { createLogger } from './logger.js'
23
+ import {
24
+ loadPrefs as loadNotificationPrefs,
25
+ savePrefs as saveNotificationPrefs,
26
+ defaultPrefs as defaultNotificationPrefs,
27
+ isCategoryEnabledIn,
28
+ isInQuietHoursIn,
29
+ shouldBypassQuietHours,
30
+ } from './notification-prefs.js'
31
+ import { SinkRegistry } from './notifications/sink-registry.js'
32
+ import {
33
+ ExpoPushSink,
34
+ fetchWithRetry,
35
+ FETCH_TIMEOUT_MS,
36
+ MAX_RETRIES,
37
+ BACKOFF_BASE_MS,
38
+ } from './notifications/expo-push-sink.js'
39
+ import { DiscordWebhookSink } from './notifications/discord-webhook-sink.js'
40
+ import { DiscordBillingSink } from './notifications/discord-billing-sink.js'
41
+
42
+ const log = createLogger('push')
43
+
44
+ // #5702 (8d): settle a fire-and-forget pushManager.send() so neither a failed
45
+ // delivery (resolves `false`) nor a dispatch error (rejects) is silently
46
+ // dropped. A bare `pushManager.send(...)` leaves the rejection unhandled (it's
47
+ // an async method) AND hides a half-open-link delivery failure while the
48
+ // dashboard card still appears — the exact silent asymmetry #5702 calls out.
49
+ // `label` names the call site so the log is greppable. `logger` defaults to the
50
+ // push logger but call sites pass their own so the line is attributed correctly.
51
+ export function settlePush(promise, label, logger = log) {
52
+ // Returns the settled chain so callers/tests CAN await it; the fire-and-forget
53
+ // call sites simply ignore the return.
54
+ return Promise.resolve(promise)
55
+ .then((ok) => { if (ok === false) logger.warn(`push notification not delivered (${label})`) })
56
+ .catch((err) => { logger.warn(`push notification error (${label}): ${String(err?.message || err)}`) })
57
+ }
58
+
59
+ // Rate limits per category (ms) — prevents notification spam.
60
+ //
61
+ // History:
62
+ // - PR #2621 removed stream_start / tool_start → activity_update pushes,
63
+ // so 'activity_update' now fires only on unattended 'result' events (the
64
+ // noActiveViewers gate in server-cli.js prevents spam structurally, not
65
+ // via this rate limit).
66
+ // - The 'idle' category was removed from the server's event-handling in
67
+ // 2026-04-11's notification audit after it was found to be firing in
68
+ // duplicate with 'activity_update' for the same unattended-completion
69
+ // case, producing two OS-level notifications per query. Left out of this
70
+ // map so a future resurrection has to be deliberate.
71
+ const RATE_LIMITS = {
72
+ permission: 0, // Always send permission prompts immediately
73
+ result: 30_000, // At most once per 30s for task completion
74
+ activity_update: 0, // Immediate: one push per unattended completion (noActiveViewers gate is the real dedupe)
75
+ activity_waiting: 0, // Immediate: permission/input waiting
76
+ activity_error: 0, // Immediate: session errors
77
+ inactivity_warning: 0, // #3899: immediate — naturally rate-limited by the soft warning window (default 30 min between fires per session)
78
+ live_activity: 5_000, // Live Activity updates: 5s throttle
79
+ // #5413 Phase 3: external-session lifecycle/activity categories fed by
80
+ // POST /api/events (event-ingest.js). Lifecycle transitions are rare and
81
+ // meaningful → immediate; activity is a heartbeat → throttled here AND
82
+ // per-source at the ingest route AND per-project in the Discord sink.
83
+ session_online: 0,
84
+ session_offline: 0,
85
+ session_activity: 30_000,
86
+ // #5828: billing-canary warnings (silent metered default; reclassification
87
+ // trip). The monitor only emits on a CHANGED warning set, so this is already
88
+ // dedup'd at the source — immediate is fine, no extra throttle needed.
89
+ billing_warning: 0,
90
+ // Mailbox live-interrupt: a "new mail" ping for an agent (POST /api/mailbox,
91
+ // mailbox-route.js). Rare and meaningful → immediate.
92
+ mailbox: 0,
93
+ }
94
+
95
+ // Re-exported for existing importers/tests — the implementation moved to
96
+ // notifications/expo-push-sink.js with the rest of the Expo delivery code.
97
+ export { fetchWithRetry, FETCH_TIMEOUT_MS, MAX_RETRIES, BACKOFF_BASE_MS }
98
+
99
+ export class PushManager {
100
+ /**
101
+ * @param {object} [opts]
102
+ * @param {string} [opts.storagePath] - Expo push-token persistence file
103
+ * @param {string} [opts.prefsPath] - Notification-prefs persistence file
104
+ * @param {object} [opts.discord] - DiscordWebhookSink options (#5413
105
+ * Phase 2): `statePath` + the config-surface knobs (botName, colors,
106
+ * throttle/heartbeat intervals). The sink is ALWAYS registered but is
107
+ * off by default — `isConfigured()` is true only when a webhook URL
108
+ * resolves from CHROXY_DISCORD_WEBHOOK_URL or the 0600
109
+ * ~/.chroxy/credentials.json, so unconfigured setups never touch it.
110
+ * #5828: also feeds DiscordBillingSink — `billingStatePath` (its own state
111
+ * file, kept separate from the status store) and `billingAlerts` (kill-switch,
112
+ * default on when a webhook resolves).
113
+ * @param {() => number} [opts.now] - #6146 injectable clock (epoch ms),
114
+ * defaults to `Date.now`. send()'s rate-limit AND the #4544 quiet-hours gate
115
+ * evaluate against "now"; tests pin it to a deterministic instant so the
116
+ * quiet-hours classification can't flip on a CI run near a window boundary.
117
+ */
118
+ constructor({ storagePath, prefsPath, discord = {}, now = Date.now } = {}) {
119
+ // #6146: injectable clock (default Date.now). Assigned directly — an invalid
120
+ // value fails fast on use rather than silently reverting, matching the
121
+ // codebase's clock-seam convention (utils/respawn-rate-limiter.js,
122
+ // turn-tracker.js).
123
+ this._now = now
124
+ // #4541: notification-prefs path. Optional — when omitted PushManager
125
+ // operates entirely in-memory (callers like one-off tests don't need
126
+ // to write to disk). When set, getPrefs / setPrefs round-trip
127
+ // ~/.chroxy/notification-prefs.json with atomic temp+rename writes.
128
+ this._prefsPath = prefsPath || null
129
+ this._prefs = this._prefsPath
130
+ ? loadNotificationPrefs(this._prefsPath, { log })
131
+ : defaultNotificationPrefs()
132
+ this._lastSent = new Map() // category -> timestamp
133
+ // #5413 Phase 1: delivery channels live behind the sink registry. The
134
+ // Expo sink owns the token registry + persistence; it's also kept on a
135
+ // named field because PushManager's legacy public surface (registerToken,
136
+ // Live Activity, the `tokens` set) delegates to it directly.
137
+ this._expoSink = new ExpoPushSink({ storagePath })
138
+ this._sinks = new SinkRegistry({ logger: log })
139
+ this._sinks.register(this._expoSink)
140
+ // #5413 Phase 2: the Discord status-embed sink. Registered alongside
141
+ // Expo, gated on configuration via the registry's isConfigured() skip.
142
+ this._discordSink = new DiscordWebhookSink(discord)
143
+ this._sinks.register(this._discordSink)
144
+ // #5828: the Discord billing-alert sink. Separate from the status sink (a
145
+ // billing warning is daemon-global, not a per-project session state), with
146
+ // its OWN state file so it never collides with the status store. Shares the
147
+ // same webhook + gating; off when no webhook resolves or billingAlerts is
148
+ // false.
149
+ this._discordBillingSink = new DiscordBillingSink({
150
+ statePath: discord.billingStatePath || null,
151
+ botName: discord.botName,
152
+ billingAlerts: discord.billingAlerts,
153
+ // Same channel as the status sink — forward the resolver injection seam so
154
+ // both sinks see the same webhook (undefined in production → the cached
155
+ // env/credentials resolver).
156
+ resolveWebhookUrl: discord.resolveWebhookUrl,
157
+ })
158
+ this._sinks.register(this._discordBillingSink)
159
+ }
160
+
161
+ /**
162
+ * True when at least one delivery channel is currently configured
163
+ * (Expo tokens registered, Discord webhook URL present, ...). The
164
+ * sink-agnostic replacement for gating on the Expo-only `hasTokens`
165
+ * (#5413 Phase 2): a Discord-only setup must not have its notifications
166
+ * suppressed upstream of the pipeline.
167
+ */
168
+ hasConfiguredSinks() {
169
+ return this._sinks.hasConfigured()
170
+ }
171
+
172
+ /**
173
+ * Release sink resources (today: the Discord heartbeat interval). Safe
174
+ * to call multiple times. Call when discarding a PushManager before
175
+ * process exit (e.g. the supervisor's per-send instances).
176
+ */
177
+ destroy() {
178
+ for (const sink of this._sinks.sinks) {
179
+ try {
180
+ sink.destroy?.()
181
+ } catch (err) {
182
+ log.error(`Sink '${sink.name}' threw during destroy: ${err?.message || err}`)
183
+ }
184
+ }
185
+ }
186
+
187
+ /**
188
+ * Registered push tokens (delegates to the Expo sink — same live Set,
189
+ * so existing callers/tests that mutate it directly keep working).
190
+ */
191
+ get tokens() {
192
+ return this._expoSink.tokens
193
+ }
194
+
195
+ /** Live Activity tokens (delegates to the Expo sink — same live Set). */
196
+ get _liveActivityTokens() {
197
+ return this._expoSink._liveActivityTokens
198
+ }
199
+
200
+ /**
201
+ * Return the current notification preferences (#4541). Returns a deep
202
+ * clone so callers can read freely without aliasing internal state.
203
+ * Categories not yet declared on disk fall through to documented
204
+ * defaults via the loadPrefs merge.
205
+ */
206
+ getPrefs() {
207
+ // Structured clone preserves nested categories / devices objects so
208
+ // callers patching the returned object can't accidentally mutate
209
+ // this._prefs.
210
+ return JSON.parse(JSON.stringify(this._prefs))
211
+ }
212
+
213
+ /**
214
+ * Patch preferences. Shallow-merge at the top level (`categories`,
215
+ * `devices`, `quietHours`, `bypassCategories`); the categories map
216
+ * itself is shallow-merged so an inbound patch that only mentions
217
+ * `result` does not wipe the `permission` toggle the user set earlier.
218
+ * Per-device entries are field-merged so the caller can patch one
219
+ * device's quiet-hours window without wiping its category overrides.
220
+ * Persists to disk when a `prefsPath` was configured at construction
221
+ * time.
222
+ *
223
+ * #4544: `quietHours` now carries an IANA `timezone`; `bypassCategories`
224
+ * is a list of category names that fire even during quiet hours
225
+ * (defaults to permission + activity_error). Both fields accept the
226
+ * same per-device override shape as the existing `categories` map.
227
+ *
228
+ * #4587: per-device entries are stamped with `lastSeenAt = Date.now()`
229
+ * on every touch (create + modify; not on `null` delete). When the
230
+ * caller supplies a `platform` (e.g. WS handler passing
231
+ * `client.deviceInfo?.platform`) it's persisted with the entry — a
232
+ * patch-supplied `platform` wins over the caller-supplied default so a
233
+ * future client carrying richer info can still override the
234
+ * auth-derived value.
235
+ *
236
+ * @param {object} patch - Partial prefs ({ categories?, devices?, quietHours?, bypassCategories? })
237
+ * @param {object} [opts]
238
+ * @param {string|null} [opts.platform] - Caller-supplied platform hint
239
+ * (from `client.deviceInfo.platform` in the WS auth context) used to
240
+ * stamp NEW per-device entries when the patch itself doesn't carry one.
241
+ */
242
+ setPrefs(patch, { platform = null } = {}) {
243
+ if (!patch || typeof patch !== 'object') return this.getPrefs()
244
+ const next = {
245
+ categories: { ...this._prefs.categories },
246
+ devices: { ...this._prefs.devices },
247
+ quietHours: this._prefs.quietHours,
248
+ bypassCategories: Array.isArray(this._prefs.bypassCategories)
249
+ ? [...this._prefs.bypassCategories]
250
+ : [],
251
+ }
252
+ if (patch.categories && typeof patch.categories === 'object') {
253
+ // Shallow-merge into the existing categories map so unmentioned
254
+ // toggles survive (per-category UI sends one category at a time).
255
+ for (const [k, v] of Object.entries(patch.categories)) {
256
+ if (typeof v === 'boolean') next.categories[k] = v
257
+ }
258
+ }
259
+ if (patch.devices && typeof patch.devices === 'object') {
260
+ // Per-device: shallow-merge the inner fields per device key. The
261
+ // caller may patch one field (e.g. just `quietHours`) without
262
+ // wiping the rest (e.g. an existing `categories` mute). A device
263
+ // key not mentioned in the patch survives.
264
+ for (const [token, entry] of Object.entries(patch.devices)) {
265
+ if (entry === null) {
266
+ // Explicit null deletes the entry.
267
+ delete next.devices[token]
268
+ continue
269
+ }
270
+ if (!entry || typeof entry !== 'object') continue
271
+ const existing = next.devices[token] || { categories: {} }
272
+ const merged = { ...existing }
273
+ if (entry.categories && typeof entry.categories === 'object') {
274
+ const mergedCategories = { ...(existing.categories || {}) }
275
+ for (const [k, v] of Object.entries(entry.categories)) {
276
+ if (typeof v === 'boolean') mergedCategories[k] = v
277
+ }
278
+ merged.categories = mergedCategories
279
+ } else {
280
+ merged.categories = existing.categories || {}
281
+ }
282
+ // Tri-state: present `quietHours` key (including null) is honoured;
283
+ // absent key leaves the existing value alone. Matches the loader
284
+ // semantics — `null` means "this device opts out of muting" while
285
+ // `undefined` means "inherit global".
286
+ if (Object.prototype.hasOwnProperty.call(entry, 'quietHours')) {
287
+ merged.quietHours = entry.quietHours
288
+ }
289
+ // Same tri-state for bypassCategories. An explicit `null` resets
290
+ // the device to inheriting the global list; an array (including
291
+ // empty) records an override.
292
+ if (Object.prototype.hasOwnProperty.call(entry, 'bypassCategories')) {
293
+ if (entry.bypassCategories === null) {
294
+ delete merged.bypassCategories
295
+ } else if (Array.isArray(entry.bypassCategories)) {
296
+ merged.bypassCategories = entry.bypassCategories.filter((c) => typeof c === 'string' && c.length > 0)
297
+ }
298
+ }
299
+ // #4587: stamp lastSeenAt on every touch. The per-device list UI
300
+ // uses this to render "Last seen X ago" so operators can tell
301
+ // recently-active devices apart from stale orphans without having
302
+ // to hand-read the prefs file.
303
+ merged.lastSeenAt = Date.now()
304
+ // Allow the caller to inject the canonical platform (from auth
305
+ // deviceInfo). Patch-supplied platform wins over caller-supplied
306
+ // (forward-compat: a future client could send a more specific value
307
+ // than auth carries). Both paths clamp to 32 chars to match the
308
+ // wire schema bound.
309
+ if (typeof entry.platform === 'string' && entry.platform.length > 0) {
310
+ merged.platform = entry.platform.slice(0, 32)
311
+ } else if (typeof platform === 'string' && platform.length > 0) {
312
+ merged.platform = platform.slice(0, 32)
313
+ }
314
+ next.devices[token] = merged
315
+ }
316
+ }
317
+ if (Object.prototype.hasOwnProperty.call(patch, 'quietHours')) {
318
+ // Allow explicit null to clear the window; the loader sanitises
319
+ // shape on re-read so we don't need to validate here.
320
+ next.quietHours = patch.quietHours || null
321
+ }
322
+ if (Object.prototype.hasOwnProperty.call(patch, 'bypassCategories')) {
323
+ // Replace the bypass list wholesale. An empty array is a legitimate
324
+ // value (user says "nothing bypasses, not even errors") so we
325
+ // intentionally do NOT default-fill here — that distinction is
326
+ // preserved by `resolveBypassCategories` on the read path.
327
+ if (Array.isArray(patch.bypassCategories)) {
328
+ next.bypassCategories = patch.bypassCategories.filter((c) => typeof c === 'string' && c.length > 0)
329
+ } else if (patch.bypassCategories === null) {
330
+ // Explicit null restores defaults.
331
+ next.bypassCategories = [...defaultNotificationPrefs().bypassCategories]
332
+ }
333
+ }
334
+ // #4550: persist FIRST, swap in-memory state only after the save
335
+ // succeeds. Pre-#4550 we assigned `this._prefs = next` unconditionally
336
+ // and then tried to save; a failed rename (EACCES / EXDEV / quota)
337
+ // re-threw out to the WS handler but left `_prefs` already mutated,
338
+ // so `isCategoryEnabled` answered based on a value the user thought
339
+ // failed to save — and the next process restart silently reverted
340
+ // the change because disk never received it.
341
+ if (this._prefsPath) {
342
+ try {
343
+ saveNotificationPrefs(next, this._prefsPath)
344
+ } catch (err) {
345
+ log.error(`Failed to persist notification prefs: ${err?.message || err}`)
346
+ // Re-throw so the WS handler can surface a CREDENTIALS_WRITE_FAILED-
347
+ // style error rather than silently lying about persistence. The
348
+ // in-memory `_prefs` is intentionally left untouched here so the
349
+ // next isCategoryEnabled / getPrefs call reflects the pre-patch
350
+ // state, matching what's actually on disk.
351
+ throw err
352
+ }
353
+ }
354
+ this._prefs = next
355
+ return this.getPrefs()
356
+ }
357
+
358
+ /**
359
+ * Stamp `lastSeenAt` (and optionally `platform`) on an EXISTING device
360
+ * entry without otherwise modifying it (#4587).
361
+ *
362
+ * No-op when the device has no entry — `register_push_token` calls this
363
+ * on every reconnect, but we don't want to create empty per-device
364
+ * entries for devices that have never muted anything. Empty entries
365
+ * would clutter the per-device list with rows that have no overrides to
366
+ * clear, defeating the purpose of the orphan-clearing UI in #4564.
367
+ *
368
+ * Called from `handleRegisterPushToken` so the per-device list reflects
369
+ * the last CONNECT time of each device, not just the last time its
370
+ * prefs were patched — without this, a device that registers but never
371
+ * mutes a category would show a `lastSeenAt` from the first mute
372
+ * forever.
373
+ */
374
+ touchDevice(token, platform = null) {
375
+ if (typeof token !== 'string' || token.length === 0) return
376
+ const existing = this._prefs.devices?.[token]
377
+ if (!existing) return
378
+ existing.lastSeenAt = Date.now()
379
+ if (typeof platform === 'string' && platform.length > 0) {
380
+ existing.platform = platform.slice(0, 32)
381
+ }
382
+ if (this._prefsPath) {
383
+ try {
384
+ saveNotificationPrefs(this._prefs, this._prefsPath)
385
+ } catch (err) {
386
+ // Metadata write failure is non-critical (push delivery still
387
+ // works), so log and continue rather than throwing — unlike
388
+ // setPrefs, which surfaces a write failure to the WS handler so
389
+ // the client knows their patch didn't persist.
390
+ log.error(`Failed to persist notification prefs: ${err?.message || err}`)
391
+ }
392
+ }
393
+ }
394
+
395
+ /**
396
+ * Resolve "should category X fire for this device?" — composes the
397
+ * global default and any per-device override. See `notification-prefs.js`
398
+ * for the precedence rules. The defensive RATE_LIMITS gate in send()
399
+ * still applies on top of this check, so user prefs can only mute
400
+ * further than the server's rate limits already permit.
401
+ */
402
+ isCategoryEnabled(category, pushToken = null) {
403
+ return isCategoryEnabledIn(this._prefs, category, pushToken)
404
+ }
405
+
406
+ /**
407
+ * Resolve "is `now` inside this device's quiet-hours window?" (#4544).
408
+ *
409
+ * Honours per-device override precedence and timezone-aware boundary
410
+ * math (including midnight wrap + DST). See `notification-prefs.js`
411
+ * `isInQuietHoursIn` for the full evaluation rules and fail-open
412
+ * defensive cases.
413
+ */
414
+ isInQuietHours(now = Date.now(), pushToken = null) {
415
+ return isInQuietHoursIn(this._prefs, now, pushToken)
416
+ }
417
+
418
+ /**
419
+ * Resolve "does this category bypass quiet hours for this device?"
420
+ * (#4544). Operator-blocking categories (`permission`,
421
+ * `activity_error`) bypass by default; users can extend or override
422
+ * this list globally and per-device.
423
+ */
424
+ shouldBypassQuietHours(category, pushToken = null) {
425
+ return shouldBypassQuietHours(this._prefs, category, pushToken)
426
+ }
427
+
428
+ /**
429
+ * Register a push token from a client. Delegates to the Expo sink —
430
+ * see ExpoPushSink.registerToken for format validation and the
431
+ * 2026-04-11 audit (blocker 6) history.
432
+ */
433
+ registerToken(token, ownerId = null) {
434
+ return this._expoSink.registerToken(token, ownerId)
435
+ }
436
+
437
+ /**
438
+ * Release one owner's claim on a token. If the last owner goes away,
439
+ * the token is removed from the registry entirely. Returns true if
440
+ * the token was actually pruned (last owner), false if it's still
441
+ * held by someone else.
442
+ *
443
+ * Used by WsServer._handleClientDeparture to prune on disconnect
444
+ * without breaking legitimate multi-connection scenarios.
445
+ */
446
+ releaseTokenOwner(token, ownerId) {
447
+ return this._expoSink.releaseTokenOwner(token, ownerId)
448
+ }
449
+
450
+ /**
451
+ * Validate a push-token string. Implementation lives on ExpoPushSink
452
+ * (it's an Expo/FCM token format concern); kept on PushManager because
453
+ * the WS prefs handler validates device keys through this surface.
454
+ */
455
+ static isValidPushTokenFormat(token) {
456
+ return ExpoPushSink.isValidPushTokenFormat(token)
457
+ }
458
+
459
+ /**
460
+ * Remove a push token unconditionally. Most callers should use
461
+ * releaseTokenOwner() instead so multi-owner tokens aren't stripped
462
+ * when one connection drops.
463
+ */
464
+ removeToken(token) {
465
+ return this._expoSink.removeToken(token)
466
+ }
467
+
468
+ /** Register a Live Activity push token (iOS). Delegates to the Expo sink. */
469
+ registerLiveActivityToken(token) {
470
+ return this._expoSink.registerLiveActivityToken(token)
471
+ }
472
+
473
+ /** Remove a Live Activity push token */
474
+ unregisterLiveActivityToken(token) {
475
+ return this._expoSink.unregisterLiveActivityToken(token)
476
+ }
477
+
478
+ /** Check if we have any registered tokens */
479
+ get hasTokens() {
480
+ return this._expoSink.hasTokens
481
+ }
482
+
483
+ /**
484
+ * Send a notification through the pipeline: shared rate limit, then fan
485
+ * out to every configured sink (per-device category/quiet-hours prefs
486
+ * are evaluated inside each sink via the context evaluators below).
487
+ *
488
+ * Category names listed here are the only ones with explicit RATE_LIMITS
489
+ * entries. Any other string still works but falls through to the
490
+ * `?? 30_000` default inside send() — if you're adding a new category,
491
+ * declare its rate limit explicitly in RATE_LIMITS. Note that `'idle'`
492
+ * was intentionally removed during the 2026-04-11 notification audit
493
+ * (it was firing in duplicate with activity_update); resurrecting it
494
+ * should be a deliberate, documented decision.
495
+ *
496
+ * @param {string} category - 'permission' | 'result' | 'activity_update' | 'activity_waiting' | 'activity_error'
497
+ * @param {string} title - Notification title
498
+ * @param {string} body - Notification body text
499
+ * @param {object} [data] - Extra data payload
500
+ * @param {string} [categoryId] - iOS notification category for action buttons
501
+ * @returns {Promise<boolean>} `true` when no hard delivery failure occurred
502
+ * (the sinks accepted it, or there was nothing to send / we were
503
+ * rate-limited — both of which are "no error" from the caller's view).
504
+ * `false` ONLY when a configured sink hard-failed (for Expo: non-2xx,
505
+ * network throw). Callers like the idle-push dedupe in server-cli.js
506
+ * (#3870) use this to decide whether to release a latch so a transient
507
+ * failure doesn't permanently suppress future notifications.
508
+ */
509
+ async send(category, title, body, data = {}, categoryId = undefined) {
510
+ // No sink has anywhere to deliver to — silent no-op, and intentionally
511
+ // BEFORE the rate-limit stamp (matching the pre-extraction
512
+ // `tokens.size === 0` early return) so a tokenless send doesn't burn
513
+ // the category's rate-limit window.
514
+ if (!this._sinks.hasConfigured()) return true
515
+
516
+ // Rate limit check — the FIRST line of defence. Stays in place
517
+ // ahead of the #4542 per-category mute and the #4544 quiet-hours
518
+ // gate so a single shared throttle still applies regardless of
519
+ // per-device prefs. See RATE_LIMITS history comments above.
520
+ const limit = RATE_LIMITS[category] ?? 30_000
521
+ const nowMs = this._now()
522
+ const lastSent = this._lastSent.get(category) || 0
523
+ if (nowMs - lastSent < limit) {
524
+ return true
525
+ }
526
+ this._lastSent.set(category, nowMs)
527
+
528
+ return await this._sinks.fanOut(
529
+ { category, title, body, data, categoryId },
530
+ {
531
+ now: nowMs,
532
+ isCategoryEnabled: (cat, deviceId) => this.isCategoryEnabled(cat, deviceId),
533
+ isInQuietHours: (now, deviceId) => this.isInQuietHours(now, deviceId),
534
+ shouldBypassQuietHours: (cat, deviceId) => this.shouldBypassQuietHours(cat, deviceId),
535
+ }
536
+ )
537
+ }
538
+
539
+ /**
540
+ * Send a Live Activity update to all registered Live Activity tokens.
541
+ * Expo-only side channel — goes straight to the Expo sink rather than
542
+ * through the registry fan-out (no other sink has a Live Activity
543
+ * concept). The shared rate-limit map still applies here so the
544
+ * `live_activity` throttle and notification categories share one clock.
545
+ * @param {string} state - Current activity state (e.g. 'thinking', 'writing', 'idle')
546
+ * @param {string} detail - Human-readable detail text
547
+ */
548
+ async sendLiveActivityUpdate(state, detail) {
549
+ if (!this._expoSink.hasLiveActivityTokens) return
550
+
551
+ // Rate limit check (live_activity category: 5s). #6165: use the injected
552
+ // clock seam (same as send()) — both share `_lastSent`, so reading the wall
553
+ // clock here while send() honoured `_now` would mix clocks through the map.
554
+ const category = 'live_activity'
555
+ const limit = RATE_LIMITS[category]
556
+ const nowMs = this._now()
557
+ const lastSent = this._lastSent.get(category) || 0
558
+ if (nowMs - lastSent < limit) {
559
+ return
560
+ }
561
+ this._lastSent.set(category, nowMs)
562
+
563
+ await this._expoSink.sendLiveActivityUpdate(state, detail)
564
+ }
565
+ }