@openclaw/tlon 2026.2.21

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.
@@ -0,0 +1,131 @@
1
+ import { scot, da } from "@urbit/aura";
2
+
3
+ export type TlonPokeApi = {
4
+ poke: (params: { app: string; mark: string; json: unknown }) => Promise<unknown>;
5
+ };
6
+
7
+ type SendTextParams = {
8
+ api: TlonPokeApi;
9
+ fromShip: string;
10
+ toShip: string;
11
+ text: string;
12
+ };
13
+
14
+ export async function sendDm({ api, fromShip, toShip, text }: SendTextParams) {
15
+ const story = [{ inline: [text] }];
16
+ const sentAt = Date.now();
17
+ const idUd = scot("ud", da.fromUnix(sentAt));
18
+ const id = `${fromShip}/${idUd}`;
19
+
20
+ const delta = {
21
+ add: {
22
+ memo: {
23
+ content: story,
24
+ author: fromShip,
25
+ sent: sentAt,
26
+ },
27
+ kind: null,
28
+ time: null,
29
+ },
30
+ };
31
+
32
+ const action = {
33
+ ship: toShip,
34
+ diff: { id, delta },
35
+ };
36
+
37
+ await api.poke({
38
+ app: "chat",
39
+ mark: "chat-dm-action",
40
+ json: action,
41
+ });
42
+
43
+ return { channel: "tlon", messageId: id };
44
+ }
45
+
46
+ type SendGroupParams = {
47
+ api: TlonPokeApi;
48
+ fromShip: string;
49
+ hostShip: string;
50
+ channelName: string;
51
+ text: string;
52
+ replyToId?: string | null;
53
+ };
54
+
55
+ export async function sendGroupMessage({
56
+ api,
57
+ fromShip,
58
+ hostShip,
59
+ channelName,
60
+ text,
61
+ replyToId,
62
+ }: SendGroupParams) {
63
+ const story = [{ inline: [text] }];
64
+ const sentAt = Date.now();
65
+
66
+ // Format reply ID as @ud (with dots) - required for Tlon to recognize thread replies
67
+ let formattedReplyId = replyToId;
68
+ if (replyToId && /^\d+$/.test(replyToId)) {
69
+ try {
70
+ formattedReplyId = scot("ud", BigInt(replyToId));
71
+ } catch {
72
+ // Fall back to raw ID if formatting fails
73
+ }
74
+ }
75
+
76
+ const action = {
77
+ channel: {
78
+ nest: `chat/${hostShip}/${channelName}`,
79
+ action: formattedReplyId
80
+ ? {
81
+ // Thread reply - needs post wrapper around reply action
82
+ // ReplyActionAdd takes Memo: {content, author, sent} - no kind/blob/meta
83
+ post: {
84
+ reply: {
85
+ id: formattedReplyId,
86
+ action: {
87
+ add: {
88
+ content: story,
89
+ author: fromShip,
90
+ sent: sentAt,
91
+ },
92
+ },
93
+ },
94
+ },
95
+ }
96
+ : {
97
+ // Regular post
98
+ post: {
99
+ add: {
100
+ content: story,
101
+ author: fromShip,
102
+ sent: sentAt,
103
+ kind: "/chat",
104
+ blob: null,
105
+ meta: null,
106
+ },
107
+ },
108
+ },
109
+ },
110
+ };
111
+
112
+ await api.poke({
113
+ app: "channels",
114
+ mark: "channel-action-1",
115
+ json: action,
116
+ });
117
+
118
+ return { channel: "tlon", messageId: `${fromShip}/${sentAt}` };
119
+ }
120
+
121
+ export function buildMediaText(text: string | undefined, mediaUrl: string | undefined): string {
122
+ const cleanText = text?.trim() ?? "";
123
+ const cleanUrl = mediaUrl?.trim() ?? "";
124
+ if (cleanText && cleanUrl) {
125
+ return `${cleanText}\n${cleanUrl}`;
126
+ }
127
+ if (cleanUrl) {
128
+ return cleanUrl;
129
+ }
130
+ return cleanText;
131
+ }
@@ -0,0 +1,44 @@
1
+ import type { LookupFn } from "openclaw/plugin-sdk";
2
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
3
+ import { UrbitSSEClient } from "./sse-client.js";
4
+
5
+ const mockFetch = vi.fn();
6
+
7
+ describe("UrbitSSEClient", () => {
8
+ beforeEach(() => {
9
+ vi.stubGlobal("fetch", mockFetch);
10
+ mockFetch.mockReset();
11
+ });
12
+
13
+ afterEach(() => {
14
+ vi.unstubAllGlobals();
15
+ });
16
+
17
+ it("sends subscriptions added after connect", async () => {
18
+ mockFetch.mockResolvedValue({ ok: true, status: 200, text: async () => "" });
19
+ const lookupFn = (async () => [{ address: "1.1.1.1", family: 4 }]) as unknown as LookupFn;
20
+
21
+ const client = new UrbitSSEClient("https://example.com", "urbauth-~zod=123", {
22
+ lookupFn,
23
+ });
24
+ (client as { isConnected: boolean }).isConnected = true;
25
+
26
+ await client.subscribe({
27
+ app: "chat",
28
+ path: "/dm/~zod",
29
+ event: () => {},
30
+ });
31
+
32
+ expect(mockFetch).toHaveBeenCalledTimes(1);
33
+ const [url, init] = mockFetch.mock.calls[0];
34
+ expect(url).toBe(client.channelUrl);
35
+ expect(init.method).toBe("PUT");
36
+ const body = JSON.parse(init.body as string);
37
+ expect(body).toHaveLength(1);
38
+ expect(body[0]).toMatchObject({
39
+ action: "subscribe",
40
+ app: "chat",
41
+ path: "/dm/~zod",
42
+ });
43
+ });
44
+ });
@@ -0,0 +1,430 @@
1
+ import { Readable } from "node:stream";
2
+ import type { LookupFn, SsrFPolicy } from "openclaw/plugin-sdk";
3
+ import { ensureUrbitChannelOpen, pokeUrbitChannel, scryUrbitPath } from "./channel-ops.js";
4
+ import { getUrbitContext, normalizeUrbitCookie } from "./context.js";
5
+ import { urbitFetch } from "./fetch.js";
6
+
7
+ export type UrbitSseLogger = {
8
+ log?: (message: string) => void;
9
+ error?: (message: string) => void;
10
+ };
11
+
12
+ type UrbitSseOptions = {
13
+ ship?: string;
14
+ ssrfPolicy?: SsrFPolicy;
15
+ lookupFn?: LookupFn;
16
+ fetchImpl?: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
17
+ onReconnect?: (client: UrbitSSEClient) => Promise<void> | void;
18
+ autoReconnect?: boolean;
19
+ maxReconnectAttempts?: number;
20
+ reconnectDelay?: number;
21
+ maxReconnectDelay?: number;
22
+ logger?: UrbitSseLogger;
23
+ };
24
+
25
+ export class UrbitSSEClient {
26
+ url: string;
27
+ cookie: string;
28
+ ship: string;
29
+ channelId: string;
30
+ channelUrl: string;
31
+ subscriptions: Array<{
32
+ id: number;
33
+ action: "subscribe";
34
+ ship: string;
35
+ app: string;
36
+ path: string;
37
+ }> = [];
38
+ eventHandlers = new Map<
39
+ number,
40
+ { event?: (data: unknown) => void; err?: (error: unknown) => void; quit?: () => void }
41
+ >();
42
+ aborted = false;
43
+ streamController: AbortController | null = null;
44
+ onReconnect: UrbitSseOptions["onReconnect"] | null;
45
+ autoReconnect: boolean;
46
+ reconnectAttempts = 0;
47
+ maxReconnectAttempts: number;
48
+ reconnectDelay: number;
49
+ maxReconnectDelay: number;
50
+ isConnected = false;
51
+ logger: UrbitSseLogger;
52
+ ssrfPolicy?: SsrFPolicy;
53
+ lookupFn?: LookupFn;
54
+ fetchImpl?: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
55
+ streamRelease: (() => Promise<void>) | null = null;
56
+
57
+ constructor(url: string, cookie: string, options: UrbitSseOptions = {}) {
58
+ const ctx = getUrbitContext(url, options.ship);
59
+ this.url = ctx.baseUrl;
60
+ this.cookie = normalizeUrbitCookie(cookie);
61
+ this.ship = ctx.ship;
62
+ this.channelId = `${Math.floor(Date.now() / 1000)}-${Math.random().toString(36).substring(2, 8)}`;
63
+ this.channelUrl = new URL(`/~/channel/${this.channelId}`, this.url).toString();
64
+ this.onReconnect = options.onReconnect ?? null;
65
+ this.autoReconnect = options.autoReconnect !== false;
66
+ this.maxReconnectAttempts = options.maxReconnectAttempts ?? 10;
67
+ this.reconnectDelay = options.reconnectDelay ?? 1000;
68
+ this.maxReconnectDelay = options.maxReconnectDelay ?? 30000;
69
+ this.logger = options.logger ?? {};
70
+ this.ssrfPolicy = options.ssrfPolicy;
71
+ this.lookupFn = options.lookupFn;
72
+ this.fetchImpl = options.fetchImpl;
73
+ }
74
+
75
+ async subscribe(params: {
76
+ app: string;
77
+ path: string;
78
+ event?: (data: unknown) => void;
79
+ err?: (error: unknown) => void;
80
+ quit?: () => void;
81
+ }) {
82
+ const subId = this.subscriptions.length + 1;
83
+ const subscription = {
84
+ id: subId,
85
+ action: "subscribe",
86
+ ship: this.ship,
87
+ app: params.app,
88
+ path: params.path,
89
+ } as const;
90
+
91
+ this.subscriptions.push(subscription);
92
+ this.eventHandlers.set(subId, { event: params.event, err: params.err, quit: params.quit });
93
+
94
+ if (this.isConnected) {
95
+ try {
96
+ await this.sendSubscription(subscription);
97
+ } catch (error) {
98
+ const handler = this.eventHandlers.get(subId);
99
+ handler?.err?.(error);
100
+ }
101
+ }
102
+ return subId;
103
+ }
104
+
105
+ private async sendSubscription(subscription: {
106
+ id: number;
107
+ action: "subscribe";
108
+ ship: string;
109
+ app: string;
110
+ path: string;
111
+ }) {
112
+ const { response, release } = await urbitFetch({
113
+ baseUrl: this.url,
114
+ path: `/~/channel/${this.channelId}`,
115
+ init: {
116
+ method: "PUT",
117
+ headers: {
118
+ "Content-Type": "application/json",
119
+ Cookie: this.cookie,
120
+ },
121
+ body: JSON.stringify([subscription]),
122
+ },
123
+ ssrfPolicy: this.ssrfPolicy,
124
+ lookupFn: this.lookupFn,
125
+ fetchImpl: this.fetchImpl,
126
+ timeoutMs: 30_000,
127
+ auditContext: "tlon-urbit-subscribe",
128
+ });
129
+
130
+ try {
131
+ if (!response.ok && response.status !== 204) {
132
+ const errorText = await response.text().catch(() => "");
133
+ throw new Error(
134
+ `Subscribe failed: ${response.status}${errorText ? ` - ${errorText}` : ""}`,
135
+ );
136
+ }
137
+ } finally {
138
+ await release();
139
+ }
140
+ }
141
+
142
+ async connect() {
143
+ await ensureUrbitChannelOpen(
144
+ {
145
+ baseUrl: this.url,
146
+ cookie: this.cookie,
147
+ ship: this.ship,
148
+ channelId: this.channelId,
149
+ ssrfPolicy: this.ssrfPolicy,
150
+ lookupFn: this.lookupFn,
151
+ fetchImpl: this.fetchImpl,
152
+ },
153
+ {
154
+ createBody: this.subscriptions,
155
+ createAuditContext: "tlon-urbit-channel-create",
156
+ },
157
+ );
158
+
159
+ await this.openStream();
160
+ this.isConnected = true;
161
+ this.reconnectAttempts = 0;
162
+ }
163
+
164
+ async openStream() {
165
+ // Use AbortController with manual timeout so we only abort during initial connection,
166
+ // not after the SSE stream is established and actively streaming.
167
+ const controller = new AbortController();
168
+ const timeoutId = setTimeout(() => controller.abort(), 60_000);
169
+
170
+ this.streamController = controller;
171
+
172
+ const { response, release } = await urbitFetch({
173
+ baseUrl: this.url,
174
+ path: `/~/channel/${this.channelId}`,
175
+ init: {
176
+ method: "GET",
177
+ headers: {
178
+ Accept: "text/event-stream",
179
+ Cookie: this.cookie,
180
+ },
181
+ },
182
+ ssrfPolicy: this.ssrfPolicy,
183
+ lookupFn: this.lookupFn,
184
+ fetchImpl: this.fetchImpl,
185
+ signal: controller.signal,
186
+ auditContext: "tlon-urbit-sse-stream",
187
+ });
188
+
189
+ this.streamRelease = release;
190
+
191
+ // Clear timeout once connection established (headers received).
192
+ clearTimeout(timeoutId);
193
+
194
+ if (!response.ok) {
195
+ await release();
196
+ this.streamRelease = null;
197
+ throw new Error(`Stream connection failed: ${response.status}`);
198
+ }
199
+
200
+ this.processStream(response.body).catch((error) => {
201
+ if (!this.aborted) {
202
+ this.logger.error?.(`Stream error: ${String(error)}`);
203
+ for (const { err } of this.eventHandlers.values()) {
204
+ if (err) {
205
+ err(error);
206
+ }
207
+ }
208
+ }
209
+ });
210
+ }
211
+
212
+ async processStream(body: ReadableStream<Uint8Array> | Readable | null) {
213
+ if (!body) {
214
+ return;
215
+ }
216
+ // oxlint-disable-next-line typescript/no-explicit-any
217
+ const stream = body instanceof ReadableStream ? Readable.fromWeb(body as any) : body;
218
+ let buffer = "";
219
+
220
+ try {
221
+ for await (const chunk of stream) {
222
+ if (this.aborted) {
223
+ break;
224
+ }
225
+ buffer += chunk.toString();
226
+ let eventEnd;
227
+ while ((eventEnd = buffer.indexOf("\n\n")) !== -1) {
228
+ const eventData = buffer.substring(0, eventEnd);
229
+ buffer = buffer.substring(eventEnd + 2);
230
+ this.processEvent(eventData);
231
+ }
232
+ }
233
+ } finally {
234
+ if (this.streamRelease) {
235
+ const release = this.streamRelease;
236
+ this.streamRelease = null;
237
+ await release();
238
+ }
239
+ this.streamController = null;
240
+ if (!this.aborted && this.autoReconnect) {
241
+ this.isConnected = false;
242
+ this.logger.log?.("[SSE] Stream ended, attempting reconnection...");
243
+ await this.attemptReconnect();
244
+ }
245
+ }
246
+ }
247
+
248
+ processEvent(eventData: string) {
249
+ const lines = eventData.split("\n");
250
+ let data: string | null = null;
251
+
252
+ for (const line of lines) {
253
+ if (line.startsWith("data: ")) {
254
+ data = line.substring(6);
255
+ }
256
+ }
257
+
258
+ if (!data) {
259
+ return;
260
+ }
261
+
262
+ try {
263
+ const parsed = JSON.parse(data) as { id?: number; json?: unknown; response?: string };
264
+
265
+ if (parsed.response === "quit") {
266
+ if (parsed.id) {
267
+ const handlers = this.eventHandlers.get(parsed.id);
268
+ if (handlers?.quit) {
269
+ handlers.quit();
270
+ }
271
+ }
272
+ return;
273
+ }
274
+
275
+ if (parsed.id && this.eventHandlers.has(parsed.id)) {
276
+ const { event } = this.eventHandlers.get(parsed.id) ?? {};
277
+ if (event && parsed.json) {
278
+ event(parsed.json);
279
+ }
280
+ } else if (parsed.json) {
281
+ for (const { event } of this.eventHandlers.values()) {
282
+ if (event) {
283
+ event(parsed.json);
284
+ }
285
+ }
286
+ }
287
+ } catch (error) {
288
+ this.logger.error?.(`Error parsing SSE event: ${String(error)}`);
289
+ }
290
+ }
291
+
292
+ async poke(params: { app: string; mark: string; json: unknown }) {
293
+ return await pokeUrbitChannel(
294
+ {
295
+ baseUrl: this.url,
296
+ cookie: this.cookie,
297
+ ship: this.ship,
298
+ channelId: this.channelId,
299
+ ssrfPolicy: this.ssrfPolicy,
300
+ lookupFn: this.lookupFn,
301
+ fetchImpl: this.fetchImpl,
302
+ },
303
+ { ...params, auditContext: "tlon-urbit-poke" },
304
+ );
305
+ }
306
+
307
+ async scry(path: string) {
308
+ return await scryUrbitPath(
309
+ {
310
+ baseUrl: this.url,
311
+ cookie: this.cookie,
312
+ ssrfPolicy: this.ssrfPolicy,
313
+ lookupFn: this.lookupFn,
314
+ fetchImpl: this.fetchImpl,
315
+ },
316
+ { path, auditContext: "tlon-urbit-scry" },
317
+ );
318
+ }
319
+
320
+ async attemptReconnect() {
321
+ if (this.aborted || !this.autoReconnect) {
322
+ this.logger.log?.("[SSE] Reconnection aborted or disabled");
323
+ return;
324
+ }
325
+
326
+ if (this.reconnectAttempts >= this.maxReconnectAttempts) {
327
+ this.logger.error?.(
328
+ `[SSE] Max reconnection attempts (${this.maxReconnectAttempts}) reached. Giving up.`,
329
+ );
330
+ return;
331
+ }
332
+
333
+ this.reconnectAttempts += 1;
334
+ const delay = Math.min(
335
+ this.reconnectDelay * Math.pow(2, this.reconnectAttempts - 1),
336
+ this.maxReconnectDelay,
337
+ );
338
+
339
+ this.logger.log?.(
340
+ `[SSE] Reconnection attempt ${this.reconnectAttempts}/${this.maxReconnectAttempts} in ${delay}ms...`,
341
+ );
342
+
343
+ await new Promise((resolve) => setTimeout(resolve, delay));
344
+
345
+ try {
346
+ this.channelId = `${Math.floor(Date.now() / 1000)}-${Math.random().toString(36).substring(2, 8)}`;
347
+ this.channelUrl = new URL(`/~/channel/${this.channelId}`, this.url).toString();
348
+
349
+ if (this.onReconnect) {
350
+ await this.onReconnect(this);
351
+ }
352
+
353
+ await this.connect();
354
+ this.logger.log?.("[SSE] Reconnection successful!");
355
+ } catch (error) {
356
+ this.logger.error?.(`[SSE] Reconnection failed: ${String(error)}`);
357
+ await this.attemptReconnect();
358
+ }
359
+ }
360
+
361
+ async close() {
362
+ this.aborted = true;
363
+ this.isConnected = false;
364
+ this.streamController?.abort();
365
+
366
+ try {
367
+ const unsubscribes = this.subscriptions.map((sub) => ({
368
+ id: sub.id,
369
+ action: "unsubscribe",
370
+ subscription: sub.id,
371
+ }));
372
+
373
+ {
374
+ const { response, release } = await urbitFetch({
375
+ baseUrl: this.url,
376
+ path: `/~/channel/${this.channelId}`,
377
+ init: {
378
+ method: "PUT",
379
+ headers: {
380
+ "Content-Type": "application/json",
381
+ Cookie: this.cookie,
382
+ },
383
+ body: JSON.stringify(unsubscribes),
384
+ },
385
+ ssrfPolicy: this.ssrfPolicy,
386
+ lookupFn: this.lookupFn,
387
+ fetchImpl: this.fetchImpl,
388
+ timeoutMs: 30_000,
389
+ auditContext: "tlon-urbit-unsubscribe",
390
+ });
391
+ try {
392
+ void response.body?.cancel();
393
+ } finally {
394
+ await release();
395
+ }
396
+ }
397
+
398
+ {
399
+ const { response, release } = await urbitFetch({
400
+ baseUrl: this.url,
401
+ path: `/~/channel/${this.channelId}`,
402
+ init: {
403
+ method: "DELETE",
404
+ headers: {
405
+ Cookie: this.cookie,
406
+ },
407
+ },
408
+ ssrfPolicy: this.ssrfPolicy,
409
+ lookupFn: this.lookupFn,
410
+ fetchImpl: this.fetchImpl,
411
+ timeoutMs: 30_000,
412
+ auditContext: "tlon-urbit-channel-close",
413
+ });
414
+ try {
415
+ void response.body?.cancel();
416
+ } finally {
417
+ await release();
418
+ }
419
+ }
420
+ } catch (error) {
421
+ this.logger.error?.(`Error closing channel: ${String(error)}`);
422
+ }
423
+
424
+ if (this.streamRelease) {
425
+ const release = this.streamRelease;
426
+ this.streamRelease = null;
427
+ await release();
428
+ }
429
+ }
430
+ }