@chroxy/server 0.11.0 → 0.11.11
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 +206 -18
- package/README.md +2 -2
- package/hooks/claude-native-route-check.mjs +17 -0
- package/hooks/permission-hook.sh +166 -11
- package/package.json +16 -12
- package/sidecar/Dockerfile +1 -1
- package/sidecar/PROTOCOL.md +9 -1
- package/sidecar/agent.js +102 -10
- package/sidecar/package-lock.json +3 -3
- package/src/acp-config.js +206 -0
- package/src/acp-session.js +958 -0
- package/src/activity-registry.js +110 -5
- package/src/agent-connections.js +304 -0
- package/src/agent-control/client.js +1645 -0
- package/src/agent-control/events.js +551 -0
- package/src/agent-control/local-connection.js +293 -0
- package/src/agent-control/mcp-server.js +547 -0
- package/src/anthropic-compatible-config.js +30 -4
- package/src/anthropic-compatible-session.js +15 -6
- package/src/anthropic-gemini-shim.js +444 -0
- package/src/anthropic-gemini-translate.js +1030 -0
- package/src/anthropic-openai-shim.js +0 -1
- package/src/archive-continuation.js +164 -0
- package/src/assistant-response.js +24 -0
- package/src/auth-probes.js +120 -13
- package/src/background-shell-tracker.js +27 -0
- package/src/base-session.js +1520 -36
- package/src/bearer-recheck.js +49 -0
- package/src/billing-budget.js +19 -0
- package/src/billing-class.js +40 -7
- package/src/binary-provenance-trust.js +11 -5
- package/src/bound-client-policy.js +291 -0
- package/src/built-in-tools/bash-exec.js +46 -7
- package/src/built-in-tools/file-ops.js +69 -5
- package/src/built-in-tools/tool-transforms.js +1113 -13
- package/src/byok-compose-state.js +6 -9
- package/src/byok-credentials.js +2 -3
- package/src/byok-mcp-client.js +92 -7
- package/src/byok-mcp-config.js +633 -122
- package/src/byok-mcp-fleet.js +49 -7
- package/src/byok-mcp-oauth-store.js +18 -16
- package/src/byok-mcp-trust.js +37 -23
- package/src/byok-session.js +707 -179
- package/src/byok-tool-executor.js +2742 -26
- package/src/byok-tools.js +9 -2
- package/src/channels/chroxy-channel-server.js +2 -3
- package/src/checkpoint-manager.js +64 -46
- package/src/claude-channel-session.js +16 -10
- package/src/claude-model-catalog.js +131 -16
- package/src/claude-model-refresh.js +385 -0
- package/src/claude-model-request.js +103 -0
- package/src/claude-setting-sources.js +74 -0
- package/src/claude-stream-parser.js +53 -3
- package/src/claude-tui/diagnostic-tail.js +83 -0
- package/src/claude-tui/form-driver.js +44 -7
- package/src/claude-tui/model-error.js +41 -0
- package/src/claude-tui/pty-driver.js +215 -88
- package/src/claude-tui/sanitize-question-payload.js +109 -0
- package/src/claude-tui/usage-limit.js +239 -0
- package/src/claude-tui-session.js +3563 -284
- package/src/claude-tui-tool-response.js +300 -0
- package/src/cli/agent-cmd.js +236 -0
- package/src/cli/agent-control-cmd.js +65 -0
- package/src/cli/config-cmd.js +4 -4
- package/src/cli/config-dir-cmd.js +234 -0
- package/src/cli/connection-state.js +54 -0
- package/src/cli/deploy-cmd.js +45 -10
- package/src/cli/doctor-cmd.js +7 -3
- package/src/cli/freshness-cmd.js +53 -0
- package/src/cli/init-cmd.js +15 -16
- package/src/cli/pages-cmd.js +6 -4
- package/src/cli/pair-code-cmd.js +7 -6
- package/src/cli/pair-discord-cmd.js +7 -6
- package/src/cli/providers-cmd.js +3 -3
- package/src/cli/schedule-cmd.js +91 -40
- package/src/cli/server-cmd.js +54 -1
- package/src/cli/service-cmd.js +33 -10
- package/src/cli/session-cmd.js +227 -74
- package/src/cli/shared.js +162 -11
- package/src/cli/shell-cmd.js +7 -4
- package/src/cli/status-cmd.js +19 -5
- package/src/cli/tokens-cmd.js +4 -5
- package/src/cli/tunnel-cmd.js +255 -24
- package/src/cli/worktree-gc-cmd.js +2 -2
- package/src/cli-session.js +1250 -126
- package/src/cli.js +8 -0
- package/src/codex-app-server-client.js +36 -3
- package/src/codex-app-server-session.js +1517 -81
- package/src/codex-bundled-client.js +66 -0
- package/src/codex-error-text.js +114 -0
- package/src/codex-model-catalog.js +548 -0
- package/src/codex-model-rejections.js +87 -0
- package/src/codex-native-resume.js +104 -0
- package/src/codex-protocol-capabilities.js +188 -0
- package/src/codex-session.js +450 -27
- package/src/config-dir-migration.js +449 -0
- package/src/config-dir.js +108 -0
- package/src/config.js +306 -26
- package/src/connection-authority.js +48 -0
- package/src/connection-info.js +78 -23
- package/src/connection-locality.js +60 -0
- package/src/container-liveness-monitor.js +189 -0
- package/src/continuation-metadata-worker.js +17 -0
- package/src/continuations.js +227 -0
- package/src/control-room/host-prune.js +5 -0
- package/src/control-room/integrations.js +7 -20
- package/src/control-room/skills-inventory.js +2 -2
- package/src/conversation-scanner.js +42 -39
- package/src/conversation-scope.js +59 -39
- package/src/conversation-search.js +28 -39
- package/src/credential-store.js +23 -19
- package/src/daemon-commit.js +92 -0
- package/src/daemon-idle-state.js +171 -0
- package/src/daemon-update-status.js +314 -0
- package/src/dashboard-build.js +70 -0
- package/src/declared-status.js +90 -0
- package/src/deepseek-credentials.js +2 -3
- package/src/dev-preview.js +170 -182
- package/src/device-preferences.js +2 -2
- package/src/diff-parser.js +87 -0
- package/src/discord-credentials.js +2 -3
- package/src/docker-byok-pool.js +3 -1
- package/src/docker-byok-session.js +678 -78
- package/src/docker-image-allowlist.js +23 -1
- package/src/docker-sdk-session.js +172 -3
- package/src/docker-session.js +294 -11
- package/src/doctor.js +781 -64
- package/src/durable-write.js +35 -0
- package/src/edited-input.js +264 -0
- package/src/environment-manager.js +175 -36
- package/src/environments/authority.js +101 -0
- package/src/environments/backends/container-claude-spawn.js +94 -0
- package/src/environments/backends/docker.js +31 -10
- package/src/environments/backends/k8s.js +49 -24
- package/src/environments/destroy-with-sessions.js +142 -0
- package/src/event-ingest.js +118 -13
- package/src/event-normalizer.js +186 -235
- package/src/folder-trust-wire.js +137 -0
- package/src/folder-trust-worker.js +17 -0
- package/src/folder-trust.js +1572 -0
- package/src/freshness/activity-meter.js +101 -0
- package/src/freshness/adapter.js +199 -0
- package/src/freshness/checks.js +239 -0
- package/src/freshness/config.js +98 -0
- package/src/freshness/core.js +185 -0
- package/src/freshness/derive.js +680 -0
- package/src/freshness/exchange.js +305 -0
- package/src/freshness/file-ledger.js +400 -0
- package/src/freshness/grade.js +81 -0
- package/src/freshness/hash.js +45 -0
- package/src/freshness/inbox.js +163 -0
- package/src/freshness/index.js +20 -0
- package/src/freshness/investigation.js +474 -0
- package/src/freshness/keys.js +177 -0
- package/src/freshness/ledger.js +122 -0
- package/src/freshness/outbox.js +131 -0
- package/src/freshness/policy.js +599 -0
- package/src/freshness/queue.js +843 -0
- package/src/freshness/read-errors.js +23 -0
- package/src/freshness/render.js +153 -0
- package/src/freshness/runtime.js +113 -0
- package/src/freshness/session-registry-adapter.js +161 -0
- package/src/freshness/state-file-adapter.js +167 -0
- package/src/freshness-runner/build-info.js +139 -0
- package/src/freshness-runner/cli.js +105 -0
- package/src/freshness-runner/run-tick.js +109 -0
- package/src/freshness-runner/stamp.js +57 -0
- package/src/freshness-sources/claude-transcript-adapter.js +211 -0
- package/src/freshness-sources/codex-transcript-adapter.js +33 -0
- package/src/freshness-sources/index.js +8 -0
- package/src/gemini-byok-session.js +292 -0
- package/src/gemini-credentials.js +67 -0
- package/src/gemini-key-safety.js +246 -0
- package/src/gemini-models.js +386 -0
- package/src/gemini-session.js +81 -5
- package/src/handler-utils.js +540 -80
- package/src/handlers/checkpoint-handlers.js +47 -4
- package/src/handlers/control-room-handlers.js +51 -11
- package/src/handlers/conversation-handlers.js +469 -56
- package/src/handlers/daemon-update-handlers.js +81 -0
- package/src/handlers/evaluator-handlers.js +14 -1
- package/src/handlers/feature-handlers.js +186 -69
- package/src/handlers/file-handlers.js +57 -13
- package/src/handlers/folder-trust-handlers.js +90 -0
- package/src/handlers/input-handlers.js +714 -48
- package/src/handlers/orchestration-handlers.js +3 -3
- package/src/handlers/principal-admin-handlers.js +229 -0
- package/src/handlers/principal-handlers.js +262 -0
- package/src/handlers/scheduler-handlers.js +92 -18
- package/src/handlers/session-handlers.js +551 -20
- package/src/handlers/session-pr-status-handlers.js +283 -0
- package/src/handlers/session-pr-threads-handlers.js +247 -0
- package/src/handlers/settings-handlers.js +372 -50
- package/src/handlers/skills-handlers.js +20 -4
- package/src/handlers/summarize-handlers.js +32 -1
- package/src/handlers/survey-throttle.js +380 -0
- package/src/health-proof.js +40 -0
- package/src/history-page.js +112 -0
- package/src/http-routes.js +127 -8
- package/src/ide/search.js +24 -6
- package/src/ide/symbols.js +20 -6
- package/src/input-context.js +117 -0
- package/src/instruction-policy-compiler.js +229 -0
- package/src/instruction-policy.js +250 -0
- package/src/jsonl-reader.js +378 -91
- package/src/jsonl-subprocess-session.js +96 -9
- package/src/keychain.js +1 -1
- package/src/logger.js +166 -30
- package/src/mailbox-route.js +113 -22
- package/src/message-wire.js +386 -0
- package/src/model-discovery.js +43 -3
- package/src/models.js +1276 -174
- package/src/notification-prefs.js +27 -4
- package/src/notifications/discord-billing-sink.js +22 -5
- package/src/notifications/discord-ci-sink.js +243 -0
- package/src/notifications/discord-webhook-client.js +71 -0
- package/src/notifications/discord-webhook-sink.js +64 -23
- package/src/notifications/expo-push-sink.js +85 -6
- package/src/notifications/ready-body.js +16 -5
- package/src/ollama-session.js +34 -2
- package/src/orchestration/build-manager.js +9 -2
- package/src/orchestration/git-ops.js +41 -7
- package/src/orchestration/orchestration-manager.js +112 -36
- package/src/orchestration/permission-gate.js +17 -2
- package/src/orchestration/run-model.js +2 -1
- package/src/orchestration/run-record.js +11 -0
- package/src/orchestration/turn-driver.js +185 -43
- package/src/orphan-reaper.js +470 -0
- package/src/outgoing-policy.js +189 -0
- package/src/pairing.js +92 -13
- package/src/path-hash-trust-ledger.js +642 -25
- package/src/permission-deadlines.js +82 -0
- package/src/permission-floor.js +1410 -43
- package/src/permission-hook.js +180 -69
- package/src/permission-manager.js +737 -89
- package/src/permission-mode-support.js +35 -0
- package/src/permission-resolved-by.js +89 -0
- package/src/permission-resolver.js +126 -8
- package/src/permission-scope.js +43 -0
- package/src/platform.js +315 -47
- package/src/preview-ingress.js +54 -0
- package/src/preview-target.js +213 -0
- package/src/principal-audit.js +189 -0
- package/src/principal-binding.js +25 -0
- package/src/principal-brakes.js +21 -0
- package/src/principal-effect.js +101 -0
- package/src/principal-journal.js +905 -0
- package/src/principal-kill-switch.js +183 -0
- package/src/principal-label.js +5 -0
- package/src/principal-pending-permissions.js +177 -0
- package/src/principal-policy.js +1094 -0
- package/src/principal-sessions-snapshot.js +208 -0
- package/src/principal-store.js +488 -0
- package/src/principal-subscriptions.js +283 -0
- package/src/prompt-evaluator.js +34 -4
- package/src/provider-customization.js +180 -0
- package/src/providers.js +209 -4
- package/src/push.js +30 -4
- package/src/question-route-map.js +130 -0
- package/src/redaction.js +531 -20
- package/src/roster-broadcast.js +186 -0
- package/src/scheduled-task-store.js +330 -26
- package/src/scheduler.js +368 -11
- package/src/sdk-session.js +2114 -188
- package/src/server-cli/preview-shutdown.js +22 -0
- package/src/server-cli/push-notification-handler.js +17 -3
- package/src/server-cli/server-orchestrator.js +28 -5
- package/src/server-cli-child.js +33 -18
- package/src/server-cli.js +553 -38
- package/src/server-identity.js +15 -11
- package/src/service.js +396 -25
- package/src/session-archive-limits.js +15 -0
- package/src/session-archive.js +1029 -0
- package/src/session-busy-state.js +72 -0
- package/src/session-ci-watcher.js +1099 -0
- package/src/session-context.js +7 -2
- package/src/session-manager.js +4062 -312
- package/src/session-message-history.js +841 -16
- package/src/session-name-allocator.js +685 -0
- package/src/session-pr-status.js +654 -0
- package/src/session-pr-threads.js +271 -0
- package/src/session-preset-trust.js +3 -3
- package/src/session-preset.js +10 -5
- package/src/session-state-persistence.js +94 -17
- package/src/session-timeout-manager.js +20 -0
- package/src/session-token-store.js +17 -8
- package/src/session-wake.js +240 -0
- package/src/shell-approval-info.js +2 -2
- package/src/shell-approval-store.js +3 -1
- package/src/skills-loader.js +7 -4
- package/src/skills-manager.js +2 -2
- package/src/skills-trust.js +95 -13
- package/src/skills-usage.js +2 -3
- package/src/snapshots-store.js +2 -3
- package/src/statusline.js +100 -29
- package/src/summarize-session.js +53 -4
- package/src/supervisor.js +22 -11
- package/src/sweep-stale-provider-dirs.js +95 -0
- package/src/thinking-level-wire.js +39 -0
- package/src/thinking-stream.js +179 -0
- package/src/tool-result.js +61 -0
- package/src/transcript-sources.js +109 -0
- package/src/transcript-tasks.js +372 -25
- package/src/trusted-file-read.js +302 -0
- package/src/tunnel/base.js +0 -8
- package/src/tunnel/cloudflare.js +34 -31
- package/src/tunnel/index.js +9 -0
- package/src/tunnel/preview.js +64 -0
- package/src/turn-outcome.js +140 -0
- package/src/usage-normalize.js +9 -5
- package/src/user-shell-session.js +59 -5
- package/src/utils/agent-sdk-version.js +107 -0
- package/src/utils/argv-safety.js +770 -0
- package/src/utils/auth-cause.js +60 -0
- package/src/utils/binary-package-manifest.js +639 -0
- package/src/utils/binary-version.js +224 -0
- package/src/utils/bounded-regex-worker.js +29 -0
- package/src/utils/bounded-regex.js +162 -0
- package/src/utils/claude-binary.js +43 -0
- package/src/utils/claude-config-dir.js +245 -0
- package/src/utils/claude-login-command.js +16 -0
- package/src/utils/claude-native-route.js +81 -0
- package/src/utils/componentwise-resolver.js +133 -37
- package/src/utils/deploy-control-files.js +87 -0
- package/src/utils/exec-failure-reason.js +21 -0
- package/src/utils/git-repo.js +42 -0
- package/src/utils/is-entry-point.js +137 -0
- package/src/utils/node-pty-probe.js +95 -0
- package/src/utils/node-pty-support.js +118 -0
- package/src/utils/opened-file-path.js +167 -0
- package/src/utils/path-containment.js +165 -0
- package/src/utils/permission-mode-sidecar.js +51 -0
- package/src/utils/pid-liveness.js +47 -0
- package/src/utils/preflight.js +360 -16
- package/src/utils/read-limiter.js +217 -0
- package/src/utils/regular-file.js +375 -0
- package/src/utils/safe-regex.js +113 -0
- package/src/utils/small-file.js +129 -0
- package/src/utils/spawn-env.js +189 -4
- package/src/utils/stale-session-dirs.js +182 -0
- package/src/utils/stat-identity.js +43 -0
- package/src/utils/verify-provenance.js +406 -13
- package/src/web-task-manager.js +297 -16
- package/src/worktree-gc.js +202 -6
- package/src/ws-auth.js +163 -31
- package/src/ws-broadcaster.js +49 -5
- package/src/ws-client-manager.js +24 -1
- package/src/ws-client-sender.js +7 -0
- package/src/ws-file-ops/browser.js +363 -58
- package/src/ws-file-ops/common.js +320 -14
- package/src/ws-file-ops/git.js +395 -42
- package/src/ws-file-ops/index.js +2 -0
- package/src/ws-file-ops/memory.js +137 -35
- package/src/ws-file-ops/open-nofollow.js +354 -0
- package/src/ws-file-ops/reader.js +571 -113
- package/src/ws-forwarding.js +349 -39
- package/src/ws-handler-context.js +88 -2
- package/src/ws-history.js +1010 -175
- package/src/ws-message-handlers.js +25 -1
- package/src/ws-permissions.js +307 -37
- package/src/ws-schemas.js +5 -0
- package/src/ws-server.js +885 -98
- package/sidecar/node_modules/.package-lock.json +0 -29
- package/sidecar/node_modules/ws/LICENSE +0 -20
- package/sidecar/node_modules/ws/README.md +0 -548
- package/sidecar/node_modules/ws/browser.js +0 -8
- package/sidecar/node_modules/ws/index.js +0 -22
- package/sidecar/node_modules/ws/lib/buffer-util.js +0 -131
- package/sidecar/node_modules/ws/lib/constants.js +0 -19
- package/sidecar/node_modules/ws/lib/event-target.js +0 -292
- package/sidecar/node_modules/ws/lib/extension.js +0 -203
- package/sidecar/node_modules/ws/lib/limiter.js +0 -55
- package/sidecar/node_modules/ws/lib/permessage-deflate.js +0 -528
- package/sidecar/node_modules/ws/lib/receiver.js +0 -706
- package/sidecar/node_modules/ws/lib/sender.js +0 -602
- package/sidecar/node_modules/ws/lib/stream.js +0 -161
- package/sidecar/node_modules/ws/lib/subprotocol.js +0 -62
- package/sidecar/node_modules/ws/lib/validation.js +0 -152
- package/sidecar/node_modules/ws/lib/websocket-server.js +0 -554
- package/sidecar/node_modules/ws/lib/websocket.js +0 -1393
- package/sidecar/node_modules/ws/package.json +0 -70
- package/sidecar/node_modules/ws/wrapper.mjs +0 -21
- package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +0 -111
- package/src/dashboard-next/dist/assets/index-DM-_dISG.css +0 -1
- package/src/dashboard-next/dist/index.html +0 -13
- package/src/dashboard-next/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +0 -1
|
@@ -55,14 +55,26 @@
|
|
|
55
55
|
*/
|
|
56
56
|
|
|
57
57
|
import { existsSync, readFileSync, writeFileSync, mkdirSync, renameSync, chmodSync, unlinkSync } from 'node:fs'
|
|
58
|
-
import {
|
|
59
|
-
import {
|
|
58
|
+
import { dirname } from 'node:path'
|
|
59
|
+
import { configPath } from './config-dir.js'
|
|
60
60
|
|
|
61
61
|
/**
|
|
62
62
|
* Authoritative category list. MUST stay in sync with the keys of
|
|
63
63
|
* `RATE_LIMITS` in `push.js` — these are the categories the server can
|
|
64
64
|
* fire today. The schema-coverage test asserts every category has a
|
|
65
|
-
* default.
|
|
65
|
+
* default. It is also pinned, in both directions, to the client roster
|
|
66
|
+
* (labels + render order) in `@chroxy/protocol`
|
|
67
|
+
* (`notification-categories.ts`) by `tests/notification-category-roster.test.js`
|
|
68
|
+
* (#7429): add a new category there too, or that test names the one missing.
|
|
69
|
+
*
|
|
70
|
+
* Deliberately an independent literal, NOT derived from `@chroxy/protocol`
|
|
71
|
+
* (#9163): the protocol exports only the client render roster
|
|
72
|
+
* (`NOTIFICATION_CATEGORIES`), whose order differs from the wire order here,
|
|
73
|
+
* and the daemon must not decide what it can fire from a UI table. Deriving
|
|
74
|
+
* this list from that roster would make the server<->client roster pairs
|
|
75
|
+
* (every server key has a label, every client key is fireable, same set)
|
|
76
|
+
* compare the roster with itself, so they could not go red. Only the
|
|
77
|
+
* `RATE_LIMITS` comparison would still be live.
|
|
66
78
|
*
|
|
67
79
|
* History: the issue text (#4541) sketches `permission / question / error /
|
|
68
80
|
* result / inactivity` as user-facing labels; the wire-level set below is
|
|
@@ -70,6 +82,7 @@ import { join, dirname } from 'node:path'
|
|
|
70
82
|
* can map these to friendlier labels without changing the protocol).
|
|
71
83
|
*/
|
|
72
84
|
export const ALL_CATEGORIES = Object.freeze([
|
|
85
|
+
'continuation',
|
|
73
86
|
'permission',
|
|
74
87
|
'result',
|
|
75
88
|
'activity_update',
|
|
@@ -92,6 +105,10 @@ export const ALL_CATEGORIES = Object.freeze([
|
|
|
92
105
|
// (mailbox-route.js). Listed so the category is mutable in prefs and visible
|
|
93
106
|
// in snapshots (sanitizeCategoryMap strips unknown keys otherwise).
|
|
94
107
|
'mailbox',
|
|
108
|
+
// #7424: CI-completion events from the session CI watcher. Listed so the
|
|
109
|
+
// category is mutable in prefs and visible in snapshots (sanitizeCategoryMap
|
|
110
|
+
// strips unknown keys otherwise).
|
|
111
|
+
'ci_complete',
|
|
95
112
|
])
|
|
96
113
|
|
|
97
114
|
/**
|
|
@@ -116,6 +133,12 @@ export const CATEGORY_DEFAULTS = Object.freeze(
|
|
|
116
133
|
*
|
|
117
134
|
* Users can opt out per-device (`bypassCategories: []`) or extend the
|
|
118
135
|
* global list to silence even errors if they want.
|
|
136
|
+
* Pinned in both directions to the shared client default in
|
|
137
|
+
* `@chroxy/protocol` by `tests/notification-category-roster.test.js` (#8567).
|
|
138
|
+
* Kept as its own literal for the same reason as `ALL_CATEGORIES` (#9163):
|
|
139
|
+
* if it were imported from the protocol, the bypass pair in the roster test
|
|
140
|
+
* would compare one array with itself in both directions and could not go red;
|
|
141
|
+
* the only remaining check would be the protocol test's literal.
|
|
119
142
|
*/
|
|
120
143
|
export const DEFAULT_BYPASS_CATEGORIES = Object.freeze(['permission', 'activity_error'])
|
|
121
144
|
|
|
@@ -147,7 +170,7 @@ const _ALL_CATEGORIES_SET = new Set(ALL_CATEGORIES)
|
|
|
147
170
|
const _HHMM_RE = /^(?:[01]\d|2[0-3]):[0-5]\d$/
|
|
148
171
|
|
|
149
172
|
export function defaultNotificationPrefsPath() {
|
|
150
|
-
return process.env.CHROXY_NOTIFICATION_PREFS_PATH ||
|
|
173
|
+
return process.env.CHROXY_NOTIFICATION_PREFS_PATH || configPath('notification-prefs.json')
|
|
151
174
|
}
|
|
152
175
|
|
|
153
176
|
/**
|
|
@@ -37,12 +37,12 @@
|
|
|
37
37
|
*/
|
|
38
38
|
|
|
39
39
|
import { readFileSync, mkdirSync } from 'node:fs'
|
|
40
|
-
import { dirname
|
|
41
|
-
import { homedir } from 'node:os'
|
|
40
|
+
import { dirname } from 'node:path'
|
|
42
41
|
import { writeFileRestricted } from '../platform.js'
|
|
43
42
|
import { createLogger } from '../logger.js'
|
|
44
43
|
import { sleep } from '../utils/sleep.js'
|
|
45
44
|
import { NotificationSink } from './sink.js'
|
|
45
|
+
import { configPath } from '../config-dir.js'
|
|
46
46
|
import {
|
|
47
47
|
cachedResolveDiscordWebhookUrl,
|
|
48
48
|
isValidDiscordWebhookUrl,
|
|
@@ -50,8 +50,10 @@ import {
|
|
|
50
50
|
import {
|
|
51
51
|
DEFAULT_ERROR_COLOR,
|
|
52
52
|
DEFAULT_ONLINE_COLOR,
|
|
53
|
+
DEFAULT_ALLOWED_MENTIONS,
|
|
53
54
|
isValidColor,
|
|
54
55
|
escapeAndCap,
|
|
56
|
+
neutralizeMentions,
|
|
55
57
|
apiBase,
|
|
56
58
|
fetchWithDiscordRetry,
|
|
57
59
|
} from './discord-webhook-client.js'
|
|
@@ -124,7 +126,7 @@ export class DiscordBillingSink extends NotificationSink {
|
|
|
124
126
|
// -- State persistence ----------------------------------------------------
|
|
125
127
|
|
|
126
128
|
_resolvedStatePath() {
|
|
127
|
-
return this._statePath ||
|
|
129
|
+
return this._statePath || configPath('discord-billing-state.json')
|
|
128
130
|
}
|
|
129
131
|
|
|
130
132
|
/** Load the single-message store fresh from disk (read-per-send). */
|
|
@@ -295,15 +297,25 @@ export class DiscordBillingSink extends NotificationSink {
|
|
|
295
297
|
? notification.data.codes.filter((c) => typeof c === 'string')
|
|
296
298
|
: []
|
|
297
299
|
const fields = []
|
|
300
|
+
// #5475/#8105: neutralize Discord mention syntax FIRST, then escape
|
|
301
|
+
// markdown. `body` is the billing canary's free-text warning message and
|
|
302
|
+
// `codes` are its identifiers — both ultimately caller-supplied
|
|
303
|
+
// (notification.data), so a literal `@everyone`/`@here`/role/user mention
|
|
304
|
+
// in either must not reach Discord as a live ping. Same ordering
|
|
305
|
+
// requirement as the status sink: neutralizeMentions on the raw value,
|
|
306
|
+
// escapeAndCap (truncate + escape + re-clamp) after.
|
|
298
307
|
if (body) {
|
|
299
|
-
fields.push({ name: resolved ? 'Resolved' : 'Warnings', value: escapeAndCap(body), inline: false })
|
|
308
|
+
fields.push({ name: resolved ? 'Resolved' : 'Warnings', value: escapeAndCap(neutralizeMentions(body)), inline: false })
|
|
300
309
|
}
|
|
301
310
|
if (!resolved && codes.length > 0) {
|
|
302
311
|
// 200 is a deliberate short cap — codes are short identifiers
|
|
303
312
|
// (SILENT_METERED_DEFAULT, …); a handful never approaches the 1024 field
|
|
304
313
|
// limit, and a runaway list is fine to truncate.
|
|
305
|
-
fields.push({ name: 'Codes', value: escapeAndCap(codes.join(', '), 200), inline: false })
|
|
314
|
+
fields.push({ name: 'Codes', value: escapeAndCap(neutralizeMentions(codes.join(', ')), 200), inline: false })
|
|
306
315
|
}
|
|
316
|
+
// Title is built entirely from `this._botName` (trusted, admin-set) and
|
|
317
|
+
// `codes.length` (a number) — no caller-supplied free text, so no
|
|
318
|
+
// neutralization is needed here (unlike the fields above).
|
|
307
319
|
const title = resolved
|
|
308
320
|
? `\u{2705} ${this._botName} — Billing alerts cleared`
|
|
309
321
|
: codes.length > 1
|
|
@@ -315,9 +327,14 @@ export class DiscordBillingSink extends NotificationSink {
|
|
|
315
327
|
title,
|
|
316
328
|
color: resolved ? this._resolvedColor : this._alertColor,
|
|
317
329
|
fields,
|
|
330
|
+
// Same reasoning as the title: this._botName is trusted, not free text.
|
|
318
331
|
footer: { text: this._botName },
|
|
319
332
|
timestamp: new Date(this._now()).toISOString(),
|
|
320
333
|
}],
|
|
334
|
+
// Server-side backstop (#8105), on top of neutralizeMentions() above: no
|
|
335
|
+
// configured user/role ping exists for this sink — see
|
|
336
|
+
// DEFAULT_ALLOWED_MENTIONS in discord-webhook-client.js.
|
|
337
|
+
allowed_mentions: DEFAULT_ALLOWED_MENTIONS,
|
|
321
338
|
}
|
|
322
339
|
}
|
|
323
340
|
}
|
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* DiscordCiSink — one fresh Discord message per CI run (#7428).
|
|
3
|
+
*
|
|
4
|
+
* #7424/#7426 added the `ci_complete` push category (a CI run settling on the
|
|
5
|
+
* pull request a session opened) and wired the Expo sink to deliver it. The
|
|
6
|
+
* per-project status sink (`discord-webhook-sink.js`) does not: `ci_complete`
|
|
7
|
+
* has no entry in its `STATE_FOR_CATEGORY` map, so its `send()` returns
|
|
8
|
+
* `true` — a silent no-op indistinguishable from delivery (#7428's original
|
|
9
|
+
* bug report). CI completion is not a session-lifecycle state; folding it
|
|
10
|
+
* into the status embed would repaint whatever the session's actual state is
|
|
11
|
+
* (idle/online/...) with a CI verdict from a run that may have settled long
|
|
12
|
+
* after the session moved on to something else.
|
|
13
|
+
*
|
|
14
|
+
* Decided (#7428, option 2 — Chris, 2026-09-28): **one Discord message per CI
|
|
15
|
+
* run**, always a fresh POST, never an edit. Unlike `discord-billing-sink.js`
|
|
16
|
+
* (its precedent for "an event that is not a session state" — one tracked
|
|
17
|
+
* global message, re-pinged on change) this sink keeps NO state file at all:
|
|
18
|
+
* two `ci_complete` events for the same PR (a re-push settling a second time)
|
|
19
|
+
* are two distinct completions and get two distinct messages. Editing the
|
|
20
|
+
* first message in place would erase the fact that a second run happened.
|
|
21
|
+
*
|
|
22
|
+
* The embed only ever uses fields the `ci_complete` payload
|
|
23
|
+
* (`ciCompletionPush` in session-ci-watcher.js) actually carries today: the
|
|
24
|
+
* PR number and link (`data.prNumber` / `data.prUrl`), a ✅/❌ conclusion
|
|
25
|
+
* (`data.verdict`), and the human-readable title/body chroxy already built
|
|
26
|
+
* (`describeCiCompletion` — check counts, merge state, and the PR title as a
|
|
27
|
+
* trailing " — <title>" clause). That payload carries no duration/timing
|
|
28
|
+
* field at all yet, so a duration is rendered only when the notification
|
|
29
|
+
* happens to carry a numeric `data.durationSeconds` — never fabricated — and
|
|
30
|
+
* omitted otherwise (see `_buildPayload`).
|
|
31
|
+
*
|
|
32
|
+
* A PR title is GitHub-authored free text, so it goes through the same
|
|
33
|
+
* markdown escaping (`escapeAndCap`) every other Discord sink applies to
|
|
34
|
+
* user/transcript content (#5475), plus mention neutralization
|
|
35
|
+
* (`neutralizeMentions`, discord-webhook-client.js) so an `@everyone` /
|
|
36
|
+
* `@here` / role-or-user mention in a PR title can't read as a live ping.
|
|
37
|
+
*/
|
|
38
|
+
|
|
39
|
+
import { createLogger } from '../logger.js'
|
|
40
|
+
import { sleep } from '../utils/sleep.js'
|
|
41
|
+
import { NotificationSink } from './sink.js'
|
|
42
|
+
import {
|
|
43
|
+
cachedResolveDiscordWebhookUrl,
|
|
44
|
+
isValidDiscordWebhookUrl,
|
|
45
|
+
} from '../discord-credentials.js'
|
|
46
|
+
import {
|
|
47
|
+
DEFAULT_PROJECT_COLOR,
|
|
48
|
+
DEFAULT_ERROR_COLOR,
|
|
49
|
+
DEFAULT_ONLINE_COLOR,
|
|
50
|
+
DEFAULT_ALLOWED_MENTIONS,
|
|
51
|
+
MAX_EMBED_TITLE_CHARS,
|
|
52
|
+
isValidColor,
|
|
53
|
+
escapeAndCap,
|
|
54
|
+
neutralizeMentions,
|
|
55
|
+
formatDuration,
|
|
56
|
+
apiBase,
|
|
57
|
+
fetchWithDiscordRetry,
|
|
58
|
+
} from './discord-webhook-client.js'
|
|
59
|
+
|
|
60
|
+
const log = createLogger('discord')
|
|
61
|
+
|
|
62
|
+
const CI_CATEGORY = 'ci_complete'
|
|
63
|
+
|
|
64
|
+
export class DiscordCiSink extends NotificationSink {
|
|
65
|
+
/**
|
|
66
|
+
* @param {object} [opts]
|
|
67
|
+
* @param {string} [opts.botName] - Webhook display name + footer label.
|
|
68
|
+
* @param {boolean} [opts.ciAlerts] - Kill-switch
|
|
69
|
+
* (notifications.discord.ciAlerts). Default ON when a webhook resolves;
|
|
70
|
+
* set false to keep CI-completion notices off Discord while the status
|
|
71
|
+
* sink / billing sink stay on.
|
|
72
|
+
* @param {number} [opts.successColor] - Sidebar color for a passing run
|
|
73
|
+
* (default: green, same as the status sink's online color).
|
|
74
|
+
* @param {number} [opts.failureColor] - Sidebar color for a failing run
|
|
75
|
+
* (default: red).
|
|
76
|
+
* @param {number} [opts.unknownColor] - Sidebar color for a verdict this
|
|
77
|
+
* daemon does not recognise (default: blurple — neutral, not a false
|
|
78
|
+
* "passed" or "failed").
|
|
79
|
+
* @param {Function} [opts.resolveWebhookUrl] - Injection seam for tests;
|
|
80
|
+
* defaults to the env > 0600-credentials.json resolver.
|
|
81
|
+
* @param {Function} [opts.sleepImpl] - Injection seam for tests (429/backoff waits).
|
|
82
|
+
* @param {Function} [opts.now] - Clock seam for tests; defaults to Date.now.
|
|
83
|
+
*/
|
|
84
|
+
constructor({
|
|
85
|
+
botName = 'Chroxy',
|
|
86
|
+
ciAlerts = true,
|
|
87
|
+
successColor = DEFAULT_ONLINE_COLOR,
|
|
88
|
+
failureColor = DEFAULT_ERROR_COLOR,
|
|
89
|
+
unknownColor = DEFAULT_PROJECT_COLOR,
|
|
90
|
+
resolveWebhookUrl = cachedResolveDiscordWebhookUrl,
|
|
91
|
+
sleepImpl = sleep,
|
|
92
|
+
now = Date.now,
|
|
93
|
+
} = {}) {
|
|
94
|
+
super({ name: 'discord-ci' })
|
|
95
|
+
this._botName = typeof botName === 'string' && botName.length > 0 ? botName.slice(0, 80) : 'Chroxy'
|
|
96
|
+
this._enabled = ciAlerts !== false
|
|
97
|
+
this._successColor = isValidColor(successColor) ? successColor : DEFAULT_ONLINE_COLOR
|
|
98
|
+
this._failureColor = isValidColor(failureColor) ? failureColor : DEFAULT_ERROR_COLOR
|
|
99
|
+
this._unknownColor = isValidColor(unknownColor) ? unknownColor : DEFAULT_PROJECT_COLOR
|
|
100
|
+
this._resolveWebhookUrl = resolveWebhookUrl
|
|
101
|
+
this._sleep = sleepImpl
|
|
102
|
+
this._now = now
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* Sink contract: configured iff CI alerts are enabled AND a syntactically
|
|
107
|
+
* valid webhook URL resolves. Off when either is missing — the registry
|
|
108
|
+
* then never asks this sink to send.
|
|
109
|
+
*/
|
|
110
|
+
isConfigured() {
|
|
111
|
+
return this._enabled && this._configuredUrl() != null
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** Resolve + validate the webhook URL, or null. Never throws, never logs the URL. */
|
|
115
|
+
_configuredUrl() {
|
|
116
|
+
let resolved
|
|
117
|
+
try {
|
|
118
|
+
resolved = this._resolveWebhookUrl()
|
|
119
|
+
} catch {
|
|
120
|
+
return null
|
|
121
|
+
}
|
|
122
|
+
const url = resolved?.url
|
|
123
|
+
return typeof url === 'string' && isValidDiscordWebhookUrl(url) ? url : null
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
// -- Sink contract --------------------------------------------------------
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* Deliver one `ci_complete` notification as a brand-new Discord message.
|
|
130
|
+
* Only the `ci_complete` category is handled; everything else is skipped so
|
|
131
|
+
* the status sink keeps sole ownership of session-lifecycle events (the
|
|
132
|
+
* same "not ours" no-op the billing sink applies to non-billing
|
|
133
|
+
* categories).
|
|
134
|
+
*
|
|
135
|
+
* Resolves `false` ONLY on a hard channel failure (final non-2xx, network
|
|
136
|
+
* throw), per the sink contract. The per-DEVICE context evaluators are run
|
|
137
|
+
* once with `deviceId = null` (a webhook has no device identity), matching
|
|
138
|
+
* the other two Discord sinks.
|
|
139
|
+
*/
|
|
140
|
+
async send(notification, context = {}) {
|
|
141
|
+
if (notification?.category !== CI_CATEGORY) return true // not ours — skip
|
|
142
|
+
|
|
143
|
+
const webhookUrl = this._configuredUrl()
|
|
144
|
+
if (!webhookUrl || !this._enabled) return true // unconfigured — registry normally skips us anyway
|
|
145
|
+
|
|
146
|
+
const now0 = context.now ?? this._now()
|
|
147
|
+
const isCategoryEnabled = context.isCategoryEnabled ?? (() => true)
|
|
148
|
+
const isInQuietHours = context.isInQuietHours ?? (() => false)
|
|
149
|
+
const shouldBypassQuietHours = context.shouldBypassQuietHours ?? (() => false)
|
|
150
|
+
if (!isCategoryEnabled(CI_CATEGORY, null)) return true
|
|
151
|
+
if (isInQuietHours(now0, null) && !shouldBypassQuietHours(CI_CATEGORY, null)) return true
|
|
152
|
+
|
|
153
|
+
try {
|
|
154
|
+
const payload = this._buildPayload(notification)
|
|
155
|
+
const res = await this._discordFetch(`${apiBase(webhookUrl)}?wait=true`, {
|
|
156
|
+
method: 'POST',
|
|
157
|
+
headers: { 'Content-Type': 'application/json' },
|
|
158
|
+
body: JSON.stringify(payload),
|
|
159
|
+
})
|
|
160
|
+
if (!res.ok) {
|
|
161
|
+
log.error(`Discord CI-completion POST failed (HTTP ${res.status})`)
|
|
162
|
+
return false
|
|
163
|
+
}
|
|
164
|
+
return true
|
|
165
|
+
} catch (err) {
|
|
166
|
+
log.error(`Discord CI-completion alert failed: ${err?.message || err}`)
|
|
167
|
+
return false
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** Delegate to the shared client's fetch policy, passing the injected sleep seam. */
|
|
172
|
+
async _discordFetch(url, options) {
|
|
173
|
+
return fetchWithDiscordRetry(url, options, { sleepImpl: this._sleep })
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
// -- Embed building ---------------------------------------------------------
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* Build the one-shot embed from whatever the `ci_complete` payload actually
|
|
180
|
+
* carries. Every field is read defensively (wrong type / missing → treated
|
|
181
|
+
* as absent) since a notification object is, in the end, caller-supplied
|
|
182
|
+
* data, not a trusted internal type.
|
|
183
|
+
*/
|
|
184
|
+
_buildPayload(notification) {
|
|
185
|
+
const data = notification?.data && typeof notification.data === 'object' && !Array.isArray(notification.data)
|
|
186
|
+
? notification.data
|
|
187
|
+
: {}
|
|
188
|
+
const verdict = typeof data.verdict === 'string' ? data.verdict : null
|
|
189
|
+
const prNumber = Number.isInteger(data.prNumber) ? data.prNumber : null
|
|
190
|
+
const prUrl = typeof data.prUrl === 'string' && data.prUrl.length > 0 ? data.prUrl : null
|
|
191
|
+
// The producer (session-ci-watcher.js ciCompletionPush) carries no timing
|
|
192
|
+
// field today — render gracefully rather than assume that never changes.
|
|
193
|
+
const durationSeconds = Number.isFinite(data.durationSeconds) ? data.durationSeconds : null
|
|
194
|
+
|
|
195
|
+
const emoji = verdict === 'failure' ? '\u{274C}' : verdict === 'success' ? '\u{2705}' : '\u{2753}'
|
|
196
|
+
const color = verdict === 'failure' ? this._failureColor : verdict === 'success' ? this._successColor : this._unknownColor
|
|
197
|
+
|
|
198
|
+
// `notification.title` (describeCiCompletion) already reads "CI passed on
|
|
199
|
+
// #1234" / "CI failed on #1234" / "CI finished on #1234 with unrecognised
|
|
200
|
+
// checks" — chroxy-authored, but still sanitized defensively since a
|
|
201
|
+
// notification object is caller-supplied. Missing/malformed → fall back
|
|
202
|
+
// to a title built from the one field we know is safe (an integer).
|
|
203
|
+
const rawTitle = typeof notification?.title === 'string' && notification.title.length > 0
|
|
204
|
+
? notification.title
|
|
205
|
+
: (prNumber != null ? `CI finished on #${prNumber}` : 'CI finished')
|
|
206
|
+
const title = escapeAndCap(neutralizeMentions(`${emoji} ${rawTitle}`), MAX_EMBED_TITLE_CHARS)
|
|
207
|
+
|
|
208
|
+
// `notification.body` carries the check-count summary plus, when GitHub
|
|
209
|
+
// reports one, a trailing " — <PR title>" clause (describeCiCompletion) —
|
|
210
|
+
// the one place the actual (GitHub-authored) PR title text shows up.
|
|
211
|
+
const description = typeof notification?.body === 'string' && notification.body.length > 0
|
|
212
|
+
? escapeAndCap(neutralizeMentions(notification.body))
|
|
213
|
+
: undefined
|
|
214
|
+
|
|
215
|
+
const fields = []
|
|
216
|
+
if (durationSeconds != null) {
|
|
217
|
+
fields.push({ name: 'Duration', value: formatDuration(durationSeconds), inline: true })
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
const embed = {
|
|
221
|
+
title,
|
|
222
|
+
color,
|
|
223
|
+
fields,
|
|
224
|
+
footer: { text: this._botName },
|
|
225
|
+
timestamp: new Date(this._now()).toISOString(),
|
|
226
|
+
}
|
|
227
|
+
if (description) embed.description = description
|
|
228
|
+
// Makes the embed title a clickable link to the PR — the "link" the
|
|
229
|
+
// decision comment asks for — without inventing a separate field for it.
|
|
230
|
+
if (prUrl) embed.url = prUrl
|
|
231
|
+
|
|
232
|
+
return {
|
|
233
|
+
username: this._botName,
|
|
234
|
+
embeds: [embed],
|
|
235
|
+
// Server-side backstop for neutralizeMentions() (#8105: now the shared
|
|
236
|
+
// default every Discord sink sets — see DEFAULT_ALLOWED_MENTIONS):
|
|
237
|
+
// Discord itself parses no mentions from this message, so nothing in a
|
|
238
|
+
// GitHub-authored PR title can ping anyone even if a mention form slips
|
|
239
|
+
// past the text transform.
|
|
240
|
+
allowed_mentions: DEFAULT_ALLOWED_MENTIONS,
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
}
|
|
@@ -108,6 +108,77 @@ export function escapeAndCap(text, max = 1000) {
|
|
|
108
108
|
return trailing % 2 === 1 ? cut.slice(0, -1) : cut
|
|
109
109
|
}
|
|
110
110
|
|
|
111
|
+
/**
|
|
112
|
+
* Discord's hard embed-title limit (#7105, moved here from
|
|
113
|
+
* discord-webhook-sink.js in #7428 so a second embed-building sink —
|
|
114
|
+
* discord-ci-sink.js — can share it without importing the status sink).
|
|
115
|
+
*
|
|
116
|
+
* Past it the ENTIRE webhook POST/PATCH comes back 400, so whatever the embed
|
|
117
|
+
* was reporting silently stops updating. Every free-text field goes through
|
|
118
|
+
* escapeAndCap for the same reason; a title needs the same ceiling even
|
|
119
|
+
* though Discord does not render markdown in titles (escapeAndCap's escaping
|
|
120
|
+
* step is then a no-op for a plain chroxy-authored title, but the length cap
|
|
121
|
+
* still applies).
|
|
122
|
+
*
|
|
123
|
+
* https://discord.com/developers/docs/resources/message#embed-object-embed-limits
|
|
124
|
+
*/
|
|
125
|
+
export const MAX_EMBED_TITLE_CHARS = 256
|
|
126
|
+
|
|
127
|
+
// Discord's mention grammar: `@everyone` / `@here` (exact, case-sensitive in
|
|
128
|
+
// the client, matched case-insensitively here to be conservative) and the
|
|
129
|
+
// snowflake forms `<@123>` (user), `<@!123>` (nickname-mention user), `<@&123>`
|
|
130
|
+
// (role).
|
|
131
|
+
const MENTION_PATTERN = /<@[!&]?\d+>|@(?:everyone|here)\b/gi
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* Neutralize Discord mention syntax in free text so a PR title (or any other
|
|
135
|
+
* GitHub-authored string a sink embeds) can't ping `@everyone`/`@here`/a
|
|
136
|
+
* role/a user (#7428). Discord's mention parser needs the EXACT substring
|
|
137
|
+
* (`@everyone`, `<@123>`, ...) with nothing in between; inserting an
|
|
138
|
+
* invisible zero-width space (U+200B) right after the leading `@` breaks that
|
|
139
|
+
* match while leaving the text visually unchanged to a human reader — the
|
|
140
|
+
* same technique used by webhook bots generally, and cheaper than stripping
|
|
141
|
+
* or rewriting the mention (which would make a legitimately-named PR like
|
|
142
|
+
* "Add @here handling" unreadable).
|
|
143
|
+
*
|
|
144
|
+
* Order matters relative to escapeAndCap: call this FIRST, then escapeAndCap
|
|
145
|
+
* — escaping doesn't touch `@`/`<`/`>`/digits so the two passes don't
|
|
146
|
+
* interact, but running mention neutralization after a truncation could clip
|
|
147
|
+
* a mention mid-match and skip it.
|
|
148
|
+
*/
|
|
149
|
+
export function neutralizeMentions(text) {
|
|
150
|
+
if (typeof text !== 'string') return ''
|
|
151
|
+
return text.replace(MENTION_PATTERN, (match) => (
|
|
152
|
+
match.startsWith('<@') ? `<@${match.slice(2)}` : `@${match.slice(1)}`
|
|
153
|
+
))
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* Default `allowed_mentions` payload for every Discord sink (#8105): a
|
|
158
|
+
* server-side backstop telling Discord to parse NO mentions out of the
|
|
159
|
+
* message at all, regardless of what text reaches the wire. This is
|
|
160
|
+
* defense-in-depth layered ON TOP OF neutralizeMentions() (#7428), not a
|
|
161
|
+
* substitute for it — the text transform keeps a mention from being
|
|
162
|
+
* recognisable even by a human glancing at the raw JSON payload or a client
|
|
163
|
+
* that doesn't honour `allowed_mentions`, while this field is Discord's own
|
|
164
|
+
* guarantee that its API won't ping anyone even if a mention form ever slips
|
|
165
|
+
* past the text transform (a regex miss, a future field that forgets to
|
|
166
|
+
* call it, ...).
|
|
167
|
+
*
|
|
168
|
+
* None of the three Discord sinks (status, billing, CI) configure a
|
|
169
|
+
* deliberate ping to a specific user or role — `notifications.discord` has
|
|
170
|
+
* no such config key (see CONFIG.md / docs/guides/discord-notifications.md)
|
|
171
|
+
* — so `{ parse: [] }` (no mention types allowed at all) is correct for
|
|
172
|
+
* every sink today. A sink that ever needs a deliberate, configured ping
|
|
173
|
+
* would pass its own `{ parse: [], users: [id] }` / `{ ..., roles: [id] }`
|
|
174
|
+
* instead of this default — never a blanket `parse: []` that would silently
|
|
175
|
+
* swallow it.
|
|
176
|
+
*
|
|
177
|
+
* Frozen so sharing one reference across every payload can't be mutated by
|
|
178
|
+
* accident; JSON.stringify doesn't care either way, this is just hygiene.
|
|
179
|
+
*/
|
|
180
|
+
export const DEFAULT_ALLOWED_MENTIONS = Object.freeze({ parse: [] })
|
|
181
|
+
|
|
111
182
|
/** Build the Discord webhook API base from a validated webhook URL. */
|
|
112
183
|
export function apiBase(webhookUrl) {
|
|
113
184
|
const parts = extractWebhookIdToken(webhookUrl)
|
|
@@ -42,12 +42,13 @@
|
|
|
42
42
|
*/
|
|
43
43
|
|
|
44
44
|
import { readFileSync, mkdirSync } from 'node:fs'
|
|
45
|
-
import { dirname
|
|
46
|
-
import { homedir } from 'node:os'
|
|
45
|
+
import { dirname } from 'node:path'
|
|
47
46
|
import { writeFileRestricted } from '../platform.js'
|
|
48
47
|
import { createLogger } from '../logger.js'
|
|
49
48
|
import { sleep } from '../utils/sleep.js'
|
|
50
49
|
import { NotificationSink } from './sink.js'
|
|
50
|
+
import { configPath } from '../config-dir.js'
|
|
51
|
+
import { MAX_EXTERNAL_PROJECT_CHARS } from '../external-session-registry.js'
|
|
51
52
|
import {
|
|
52
53
|
cachedResolveDiscordWebhookUrl,
|
|
53
54
|
isValidDiscordWebhookUrl,
|
|
@@ -62,12 +63,15 @@ import {
|
|
|
62
63
|
DEFAULT_ERROR_COLOR,
|
|
63
64
|
DEFAULT_ONLINE_COLOR,
|
|
64
65
|
DEFAULT_OFFLINE_COLOR,
|
|
66
|
+
DEFAULT_ALLOWED_MENTIONS,
|
|
65
67
|
isValidColor,
|
|
66
68
|
escapeAndCap,
|
|
67
69
|
truncate,
|
|
70
|
+
neutralizeMentions,
|
|
68
71
|
formatDuration,
|
|
69
72
|
apiBase,
|
|
70
73
|
fetchWithDiscordRetry,
|
|
74
|
+
MAX_EMBED_TITLE_CHARS,
|
|
71
75
|
} from './discord-webhook-client.js'
|
|
72
76
|
|
|
73
77
|
const log = createLogger('discord')
|
|
@@ -125,6 +129,16 @@ const DEFAULT_OFFLINE_AFTER_MS = 30 * 60_000 // 30m
|
|
|
125
129
|
// events keep it fresh via routine PATCH.
|
|
126
130
|
// offline — session ended (bash SessionEnd: routine PATCH in place;
|
|
127
131
|
// no-op when nothing is tracked or already offline)
|
|
132
|
+
//
|
|
133
|
+
// `ci_complete` (#7424) is deliberately NOT listed here: a CI-completion event
|
|
134
|
+
// is not a session-lifecycle state, and mapping it onto one would repaint
|
|
135
|
+
// whatever this project's status embed actually shows (idle/online/...) with
|
|
136
|
+
// a stale CI verdict from a run that may have settled long after the session
|
|
137
|
+
// moved on — see #7428. `send()` below returns `true` for any unmapped
|
|
138
|
+
// category without touching the store or the wire, which is the same "not
|
|
139
|
+
// ours" no-op every other unmapped category gets; `discord-ci-sink.js`
|
|
140
|
+
// (registered alongside this sink) is the one that actually delivers it, as
|
|
141
|
+
// its own separate message.
|
|
128
142
|
const STATE_FOR_CATEGORY = {
|
|
129
143
|
activity_update: 'idle',
|
|
130
144
|
result: 'idle',
|
|
@@ -149,18 +163,9 @@ const STATE_TITLES = {
|
|
|
149
163
|
offline: (project) => `\u{1F534} ${project} — Session Offline`,
|
|
150
164
|
}
|
|
151
165
|
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
* Past it the ENTIRE webhook POST/PATCH comes back 400, so the project's status
|
|
156
|
-
* embed silently stops updating — the failure is logged and invisible to the
|
|
157
|
-
* user. Every other field `_buildPayload` emits already goes through
|
|
158
|
-
* `escapeAndCap` for exactly this reason; the title did not, and it is the one
|
|
159
|
-
* that costs the whole embed rather than one field.
|
|
160
|
-
*
|
|
161
|
-
* https://discord.com/developers/docs/resources/message#embed-object-embed-limits
|
|
162
|
-
*/
|
|
163
|
-
export const MAX_EMBED_TITLE_CHARS = 256
|
|
166
|
+
// Re-exported for back-compat: moved to discord-webhook-client.js in #7428 so
|
|
167
|
+
// discord-ci-sink.js can share it without importing this (much larger) file.
|
|
168
|
+
export { MAX_EMBED_TITLE_CHARS }
|
|
164
169
|
|
|
165
170
|
export class DiscordWebhookSink extends NotificationSink {
|
|
166
171
|
/**
|
|
@@ -279,7 +284,7 @@ export class DiscordWebhookSink extends NotificationSink {
|
|
|
279
284
|
_resolvedStatePath() {
|
|
280
285
|
// Lazy like discord-credentials.credentialsFilePath so tests that mutate
|
|
281
286
|
// HOME (and the sandbox guard) see the current home, not a frozen one.
|
|
282
|
-
return this._statePath ||
|
|
287
|
+
return this._statePath || configPath('discord-webhook-state.json')
|
|
283
288
|
}
|
|
284
289
|
|
|
285
290
|
/**
|
|
@@ -354,12 +359,31 @@ export class DiscordWebhookSink extends NotificationSink {
|
|
|
354
359
|
* pipeline notification carries (Phase 3 ingest events will carry an
|
|
355
360
|
* explicit `project`). Sanitized the same way the bash original sanitized
|
|
356
361
|
* project names so state keys stay filesystem/log safe.
|
|
362
|
+
*
|
|
363
|
+
* #8063 review (found while closing #7123): every fallback in the chain
|
|
364
|
+
* above — `data.project`, `data.sessionName`, `data.sessionId` — is a raw
|
|
365
|
+
* `IngestEventDataSchema` value, wire-legal up to 4096 chars (16x
|
|
366
|
+
* `MAX_EXTERNAL_PROJECT_CHARS`). #7123 stripped `data.project` from the
|
|
367
|
+
* ingest-side spread, but `sessionName`/`sessionId` reach this function
|
|
368
|
+
* unclamped the same way `project` did, and `event.sessionId`'s envelope
|
|
369
|
+
* override in event-ingest.js only fires when it's truthy — sessionId is
|
|
370
|
+
* optional. Clamping HERE, on the OUTPUT, closes every current fallback in
|
|
371
|
+
* one place and any future one added to the chain, rather than chasing
|
|
372
|
+
* each raw field at its source. `MAX_EXTERNAL_PROJECT_CHARS` (not
|
|
373
|
+
* `MAX_EXTERNAL_SESSION_ID_CHARS`) is the right bound: whichever field
|
|
374
|
+
* produced it, this function's return value is always used downstream as
|
|
375
|
+
* a PROJECT identifier — the state-file map key and the per-project color
|
|
376
|
+
* override lookup — never as a session id in its own right. Slicing the
|
|
377
|
+
* already-sanitized string (not the raw input) means a short key is
|
|
378
|
+
* returned byte-for-byte unchanged — existing on-disk state-file entries
|
|
379
|
+
* for values under the cap are not rewritten or orphaned.
|
|
357
380
|
*/
|
|
358
381
|
_projectKey(notification) {
|
|
359
382
|
const data = notification?.data || {}
|
|
360
383
|
const raw = data.project || data.sessionName || data.sessionId || 'chroxy'
|
|
361
384
|
const sanitized = String(raw).replace(/[^A-Za-z0-9._-]/g, '')
|
|
362
|
-
|
|
385
|
+
const key = sanitized.length > 0 ? sanitized : 'unknown'
|
|
386
|
+
return key.length > MAX_EXTERNAL_PROJECT_CHARS ? key.slice(0, MAX_EXTERNAL_PROJECT_CHARS) : key
|
|
363
387
|
}
|
|
364
388
|
|
|
365
389
|
// -- Sink contract --------------------------------------------------------
|
|
@@ -665,20 +689,30 @@ export class DiscordWebhookSink extends NotificationSink {
|
|
|
665
689
|
// put a visible backslash in front of every `_` — a character `_projectKey`
|
|
666
690
|
// deliberately allows in a project name. Length is the only hazard here.
|
|
667
691
|
const projectBudget = MAX_EMBED_TITLE_CHARS - titleFor('').length
|
|
692
|
+
// `project` is NOT re-neutralized here: it is already `_projectKey()`'s
|
|
693
|
+
// sanitized output (`[^A-Za-z0-9._-]` stripped, #7105/#8063), and that
|
|
694
|
+
// charset excludes `@`/`<`/`>` outright — a mention can't survive into the
|
|
695
|
+
// title through this path. (`truncate`, not `escapeAndCap`, for the same
|
|
696
|
+
// reason noted below: Discord doesn't render markdown in embed titles.)
|
|
668
697
|
const title = truncate(titleFor(truncate(project, projectBudget)), MAX_EMBED_TITLE_CHARS)
|
|
669
698
|
const fields = []
|
|
670
|
-
// Free-text user/transcript fields (#5475):
|
|
671
|
-
//
|
|
672
|
-
//
|
|
673
|
-
//
|
|
699
|
+
// Free-text user/transcript fields (#5475/#8105): neutralize Discord
|
|
700
|
+
// mention syntax FIRST (a session name, task body, or tool detail can
|
|
701
|
+
// carry a literal `@everyone`/`@here`/role/user mention straight from
|
|
702
|
+
// caller-supplied data — #8105), THEN escape markdown so e.g.
|
|
703
|
+
// `watch dist/*_test.js` still renders literally. escapeAndCap truncates
|
|
704
|
+
// first, escapes, then clamps the FINAL escaped string so it can't blow
|
|
705
|
+
// past Discord's 1024-char field limit (see escapeAndCap); running
|
|
706
|
+
// neutralizeMentions after truncation could instead clip a mention
|
|
707
|
+
// mid-match and let it through, so it always runs on the raw value.
|
|
674
708
|
if (entry.body) {
|
|
675
|
-
fields.push({ name: 'Status', value: escapeAndCap(entry.body), inline: false })
|
|
709
|
+
fields.push({ name: 'Status', value: escapeAndCap(neutralizeMentions(entry.body)), inline: false })
|
|
676
710
|
}
|
|
677
711
|
if (entry.detail) {
|
|
678
|
-
fields.push({ name: 'Detail', value: escapeAndCap(entry.detail), inline: false })
|
|
712
|
+
fields.push({ name: 'Detail', value: escapeAndCap(neutralizeMentions(entry.detail)), inline: false })
|
|
679
713
|
}
|
|
680
714
|
if (entry.sessionName) {
|
|
681
|
-
fields.push({ name: 'Session', value: escapeAndCap(entry.sessionName, 100), inline: true })
|
|
715
|
+
fields.push({ name: 'Session', value: escapeAndCap(neutralizeMentions(entry.sessionName), 100), inline: true })
|
|
682
716
|
}
|
|
683
717
|
if (Number.isFinite(entry.subagents) && entry.subagents > 0) {
|
|
684
718
|
fields.push({ name: 'Subagents', value: String(entry.subagents), inline: true })
|
|
@@ -690,9 +724,16 @@ export class DiscordWebhookSink extends NotificationSink {
|
|
|
690
724
|
title,
|
|
691
725
|
color: this._colorFor(project, entry.state),
|
|
692
726
|
fields,
|
|
727
|
+
// `this._botName` is a trusted, admin-set constructor option (config.json
|
|
728
|
+
// / CLI default), never caller-supplied free text — no neutralization
|
|
729
|
+
// needed for the footer.
|
|
693
730
|
footer: { text: `${this._botName} · ${formatDuration(elapsedSec)}` },
|
|
694
731
|
timestamp: new Date(this._now()).toISOString(),
|
|
695
732
|
}],
|
|
733
|
+
// Server-side backstop (#8105), on top of neutralizeMentions() above: no
|
|
734
|
+
// configured user/role ping exists for this sink (see
|
|
735
|
+
// DEFAULT_ALLOWED_MENTIONS), so no mention type is allowed at all.
|
|
736
|
+
allowed_mentions: DEFAULT_ALLOWED_MENTIONS,
|
|
696
737
|
}
|
|
697
738
|
}
|
|
698
739
|
|