@arnilo/prism-hosts 0.13.1 → 0.14.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (127) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/a2a/README.md +195 -0
  3. package/a2a/src/card.ts +208 -0
  4. package/a2a/src/codec.ts +523 -0
  5. package/a2a/src/connect.ts +415 -0
  6. package/a2a/src/errors.ts +87 -0
  7. package/a2a/src/index.ts +40 -0
  8. package/a2a/src/limits.ts +43 -0
  9. package/a2a/src/pending.ts +28 -0
  10. package/a2a/src/proxy.ts +526 -0
  11. package/a2a/src/serve.ts +886 -0
  12. package/acp/README.md +3 -1
  13. package/acp/src/limits.ts +3 -16
  14. package/acp/src/mapper.ts +26 -5
  15. package/acp/src/serve.ts +6 -5
  16. package/ag-ui/README.md +2 -1
  17. package/ag-ui/src/a2ui.ts +8 -31
  18. package/ag-ui/src/ag-ui-mapper.ts +27 -1
  19. package/ag-ui/src/encrypted-value.ts +3 -3
  20. package/ag-ui/src/handler.ts +4 -4
  21. package/ag-ui/src/index.ts +0 -33
  22. package/ag-ui/src/limits.ts +5 -88
  23. package/ag-ui/src/projectors.ts +8 -6
  24. package/ag-ui/src/renderer/bind.ts +2 -1
  25. package/channels/README.md +61 -5
  26. package/channels/src/discord-gateway.ts +354 -0
  27. package/channels/src/discord.ts +873 -0
  28. package/channels/src/index.ts +4 -2
  29. package/channels/src/limits.ts +3 -19
  30. package/channels/src/pairing.ts +1 -2
  31. package/channels/src/runtime-turn.ts +10 -2
  32. package/channels/src/signal.ts +11 -19
  33. package/channels/src/slack.ts +854 -0
  34. package/channels/src/telegram.ts +22 -44
  35. package/channels/src/types.ts +5 -2
  36. package/devtools/README.md +1 -1
  37. package/driver-process/src/driver.ts +3 -1
  38. package/driver-process/src/testing.ts +1 -1
  39. package/driver-process/src/turn.ts +5 -1
  40. package/evals/README.md +11 -7
  41. package/evals/src/calibration.ts +5 -13
  42. package/evals/src/compare-experiments.ts +1 -2
  43. package/evals/src/comparison.ts +7 -25
  44. package/evals/src/curate.ts +3 -9
  45. package/evals/src/dataset.ts +0 -2
  46. package/evals/src/index.ts +3 -20
  47. package/evals/src/injection.ts +33 -6
  48. package/evals/src/judge.ts +9 -13
  49. package/evals/src/limits.ts +0 -17
  50. package/evals/src/rubric-judge.ts +5 -10
  51. package/evals/src/scenario-runner.ts +8 -4
  52. package/evals/src/scenarios.ts +5 -5
  53. package/evals/src/score.ts +3 -5
  54. package/evals/src/stats.ts +0 -2
  55. package/evals/src/threshold.ts +3 -3
  56. package/evals/src/toolless-session.ts +7 -3
  57. package/evals/src/trace.ts +8 -14
  58. package/evals/src/trajectory.ts +45 -11
  59. package/evals/src/types.ts +2 -2
  60. package/evals/src/user-simulator.ts +1 -7
  61. package/evals/src/util.ts +3 -9
  62. package/headless/README.md +20 -1
  63. package/headless/src/authority.ts +14 -1
  64. package/headless/src/errors.ts +3 -1
  65. package/headless/src/index.ts +10 -1
  66. package/headless/src/limits.ts +2 -2
  67. package/headless/src/pending.ts +4 -3
  68. package/headless/src/recover.ts +126 -0
  69. package/headless/src/resume.ts +1 -1
  70. package/host-builder/data/api.json +1276 -1365
  71. package/host-builder/data/errors.json +199 -185
  72. package/host-builder/data/examples/a2a-client.ts +125 -0
  73. package/host-builder/data/examples/a2a-server.ts +133 -0
  74. package/host-builder/data/examples/autonomous-coding-loop.ts +1 -1
  75. package/host-builder/data/examples/build-workflow.ts +2 -2
  76. package/host-builder/data/examples/caveman-ponytail.ts +1 -1
  77. package/host-builder/data/examples/channel-discord.ts +176 -0
  78. package/host-builder/data/examples/channel-slack.ts +146 -0
  79. package/host-builder/data/examples/continue-after-failure.ts +80 -0
  80. package/host-builder/data/examples/custom-adapter.ts +1 -1
  81. package/host-builder/data/examples/decision-models.ts +1 -1
  82. package/host-builder/data/examples/define-package.ts +1 -1
  83. package/host-builder/data/examples/delegate.ts +74 -9
  84. package/host-builder/data/examples/durable-loops-and-approvals.ts +11 -10
  85. package/host-builder/data/examples/governance-deny.ts +1 -1
  86. package/host-builder/data/examples/guardrail-content.ts +126 -0
  87. package/host-builder/data/examples/headless-host.ts +1 -1
  88. package/host-builder/data/examples/long-running-job.ts +129 -0
  89. package/host-builder/data/examples/long-term-memory.ts +1 -1
  90. package/host-builder/data/examples/mcp-oauth.ts +197 -0
  91. package/host-builder/data/examples/mcp-trust.ts +1 -1
  92. package/host-builder/data/examples/memory-and-wiki.ts +2 -2
  93. package/host-builder/data/examples/memory-system.ts +19 -9
  94. package/host-builder/data/examples/model-router-aggregate-budgets.ts +1 -1
  95. package/host-builder/data/examples/parallel-tools.ts +70 -0
  96. package/host-builder/data/examples/remote-agent.ts +1 -1
  97. package/host-builder/data/examples/serve-tools.ts +1 -1
  98. package/host-builder/data/examples/session-memory.ts +18 -16
  99. package/host-builder/data/examples/side-call.ts +1 -1
  100. package/host-builder/data/examples/sqlite-resume.ts +1 -1
  101. package/host-builder/data/examples/structured-output.ts +57 -0
  102. package/host-builder/data/examples.json +14 -4
  103. package/host-builder/skills/prism-host-builder/SKILL.md +1 -1
  104. package/host-builder/skills/prism-host-builder/references/choosing.md +14 -10
  105. package/host-builder/skills/prism-host-builder/references/pitfalls.md +5 -3
  106. package/host-builder/skills/prism-host-builder/references/recipes.md +5 -5
  107. package/host-builder/skills/prism-host-builder/references/verification.md +1 -1
  108. package/host-builder/src/check/runner.ts +2 -3
  109. package/host-builder/src/server.ts +2 -2
  110. package/mcp-server/README.md +3 -3
  111. package/mcp-server/src/bounds.ts +3 -3
  112. package/mcp-server/src/serve-tools.ts +2 -9
  113. package/mcp-server/src/serve.ts +2 -4
  114. package/mcp-server/src/server.ts +10 -20
  115. package/package.json +12 -6
  116. package/remote/README.md +7 -4
  117. package/remote/src/channel.ts +6 -2
  118. package/remote/src/connect.ts +9 -3
  119. package/remote/src/errors.ts +3 -1
  120. package/remote/src/limits.ts +3 -13
  121. package/remote/src/mirror.ts +2 -1
  122. package/remote/src/pending.ts +4 -3
  123. package/remote/src/protocol.ts +3 -0
  124. package/remote/src/serve.ts +43 -5
  125. package/remote/src/session-proxy.ts +28 -5
  126. package/remote/src/testing.ts +3 -1
  127. package/remote/src/wire.ts +74 -14
