@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.
- package/CONFIG.md +695 -0
- package/README.md +105 -0
- package/hooks/permission-hook.sh +285 -0
- package/package.json +69 -0
- package/scripts/fix-node-pty-helper.js +44 -0
- package/sidecar/Dockerfile +40 -0
- package/sidecar/PROTOCOL.md +691 -0
- package/sidecar/agent.js +1290 -0
- package/sidecar/package-lock.json +43 -0
- package/sidecar/package.json +17 -0
- package/src/activity-registry.js +491 -0
- package/src/anthropic-compatible-config.js +534 -0
- package/src/anthropic-compatible-session.js +579 -0
- package/src/anthropic-openai-shim.js +109 -0
- package/src/anthropic-openai-translate.js +377 -0
- package/src/auth-probes.js +296 -0
- package/src/background-shell-tracker.js +320 -0
- package/src/background-shells.js +125 -0
- package/src/base-session.js +1518 -0
- package/src/billing-budget.js +191 -0
- package/src/billing-canary-monitor.js +203 -0
- package/src/billing-class.js +149 -0
- package/src/bind-host.js +82 -0
- package/src/built-in-tools/bash-exec.js +167 -0
- package/src/built-in-tools/file-ops.js +198 -0
- package/src/built-in-tools/tool-transforms.js +179 -0
- package/src/builtin-commands.js +107 -0
- package/src/byok-compose-state-shared.js +31 -0
- package/src/byok-compose-state.js +234 -0
- package/src/byok-credentials.js +127 -0
- package/src/byok-event-translator.js +136 -0
- package/src/byok-mcp-client.js +404 -0
- package/src/byok-mcp-config.js +159 -0
- package/src/byok-mcp-fleet.js +214 -0
- package/src/byok-mcp-trust.js +175 -0
- package/src/byok-session.js +2019 -0
- package/src/byok-subagent-profiles.js +101 -0
- package/src/byok-tool-executor.js +813 -0
- package/src/byok-tools.js +271 -0
- package/src/channels/PACKAGING.md +181 -0
- package/src/channels/README.md +99 -0
- package/src/channels/chroxy-channel-server.js +248 -0
- package/src/checkpoint-manager.js +515 -0
- package/src/child-stream-guard.js +38 -0
- package/src/claude-channel-session.js +185 -0
- package/src/claude-model-catalog.js +266 -0
- package/src/claude-stream-parser.js +106 -0
- package/src/claude-tui/form-driver.js +874 -0
- package/src/claude-tui/pty-driver.js +520 -0
- package/src/claude-tui/tested-cli-version.js +22 -0
- package/src/claude-tui-attachments.js +342 -0
- package/src/claude-tui-session.js +4029 -0
- package/src/cli/config-cmd.js +34 -0
- package/src/cli/credentials-cmd.js +59 -0
- package/src/cli/deploy-cmd.js +167 -0
- package/src/cli/doctor-cmd.js +52 -0
- package/src/cli/identity-cmd.js +82 -0
- package/src/cli/init-cmd.js +209 -0
- package/src/cli/pages-cmd.js +167 -0
- package/src/cli/pair-code-cmd.js +108 -0
- package/src/cli/pair-discord-cmd.js +100 -0
- package/src/cli/providers-cmd.js +168 -0
- package/src/cli/server-cmd.js +94 -0
- package/src/cli/service-cmd.js +237 -0
- package/src/cli/session-cmd.js +143 -0
- package/src/cli/shared.js +194 -0
- package/src/cli/shell-cmd.js +130 -0
- package/src/cli/status-cmd.js +204 -0
- package/src/cli/tunnel-cmd.js +101 -0
- package/src/cli/update-cmd.js +45 -0
- package/src/cli/worktree-gc-cmd.js +195 -0
- package/src/cli-session.js +1820 -0
- package/src/cli.js +60 -0
- package/src/codex-app-server-client.js +156 -0
- package/src/codex-app-server-session.js +572 -0
- package/src/codex-session.js +604 -0
- package/src/config.js +1757 -0
- package/src/connection-info.js +42 -0
- package/src/connection-locality.js +55 -0
- package/src/content-blocks.js +42 -0
- package/src/control-room/byok-pool.js +130 -0
- package/src/control-room/constants.js +26 -0
- package/src/control-room/containers.js +258 -0
- package/src/control-room/emulators.js +279 -0
- package/src/control-room/handler-factory.js +142 -0
- package/src/control-room/host-prune.js +387 -0
- package/src/control-room/integrations.js +929 -0
- package/src/control-room/repo-runtime-config.js +239 -0
- package/src/control-room/repo-set.js +162 -0
- package/src/control-room/runners.js +479 -0
- package/src/control-room/simulators.js +223 -0
- package/src/control-room/skills-inventory.js +303 -0
- package/src/control-room/survey.js +685 -0
- package/src/control-room/wsl.js +182 -0
- package/src/conversation-scanner.js +270 -0
- package/src/conversation-scope.js +52 -0
- package/src/conversation-search.js +216 -0
- package/src/cost-budget-manager.js +190 -0
- package/src/credential-cipher.js +179 -0
- package/src/credential-store.js +786 -0
- package/src/credential-test.js +145 -0
- package/src/credentials-file.js +58 -0
- package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +111 -0
- package/src/dashboard-next/dist/assets/index-DM-_dISG.css +1 -0
- package/src/dashboard-next/dist/index.html +13 -0
- package/src/deepseek-credentials.js +58 -0
- package/src/deepseek-session.js +192 -0
- package/src/detect-thinking-keyword.js +67 -0
- package/src/dev-preview.js +227 -0
- package/src/devcontainer-config.js +269 -0
- package/src/device-preferences.js +267 -0
- package/src/diagnostics.js +187 -0
- package/src/diff-parser.js +157 -0
- package/src/discord-credentials.js +188 -0
- package/src/discord-pair-delivery.js +113 -0
- package/src/docker-byok-pool-stats.js +221 -0
- package/src/docker-byok-pool.js +841 -0
- package/src/docker-byok-session.js +2172 -0
- package/src/docker-image-allowlist.js +99 -0
- package/src/docker-sdk-session.js +396 -0
- package/src/docker-session.js +382 -0
- package/src/doctor-billing.js +179 -0
- package/src/doctor.js +667 -0
- package/src/duration.js +77 -0
- package/src/environment-manager.js +753 -0
- package/src/environment-statuses.js +20 -0
- package/src/environments/backends/docker.js +931 -0
- package/src/environments/backends/k8s.js +3030 -0
- package/src/environments/backends/rancher.js +326 -0
- package/src/environments/backends/types.js +332 -0
- package/src/event-ingest.js +546 -0
- package/src/event-normalizer.js +1083 -0
- package/src/external-session-registry.js +0 -0
- package/src/file-store.js +52 -0
- package/src/gemini-session.js +498 -0
- package/src/get-public-ip.js +52 -0
- package/src/git.js +15 -0
- package/src/github-webhook.js +256 -0
- package/src/handler-utils.js +663 -0
- package/src/handlers/checkpoint-handlers.js +202 -0
- package/src/handlers/control-room-handlers.js +1945 -0
- package/src/handlers/conversation-handlers.js +201 -0
- package/src/handlers/credential-handlers.js +247 -0
- package/src/handlers/evaluator-handlers.js +94 -0
- package/src/handlers/feature-handlers.js +332 -0
- package/src/handlers/file-handlers.js +142 -0
- package/src/handlers/ide-handlers.js +238 -0
- package/src/handlers/input-handlers.js +1048 -0
- package/src/handlers/pairing-handlers.js +94 -0
- package/src/handlers/repo-handlers.js +295 -0
- package/src/handlers/session-handlers.js +660 -0
- package/src/handlers/settings-handlers.js +818 -0
- package/src/handlers/skills-handlers.js +682 -0
- package/src/handlers/summarize-handlers.js +172 -0
- package/src/handlers/token-handlers.js +57 -0
- package/src/http-oversize.js +51 -0
- package/src/http-routes.js +1158 -0
- package/src/ide/search.js +268 -0
- package/src/ide/symbols.js +423 -0
- package/src/ip-utils.js +85 -0
- package/src/json-state-file.js +169 -0
- package/src/jsonl-reader.js +187 -0
- package/src/jsonl-subprocess-session.js +441 -0
- package/src/keychain.js +458 -0
- package/src/lan-ip.js +38 -0
- package/src/logger.js +388 -0
- package/src/mailbox-route.js +252 -0
- package/src/mcp-tools.js +46 -0
- package/src/message-transform.js +102 -0
- package/src/metrics.js +67 -0
- package/src/model-discovery.js +288 -0
- package/src/models.js +1426 -0
- package/src/notification-prefs.js +544 -0
- package/src/notifications/discord-billing-sink.js +323 -0
- package/src/notifications/discord-webhook-client.js +187 -0
- package/src/notifications/discord-webhook-sink.js +768 -0
- package/src/notifications/expo-push-sink.js +414 -0
- package/src/notifications/ready-body.js +177 -0
- package/src/notifications/sink-registry.js +98 -0
- package/src/notifications/sink.js +82 -0
- package/src/ollama-session.js +221 -0
- package/src/ollama-tags.js +238 -0
- package/src/openai-compatible-session.js +118 -0
- package/src/pages-store.js +255 -0
- package/src/pairing.js +836 -0
- package/src/path-hash-trust-ledger.js +311 -0
- package/src/per-session-settings.js +366 -0
- package/src/permission-audit.js +120 -0
- package/src/permission-hook.js +257 -0
- package/src/permission-manager.js +829 -0
- package/src/permission-resolver.js +144 -0
- package/src/platform.js +139 -0
- package/src/prompt-evaluator.js +386 -0
- package/src/providers.js +436 -0
- package/src/push.js +565 -0
- package/src/rate-limiter.js +433 -0
- package/src/redaction.js +206 -0
- package/src/sdk-session.js +1773 -0
- package/src/semver.js +92 -0
- package/src/server-cli/push-notification-handler.js +240 -0
- package/src/server-cli/server-orchestrator.js +168 -0
- package/src/server-cli/startup-display.js +146 -0
- package/src/server-cli/tunnel-lifecycle-handler.js +219 -0
- package/src/server-cli-child.js +207 -0
- package/src/server-cli.js +1223 -0
- package/src/server-identity.js +383 -0
- package/src/service.js +835 -0
- package/src/session-context.js +49 -0
- package/src/session-lock.js +60 -0
- package/src/session-manager.js +3257 -0
- package/src/session-message-history.js +511 -0
- package/src/session-preset-trust.js +78 -0
- package/src/session-preset.js +458 -0
- package/src/session-state-persistence.js +307 -0
- package/src/session-timeout-manager.js +166 -0
- package/src/session-token-store.js +83 -0
- package/src/shell-approval-info.js +45 -0
- package/src/shell-approval-store.js +163 -0
- package/src/shell-audit.js +63 -0
- package/src/skills-budget.js +181 -0
- package/src/skills-content-validator.js +106 -0
- package/src/skills-frontmatter.js +422 -0
- package/src/skills-loader.js +1893 -0
- package/src/skills-manager.js +256 -0
- package/src/skills-trust.js +532 -0
- package/src/skills-usage.js +335 -0
- package/src/snapshots-store.js +345 -0
- package/src/ssrf-guard.js +130 -0
- package/src/subagent-counter.js +149 -0
- package/src/summarize-session.js +268 -0
- package/src/supervisor.js +929 -0
- package/src/test-client.js +131 -0
- package/src/token-compare.js +28 -0
- package/src/token-manager.js +220 -0
- package/src/tool-result.js +87 -0
- package/src/transcript-tasks.js +334 -0
- package/src/tunnel/base.js +294 -0
- package/src/tunnel/cloudflare.js +281 -0
- package/src/tunnel/index.js +54 -0
- package/src/tunnel-check.js +84 -0
- package/src/turn-tracker.js +0 -0
- package/src/user-shell-registry.js +218 -0
- package/src/user-shell-session.js +411 -0
- package/src/utils/check-dependencies.js +70 -0
- package/src/utils/concurrency.js +24 -0
- package/src/utils/context-window-learn.js +148 -0
- package/src/utils/error-message.js +25 -0
- package/src/utils/format-bytes.js +35 -0
- package/src/utils/preflight.js +143 -0
- package/src/utils/resolve-binary.js +91 -0
- package/src/utils/respawn-rate-limiter.js +59 -0
- package/src/utils/sleep.js +58 -0
- package/src/utils/spawn-env.js +193 -0
- package/src/utils/validation-patterns.js +23 -0
- package/src/utils/win-spawn.js +98 -0
- package/src/version-check.js +16 -0
- package/src/web-task-manager.js +383 -0
- package/src/worktree-gc.js +418 -0
- package/src/worktree-reaper.js +168 -0
- package/src/ws-auth.js +645 -0
- package/src/ws-broadcaster.js +385 -0
- package/src/ws-client-manager.js +476 -0
- package/src/ws-client-sender.js +115 -0
- package/src/ws-file-ops/browser.js +594 -0
- package/src/ws-file-ops/common.js +163 -0
- package/src/ws-file-ops/git.js +298 -0
- package/src/ws-file-ops/index.js +52 -0
- package/src/ws-file-ops/reader.js +595 -0
- package/src/ws-forwarding.js +543 -0
- package/src/ws-handler-context.js +196 -0
- package/src/ws-history.js +1251 -0
- package/src/ws-message-handlers.js +165 -0
- package/src/ws-permissions.js +676 -0
- package/src/ws-schemas.js +119 -0
- 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
|
+
}
|