@openclaw/tlon 2026.5.2 → 2026.5.3-beta.2

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 (75) hide show
  1. package/dist/api.js +4 -0
  2. package/dist/channel-B4LtNGeZ.js +221 -0
  3. package/dist/channel-plugin-api.js +2 -0
  4. package/dist/channel.runtime-v-_0sHkJ.js +3584 -0
  5. package/dist/doctor-contract-W99wMbar.js +7 -0
  6. package/dist/doctor-contract-api.js +2 -0
  7. package/dist/index.js +18 -0
  8. package/dist/runtime-5FiW9E50.js +8 -0
  9. package/dist/runtime-api-C0hr1Rtn.js +4 -0
  10. package/dist/runtime-api.js +2 -0
  11. package/dist/setup-api.js +3 -0
  12. package/dist/setup-core-BUkZJ-MU.js +386 -0
  13. package/dist/setup-entry.js +11 -0
  14. package/dist/setup-surface-FxNMaluC.js +72 -0
  15. package/dist/test-api.js +2 -0
  16. package/package.json +15 -6
  17. package/api.ts +0 -16
  18. package/channel-plugin-api.ts +0 -1
  19. package/doctor-contract-api.ts +0 -1
  20. package/index.ts +0 -183
  21. package/runtime-api.ts +0 -17
  22. package/setup-api.ts +0 -2
  23. package/setup-entry.ts +0 -9
  24. package/src/account-fields.ts +0 -31
  25. package/src/channel.runtime.ts +0 -248
  26. package/src/channel.ts +0 -173
  27. package/src/config-schema.ts +0 -53
  28. package/src/core.test.ts +0 -278
  29. package/src/doctor-contract.ts +0 -9
  30. package/src/doctor.test.ts +0 -40
  31. package/src/doctor.ts +0 -10
  32. package/src/logger-runtime.ts +0 -1
  33. package/src/monitor/approval-runtime.ts +0 -363
  34. package/src/monitor/approval.test.ts +0 -33
  35. package/src/monitor/approval.ts +0 -286
  36. package/src/monitor/authorization.ts +0 -30
  37. package/src/monitor/cites.ts +0 -54
  38. package/src/monitor/discovery.ts +0 -68
  39. package/src/monitor/history.ts +0 -226
  40. package/src/monitor/index.ts +0 -1524
  41. package/src/monitor/media.test.ts +0 -91
  42. package/src/monitor/media.ts +0 -172
  43. package/src/monitor/processed-messages.test.ts +0 -58
  44. package/src/monitor/processed-messages.ts +0 -89
  45. package/src/monitor/settings-helpers.test.ts +0 -113
  46. package/src/monitor/settings-helpers.ts +0 -158
  47. package/src/monitor/utils.ts +0 -372
  48. package/src/runtime.ts +0 -9
  49. package/src/security.test.ts +0 -622
  50. package/src/session-route.ts +0 -40
  51. package/src/settings.ts +0 -391
  52. package/src/setup-core.ts +0 -228
  53. package/src/setup-surface.ts +0 -103
  54. package/src/targets.ts +0 -102
  55. package/src/tlon-api.test.ts +0 -589
  56. package/src/tlon-api.ts +0 -402
  57. package/src/types.ts +0 -160
  58. package/src/urbit/auth.ssrf.test.ts +0 -45
  59. package/src/urbit/auth.ts +0 -48
  60. package/src/urbit/base-url.test.ts +0 -48
  61. package/src/urbit/base-url.ts +0 -61
  62. package/src/urbit/channel-ops.ts +0 -145
  63. package/src/urbit/context.ts +0 -50
  64. package/src/urbit/errors.ts +0 -51
  65. package/src/urbit/fetch.ts +0 -42
  66. package/src/urbit/foreigns.ts +0 -49
  67. package/src/urbit/send.test.ts +0 -38
  68. package/src/urbit/send.ts +0 -176
  69. package/src/urbit/sse-client.test.ts +0 -203
  70. package/src/urbit/sse-client.ts +0 -484
  71. package/src/urbit/story.ts +0 -332
  72. package/src/urbit/upload.test.ts +0 -154
  73. package/src/urbit/upload.ts +0 -60
  74. package/test-api.ts +0 -1
  75. package/tsconfig.json +0 -16