@@ -1,12 +1,12 @@
1
1
  # @arnilo/prism-hosts/channels
2
2
 
3
- Host library connecting one Prism `Agent` to Telegram and Signal messaging channels without building another agent runtime, conversation store, or turn queue.
3
+ Host library connecting one Prism `Agent` to Telegram, Signal, Slack, and Discord messaging channels without building another agent runtime, conversation store, or turn queue.
4
4
 
5
5
  ## Overview
6
6
 
7
- - **One Agent per connection** — `connectTelegram(agent, options)` and `connectSignal(agent, options)` bind one host-configured Prism `Agent` directly to chat transports. Each inbound conversation binds to `agent.session({ id })` in the channel state store and runs turns through `session.run(text, { interactive: false })`.
7
+ - **One Agent per connection** — `connectTelegram(agent, options)`, `connectSignal(agent, options)`, `connectSlack(agent, options)`, and `connectDiscord(agent, options)` bind one host-configured Prism `Agent` directly to chat transports. Each inbound conversation binds to `agent.session({ id })` in the channel state store and runs turns through `session.run(text, { interactive: false })`.
8
8
  - **Durable journal** — bindings, `/new` generations, admission deduplication, claims, and staged replies live in host-owned checkpoint and lease stores. Recovery is explicit via `reconcile()`, never an uncoordinated replay. The package declares the two store shapes it accepts locally (`src/checkpoint-contract.ts`, not re-exported) instead of depending on the workflows engine that owns the `checkpoints`/`leases` services.
