@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
@@ -0,0 +1,768 @@
1
+ /**
2
+ * DiscordWebhookSink — per-project Discord status embed (#5413 Phase 2).
3
+ *
4
+ * A behavior port of claude-code-notify's bash state machine to a
5
+ * NotificationSink (see sink.js for the contract). One status message per
6
+ * project, kept fresh in place:
7
+ *
8
+ * - routine state updates → PATCH the existing message (no ping)
9
+ * - ping-worthy states → DELETE the old message + POST a new one, so
10
+ * Discord re-notifies and the message moves to the bottom of the channel
11
+ * (idle / needs-approval — the states the user actually waits on)
12
+ * - PATCH 404 (message deleted externally) → self-heal by POSTing fresh
13
+ * - per-project embed sidebar colors (config), per-state title/emoji
14
+ * - throttle window between same-state routine updates
15
+ *
16
+ * What moved vs the bash original:
17
+ * - State (message id, current state, subagent count, timestamps) lives in
18
+ * ONE JSON file under ~/.chroxy/ written atomically (temp+rename via
19
+ * writeFileRestricted) — not a pile of /tmp files with mkdir locking.
20
+ * The /tmp state machine was the root cause of the reliability pain the
21
+ * epic exists to fix.
22
+ * - The heartbeat is a single unref'd in-process setInterval that PATCHes
23
+ * each LIVE embed so the elapsed-time footer stays current — not a
24
+ * forked bash daemon with a PID file. Offline embeds are final and are
25
+ * skipped; entries untouched longer than `pruneAfterMs` are pruned from
26
+ * the state store at load time (#5429/#5434), keeping both the file and
27
+ * the heartbeat's per-tick work bounded to live projects.
28
+ * - Driven by chroxy's own notification pipeline categories (Phase 2).
29
+ * External Claude Code hook ingest is Phase 3; subagent counting from
30
+ * hooks is Phase 4 — until then the embed reflects what chroxy-launched
31
+ * sessions expose (`data.subagents` when a caller provides it).
32
+ *
33
+ * The webhook URL is a SECRET (posting + message-delete capability on the
34
+ * channel). It is sourced from the env / 0600 credentials.json via
35
+ * discord-credentials.js, never from config.json, and never logged (the
36
+ * logger redacts discord webhook URLs as a second layer).
37
+ *
38
+ * Discord rate limits: webhook endpoints return 429 with a `retry_after`
39
+ * (seconds) in the JSON body and a Retry-After header. fetchWithRetry
40
+ * (push.js) treats all 4xx as non-retryable, so this sink carries its own
41
+ * fetch helper that respects retry_after instead of hammering.
42
+ */
43
+
44
+ import { readFileSync, mkdirSync } from 'node:fs'
45
+ import { dirname, join } from 'node:path'
46
+ import { homedir } from 'node:os'
47
+ import { writeFileRestricted } from '../platform.js'
48
+ import { createLogger } from '../logger.js'
49
+ import { sleep } from '../utils/sleep.js'
50
+ import { NotificationSink } from './sink.js'
51
+ import {
52
+ cachedResolveDiscordWebhookUrl,
53
+ isValidDiscordWebhookUrl,
54
+ } from '../discord-credentials.js'
55
+ // #5828: the channel-level wire primitives (fetch policy, 429 handling, id/token
56
+ // extraction, markdown escaping, embed colors) moved to a shared client so the
57
+ // billing-alert sink can reuse them. The status sink delegates to them below —
58
+ // this is a pure-swap of the previous private helpers.
59
+ import {
60
+ DEFAULT_PROJECT_COLOR,
61
+ DEFAULT_PERMISSION_COLOR,
62
+ DEFAULT_ERROR_COLOR,
63
+ DEFAULT_ONLINE_COLOR,
64
+ DEFAULT_OFFLINE_COLOR,
65
+ isValidColor,
66
+ escapeAndCap,
67
+ formatDuration,
68
+ apiBase,
69
+ fetchWithDiscordRetry,
70
+ } from './discord-webhook-client.js'
71
+
72
+ const log = createLogger('discord')
73
+
74
+ // Re-exported for back-compat: the status sink's test imports formatDuration
75
+ // from here. The implementation now lives in discord-webhook-client.js.
76
+ export { formatDuration }
77
+
78
+ // #5429/#5434: retention for state-store entries. Project keys fall back to
79
+ // session ids (and Phase 3 ingest accepts arbitrary project names), so
80
+ // without pruning the store grows one entry per key forever — and the
81
+ // heartbeat's per-tick work grows with it. Entries untouched for longer than
82
+ // this are dropped at load time; the Discord message itself is KEPT (an
83
+ // offline embed is a final record — only the tracking stops).
84
+ const DEFAULT_PRUNE_AFTER_MS = 86_400_000 // 24h
85
+ // #5457: sanity floor. A retention shorter than the gap between consecutive
86
+ // events prunes the entry (and its messageId) in between, so every event
87
+ // takes the no-`prev` path and POSTs a brand-new message — message-per-event
88
+ // spam instead of one embed PATCHed in place. Anything below updateThrottleMs
89
+ // is definitely pathological; 60s is the conservative line. 0 stays the
90
+ // documented disable (parity with the heartbeatIntervalMs 10s floor).
91
+ const MIN_PRUNE_AFTER_MS = 60_000 // 60s
92
+
93
+ // #5676: two-stage staleness watchdog for the heartbeat. A hook-based external
94
+ // session (chroxy-hooks) that dies WITHOUT emitting session_end — kill -9,
95
+ // crash, OOM, terminal closed, laptop sleep, daemon restart mid-session — never
96
+ // fires session_offline, so its `online` embed would stay "🟢 working" forever
97
+ // while the heartbeat keeps re-rendering it as alive. The internal session
98
+ // types emit `inactivity_warning` to cover this; the ingest hook path has no
99
+ // equivalent. The heartbeat therefore watches silence = now - lastUpdateTs (the
100
+ // last REAL event, NOT a heartbeat tick) and downgrades a quiet embed:
101
+ // online → stale after STALE_AFTER_MS of silence,
102
+ // stale → offline after OFFLINE_AFTER_MS of silence (final).
103
+ // idle/permission are spared — those are legitimately waiting on the human, not
104
+ // dead. A real event takes the normal update() path and restores the true
105
+ // state, resetting the silence clock automatically.
106
+ const DEFAULT_STALE_AFTER_MS = 10 * 60_000 // 10m
107
+ const DEFAULT_OFFLINE_AFTER_MS = 30 * 60_000 // 30m
108
+
109
+ // Pipeline notification category → embed state. Phase 2 maps chroxy's own
110
+ // session events (the categories PushManager.send is called with). The
111
+ // bash original's hook-driven states (online/offline/idle_busy/approved)
112
+ // return with Phase 3 ingest + Phase 4 hooks.
113
+ //
114
+ // idle — session finished a turn / waiting for input (🦀 in the
115
+ // original; ping-worthy: DELETE + POST so Discord notifies)
116
+ // permission — needs approval / has a question (ping-worthy)
117
+ // error — session error (routine PATCH; new vs bash, which had no
118
+ // error surface — deliberate addition, documented in the PR)
119
+ // stale — inactivity warning: busy but silent for a long time
120
+ // (routine PATCH; replaces the bash "(stale?)" title suffix)
121
+ // online — session started / working (#5413 Phase 3 ingest). The bash
122
+ // original's SessionStart: DELETE the previous message (incl.
123
+ // a lingering offline one) + POST fresh; session_activity
124
+ // events keep it fresh via routine PATCH.
125
+ // offline — session ended (bash SessionEnd: routine PATCH in place;
126
+ // no-op when nothing is tracked or already offline)
127
+ const STATE_FOR_CATEGORY = {
128
+ activity_update: 'idle',
129
+ result: 'idle',
130
+ permission: 'permission',
131
+ activity_waiting: 'permission',
132
+ activity_error: 'error',
133
+ inactivity_warning: 'stale',
134
+ session_online: 'online',
135
+ session_offline: 'offline',
136
+ session_activity: 'online',
137
+ }
138
+
139
+ // States that re-ping: DELETE the old message + POST a new one.
140
+ const PING_STATES = new Set(['idle', 'permission'])
141
+
142
+ const STATE_TITLES = {
143
+ idle: (project) => `\u{1F980} ${project} — Ready for input`,
144
+ permission: (project) => `\u{1F510} ${project} — Needs Approval`,
145
+ error: (project) => `\u{2757} ${project} — Session Error`,
146
+ stale: (project) => `\u{23F3} ${project} — Quiet for a while`,
147
+ online: (project) => `\u{1F7E2} ${project} — Session Online`,
148
+ offline: (project) => `\u{1F534} ${project} — Session Offline`,
149
+ }
150
+
151
+ export class DiscordWebhookSink extends NotificationSink {
152
+ /**
153
+ * @param {object} [opts]
154
+ * @param {string} [opts.statePath] - Status-message state file. Defaults to
155
+ * ~/.chroxy/discord-webhook-state.json (resolved lazily so tests that
156
+ * mutate HOME, and the test sandbox guard, behave). Tests MUST inject a
157
+ * temp path.
158
+ * @param {string} [opts.botName] - Webhook display name + footer label.
159
+ * @param {Record<string, number>} [opts.colors] - Per-project sidebar color
160
+ * overrides (decimal 24-bit RGB), from config notifications.discord.colors.
161
+ * @param {number} [opts.defaultColor] - Sidebar color for projects without
162
+ * an override (default: Discord blurple).
163
+ * @param {number} [opts.permissionColor] - Sidebar color for the
164
+ * needs-approval state.
165
+ * @param {number} [opts.errorColor] - Sidebar color for the error state.
166
+ * @param {number} [opts.updateThrottleMs] - Minimum interval between
167
+ * same-state routine PATCHes per project (state CHANGES always go out).
168
+ * @param {number} [opts.heartbeatIntervalMs] - Elapsed-time refresh PATCH
169
+ * interval. 0 disables; values below 10s fall back to the default
170
+ * (parity with the bash heartbeat's interval clamp).
171
+ * @param {number} [opts.pruneAfterMs] - Retention for state-store entries
172
+ * (#5429/#5434): entries whose lastUpdateTs is older than this are
173
+ * dropped at load time (the first load after init is the startup sweep).
174
+ * 0 disables pruning; invalid values and values below 60s fall back to
175
+ * the 24h default (#5457 — a tiny retention prunes the messageId between
176
+ * events and turns the status embed into message-per-event spam).
177
+ * @param {number} [opts.staleAfterMs] - #5676 watchdog: silence after which
178
+ * an `online` embed is downgraded to `stale` in a heartbeat tick. Injected
179
+ * small for tests; defaults to 10m.
180
+ * @param {number} [opts.offlineAfterMs] - #5676 watchdog: silence after which
181
+ * a `stale` embed is downgraded to `offline` (final). Injected small for
182
+ * tests; defaults to 30m.
183
+ * @param {Function} [opts.resolveWebhookUrl] - Injection seam for tests;
184
+ * defaults to the env > 0600-credentials.json resolver.
185
+ * @param {Function} [opts.sleepImpl] - Injection seam for tests (429/backoff
186
+ * waits); defaults to utils/sleep.
187
+ * @param {Function} [opts.now] - Clock seam for tests; defaults to Date.now.
188
+ */
189
+ constructor({
190
+ statePath = null,
191
+ botName = 'Chroxy',
192
+ colors = {},
193
+ defaultColor = DEFAULT_PROJECT_COLOR,
194
+ permissionColor = DEFAULT_PERMISSION_COLOR,
195
+ errorColor = DEFAULT_ERROR_COLOR,
196
+ updateThrottleMs = 15_000,
197
+ heartbeatIntervalMs = 300_000,
198
+ pruneAfterMs = DEFAULT_PRUNE_AFTER_MS,
199
+ staleAfterMs = DEFAULT_STALE_AFTER_MS,
200
+ offlineAfterMs = DEFAULT_OFFLINE_AFTER_MS,
201
+ // Cached by default (#5427 review): isConfigured() is probed per
202
+ // notification; the cache only re-reads credentials.json when its
203
+ // mtime/size/mode or the env var changes.
204
+ resolveWebhookUrl = cachedResolveDiscordWebhookUrl,
205
+ sleepImpl = sleep,
206
+ now = Date.now,
207
+ } = {}) {
208
+ super({ name: 'discord-webhook' })
209
+ this._statePath = statePath || null
210
+ this._botName = typeof botName === 'string' && botName.length > 0 ? botName.slice(0, 80) : 'Chroxy'
211
+ this._colors = colors && typeof colors === 'object' && !Array.isArray(colors) ? colors : {}
212
+ this._defaultColor = isValidColor(defaultColor) ? defaultColor : DEFAULT_PROJECT_COLOR
213
+ this._permissionColor = isValidColor(permissionColor) ? permissionColor : DEFAULT_PERMISSION_COLOR
214
+ this._errorColor = isValidColor(errorColor) ? errorColor : DEFAULT_ERROR_COLOR
215
+ this._updateThrottleMs = Number.isFinite(updateThrottleMs) && updateThrottleMs >= 0 ? updateThrottleMs : 15_000
216
+ if (!Number.isFinite(heartbeatIntervalMs) || heartbeatIntervalMs < 0) heartbeatIntervalMs = 300_000
217
+ if (heartbeatIntervalMs > 0 && heartbeatIntervalMs < 10_000) heartbeatIntervalMs = 300_000
218
+ this._heartbeatIntervalMs = heartbeatIntervalMs
219
+ if (!Number.isFinite(pruneAfterMs) || pruneAfterMs < 0) pruneAfterMs = DEFAULT_PRUNE_AFTER_MS
220
+ if (pruneAfterMs > 0 && pruneAfterMs < MIN_PRUNE_AFTER_MS) pruneAfterMs = DEFAULT_PRUNE_AFTER_MS
221
+ this._pruneAfterMs = pruneAfterMs
222
+ // #5676 watchdog thresholds. Invalid values fall back to the defaults so a
223
+ // bad config can never disable the dead-session guard.
224
+ this._staleAfterMs = Number.isFinite(staleAfterMs) && staleAfterMs >= 0 ? staleAfterMs : DEFAULT_STALE_AFTER_MS
225
+ this._offlineAfterMs = Number.isFinite(offlineAfterMs) && offlineAfterMs >= 0 ? offlineAfterMs : DEFAULT_OFFLINE_AFTER_MS
226
+ this._resolveWebhookUrl = resolveWebhookUrl
227
+ this._sleep = sleepImpl
228
+ this._now = now
229
+ this._heartbeatTimer = null
230
+ this._destroyed = false
231
+ }
232
+
233
+ /**
234
+ * Sink contract: configured iff a syntactically valid webhook URL resolves
235
+ * from the env or the 0600 credentials file. Off by default — no URL means
236
+ * the registry never asks this sink to send (the epic's bloat guard).
237
+ */
238
+ isConfigured() {
239
+ return this._configuredUrl() != null
240
+ }
241
+
242
+ /** Resolve + validate the webhook URL, or null. Never throws, never logs the URL. */
243
+ _configuredUrl() {
244
+ let resolved
245
+ try {
246
+ resolved = this._resolveWebhookUrl()
247
+ } catch {
248
+ return null
249
+ }
250
+ const url = resolved?.url
251
+ return typeof url === 'string' && isValidDiscordWebhookUrl(url) ? url : null
252
+ }
253
+
254
+ /** Stop the heartbeat timer. Safe to call multiple times. */
255
+ destroy() {
256
+ this._destroyed = true
257
+ if (this._heartbeatTimer) {
258
+ clearInterval(this._heartbeatTimer)
259
+ this._heartbeatTimer = null
260
+ }
261
+ }
262
+
263
+ // -- State persistence (the /tmp → ~/.chroxy move) -----------------------
264
+
265
+ _resolvedStatePath() {
266
+ // Lazy like discord-credentials.credentialsFilePath so tests that mutate
267
+ // HOME (and the sandbox guard) see the current home, not a frozen one.
268
+ return this._statePath || join(homedir(), '.chroxy', 'discord-webhook-state.json')
269
+ }
270
+
271
+ /**
272
+ * Load the status-message store fresh from disk. Read-per-send (the file
273
+ * is tiny) so the supervisor's short-lived PushManager and the long-lived
274
+ * server process converge on the same message ids instead of fighting
275
+ * over cached copies.
276
+ */
277
+ _loadState() {
278
+ let store = { version: 1, projects: {} }
279
+ try {
280
+ const data = JSON.parse(readFileSync(this._resolvedStatePath(), 'utf-8'))
281
+ // Arrays are rejected too: `typeof [] === 'object'`, but string-keyed
282
+ // entries assigned onto an array are silently dropped by
283
+ // JSON.stringify, so a corrupt `projects: []` would wedge tracking
284
+ // (every persist loses the messageId) — fall back to a fresh map.
285
+ if (data && typeof data === 'object' && data.projects && typeof data.projects === 'object' && !Array.isArray(data.projects)) {
286
+ store = { version: 1, projects: data.projects }
287
+ }
288
+ } catch {
289
+ // Missing or corrupt — start fresh; the next successful send rewrites it.
290
+ }
291
+ // #5429/#5434: retention sweep on every load — the first load after init
292
+ // doubles as the startup sweep, and every send/heartbeat afterwards keeps
293
+ // the store (and the heartbeat's per-tick work) bounded to live projects.
294
+ // Persisting here reuses the atomic 0600 path, so the pruned file is
295
+ // durable even when the caller's own persist never fires (throttled
296
+ // sends, no-op heartbeat ticks).
297
+ if (this._pruneStale(store)) this._persistState(store)
298
+ return store
299
+ }
300
+
301
+ /**
302
+ * Drop entries untouched for longer than the retention (and entries with
303
+ * no usable lastUpdateTs — corrupt slots must not accumulate forever).
304
+ * The Discord message is deliberately NOT deleted: a pruned entry's last
305
+ * embed (typically a final offline one) stays in the channel as a record;
306
+ * chroxy just stops tracking and refreshing it. Returns true when the
307
+ * store was mutated. Disabled when pruneAfterMs is 0.
308
+ */
309
+ _pruneStale(store) {
310
+ if (this._pruneAfterMs === 0) return false
311
+ const now = this._now()
312
+ let pruned = false
313
+ for (const [project, entry] of Object.entries(store.projects)) {
314
+ const last = entry?.lastUpdateTs
315
+ if (!Number.isFinite(last) || now - last > this._pruneAfterMs) {
316
+ delete store.projects[project]
317
+ pruned = true
318
+ }
319
+ }
320
+ return pruned
321
+ }
322
+
323
+ /** Atomic persist (temp+rename, 0600) — mirrors how push.js persists tokens. */
324
+ _persistState(store) {
325
+ try {
326
+ const path = this._resolvedStatePath()
327
+ mkdirSync(dirname(path), { recursive: true })
328
+ writeFileRestricted(path, JSON.stringify(store))
329
+ } catch (err) {
330
+ // State-file failure must not fail delivery — worst case the next
331
+ // event POSTs a duplicate status message instead of PATCHing.
332
+ log.error(`Failed to persist Discord status state: ${err.message}`)
333
+ }
334
+ }
335
+
336
+ // -- Project keying -------------------------------------------------------
337
+
338
+ /**
339
+ * One status message per project. Phase 2 derives the key from what the
340
+ * pipeline notification carries (Phase 3 ingest events will carry an
341
+ * explicit `project`). Sanitized the same way the bash original sanitized
342
+ * project names so state keys stay filesystem/log safe.
343
+ */
344
+ _projectKey(notification) {
345
+ const data = notification?.data || {}
346
+ const raw = data.project || data.sessionName || data.sessionId || 'chroxy'
347
+ const sanitized = String(raw).replace(/[^A-Za-z0-9._-]/g, '')
348
+ return sanitized.length > 0 ? sanitized : 'unknown'
349
+ }
350
+
351
+ // -- Sink contract --------------------------------------------------------
352
+
353
+ /**
354
+ * Deliver one approved notification by updating (or re-posting) the
355
+ * project's status embed. Resolves `false` ONLY on hard channel failure
356
+ * (final non-2xx after retries, network throw) — per the sink contract the
357
+ * #3870-style latch handling is the pipeline's job, not ours.
358
+ *
359
+ * The context evaluators are per-DEVICE hooks; a webhook has no device
360
+ * identity, so they're evaluated once with `deviceId = null` — which the
361
+ * prefs resolvers treat as "the global setting". A globally muted
362
+ * category (or global quiet hours without a bypass) therefore silences
363
+ * the Discord embed update too, matching the pipeline's intent. Missing
364
+ * evaluators fail open per the contract.
365
+ */
366
+ async send(notification, context = {}) {
367
+ const webhookUrl = this._configuredUrl()
368
+ if (!webhookUrl) return true // unconfigured — registry normally skips us anyway
369
+
370
+ const state = STATE_FOR_CATEGORY[notification?.category]
371
+ if (!state) return true // unmapped category (parity: bash skipped unknown notification types)
372
+
373
+ const now0 = context.now ?? this._now()
374
+ const isCategoryEnabled = context.isCategoryEnabled ?? (() => true)
375
+ const isInQuietHours = context.isInQuietHours ?? (() => false)
376
+ const shouldBypassQuietHours = context.shouldBypassQuietHours ?? (() => false)
377
+ if (!isCategoryEnabled(notification.category, null)) return true
378
+ if (isInQuietHours(now0, null) && !shouldBypassQuietHours(notification.category, null)) return true
379
+
380
+ const project = this._projectKey(notification)
381
+ const now = this._now()
382
+ const store = this._loadState()
383
+ const prev = store.projects[project]
384
+
385
+ const data = notification.data || {}
386
+ const entry = {
387
+ messageId: prev?.messageId ?? null,
388
+ state,
389
+ body: typeof notification.body === 'string' ? notification.body : '',
390
+ detail: typeof data.detail === 'string' ? data.detail : (typeof data.tool === 'string' ? data.tool : null),
391
+ sessionName: typeof data.sessionName === 'string' ? data.sessionName : (prev?.sessionName ?? null),
392
+ // Phase 4 fills this from the hook event stream; until then callers
393
+ // may pass a count and we surface it.
394
+ subagents: Number.isFinite(data.subagents) ? data.subagents : (prev?.subagents ?? 0),
395
+ firstSeenTs: prev?.firstSeenTs ?? now,
396
+ lastUpdateTs: now,
397
+ lastStateChangeTs: prev?.state === state ? (prev?.lastStateChangeTs ?? now) : now,
398
+ }
399
+
400
+ try {
401
+ // #5413 Phase 3 — session lifecycle (bash SessionStart/SessionEnd port).
402
+ if (notification.category === 'session_online') {
403
+ // Clean slate: DELETE whatever message lingers (typically the
404
+ // previous session's offline embed) + POST fresh, resetting the
405
+ // elapsed-time epoch and the subagent count — parity with the bash
406
+ // SessionStart's delete-old-message + clear_status_files.
407
+ entry.firstSeenTs = now
408
+ entry.lastStateChangeTs = now
409
+ entry.subagents = Number.isFinite(data.subagents) ? data.subagents : 0
410
+ return await this._repost(webhookUrl, project, entry, store, prev?.messageId)
411
+ }
412
+ if (state === 'offline') {
413
+ // SessionEnd PATCHes in place — and only when there is something to
414
+ // mark offline (bash: skip when state is empty or already offline).
415
+ // #5439 GAP D: if the tracked message was deleted externally, do NOT
416
+ // POST a fresh offline embed (bash no_post_on_404) — just drop the id.
417
+ if (!prev?.messageId || prev.state === 'offline') return true
418
+ return await this._patchOrPost(webhookUrl, project, entry, store, { noPostOn404: true })
419
+ }
420
+
421
+ // #5439 GAP C — subagent/idle interplay (port of claude-notify.sh
422
+ // :528-539 and :383-384), rescoped by #5541 turn edges.
423
+ //
424
+ // The bash rule held the idle/permission embed while subagents ran on
425
+ // the assumption "idle + subagents = the user is still being waited on".
426
+ // That assumption is only correct BETWEEN turns: while a turn is in
427
+ // flight (UserPromptSubmit seen, no Stop yet) the MAIN agent is busy,
428
+ // and SubagentStart usually means it's actively working — so holding
429
+ // idle is wrong and the count→0 re-ping ("Ready for input") would
430
+ // falsely interrupt a turn the agent is still synthesizing.
431
+ //
432
+ // `turnInFlight` (server-side TurnTracker, #5541) is the per-project
433
+ // gate. It defaults to false — a missing flag (old pipeline, or the
434
+ // daemon restarting and losing its in-memory turn state) keeps today's
435
+ // GAP C behavior, which is the safe fallback.
436
+ //
437
+ // turn in flight → online-mapped events flip idle→online normally;
438
+ // when subagents > 0 the Status line reads
439
+ // "Working — N subagents" (or the lone subagent's
440
+ // agentType when count is 1). No count→0 re-ping.
441
+ // no turn → the original hold-idle / count→0-reping behavior:
442
+ // keep the waiting state and text, refresh only the
443
+ // live fields; re-ping 🦀 "Ready for input" when the
444
+ // LAST subagent finishes while idle. Permission +
445
+ // count→0 falls through to online (row-20 diff).
446
+ // The turnInFlight rescope applies ONLY to the `idle` hold. A
447
+ // `permission` embed is an approval request the user must act on, and
448
+ // permission prompts fire MID-turn (an agent hits a tool-approval gate
449
+ // while working) — so turnInFlight is true with subagents running. If
450
+ // the flip-to-online branch fired here it would hide the approval. The
451
+ // `permission` hold therefore keeps its original pre-#5541 behavior
452
+ // UNCONDITIONALLY: while subagents > 0 the permission state/text is
453
+ // held (live fields refreshed); count→0 falls through to online (the
454
+ // intentional row-20 "approval cleared by next activity" diff).
455
+ const turnInFlight = data.turnInFlight === true
456
+ if (state === 'online' && turnInFlight && entry.subagents > 0 && prev?.state !== 'permission') {
457
+ // Mid-turn with live subagents (and NOT a permission prompt): surface
458
+ // the work in the online embed (Status line) instead of holding idle.
459
+ // (Plain online with no subagents falls through to the routine path
460
+ // below, flipping to "Session Online".)
461
+ entry.body = this._workingDetail(entry.subagents, data.agentType)
462
+ } else if (
463
+ state === 'online' &&
464
+ prev?.messageId &&
465
+ ((prev.state === 'idle' && !turnInFlight) || prev.state === 'permission')
466
+ ) {
467
+ const allDone = entry.subagents === 0 && Number.isFinite(prev.subagents) && prev.subagents > 0
468
+ if (entry.subagents > 0 || (allDone && prev.state === 'idle')) {
469
+ entry.state = prev.state
470
+ if (typeof prev.body === 'string' && prev.body.length > 0) entry.body = prev.body
471
+ entry.detail = prev.detail ?? entry.detail
472
+ entry.lastStateChangeTs = prev.lastStateChangeTs ?? now
473
+ if (allDone) {
474
+ return await this._repost(webhookUrl, project, entry, store, prev.messageId)
475
+ }
476
+ if (Number.isFinite(prev.lastUpdateTs) && now - prev.lastUpdateTs < this._updateThrottleMs) {
477
+ return true
478
+ }
479
+ return await this._patchOrPost(webhookUrl, project, entry, store)
480
+ }
481
+ }
482
+
483
+ if (PING_STATES.has(state)) {
484
+ // Parity: an embed already sitting in `idle` is NOT re-posted for
485
+ // another idle event (`[ "$CURRENT_STATE" = "idle" ] && exit 0`) —
486
+ // re-pinging "still ready" is noise. `permission` always re-posts:
487
+ // each new approval request deserves a fresh ping.
488
+ if (state === 'idle' && prev?.state === 'idle' && prev?.messageId) return true
489
+ return await this._repost(webhookUrl, project, entry, store, prev?.messageId)
490
+ }
491
+
492
+ // Routine update. Same-state updates inside the throttle window are
493
+ // suppressed; a state CHANGE always goes out (the bash throttle only
494
+ // ever gated repeat activity updates, never transitions).
495
+ if (
496
+ prev?.state === state &&
497
+ Number.isFinite(prev?.lastUpdateTs) &&
498
+ now - prev.lastUpdateTs < this._updateThrottleMs
499
+ ) {
500
+ return true
501
+ }
502
+ return await this._patchOrPost(webhookUrl, project, entry, store)
503
+ } catch (err) {
504
+ log.error(`Discord status update failed for ${project}: ${err?.message || err}`)
505
+ return false
506
+ }
507
+ }
508
+
509
+ // -- Discord message operations -------------------------------------------
510
+
511
+ _apiBase(webhookUrl) {
512
+ // _configuredUrl() already validated the shape; apiBase belt-and-braces.
513
+ return apiBase(webhookUrl)
514
+ }
515
+
516
+ /** DELETE the old status message (best effort) + POST a fresh one → re-ping. */
517
+ async _repost(webhookUrl, project, entry, store, oldMessageId) {
518
+ const base = this._apiBase(webhookUrl)
519
+ if (oldMessageId) {
520
+ try {
521
+ // Single attempt, failures ignored — parity with the bash `|| true`.
522
+ // Worst case the old message lingers; the new POST still pings.
523
+ await this._discordFetch(`${base}/messages/${oldMessageId}`, { method: 'DELETE' }, { retries: 1 })
524
+ } catch {
525
+ // best-effort
526
+ }
527
+ // Drop the id NOW, before the re-POST (#5427 review S2): if the POST
528
+ // below hard-fails, a persisted {state:'idle', messageId:<deleted>}
529
+ // would satisfy the idle→idle suppression and wedge the embed until
530
+ // a state change or a heartbeat 404 (never, if heartbeat is off).
531
+ // With the id cleared, the next event falls through to a fresh POST.
532
+ if (store.projects[project]) {
533
+ store.projects[project] = { ...store.projects[project], messageId: null }
534
+ this._persistState(store)
535
+ }
536
+ entry.messageId = null
537
+ }
538
+ return await this._post(base, project, entry, store)
539
+ }
540
+
541
+ /** POST a new status message (?wait=true returns the created message). */
542
+ async _post(base, project, entry, store) {
543
+ const payload = this._buildPayload(project, entry)
544
+ const res = await this._discordFetch(`${base}?wait=true`, {
545
+ method: 'POST',
546
+ headers: { 'Content-Type': 'application/json' },
547
+ body: JSON.stringify(payload),
548
+ })
549
+ if (!res.ok) {
550
+ log.error(`Discord webhook POST failed for ${project} (HTTP ${res.status})`)
551
+ return false
552
+ }
553
+ let messageId = null
554
+ try {
555
+ messageId = (await res.json())?.id ?? null
556
+ } catch {
557
+ // 204 / unparsable body — message likely posted but we can't track it;
558
+ // treat as delivered, next event self-heals by POSTing fresh.
559
+ }
560
+ entry.messageId = messageId
561
+ store.projects[project] = entry
562
+ this._persistState(store)
563
+ this._ensureHeartbeat()
564
+ return true
565
+ }
566
+
567
+ /**
568
+ * PATCH the existing message; self-heal on 404 / missing id by POSTing.
569
+ * `noPostOn404` (#5439 GAP D, port of bash no_post_on_404) suppresses the
570
+ * healing POST — used by the offline path, where re-creating a message
571
+ * that was deleted externally would just leave an orphan offline embed.
572
+ */
573
+ async _patchOrPost(webhookUrl, project, entry, store, { noPostOn404 = false } = {}) {
574
+ const base = this._apiBase(webhookUrl)
575
+ if (!entry.messageId) {
576
+ if (noPostOn404) return true
577
+ return await this._post(base, project, entry, store)
578
+ }
579
+ const payload = this._buildPayload(project, entry)
580
+ const res = await this._discordFetch(`${base}/messages/${entry.messageId}`, {
581
+ method: 'PATCH',
582
+ headers: { 'Content-Type': 'application/json' },
583
+ body: JSON.stringify(payload),
584
+ })
585
+ if (res.status === 404) {
586
+ // Message deleted externally — re-POST (parity with the bash self-heal)
587
+ // unless suppressed: then just drop the id so the next session POSTs.
588
+ entry.messageId = null
589
+ if (noPostOn404) {
590
+ store.projects[project] = entry
591
+ this._persistState(store)
592
+ return true
593
+ }
594
+ return await this._post(base, project, entry, store)
595
+ }
596
+ if (!res.ok) {
597
+ log.error(`Discord webhook PATCH failed for ${project} (HTTP ${res.status})`)
598
+ return false
599
+ }
600
+ store.projects[project] = entry
601
+ this._persistState(store)
602
+ this._ensureHeartbeat()
603
+ return true
604
+ }
605
+
606
+ /**
607
+ * Delegate to the shared client's fetch policy (429/backoff/timeout), passing
608
+ * this sink's injected sleep seam so existing tests keep working unchanged.
609
+ */
610
+ async _discordFetch(url, options, opts = {}) {
611
+ return fetchWithDiscordRetry(url, options, { sleepImpl: this._sleep, ...opts })
612
+ }
613
+
614
+ // -- Embed building --------------------------------------------------------
615
+
616
+ _colorFor(project, state) {
617
+ if (state === 'permission') return this._permissionColor
618
+ if (state === 'error') return this._errorColor
619
+ if (state === 'online') return DEFAULT_ONLINE_COLOR
620
+ if (state === 'offline') return DEFAULT_OFFLINE_COLOR
621
+ const override = this._colors[project]
622
+ return isValidColor(override) ? override : this._defaultColor
623
+ }
624
+
625
+ /**
626
+ * #5541: the "Working — …" Status line shown on the online embed while a
627
+ * turn is in flight with live subagents. Names the single subagent's
628
+ * agentType when count is 1 and one is available; otherwise a count
629
+ * ("Working — 2 subagents", singular for 1).
630
+ */
631
+ _workingDetail(subagents, agentType) {
632
+ if (subagents === 1 && typeof agentType === 'string' && agentType.length > 0) {
633
+ return `Working — ${agentType}`
634
+ }
635
+ return `Working — ${subagents} subagent${subagents === 1 ? '' : 's'}`
636
+ }
637
+
638
+ _buildPayload(project, entry) {
639
+ const titleFor = STATE_TITLES[entry.state] || STATE_TITLES.idle
640
+ const fields = []
641
+ // Free-text user/transcript fields (#5475): escape markdown so a body like
642
+ // `watch dist/*_test.js` renders literally. escapeAndCap truncates first,
643
+ // escapes, then clamps the FINAL escaped string so it can't blow past
644
+ // Discord's 1024-char field limit (see escapeAndCap).
645
+ if (entry.body) {
646
+ fields.push({ name: 'Status', value: escapeAndCap(entry.body), inline: false })
647
+ }
648
+ if (entry.detail) {
649
+ fields.push({ name: 'Detail', value: escapeAndCap(entry.detail), inline: false })
650
+ }
651
+ if (entry.sessionName) {
652
+ fields.push({ name: 'Session', value: escapeAndCap(entry.sessionName, 100), inline: true })
653
+ }
654
+ if (Number.isFinite(entry.subagents) && entry.subagents > 0) {
655
+ fields.push({ name: 'Subagents', value: String(entry.subagents), inline: true })
656
+ }
657
+ const elapsedSec = (this._now() - (entry.firstSeenTs || this._now())) / 1000
658
+ return {
659
+ username: this._botName,
660
+ embeds: [{
661
+ title: titleFor(project),
662
+ color: this._colorFor(project, entry.state),
663
+ fields,
664
+ footer: { text: `${this._botName} · ${formatDuration(elapsedSec)}` },
665
+ timestamp: new Date(this._now()).toISOString(),
666
+ }],
667
+ }
668
+ }
669
+
670
+ // -- Heartbeat (elapsed-time refresh) --------------------------------------
671
+
672
+ /**
673
+ * Start the heartbeat lazily after the first successful message write.
674
+ * One unref'd interval per sink — it PATCHes every tracked embed so the
675
+ * footer's elapsed time stays current (the epic's "keep — it's one
676
+ * setInterval now" lean). Does nothing when unconfigured, never blocks
677
+ * process exit, and destroy() stops it.
678
+ */
679
+ _ensureHeartbeat() {
680
+ if (this._destroyed || this._heartbeatTimer || this._heartbeatIntervalMs === 0) return
681
+ this._heartbeatTimer = setInterval(() => {
682
+ this._heartbeatTick().catch((err) => {
683
+ log.debug?.(`Discord heartbeat tick failed: ${err?.message || err}`)
684
+ })
685
+ }, this._heartbeatIntervalMs)
686
+ this._heartbeatTimer.unref?.()
687
+ }
688
+
689
+ /**
690
+ * One heartbeat pass: refresh each LIVE project's embed in place, and run the
691
+ * #5676 staleness watchdog so a dead external session doesn't sit "🟢 online"
692
+ * forever.
693
+ *
694
+ * Offline entries are skipped (#5434) — the offline embed is final, and
695
+ * re-PATCHing it would both keep its elapsed-time footer counting up forever
696
+ * and spend a Discord call per dead project per tick. Entries pruned by
697
+ * retention never even reach the loop: _loadState drops them.
698
+ *
699
+ * Watchdog (before the routine footer PATCH), measuring silence against
700
+ * `lastUpdateTs` — the last REAL event time, which the heartbeat NEVER writes,
701
+ * so repeated ticks let the clock keep climbing until it trips:
702
+ * - `online` silent > staleAfterMs → downgrade to `stale`
703
+ * - `stale` silent > offlineAfterMs → downgrade to `offline` (final)
704
+ * `idle` and `permission` are spared — they are legitimately waiting on the
705
+ * human, not dead. A pending downgrade is rendered into the PATCH payload from
706
+ * a CANDIDATE state, and only committed to the entry once Discord confirms the
707
+ * PATCH (res.ok) — a failed PATCH must not persist `stale`/`offline` while the
708
+ * embed still shows the old state. That matters most for `offline`, which later
709
+ * ticks skip: persisting it on a failed PATCH would wedge the embed forever
710
+ * (the very ghost this watchdog exists to prevent). A real event (update())
711
+ * restores the true state and resets `lastUpdateTs`, so recovery is automatic.
712
+ */
713
+ async _heartbeatTick() {
714
+ const webhookUrl = this._configuredUrl()
715
+ if (!webhookUrl) return
716
+ const base = this._apiBase(webhookUrl)
717
+ const store = this._loadState()
718
+ const now = this._now()
719
+ let mutated = false
720
+ for (const [project, entry] of Object.entries(store.projects)) {
721
+ if (!entry?.messageId || entry.state === 'offline') continue
722
+
723
+ // #5676: staleness downgrade. Only `online`/`stale` decay; idle/permission
724
+ // are left to their normal footer refresh. silence reads lastUpdateTs (the
725
+ // last real event), which the heartbeat does not bump — so a long-silent
726
+ // entry eventually trips even with ticks firing in between. The downgrade
727
+ // is a CANDIDATE here; entry.state is mutated only after a successful PATCH.
728
+ const last = entry.lastUpdateTs
729
+ const silence = Number.isFinite(last) ? now - last : Infinity
730
+ let downgradeTo = null
731
+ if (entry.state === 'online' && silence > this._staleAfterMs) {
732
+ downgradeTo = 'stale'
733
+ } else if (entry.state === 'stale' && silence > this._offlineAfterMs) {
734
+ downgradeTo = 'offline'
735
+ }
736
+
737
+ // Render from the candidate state when a downgrade is pending, else the
738
+ // current state for the routine footer refresh.
739
+ const payloadEntry = downgradeTo
740
+ ? { ...entry, state: downgradeTo, lastStateChangeTs: now }
741
+ : entry
742
+
743
+ try {
744
+ const res = await this._discordFetch(`${base}/messages/${entry.messageId}`, {
745
+ method: 'PATCH',
746
+ headers: { 'Content-Type': 'application/json' },
747
+ body: JSON.stringify(this._buildPayload(project, payloadEntry)),
748
+ })
749
+ if (res.status === 404) {
750
+ // Deleted externally — forget the id so the next real event POSTs.
751
+ entry.messageId = null
752
+ mutated = true
753
+ } else if (res.ok && downgradeTo) {
754
+ // Commit the downgrade only now that Discord has the new embed. A
755
+ // failed/non-ok PATCH leaves the entry untouched so the next tick
756
+ // retries without corrupting persisted state.
757
+ entry.state = downgradeTo
758
+ entry.lastStateChangeTs = now
759
+ mutated = true
760
+ }
761
+ } catch {
762
+ // Heartbeat is best-effort; the next real event takes the full path.
763
+ // A pending downgrade is intentionally NOT committed — retried next tick.
764
+ }
765
+ }
766
+ if (mutated) this._persistState(store)
767
+ }
768
+ }