@@ -1,203 +0,0 @@
1
- import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
2
- import { urbitFetch } from "./fetch.js";
3
- import { UrbitSSEClient } from "./sse-client.js";
4
-
5
- // Mock urbitFetch to avoid real network calls
6
- vi.mock("./fetch.js", () => ({
7
- urbitFetch: vi.fn(),
8
- }));
9
-
10
- // Mock channel-ops to avoid real channel operations
11
- vi.mock("./channel-ops.js", () => ({
12
- ensureUrbitChannelOpen: vi.fn().mockResolvedValue(undefined),
13
- pokeUrbitChannel: vi.fn().mockResolvedValue(undefined),
14
- scryUrbitPath: vi.fn().mockResolvedValue({}),
15
- }));
16
-
17
- describe("UrbitSSEClient", () => {
18
- beforeEach(() => {
19
- vi.clearAllMocks();
20
- });
21
-
22
- afterEach(() => {
23
- vi.restoreAllMocks();
24
- });
25
-
26
- describe("subscribe", () => {
27
- it("sends subscriptions added after connect", async () => {
28
- const mockUrbitFetch = vi.mocked(urbitFetch);
29
- mockUrbitFetch.mockResolvedValue({
30
- response: { ok: true, status: 200 } as unknown as Response,
31
- finalUrl: "https://example.com",
32
- release: vi.fn().mockResolvedValue(undefined),
33
- });
34
-
35
- const client = new UrbitSSEClient("https://example.com", "urbauth-~zod=123");
36
- // Simulate connected state
37
- (client as { isConnected: boolean }).isConnected = true;
38
-
39
- await client.subscribe({
40
- app: "chat",
41
- path: "/dm/~zod",
42
- event: () => {},
43
- });
44
-
45
- expect(mockUrbitFetch).toHaveBeenCalledTimes(1);
46
- const callArgs = mockUrbitFetch.mock.calls[0][0];
47
- expect(callArgs.path).toContain("/~/channel/");
48
- expect(callArgs.init?.method).toBe("PUT");
49
-
50
- const body = JSON.parse(callArgs.init?.body as string);
51
- expect(body).toHaveLength(1);
52
- expect(body[0]).toMatchObject({
53
- action: "subscribe",
54
- app: "chat",
55
- path: "/dm/~zod",
56
- });
57
- });
58
-
59
- it("queues subscriptions before connect", async () => {
60
- const mockUrbitFetch = vi.mocked(urbitFetch);
61
-
62
- const client = new UrbitSSEClient("https://example.com", "urbauth-~zod=123");
63
- // Not connected yet
64
-
65
- await client.subscribe({
66
- app: "chat",
67
- path: "/dm/~zod",
68
- event: () => {},
69
- });
70
-
71
- // Should not call urbitFetch since not connected
72
- expect(mockUrbitFetch).not.toHaveBeenCalled();
73
- // But subscription should be queued
74
- expect(client.subscriptions).toHaveLength(1);
75
- expect(client.subscriptions[0]).toMatchObject({
76
- app: "chat",
77
- path: "/dm/~zod",
78
- });
79
- });
80
- });
81
-
82
- describe("updateCookie", () => {
83
- it("normalizes cookie when updating", () => {
84
- const client = new UrbitSSEClient("https://example.com", "urbauth-~zod=123");
85
-
86
- // Cookie with extra parts that should be stripped
87
- client.updateCookie("urbauth-~zod=456; Path=/; HttpOnly");
88
-
89
- expect(client.cookie).toBe("urbauth-~zod=456");
90
- });
91
-
92
- it("handles simple cookie values", () => {
93
- const client = new UrbitSSEClient("https://example.com", "urbauth-~zod=123");
94
-
95
- client.updateCookie("urbauth-~zod=newvalue");
96
-
97
- expect(client.cookie).toBe("urbauth-~zod=newvalue");
98
- });
99
- });
100
-
101
- describe("reconnection", () => {
102
- it("has autoReconnect enabled by default", () => {
103
- const client = new UrbitSSEClient("https://example.com", "urbauth-~zod=123");
104
- expect(client.autoReconnect).toBe(true);
105
- });
106
-
107
- it("can disable autoReconnect via options", () => {
108
- const client = new UrbitSSEClient("https://example.com", "urbauth-~zod=123", {
109
- autoReconnect: false,
110
- });
111
- expect(client.autoReconnect).toBe(false);
112
- });
113
-
114
- it("stores onReconnect callback", () => {
115
- const onReconnect = vi.fn();
116
- const client = new UrbitSSEClient("https://example.com", "urbauth-~zod=123", {
117
- onReconnect,
118
- });
119
- expect(client.onReconnect).toBe(onReconnect);
120
- });
121
-
122
- it("resets reconnect attempts on successful connect", async () => {
123
- const mockUrbitFetch = vi.mocked(urbitFetch);
124
-
125
- // Mock a response that returns a readable stream
126
- const mockStream = new ReadableStream({
127
- start(controller) {
128
- controller.close();
129
- },
130
- });
131
-
132
- mockUrbitFetch.mockResolvedValue({
133
- response: {
134
- ok: true,
135
- status: 200,
136
- body: mockStream,
137
- } as unknown as Response,
138
- finalUrl: "https://example.com",
139
- release: vi.fn().mockResolvedValue(undefined),
140
- });
141
-
142
- const client = new UrbitSSEClient("https://example.com", "urbauth-~zod=123", {
143
- autoReconnect: false, // Disable to prevent reconnect loop
144
- });
145
- client.reconnectAttempts = 5;
146
-
147
- await client.connect();
148
-
149
- expect(client.reconnectAttempts).toBe(0);
150
- });
151
- });
152
-
153
- describe("event acking", () => {
154
- it("tracks lastHeardEventId and ackThreshold", () => {
155
- const client = new UrbitSSEClient("https://example.com", "urbauth-~zod=123");
156
-
157
- // Access private properties for testing
158
- const lastHeardEventId = (client as unknown as { lastHeardEventId: number }).lastHeardEventId;
159
- const ackThreshold = (client as unknown as { ackThreshold: number }).ackThreshold;
160
-
161
- expect(lastHeardEventId).toBe(-1);
162
- expect(ackThreshold).toBeGreaterThan(0);
163
- });
164
- });
165
-
166
- describe("constructor", () => {
167
- it("generates unique channel ID", () => {
168
- const client1 = new UrbitSSEClient("https://example.com", "urbauth-~zod=123");
169
- const client2 = new UrbitSSEClient("https://example.com", "urbauth-~zod=123");
170
-
171
- expect(client1.channelId).not.toBe(client2.channelId);
172
- });
173
-
174
- it("normalizes cookie in constructor", () => {
175
- const client = new UrbitSSEClient(
176
- "https://example.com",
177
- "urbauth-~zod=123; Path=/; HttpOnly",
178
- );
179
-
180
- expect(client.cookie).toBe("urbauth-~zod=123");
181
- });
182
-
183
- it("sets default reconnection parameters", () => {
184
- const client = new UrbitSSEClient("https://example.com", "urbauth-~zod=123");
185
-
186
- expect(client.maxReconnectAttempts).toBe(10);
187
- expect(client.reconnectDelay).toBe(1000);
188
- expect(client.maxReconnectDelay).toBe(30000);
189
- });
190
-
191
- it("allows overriding reconnection parameters", () => {
192
- const client = new UrbitSSEClient("https://example.com", "urbauth-~zod=123", {
193
- maxReconnectAttempts: 5,
194
- reconnectDelay: 500,
195
- maxReconnectDelay: 10000,
196
- });
197
-
198
- expect(client.maxReconnectAttempts).toBe(5);
199
- expect(client.reconnectDelay).toBe(500);
200
- expect(client.maxReconnectDelay).toBe(10000);
201
- });
202
- });
203
- });
@@ -1,484 +0,0 @@
1
- import { randomUUID } from "node:crypto";
2
- import { Readable } from "node:stream";
3
- import type { LookupFn, SsrFPolicy } from "openclaw/plugin-sdk/ssrf-runtime";
4
- import { ensureUrbitChannelOpen, pokeUrbitChannel, scryUrbitPath } from "./channel-ops.js";
5
- import { getUrbitContext, normalizeUrbitCookie } from "./context.js";
6
- import { urbitFetch } from "./fetch.js";
7
-
8
- type UrbitSseLogger = {
9
- log?: (message: string) => void;
10
- error?: (message: string) => void;
11
- };
12
-
13
- type UrbitSseOptions = {
14
- ship?: string;
15
- ssrfPolicy?: SsrFPolicy;
16
- lookupFn?: LookupFn;
17
- fetchImpl?: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
18
- onReconnect?: (client: UrbitSSEClient) => Promise<void> | void;
19
- autoReconnect?: boolean;
20
- maxReconnectAttempts?: number;
21
- reconnectDelay?: number;
22
- maxReconnectDelay?: number;
23
- logger?: UrbitSseLogger;
24
- };
25
-
26
- export class UrbitSSEClient {
27
- url: string;
28
- cookie: string;
29
- ship: string;
30
- channelId: string;
31
- channelUrl: string;
32
- subscriptions: Array<{
33
- id: number;
34
- action: "subscribe";
35
- ship: string;
36
- app: string;
37
- path: string;
38
- }> = [];
39
- eventHandlers = new Map<
40
- number,
41
- { event?: (data: unknown) => void; err?: (error: unknown) => void; quit?: () => void }
42
- >();
43
- aborted = false;
44
- streamController: AbortController | null = null;
45
- onReconnect: UrbitSseOptions["onReconnect"] | null;
46
- autoReconnect: boolean;
47
- reconnectAttempts = 0;
48
- maxReconnectAttempts: number;
49
- reconnectDelay: number;
50
- maxReconnectDelay: number;
51
- isConnected = false;
52
- logger: UrbitSseLogger;
53
- ssrfPolicy?: SsrFPolicy;
54
- lookupFn?: LookupFn;
55
- fetchImpl?: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
56
- streamRelease: (() => Promise<void>) | null = null;
57
-
58
- // Event ack tracking - must ack every ~50 events to keep channel healthy
59
- private lastHeardEventId = -1;
60
- private lastAcknowledgedEventId = -1;
61
- private readonly ackThreshold = 20;
62
-
63
- constructor(url: string, cookie: string, options: UrbitSseOptions = {}) {
64
- const ctx = getUrbitContext(url, options.ship);
65
- this.url = ctx.baseUrl;
66
- this.cookie = normalizeUrbitCookie(cookie);
67
- this.ship = ctx.ship;
68
- this.channelId = `${Math.floor(Date.now() / 1000)}-${randomUUID()}`;
69
- this.channelUrl = new URL(`/~/channel/${this.channelId}`, this.url).toString();
70
- this.onReconnect = options.onReconnect ?? null;
71
- this.autoReconnect = options.autoReconnect !== false;
72
- this.maxReconnectAttempts = options.maxReconnectAttempts ?? 10;
73
- this.reconnectDelay = options.reconnectDelay ?? 1000;
74
- this.maxReconnectDelay = options.maxReconnectDelay ?? 30000;
75
- this.logger = options.logger ?? {};
76
- this.ssrfPolicy = options.ssrfPolicy;
77
- this.lookupFn = options.lookupFn;
78
- this.fetchImpl = options.fetchImpl;
79
- }
80
-
81
- private channelRequestContext() {
82
- return {
83
- baseUrl: this.url,
84
- cookie: this.cookie,
85
- ship: this.ship,
86
- channelId: this.channelId,
87
- ssrfPolicy: this.ssrfPolicy,
88
- lookupFn: this.lookupFn,
89
- fetchImpl: this.fetchImpl,
90
- };
91
- }
92
-
93
- async subscribe(params: {
94
- app: string;
95
- path: string;
96
- event?: (data: unknown) => void;
97
- err?: (error: unknown) => void;
98
- quit?: () => void;
99
- }) {
100
- const subId = this.subscriptions.length + 1;
101
- const subscription = {
102
- id: subId,
103
- action: "subscribe",
104
- ship: this.ship,
105
- app: params.app,
106
- path: params.path,
107
- } as const;
108
-
109
- this.subscriptions.push(subscription);
110
- this.eventHandlers.set(subId, { event: params.event, err: params.err, quit: params.quit });
111
-
112
- if (this.isConnected) {
113
- try {
114
- await this.sendSubscription(subscription);
115
- } catch (error) {
116
- const handler = this.eventHandlers.get(subId);
117
- handler?.err?.(error);
118
- }
119
- }
120
- return subId;
121
- }
122
-
123
- private async sendSubscription(subscription: {
124
- id: number;
125
- action: "subscribe";
126
- ship: string;
127
- app: string;
128
- path: string;
129
- }) {
130
- const { response, release } = await this.putChannelPayload([subscription], {
131
- timeoutMs: 30_000,
132
- auditContext: "tlon-urbit-subscribe",
133
- });
134
-
135
- try {
136
- if (!response.ok && response.status !== 204) {
137
- const errorText = await response.text().catch(() => "");
138
- throw new Error(
139
- `Subscribe failed: ${response.status}${errorText ? ` - ${errorText}` : ""}`,
140
- );
141
- }
142
- } finally {
143
- await release();
144
- }
145
- }
146
-
147
- async connect() {
148
- await ensureUrbitChannelOpen(this.channelRequestContext(), {
149
- createBody: this.subscriptions,
150
- createAuditContext: "tlon-urbit-channel-create",
151
- });
152
-
153
- await this.openStream();
154
- this.isConnected = true;
155
- this.reconnectAttempts = 0;
156
- }
157
-
158
- async openStream() {
159
- // Use AbortController with manual timeout so we only abort during initial connection,
160
- // not after the SSE stream is established and actively streaming.
161
- const controller = new AbortController();
162
- const timeoutId = setTimeout(() => controller.abort(), 60_000);
163
-
164
- this.streamController = controller;
165
-
166
- const { response, release } = await urbitFetch({
167
- baseUrl: this.url,
168
- path: `/~/channel/${this.channelId}`,
169
- init: {
170
- method: "GET",
171
- headers: {
172
- Accept: "text/event-stream",
173
- Cookie: this.cookie,
174
- },
175
- },
176
- ssrfPolicy: this.ssrfPolicy,
177
- lookupFn: this.lookupFn,
178
- fetchImpl: this.fetchImpl,
179
- signal: controller.signal,
180
- auditContext: "tlon-urbit-sse-stream",
181
- });
182
-
183
- this.streamRelease = release;
184
-
185
- // Clear timeout once connection established (headers received).
186
- clearTimeout(timeoutId);
187
-
188
- if (!response.ok) {
189
- await release();
190
- this.streamRelease = null;
191
- throw new Error(`Stream connection failed: ${response.status}`);
192
- }
193
-
194
- this.processStream(response.body).catch((error) => {
195
- if (!this.aborted) {
196
- this.logger.error?.(`Stream error: ${String(error)}`);
197
- for (const { err } of this.eventHandlers.values()) {
198
- if (err) {
199
- err(error);
200
- }
201
- }
202
- }
203
- });
204
- }
205
-
206
- async processStream(body: unknown) {
207
- if (!body) {
208
- return;
209
- }
210
- // Bridge DOM fetch stream types to Node's stream/web declaration on newer TS/node combos.
211
- const stream =
212
- body instanceof ReadableStream
213
- ? Readable.fromWeb(body as never)
214
- : (body as NodeJS.ReadableStream);
215
- let buffer = "";
216
-
217
- try {
218
- for await (const chunk of stream) {
219
- if (this.aborted) {
220
- break;
221
- }
222
- buffer += chunk.toString();
223
- let eventEnd;
224
- while ((eventEnd = buffer.indexOf("\n\n")) !== -1) {
225
- const eventData = buffer.slice(0, eventEnd);
226
- buffer = buffer.slice(eventEnd + 2);
227
- this.processEvent(eventData);
228
- }
229
- }
230
- } finally {
231
- if (this.streamRelease) {
232
- const release = this.streamRelease;
233
- this.streamRelease = null;
234
- await release();
235
- }
236
- this.streamController = null;
237
- if (!this.aborted && this.autoReconnect) {
238
- this.isConnected = false;
239
- this.logger.log?.("[SSE] Stream ended, attempting reconnection...");
240
- await this.attemptReconnect();
241
- }
242
- }
243
- }
244
-
245
- processEvent(eventData: string) {
246
- const lines = eventData.split("\n");
247
- let data: string | null = null;
248
- let eventId: number | null = null;
249
-
250
- for (const line of lines) {
251
- if (line.startsWith("id: ")) {
252
- eventId = Number.parseInt(line.slice(4), 10);
253
- }
254
- if (line.startsWith("data: ")) {
255
- data = line.slice(6);
256
- }
257
- }
258
-
259
- if (!data) {
260
- return;
261
- }
262
-
263
- // Track event ID and send ack if needed
264
- if (eventId !== null && !Number.isNaN(eventId)) {
265
- if (eventId > this.lastHeardEventId) {
266
- this.lastHeardEventId = eventId;
267
- if (eventId - this.lastAcknowledgedEventId > this.ackThreshold) {
268
- this.logger.log?.(
269
- `[SSE] Acking event ${eventId} (last acked: ${this.lastAcknowledgedEventId})`,
270
- );
271
- this.ack(eventId).catch((err) => {
272
- this.logger.error?.(`Failed to ack event ${eventId}: ${String(err)}`);
273
- });
274
- }
275
- }
276
- }
277
-
278
- try {
279
- const parsed = JSON.parse(data) as { id?: number; json?: unknown; response?: string };
280
-
281
- if (parsed.response === "quit") {
282
- if (parsed.id) {
283
- const handlers = this.eventHandlers.get(parsed.id);
284
- if (handlers?.quit) {
285
- handlers.quit();
286
- }
287
- }
288
- return;
289
- }
290
-
291
- if (parsed.id && this.eventHandlers.has(parsed.id)) {
292
- const { event } = this.eventHandlers.get(parsed.id) ?? {};
293
- if (event && parsed.json) {
294
- event(parsed.json);
295
- }
296
- } else if (parsed.json) {
297
- for (const { event } of this.eventHandlers.values()) {
298
- if (event) {
299
- event(parsed.json);
300
- }
301
- }
302
- }
303
- } catch (error) {
304
- this.logger.error?.(`Error parsing SSE event: ${String(error)}`);
305
- }
306
- }
307
-
308
- async poke(params: { app: string; mark: string; json: unknown }) {
309
- return await pokeUrbitChannel(this.channelRequestContext(), {
310
- ...params,
311
- auditContext: "tlon-urbit-poke",
312
- });
313
- }
314
-
315
- async scry(path: string) {
316
- return await scryUrbitPath(
317
- {
318
- baseUrl: this.url,
319
- cookie: this.cookie,
320
- ssrfPolicy: this.ssrfPolicy,
321
- lookupFn: this.lookupFn,
322
- fetchImpl: this.fetchImpl,
323
- },
324
- { path, auditContext: "tlon-urbit-scry" },
325
- );
326
- }
327
-
328
- /**
329
- * Update the cookie used for authentication.
330
- * Call this when re-authenticating after session expiry.
331
- */
332
- updateCookie(newCookie: string): void {
333
- this.cookie = normalizeUrbitCookie(newCookie);
334
- }
335
-
336
- private async ack(eventId: number): Promise<void> {
337
- this.lastAcknowledgedEventId = eventId;
338
-
339
- const ackData = {
340
- id: Date.now(),
341
- action: "ack",
342
- "event-id": eventId,
343
- };
344
-
345
- const { response, release } = await this.putChannelPayload([ackData], {
346
- timeoutMs: 10_000,
347
- auditContext: "tlon-urbit-ack",
348
- });
349
-
350
- try {
351
- if (!response.ok) {
352
- throw new Error(`Ack failed with status ${response.status}`);
353
- }
354
- } finally {
355
- await release();
356
- }
357
- }
358
-
359
- async attemptReconnect() {
360
- if (this.aborted || !this.autoReconnect) {
361
- this.logger.log?.("[SSE] Reconnection aborted or disabled");
362
- return;
363
- }
364
-
365
- // If we've hit max attempts, wait longer then reset and keep trying
366
- if (this.reconnectAttempts >= this.maxReconnectAttempts) {
367
- this.logger.log?.(
368
- `[SSE] Max reconnection attempts (${this.maxReconnectAttempts}) reached. Waiting 10s before resetting...`,
369
- );
370
- // Wait 10 seconds before resetting and trying again
371
- const extendedBackoff = 10000; // 10 seconds
372
- await new Promise((resolve) => setTimeout(resolve, extendedBackoff));
373
- this.reconnectAttempts = 0; // Reset counter to continue trying
374
- this.logger.log?.("[SSE] Reconnection attempts reset, resuming reconnection...");
375
- }
376
-
377
- this.reconnectAttempts += 1;
378
- const delay = Math.min(
379
- this.reconnectDelay * 2 ** (this.reconnectAttempts - 1),
380
- this.maxReconnectDelay,
381
- );
382
-
383
- this.logger.log?.(
384
- `[SSE] Reconnection attempt ${this.reconnectAttempts}/${this.maxReconnectAttempts} in ${delay}ms...`,
385
- );
386
-
387
- await new Promise((resolve) => setTimeout(resolve, delay));
388
-
389
- try {
390
- this.channelId = `${Math.floor(Date.now() / 1000)}-${randomUUID()}`;
391
- this.channelUrl = new URL(`/~/channel/${this.channelId}`, this.url).toString();
392
-
393
- if (this.onReconnect) {
394
- await this.onReconnect(this);
395
- }
396
-
397
- await this.connect();
398
- this.logger.log?.("[SSE] Reconnection successful!");
399
- } catch (error) {
400
- this.logger.error?.(`[SSE] Reconnection failed: ${String(error)}`);
401
- await this.attemptReconnect();
402
- }
403
- }
404
-
405
- async close() {
406
- this.aborted = true;
407
- this.isConnected = false;
408
- this.streamController?.abort();
409
-
410
- try {
411
- const unsubscribes = this.subscriptions.map((sub) => ({
412
- id: sub.id,
413
- action: "unsubscribe",
414
- subscription: sub.id,
415
- }));
416
-
417
- {
418
- const { response, release } = await this.putChannelPayload(unsubscribes, {
419
- timeoutMs: 30_000,
420
- auditContext: "tlon-urbit-unsubscribe",
421
- });
422
- try {
423
- void response.body?.cancel();
424
- } finally {
425
- await release();
426
- }
427
- }
428
-
429
- {
430
- const { response, release } = await urbitFetch({
431
- baseUrl: this.url,
432
- path: `/~/channel/${this.channelId}`,
433
- init: {
434
- method: "DELETE",
435
- headers: {
436
- Cookie: this.cookie,
437
- },
438
- },
439
- ssrfPolicy: this.ssrfPolicy,
440
- lookupFn: this.lookupFn,
441
- fetchImpl: this.fetchImpl,
442
- timeoutMs: 30_000,
443
- auditContext: "tlon-urbit-channel-close",
444
- });
445
- try {
446
- void response.body?.cancel();
447
- } finally {
448
- await release();
449
- }
450
- }
451
- } catch (error) {
452
- this.logger.error?.(`Error closing channel: ${String(error)}`);
453
- }
454
-
455
- if (this.streamRelease) {
456
- const release = this.streamRelease;
457
- this.streamRelease = null;
458
- await release();
459
- }
460
- }
461
-
462
- private async putChannelPayload(
463
- payload: unknown,
464
- params: { timeoutMs: number; auditContext: string },
465
- ) {
466
- return await urbitFetch({
467
- baseUrl: this.url,
468
- path: `/~/channel/${this.channelId}`,
469
- init: {
470
- method: "PUT",
471
- headers: {
472
- "Content-Type": "application/json",
473
- Cookie: this.cookie,
474
- },
475
- body: JSON.stringify(payload),
476
- },
477
- ssrfPolicy: this.ssrfPolicy,
478
- lookupFn: this.lookupFn,
479
- fetchImpl: this.fetchImpl,
480
- timeoutMs: params.timeoutMs,
481
- auditContext: params.auditContext,
482
- });
483
- }
484
- }