9
- - **Durable approvals** — when a tool call suspends the run (`RunResult.pending`), opaque one-use controls bind the decision to the external sender, conversation, and expiry. Telegram renders inline callback buttons; Signal renders `/approve <token>` and `/deny <token>` commands. The user's reply maps directly to `session.resume(decisions, { interactive: false })`.
9
+ - **Durable approvals** — when a tool call suspends the run (`RunResult.pending`), opaque one-use controls bind the decision to the external sender, conversation, and expiry. Telegram renders inline callback buttons; Slack renders Block Kit buttons; Discord renders message-component buttons; Signal renders `/approve <token>` and `/deny <token>` commands. The user's reply maps directly to `session.resume(decisions, { interactive: false })`.
10
10
  - **Ref-only credentials** — Telegram bot tokens, the Telegram `webhookSecret`, and Signal account credentials MUST be references (`env:<VAR>` or `keyring:<KEY>`), resolved through the agent's assigned credentials slot (`AgentConfig.slots.credentials`, else the kernel's `env:` resolver). Literal credentials fail immediately at connection time with `ChannelTokenLiteralError` (`ERR_PRISM_CHANNEL_TOKEN_LITERAL`). The low-level `createTelegramAdapter` / `createTelegramWebhookHandler` take `botToken` and `webhookSecret` as a `ChannelSecretSource` (`() => Promise<string>`), never a literal string. Tokens and webhook secrets never leak into delivered messages, errors, or diagnostics.
11
11
  - **Deny by default** — transport inputs are never trusted implicitly. Inbound updates pass through host authorization (`authorize`), verified principal identity, and ownership scopes before any session work begins.
12
12
  - **Streaming previews** — opt-in drafts (`sendDrafts: true`) forward partial text through Telegram `sendMessageDraft` previews while the turn is generating. Previews are never journaled and never replace the final reply.
@@ -106,9 +106,62 @@ const bot = await connectSignal(agent, {
106
106
  await bot.start();
107
107
  ```
108
108
 
109
+ ### Slack
110
+
111
+ ```ts
112
+ import { connectSlack } from "@arnilo/prism-hosts/channels/slack";
113
+
114
+ const slack = await connectSlack(agent, {
115
+ token: "env:SLACK_BOT_TOKEN", // xoxb- bot token
116
+ signingSecret: "env:SLACK_SIGNING_SECRET", // Events API over HTTP
117
+ // appToken: "env:SLACK_APP_TOKEN", // or Socket Mode (xapp-, connections:write)
118
+ checkpoints, leases,
119
+ authorize: (input) => allowList.has(input.externalActorId) && { identity: identityFor(input), grantRevision: "1" },
120
+ });
121
+ Bun.serve({ port: 8791, fetch: (request) => slack.handle(request) }); // Events API
122
+ await slack.start(); // Socket Mode only
123
+ ```
124
+
125
+ - **Setup.** Create a Slack app with the bot scopes `app_mentions:read`, `chat:write`, and `im:history`, and subscribe to the `app_mention` and `message.im` bot events. For the Events API, point Event Subscriptions and Interactivity at the mounted handler. For Socket Mode, enable it and pass an app-level token with `connections:write` instead; no public URL is needed. Both transports feed one parser.
126
+ - **Verification.** Over HTTP every request is checked before its body is parsed: `X-Slack-Signature` must be the HMAC-SHA256 of `v0:<timestamp>:<raw body>` under the signing secret, compared in constant time, and the timestamp must be within 5 minutes. Anything else answers 401, including every request when no `signingSecret` is configured. The `url_verification` challenge is answered only when signed. Socket Mode trusts the socket opened with the app token.
127
+ - **Acknowledgement.** The capability is `acknowledgement: "deadline"`: each event is admitted (authorized and claimed in the journal) and then acknowledged, within Slack's 3-second rule. A retryable admission (`capacity`, `unavailable`, `stopped`) answers 503, or leaves the Socket Mode envelope unacknowledged, so Slack redelivers.
128
+ - **Events.** Only `app_mention` and direct messages (`message` with `channel_type: "im"`) start turns. Events with `bot_id` or any `subtype` (edits, joins, file shares, the bot's own messages) are ignored. Events deduplicate on `event_id`, so a Slack retry runs once; a button click deduplicates on message ts + action ts + user.
129
+ - **Binding.** `externalConversationId` is `<team>:<channel>` and `externalActorId` is `<team>:<user>`; `claims.teamId` and `claims.channelType` carry the rest. A mention starts (or continues) a thread on its message, and each thread is its own session. A DM is one session unless the user replies in a thread. A follow-up in a channel thread must mention the bot again. Slack treats a leading `/` as a slash command, so `!new`, `!status`, `!cancel`, `!help`, and `!answer` are accepted for the runtime commands.
130
+ - **Deny by default.** `authorize` is required. Without it every event is denied; Slack never falls back to the runtime's open default.
131
+ - **Replies.** Replies post in the bound thread with `chat.postMessage`, split at 40,000 characters (3,000 when buttons are attached, the Block Kit section limit), with `&`, `<`, and `>` escaped so model text cannot ping `@channel` or forge links, and with link unfurling off. A 429 is waited out for its `Retry-After` (at most 60 s, 5 attempts); delivery is journaled and reconciled like Telegram's.
132
+ - **Approvals.** The decision the runtime presents renders as Allow once / Deny buttons. A click is honored only from the bound user in the bound conversation and thread, before `approvalTtlMs`, once.
133
+ - **Previews.** With `sendDrafts: true`, one preview message shows the tail of the answer, updated with `chat.update` at most once per `draftIntervalMs` (default 1,000). It is deleted with `chat.delete` after the reply is delivered. A preview write that fails is dropped.
134
+ - **Not supported.** Slack file attachments are not read, and thread replies without a mention are not admitted.
135
+
136
+ ### Discord
137
+
138
+ ```ts
139
+ import { connectDiscord } from "@arnilo/prism-hosts/channels/discord";
140
+
141
+ const discord = await connectDiscord(agent, {
142
+ token: "env:DISCORD_BOT_TOKEN", applicationId: "1234567890",
143
+ // publicKey: "env:DISCORD_PUBLIC_KEY", // only with an Interactions Endpoint URL
144
+ checkpoints, leases,
145
+ authorize: (input) => allowed(input.externalActorId) && { identity: identityFor(input), grantRevision: "1" },
146
+ });
147
+ await discord.start(); // opens the Gateway and resolves on READY
148
+ // Optional Interactions endpoint: Bun.serve({ port: 8792, fetch: (request) => discord.handle(request) });
149
+ ```
150
+
151
+ - **Setup.** Create an application with a bot, enable the privileged **Message Content** intent in the developer portal, and invite the bot with the `Send Messages`, `Read Message History`, and `Send Messages in Threads` permissions. The connection identifies with `GUILD_MESSAGES`, `DIRECT_MESSAGES`, and `MESSAGE_CONTENT` (`DISCORD_GATEWAY_INTENTS`). Without Message Content, guild text arrives empty except for mentions.
152
+ - **Gateway.** `start()` reads `GET /gateway/bot`, connects to Gateway v10, and resolves on READY. The client sends the first heartbeat after `heartbeat_interval × jitter`, treats a missed ACK as a dead connection, and resumes on `resume_gateway_url` with the last sequence. It resumes on op 7, identifies afresh on op 9 with `d: false` (or close 4007/4009), and reconnects with backoff (1 s doubling to 30 s). A fatal close (4004 bad token, 4014 intents not enabled, and the other 401x codes) stops reconnecting; before READY it rejects `start()`. The only periodic work is the heartbeat.
153
+ - **Interactions.** Component clicks arrive over the Gateway by default and are acknowledged with `DEFERRED_UPDATE_MESSAGE` (callback type 6) on the interaction callback route, alongside admission and within Discord's 3-second deadline. With an Interactions Endpoint URL configured, pass `publicKey` (hex, or an `env:`/`keyring:` ref) and mount `handle(request)`: each request is verified with Ed25519 over `X-Signature-Timestamp` + raw body before parsing (and refused outside a 5-minute window), PING answers PONG, and the HTTP response carries the type 6 acknowledgement. Without `publicKey` every request answers 401.
154
+ - **Messages.** Guild messages start turns only when they mention the bot; DMs always do. The bot's own messages are always ignored; messages from other bots, system users, and webhooks are ignored unless `allowBots: true`. Only default and reply messages are read. Messages deduplicate on the message id and clicks on the interaction id.
155
+ - **Binding.** `externalConversationId` is `<guild>:<channel>` (or `dm:<channel>`) and `externalActorId` is the Discord user id; `claims.guildId` and `claims.channelType` carry the rest. A Discord thread is its own channel, so each thread is its own session. Leading bot mentions are stripped, and `!new`, `!status`, `!cancel`, `!help`, and `!answer` work alongside the `/` forms.
156
+ - **Deny by default.** `authorize` is required. Without it every event is denied; Discord never falls back to the runtime's open default.
157
+ - **Replies.** Replies post in the bound channel, split at 2,000 characters on code-point boundaries, with `allowed_mentions: { parse: [] }` so model text cannot ping `@everyone`, and with embeds suppressed. Per-route rate-limit buckets are honored: an exhausted bucket (`X-RateLimit-Remaining: 0`) blocks its route until `X-RateLimit-Reset-After`, and a 429 blocks its route (or every route when `global`) for `retry_after` before the send is retried (at most 60 s, 5 attempts). Delivery is journaled and reconciled like Telegram's.
158
+ - **Approvals.** The decision the runtime presents renders as Allow once / Deny buttons. A click is honored only from the bound user in the bound conversation, before `approvalTtlMs`, once.
159
+ - **Previews.** With `sendDrafts: true`, one preview message shows the tail of the answer, edited at most once per `draftIntervalMs` (default 1,000) and deleted after the reply is delivered.
160
+ - **Not supported.** Slash commands, attachments, and sharding. Two processes connected with the same bot both receive every event; the runtime's journal admits each message once.
161
+
109
162
  ## Connection Handle
110
163
 
111
- Both `connectTelegram` and `connectSignal` return a `ChannelConnectionHandle`:
164
+ `connectTelegram`, `connectSignal`, `connectSlack`, and `connectDiscord` return a `ChannelConnectionHandle`:
112
165
 
113
166
  ```ts
114
167
  export interface ChannelConnectionHandle {
@@ -121,7 +174,7 @@ export interface ChannelConnectionHandle {
121
174
  ```
122
175
 
123
176
  - `handle(update)`: synchronously admits an inbound message, callback query, or webhook Request to the runtime queue and returns an admission result.
124
- - `start()`: begins polling or socket subscription.
177
+ - `start()`: begins polling or socket subscription (Discord: opens the Gateway and resolves on READY).
125
178
  - `drain()`: waits for all in-flight turns and reply deliveries to settle.
126
179
  - `close()` / `stop()`: closes network listeners and shuts down the channel runtime cleanly.
127
180
 
@@ -129,11 +182,14 @@ export interface ChannelConnectionHandle {
129
182
 
130
183
  - **Fail-closed authentication**: unverified identities and expired/foreign approval callbacks are immediately rejected.
131
184
  - **Secret redaction**: bot tokens and credentials are automatically registered with the agent's secret redactor and redacted from logs, traces, and outgoing chat replies.
185
+ - **Retried attempts in previews**: `onAssistantDelta` previews are cumulative per run; a provider attempt that ends with `error` drops its text, so the next preview restarts from the retried attempt ([Events](../../../docs/events.md#failed-attempts)).
132
186
  - **No agent construction**: the channel host library never calls `createAgent` internally; the host constructs the `Agent` and passes it in.
133
187
 
134
188
  ## Examples
135
189
 
136
190
  - [examples/telegram-agent.ts](../../../examples/telegram-agent.ts) — Telegram bot with polling and webhook mounting.
191
+ - [examples/channel-slack.ts](../../../examples/channel-slack.ts) — Slack Events API, signed requests, and an approval button on a scripted Web API.
192
+ - [examples/channel-discord.ts](../../../examples/channel-discord.ts) — Discord Gateway handshake, a mention, and a sender-bound approval button on a scripted Gateway and REST API.
137
193
  - [examples/signal-agent.ts](../../../examples/signal-agent.ts) — Signal adapter over signal-cli.
138
194
  - [examples/messaging-agent.ts](../../../examples/messaging-agent.ts) — SQLite-backed network-free demo.
139
195
  - examples/messaging-outbox.ts — PostgreSQL ERP-outbox composition.
@@ -0,0 +1,354 @@
1
+ // Plan 236 Task 5: a minimal Discord Gateway v10 client. It is a small state machine over one
2
+ // WebSocket: Hello → jittered heartbeat → Identify or Resume → dispatches, with ACK-loss (zombie)
3
+ // detection, op 7 / op 9 handling, and reconnect with backoff. It knows nothing about the runtime.
4
+ import type { ChannelSecretSource } from "./secret-ref.js";
5
+
6
+ const DEFAULT_READY_TIMEOUT_MS = 30_000;
7
+
8
+ /** The subset of the WHATWG `WebSocket` the Gateway client uses. */
9
+ export interface DiscordSocket {
10
+ send(data: string): void;
11
+ close(code?: number, reason?: string): void;
12
+ addEventListener(
13
+ type: "open" | "message" | "close" | "error",
14
+ listener: (event: { readonly data?: unknown; readonly code?: number }) => void,
15
+ ): void;
16
+ }
17
+
18
+ /** `GUILD_MESSAGES | DIRECT_MESSAGES | MESSAGE_CONTENT` (privileged: enable it in the developer portal). */
19
+ export const DISCORD_GATEWAY_INTENTS = (1 << 9) | (1 << 12) | (1 << 15);
20
+
21
+ /** Close codes after which reconnecting cannot succeed (bad token, shard or intents). */
22
+ const FATAL_CLOSE_CODES = new Set([4004, 4010, 4011, 4012, 4013, 4014]);
23
+ /** Close codes that invalidate the session: the next connection identifies afresh. */
24
+ const SESSION_CLOSE_CODES = new Set([4007, 4009]);
25
+ /** A non-1000/1001 code keeps the session resumable. */
26
+ const RESUME_CLOSE_CODE = 4000;
27
+ const MAX_RECONNECT_DELAY_MS = 30_000;
28
+ const SESSION_ID_PATTERN = /^[A-Za-z0-9_-]{1,128}$/;
29
+ const SNOWFLAKE = /^\d{1,20}$/;
30
+
31
+ export interface DiscordGatewayOptions {
32
+ readonly token: ChannelSecretSource;
33
+ readonly intents: number;
34
+ /** Returns the base `wss://` Gateway URL (`GET /gateway/bot`); called for every fresh Identify. */
35
+ readonly gatewayUrl: () => Promise<string>;
36
+ readonly webSocket: (url: string) => DiscordSocket;
37
+ /** Receives every dispatch (op 0) after the client has updated its own state. */
38
+ readonly onDispatch: (type: string, data: unknown) => unknown;
39
+ readonly maxFrameBytes: number;
40
+ /** Heartbeat jitter source in [0, 1); defaults to `Math.random`. */
41
+ readonly random?: () => number;
42
+ /** First reconnect delay, doubled per failed attempt up to 30 s (default 1,000 ms). */
43
+ readonly reconnectBaseMs?: number;
44
+ /** How long `start` waits for READY (default 30,000 ms). */
45
+ readonly readyTimeoutMs?: number;
46
+ }
47
+
48
+ export interface DiscordGatewayState {
49
+ readonly sessionId?: string;
50
+ readonly sequence: number | null;
51
+ readonly botUserId?: string;
52
+ readonly resumeUrl?: string;
53
+ readonly connected: boolean;
54
+ }
55
+
56
+ export interface DiscordGateway {
57
+ /** Opens the first connection and resolves on READY; a fatal close or timeout rejects. */
58
+ start(): Promise<void>;
59
+ stop(): void;
60
+ state(): DiscordGatewayState;
61
+ }
62
+
63
+ function asRecord(value: unknown): Record<string, unknown> | undefined {
64
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? (value as Record<string, unknown>) : undefined;
65
+ }
66
+
67
+ function gatewayEndpoint(base: string): string | undefined {
68
+ let parsed: URL;
69
+ try {
70
+ parsed = new URL(base);
71
+ } catch {
72
+ return undefined;
73
+ }
74
+ if (parsed.protocol !== "wss:" || parsed.username || parsed.password) return undefined;
75
+ return `${parsed.origin}/?v=10&encoding=json`;
76
+ }
77
+
78
+ export function createDiscordGateway(options: DiscordGatewayOptions): DiscordGateway {
79
+ const random = options.random ?? Math.random;
80
+ const reconnectBaseMs = options.reconnectBaseMs ?? 1_000;
81
+ const readyTimeoutMs = options.readyTimeoutMs ?? DEFAULT_READY_TIMEOUT_MS;
82
+ let socket: DiscordSocket | undefined;
83
+ let sessionId: string | undefined;
84
+ let resumeUrl: string | undefined;
85
+ let sequence: number | null = null;
86
+ let botUserId: string | undefined;
87
+ let heartbeatTimer: ReturnType<typeof setTimeout> | undefined;
88
+ let heartbeatInterval = 0;
89
+ let awaitingAck = false;
90
+ let reconnectTimer: ReturnType<typeof setTimeout> | undefined;
91
+ let reconnectAttempts = 0;
92
+ let started = false;
93
+ let stopped = false;
94
+ let ready = false;
95
+ let pendingStart: { resolve(): void; reject(error: Error): void; timer: ReturnType<typeof setTimeout> } | undefined;
96
+
97
+ function settleStart(error?: Error): void {
98
+ const pending = pendingStart;
99
+ if (pending === undefined) return;
100
+ pendingStart = undefined;
101
+ clearTimeout(pending.timer);
102
+ if (error === undefined) pending.resolve();
103
+ else pending.reject(error);
104
+ }
105
+
106
+ function clearHeartbeat(): void {
107
+ if (heartbeatTimer !== undefined) clearTimeout(heartbeatTimer);
108
+ heartbeatTimer = undefined;
109
+ }
110
+
111
+ function send(current: DiscordSocket, payload: unknown): void {
112
+ try {
113
+ current.send(JSON.stringify(payload));
114
+ } catch {
115
+ // The socket closed under us; its close event drives the reconnect.
116
+ }
117
+ }
118
+
119
+ /** Closes with a resumable code; the close listener schedules the reconnect. */
120
+ function drop(current: DiscordSocket, resume: boolean): void {
121
+ if (!resume) {
122
+ sessionId = undefined;
123
+ resumeUrl = undefined;
124
+ sequence = null;
125
+ }
126
+ clearHeartbeat();
127
+ try {
128
+ current.close(RESUME_CLOSE_CODE, resume ? "resume" : "reidentify");
129
+ } catch {
130
+ // Already closed.
131
+ }
132
+ }
133
+
134
+ function scheduleHeartbeat(current: DiscordSocket, wait: number): void {
135
+ clearHeartbeat();
136
+ heartbeatTimer = setTimeout(() => {
137
+ heartbeatTimer = undefined;
138
+ if (socket !== current || stopped) return;
139
+ // No ACK since the last beat: the connection is a zombie. Drop it and resume.
140
+ if (awaitingAck) return drop(current, true);
141
+ awaitingAck = true;
142
+ send(current, { op: 1, d: sequence });
143
+ scheduleHeartbeat(current, heartbeatInterval);
144
+ }, wait);
145
+ }
146
+
147
+ async function handshake(current: DiscordSocket): Promise<void> {
148
+ let token: string;
149
+ try {
150
+ token = await options.token();
151
+ } catch {
152
+ return drop(current, true);
153
+ }
154
+ if (socket !== current || stopped) return;
155
+ if (sessionId !== undefined && sequence !== null) {
156
+ send(current, { op: 6, d: { token, session_id: sessionId, seq: sequence } });
157
+ } else {
158
+ send(current, {
159
+ op: 2,
160
+ d: { token, intents: options.intents, properties: { os: process.platform, browser: "prism", device: "prism" } },
161
+ });
162
+ }
163
+ }
164
+
165
+ function onFrame(current: DiscordSocket, data: unknown): void {
166
+ if (socket !== current) return;
167
+ const raw =
168
+ typeof data === "string"
169
+ ? data
170
+ : data instanceof ArrayBuffer || ArrayBuffer.isView(data)
171
+ ? Buffer.from(data as ArrayBuffer).toString("utf8")
172
+ : undefined;
173
+ if (raw === undefined || Buffer.byteLength(raw, "utf8") > options.maxFrameBytes) return;
174
+ let frame: Record<string, unknown> | undefined;
175
+ try {
176
+ frame = asRecord(JSON.parse(raw));
177
+ } catch {
178
+ return;
179
+ }
180
+ if (frame === undefined) return;
181
+ switch (frame.op) {
182
+ case 10: {
183
+ const interval = asRecord(frame.d)?.heartbeat_interval;
184
+ if (typeof interval !== "number" || !Number.isFinite(interval) || interval < 1 || interval > 600_000) return drop(current, true);
185
+ heartbeatInterval = interval;
186
+ awaitingAck = false;
187
+ scheduleHeartbeat(current, Math.floor(interval * Math.min(Math.max(random(), 0), 1)));
188
+ void handshake(current);
189
+ return;
190
+ }
191
+ case 11:
192
+ awaitingAck = false;
193
+ return;
194
+ case 1:
195
+ send(current, { op: 1, d: sequence });
196
+ return;
197
+ case 7:
198
+ return drop(current, true);
199
+ case 9:
200
+ return drop(current, frame.d === true);
201
+ case 0:
202
+ return onDispatch(frame);
203
+ default:
204
+ return;
205
+ }
206
+ }
207
+
208
+ function onDispatch(frame: Record<string, unknown>): void {
209
+ if (typeof frame.s === "number" && Number.isSafeInteger(frame.s) && frame.s >= 0) sequence = frame.s;
210
+ const type = typeof frame.t === "string" ? frame.t : undefined;
211
+ if (type === undefined) return;
212
+ if (type === "READY") {
213
+ const data = asRecord(frame.d);
214
+ const id = data?.session_id;
215
+ const url = typeof data?.resume_gateway_url === "string" ? gatewayEndpoint(data.resume_gateway_url) : undefined;
216
+ if (typeof id === "string" && SESSION_ID_PATTERN.test(id)) sessionId = id;
217
+ resumeUrl = url;
218
+ const user = asRecord(data?.user)?.id;
219
+ if (typeof user === "string" && SNOWFLAKE.test(user)) botUserId = user;
220
+ }
221
+ if (type === "READY" || type === "RESUMED") {
222
+ reconnectAttempts = 0;
223
+ ready = true;
224
+ settleStart();
225
+ }
226
+ try {
227
+ void Promise.resolve(options.onDispatch(type, frame.d)).catch(() => undefined);
228
+ } catch {
229
+ // A throwing dispatch handler never breaks the Gateway loop.
230
+ }
231
+ }
232
+
233
+ function onClose(current: DiscordSocket, code: number | undefined): void {
234
+ if (socket !== current) return;
235
+ socket = undefined;
236
+ clearHeartbeat();
237
+ if (stopped) return;
238
+ if (code !== undefined && FATAL_CLOSE_CODES.has(code)) {
239
+ stopped = true;
240
+ settleStart(new Error(`Discord Gateway refused the connection (close ${code})`));
241
+ return;
242
+ }
243
+ if (code !== undefined && SESSION_CLOSE_CODES.has(code)) {
244
+ sessionId = undefined;
245
+ resumeUrl = undefined;
246
+ sequence = null;
247
+ }
248
+ // A first connection that never reached READY reports its failure instead of retrying.
249
+ if (!ready && pendingStart !== undefined) {
250
+ settleStart(new Error("Discord Gateway connection failed"));
251
+ return;
252
+ }
253
+ scheduleReconnect();
254
+ }
255
+
256
+ async function open(): Promise<void> {
257
+ const resume = sessionId !== undefined && sequence !== null && resumeUrl !== undefined;
258
+ let url: string | undefined;
259
+ if (resume) {
260
+ url = resumeUrl;
261
+ } else {
262
+ try {
263
+ url = gatewayEndpoint(await options.gatewayUrl());
264
+ } catch {
265
+ url = undefined;
266
+ }
267
+ }
268
+ if (url === undefined) throw new Error("Discord Gateway connection failed");
269
+ if (stopped) return;
270
+ const current = options.webSocket(url);
271
+ socket = current;
272
+ current.addEventListener("message", (event) => onFrame(current, event.data));
273
+ current.addEventListener("close", (event) => onClose(current, typeof event.code === "number" ? event.code : undefined));
274
+ current.addEventListener("error", () => {
275
+ try {
276
+ current.close(RESUME_CLOSE_CODE, "error");
277
+ } catch {
278
+ // The close event follows.
279
+ }
280
+ });
281
+ }
282
+
283
+ function scheduleReconnect(): void {
284
+ if (stopped || reconnectTimer !== undefined) return;
285
+ const wait = Math.min(MAX_RECONNECT_DELAY_MS, reconnectBaseMs * 2 ** reconnectAttempts);
286
+ reconnectAttempts += 1;
287
+ reconnectTimer = setTimeout(() => {
288
+ reconnectTimer = undefined;
289
+ open().catch(() => scheduleReconnect());
290
+ }, wait);
291
+ }
292
+
293
+ return {
294
+ async start() {
295
+ if (stopped) throw new Error("Discord Gateway is stopped");
296
+ if (started) throw new Error("Discord Gateway is already started");
297
+ started = true;
298
+ const readyPromise = new Promise<void>((resolve, reject) => {
299
+ pendingStart = {
300
+ resolve,
301
+ reject,
302
+ timer: setTimeout(() => {
303
+ settleStart(new Error("Discord Gateway did not become ready"));
304
+ if (socket !== undefined) drop(socket, true);
305
+ }, readyTimeoutMs),
306
+ };
307
+ });
308
+ try {
309
+ await open();
310
+ } catch (error) {
311
+ settleStart(error instanceof Error ? error : new Error("Discord Gateway connection failed"));
312
+ }
313
+ try {
314
+ await readyPromise;
315
+ } catch (error) {
316
+ stopped = true;
317
+ clearHeartbeat();
318
+ if (reconnectTimer !== undefined) clearTimeout(reconnectTimer);
319
+ reconnectTimer = undefined;
320
+ const current = socket;
321
+ socket = undefined;
322
+ try {
323
+ current?.close(1000, "start failed");
324
+ } catch {
325
+ // Already closed.
326
+ }
327
+ throw error;
328
+ }
329
+ },
330
+ stop() {
331
+ stopped = true;
332
+ settleStart(new Error("Discord Gateway is stopped"));
333
+ clearHeartbeat();
334
+ if (reconnectTimer !== undefined) clearTimeout(reconnectTimer);
335
+ reconnectTimer = undefined;
336
+ const current = socket;
337
+ socket = undefined;
338
+ try {
339
+ current?.close(1000, "stopped");
340
+ } catch {
341
+ // Already closed.
342
+ }
343
+ },
344
+ state() {
345
+ return {
346
+ ...(sessionId === undefined ? {} : { sessionId }),
347
+ sequence,
348
+ ...(botUserId === undefined ? {} : { botUserId }),
349
+ ...(resumeUrl === undefined ? {} : { resumeUrl }),
350
+ connected: socket !== undefined,
351
+ };
352
+ },
353
+ };
354
+ }