@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.
- package/README.md +5 -0
- package/index.ts +17 -0
- package/openclaw.plugin.json +9 -0
- package/package.json +32 -0
- package/src/account-fields.ts +25 -0
- package/src/channel.ts +384 -0
- package/src/config-schema.test.ts +31 -0
- package/src/config-schema.ts +47 -0
- package/src/monitor/discovery.ts +78 -0
- package/src/monitor/history.ts +92 -0
- package/src/monitor/index.ts +603 -0
- package/src/monitor/processed-messages.test.ts +23 -0
- package/src/monitor/processed-messages.ts +46 -0
- package/src/monitor/utils.ts +106 -0
- package/src/onboarding.ts +229 -0
- package/src/runtime.ts +14 -0
- package/src/targets.ts +89 -0
- package/src/types.ts +99 -0
- package/src/urbit/auth.ssrf.test.ts +44 -0
- package/src/urbit/auth.ts +48 -0
- package/src/urbit/base-url.test.ts +41 -0
- package/src/urbit/base-url.ts +57 -0
- package/src/urbit/channel-client.ts +157 -0
- package/src/urbit/channel-ops.ts +164 -0
- package/src/urbit/context.ts +47 -0
- package/src/urbit/errors.ts +51 -0
- package/src/urbit/fetch.ts +39 -0
- package/src/urbit/send.test.ts +38 -0
- package/src/urbit/send.ts +131 -0
- package/src/urbit/sse-client.test.ts +44 -0
- package/src/urbit/sse-client.ts +430 -0
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import type { RuntimeEnv } from "openclaw/plugin-sdk";
|
|
2
|
+
import { extractMessageText } from "./utils.js";
|
|
3
|
+
|
|
4
|
+
export type TlonHistoryEntry = {
|
|
5
|
+
author: string;
|
|
6
|
+
content: string;
|
|
7
|
+
timestamp: number;
|
|
8
|
+
id?: string;
|
|
9
|
+
};
|
|
10
|
+
|
|
11
|
+
const messageCache = new Map<string, TlonHistoryEntry[]>();
|
|
12
|
+
const MAX_CACHED_MESSAGES = 100;
|
|
13
|
+
|
|
14
|
+
export function cacheMessage(channelNest: string, message: TlonHistoryEntry) {
|
|
15
|
+
if (!messageCache.has(channelNest)) {
|
|
16
|
+
messageCache.set(channelNest, []);
|
|
17
|
+
}
|
|
18
|
+
const cache = messageCache.get(channelNest);
|
|
19
|
+
if (!cache) {
|
|
20
|
+
return;
|
|
21
|
+
}
|
|
22
|
+
cache.unshift(message);
|
|
23
|
+
if (cache.length > MAX_CACHED_MESSAGES) {
|
|
24
|
+
cache.pop();
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export async function fetchChannelHistory(
|
|
29
|
+
api: { scry: (path: string) => Promise<unknown> },
|
|
30
|
+
channelNest: string,
|
|
31
|
+
count = 50,
|
|
32
|
+
runtime?: RuntimeEnv,
|
|
33
|
+
): Promise<TlonHistoryEntry[]> {
|
|
34
|
+
try {
|
|
35
|
+
const scryPath = `/channels/v4/${channelNest}/posts/newest/${count}/outline.json`;
|
|
36
|
+
runtime?.log?.(`[tlon] Fetching history: ${scryPath}`);
|
|
37
|
+
|
|
38
|
+
// oxlint-disable-next-line typescript/no-explicit-any
|
|
39
|
+
const data: any = await api.scry(scryPath);
|
|
40
|
+
if (!data) {
|
|
41
|
+
return [];
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// oxlint-disable-next-line typescript/no-explicit-any
|
|
45
|
+
let posts: any[] = [];
|
|
46
|
+
if (Array.isArray(data)) {
|
|
47
|
+
posts = data;
|
|
48
|
+
} else if (data.posts && typeof data.posts === "object") {
|
|
49
|
+
posts = Object.values(data.posts);
|
|
50
|
+
} else if (typeof data === "object") {
|
|
51
|
+
posts = Object.values(data);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
const messages = posts
|
|
55
|
+
.map((item) => {
|
|
56
|
+
const essay = item.essay || item["r-post"]?.set?.essay;
|
|
57
|
+
const seal = item.seal || item["r-post"]?.set?.seal;
|
|
58
|
+
|
|
59
|
+
return {
|
|
60
|
+
author: essay?.author || "unknown",
|
|
61
|
+
content: extractMessageText(essay?.content || []),
|
|
62
|
+
timestamp: essay?.sent || Date.now(),
|
|
63
|
+
id: seal?.id,
|
|
64
|
+
} as TlonHistoryEntry;
|
|
65
|
+
})
|
|
66
|
+
.filter((msg) => msg.content);
|
|
67
|
+
|
|
68
|
+
runtime?.log?.(`[tlon] Extracted ${messages.length} messages from history`);
|
|
69
|
+
return messages;
|
|
70
|
+
} catch (error) {
|
|
71
|
+
runtime?.log?.(
|
|
72
|
+
`[tlon] Error fetching channel history: ${(error as { message?: string })?.message ?? String(error)}`,
|
|
73
|
+
);
|
|
74
|
+
return [];
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export async function getChannelHistory(
|
|
79
|
+
api: { scry: (path: string) => Promise<unknown> },
|
|
80
|
+
channelNest: string,
|
|
81
|
+
count = 50,
|
|
82
|
+
runtime?: RuntimeEnv,
|
|
83
|
+
): Promise<TlonHistoryEntry[]> {
|
|
84
|
+
const cache = messageCache.get(channelNest) ?? [];
|
|
85
|
+
if (cache.length >= count) {
|
|
86
|
+
runtime?.log?.(`[tlon] Using cached messages (${cache.length} available)`);
|
|
87
|
+
return cache.slice(0, count);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
runtime?.log?.(`[tlon] Cache has ${cache.length} messages, need ${count}, fetching from scry...`);
|
|
91
|
+
return await fetchChannelHistory(api, channelNest, count, runtime);
|
|
92
|
+
}
|
|
@@ -0,0 +1,603 @@
|
|
|
1
|
+
import { format } from "node:util";
|
|
2
|
+
import type { RuntimeEnv, ReplyPayload, OpenClawConfig } from "openclaw/plugin-sdk";
|
|
3
|
+
import { createReplyPrefixOptions } from "openclaw/plugin-sdk";
|
|
4
|
+
import { getTlonRuntime } from "../runtime.js";
|
|
5
|
+
import { normalizeShip, parseChannelNest } from "../targets.js";
|
|
6
|
+
import { resolveTlonAccount } from "../types.js";
|
|
7
|
+
import { authenticate } from "../urbit/auth.js";
|
|
8
|
+
import { ssrfPolicyFromAllowPrivateNetwork } from "../urbit/context.js";
|
|
9
|
+
import { sendDm, sendGroupMessage } from "../urbit/send.js";
|
|
10
|
+
import { UrbitSSEClient } from "../urbit/sse-client.js";
|
|
11
|
+
import { fetchAllChannels } from "./discovery.js";
|
|
12
|
+
import { cacheMessage, getChannelHistory } from "./history.js";
|
|
13
|
+
import { createProcessedMessageTracker } from "./processed-messages.js";
|
|
14
|
+
import {
|
|
15
|
+
extractMessageText,
|
|
16
|
+
formatModelName,
|
|
17
|
+
isBotMentioned,
|
|
18
|
+
isDmAllowed,
|
|
19
|
+
isSummarizationRequest,
|
|
20
|
+
} from "./utils.js";
|
|
21
|
+
|
|
22
|
+
function formatError(err: unknown): string {
|
|
23
|
+
if (err instanceof Error) return err.message;
|
|
24
|
+
return String(err);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export type MonitorTlonOpts = {
|
|
28
|
+
runtime?: RuntimeEnv;
|
|
29
|
+
abortSignal?: AbortSignal;
|
|
30
|
+
accountId?: string | null;
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
type ChannelAuthorization = {
|
|
34
|
+
mode?: "restricted" | "open";
|
|
35
|
+
allowedShips?: string[];
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
type UrbitMemo = {
|
|
39
|
+
author?: string;
|
|
40
|
+
content?: unknown;
|
|
41
|
+
sent?: number;
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
type UrbitSeal = {
|
|
45
|
+
"parent-id"?: string;
|
|
46
|
+
parent?: string;
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
type UrbitUpdate = {
|
|
50
|
+
id?: string | number;
|
|
51
|
+
response?: {
|
|
52
|
+
add?: { memo?: UrbitMemo };
|
|
53
|
+
post?: {
|
|
54
|
+
id?: string | number;
|
|
55
|
+
"r-post"?: {
|
|
56
|
+
set?: { essay?: UrbitMemo; seal?: UrbitSeal };
|
|
57
|
+
reply?: {
|
|
58
|
+
id?: string | number;
|
|
59
|
+
"r-reply"?: { set?: { memo?: UrbitMemo; seal?: UrbitSeal } };
|
|
60
|
+
};
|
|
61
|
+
};
|
|
62
|
+
};
|
|
63
|
+
};
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
function resolveChannelAuthorization(
|
|
67
|
+
cfg: OpenClawConfig,
|
|
68
|
+
channelNest: string,
|
|
69
|
+
): { mode: "restricted" | "open"; allowedShips: string[] } {
|
|
70
|
+
const tlonConfig = cfg.channels?.tlon as
|
|
71
|
+
| {
|
|
72
|
+
authorization?: { channelRules?: Record<string, ChannelAuthorization> };
|
|
73
|
+
defaultAuthorizedShips?: string[];
|
|
74
|
+
}
|
|
75
|
+
| undefined;
|
|
76
|
+
const rules = tlonConfig?.authorization?.channelRules ?? {};
|
|
77
|
+
const rule = rules[channelNest];
|
|
78
|
+
const allowedShips = rule?.allowedShips ?? tlonConfig?.defaultAuthorizedShips ?? [];
|
|
79
|
+
const mode = rule?.mode ?? "restricted";
|
|
80
|
+
return { mode, allowedShips };
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export async function monitorTlonProvider(opts: MonitorTlonOpts = {}): Promise<void> {
|
|
84
|
+
const core = getTlonRuntime();
|
|
85
|
+
const cfg = core.config.loadConfig();
|
|
86
|
+
if (cfg.channels?.tlon?.enabled === false) {
|
|
87
|
+
return;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
const logger = core.logging.getChildLogger({ module: "tlon-auto-reply" });
|
|
91
|
+
const formatRuntimeMessage = (...args: Parameters<RuntimeEnv["log"]>) => format(...args);
|
|
92
|
+
const runtime: RuntimeEnv = opts.runtime ?? {
|
|
93
|
+
log: (...args) => {
|
|
94
|
+
logger.info(formatRuntimeMessage(...args));
|
|
95
|
+
},
|
|
96
|
+
error: (...args) => {
|
|
97
|
+
logger.error(formatRuntimeMessage(...args));
|
|
98
|
+
},
|
|
99
|
+
exit: (code: number): never => {
|
|
100
|
+
throw new Error(`exit ${code}`);
|
|
101
|
+
},
|
|
102
|
+
};
|
|
103
|
+
|
|
104
|
+
const account = resolveTlonAccount(cfg, opts.accountId ?? undefined);
|
|
105
|
+
if (!account.enabled) {
|
|
106
|
+
return;
|
|
107
|
+
}
|
|
108
|
+
if (!account.configured || !account.ship || !account.url || !account.code) {
|
|
109
|
+
throw new Error("Tlon account not configured (ship/url/code required)");
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
const botShipName = normalizeShip(account.ship);
|
|
113
|
+
runtime.log?.(`[tlon] Starting monitor for ${botShipName}`);
|
|
114
|
+
|
|
115
|
+
let api: UrbitSSEClient | null = null;
|
|
116
|
+
try {
|
|
117
|
+
const ssrfPolicy = ssrfPolicyFromAllowPrivateNetwork(account.allowPrivateNetwork);
|
|
118
|
+
runtime.log?.(`[tlon] Attempting authentication to ${account.url}...`);
|
|
119
|
+
const cookie = await authenticate(account.url, account.code, { ssrfPolicy });
|
|
120
|
+
api = new UrbitSSEClient(account.url, cookie, {
|
|
121
|
+
ship: botShipName,
|
|
122
|
+
ssrfPolicy,
|
|
123
|
+
logger: {
|
|
124
|
+
log: (message) => runtime.log?.(message),
|
|
125
|
+
error: (message) => runtime.error?.(message),
|
|
126
|
+
},
|
|
127
|
+
});
|
|
128
|
+
} catch (error) {
|
|
129
|
+
runtime.error?.(`[tlon] Failed to authenticate: ${formatError(error)}`);
|
|
130
|
+
throw error;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
const processedTracker = createProcessedMessageTracker(2000);
|
|
134
|
+
let groupChannels: string[] = [];
|
|
135
|
+
|
|
136
|
+
if (account.autoDiscoverChannels !== false) {
|
|
137
|
+
try {
|
|
138
|
+
const discoveredChannels = await fetchAllChannels(api, runtime);
|
|
139
|
+
if (discoveredChannels.length > 0) {
|
|
140
|
+
groupChannels = discoveredChannels;
|
|
141
|
+
}
|
|
142
|
+
} catch (error) {
|
|
143
|
+
runtime.error?.(`[tlon] Auto-discovery failed: ${formatError(error)}`);
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
if (groupChannels.length === 0 && account.groupChannels.length > 0) {
|
|
148
|
+
groupChannels = account.groupChannels;
|
|
149
|
+
runtime.log?.(`[tlon] Using manual groupChannels config: ${groupChannels.join(", ")}`);
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
if (groupChannels.length > 0) {
|
|
153
|
+
runtime.log?.(
|
|
154
|
+
`[tlon] Monitoring ${groupChannels.length} group channel(s): ${groupChannels.join(", ")}`,
|
|
155
|
+
);
|
|
156
|
+
} else {
|
|
157
|
+
runtime.log?.("[tlon] No group channels to monitor (DMs only)");
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
const handleIncomingDM = async (update: UrbitUpdate) => {
|
|
161
|
+
try {
|
|
162
|
+
const memo = update?.response?.add?.memo;
|
|
163
|
+
if (!memo) {
|
|
164
|
+
return;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
const messageId = update.id != null ? String(update.id) : undefined;
|
|
168
|
+
if (!processedTracker.mark(messageId)) {
|
|
169
|
+
return;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
const senderShip = normalizeShip(memo.author ?? "");
|
|
173
|
+
if (!senderShip || senderShip === botShipName) {
|
|
174
|
+
return;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
const messageText = extractMessageText(memo.content);
|
|
178
|
+
if (!messageText) {
|
|
179
|
+
return;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
if (!isDmAllowed(senderShip, account.dmAllowlist)) {
|
|
183
|
+
runtime.log?.(`[tlon] Blocked DM from ${senderShip}: not in allowlist`);
|
|
184
|
+
return;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
await processMessage({
|
|
188
|
+
messageId: messageId ?? "",
|
|
189
|
+
senderShip,
|
|
190
|
+
messageText,
|
|
191
|
+
isGroup: false,
|
|
192
|
+
timestamp: memo.sent || Date.now(),
|
|
193
|
+
});
|
|
194
|
+
} catch (error) {
|
|
195
|
+
runtime.error?.(`[tlon] Error handling DM: ${formatError(error)}`);
|
|
196
|
+
}
|
|
197
|
+
};
|
|
198
|
+
|
|
199
|
+
const handleIncomingGroupMessage = (channelNest: string) => async (update: UrbitUpdate) => {
|
|
200
|
+
try {
|
|
201
|
+
const parsed = parseChannelNest(channelNest);
|
|
202
|
+
if (!parsed) {
|
|
203
|
+
return;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
const post = update?.response?.post?.["r-post"];
|
|
207
|
+
const essay = post?.set?.essay;
|
|
208
|
+
const memo = post?.reply?.["r-reply"]?.set?.memo;
|
|
209
|
+
if (!essay && !memo) {
|
|
210
|
+
return;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
const content = memo || essay;
|
|
214
|
+
if (!content) {
|
|
215
|
+
return;
|
|
216
|
+
}
|
|
217
|
+
const isThreadReply = Boolean(memo);
|
|
218
|
+
const rawMessageId = isThreadReply ? post?.reply?.id : update?.response?.post?.id;
|
|
219
|
+
const messageId = rawMessageId != null ? String(rawMessageId) : undefined;
|
|
220
|
+
|
|
221
|
+
if (!processedTracker.mark(messageId)) {
|
|
222
|
+
return;
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
const senderShip = normalizeShip(content.author ?? "");
|
|
226
|
+
if (!senderShip || senderShip === botShipName) {
|
|
227
|
+
return;
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
const messageText = extractMessageText(content.content);
|
|
231
|
+
if (!messageText) {
|
|
232
|
+
return;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
cacheMessage(channelNest, {
|
|
236
|
+
author: senderShip,
|
|
237
|
+
content: messageText,
|
|
238
|
+
timestamp: content.sent || Date.now(),
|
|
239
|
+
id: messageId,
|
|
240
|
+
});
|
|
241
|
+
|
|
242
|
+
const mentioned = isBotMentioned(messageText, botShipName);
|
|
243
|
+
if (!mentioned) {
|
|
244
|
+
return;
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
const { mode, allowedShips } = resolveChannelAuthorization(cfg, channelNest);
|
|
248
|
+
if (mode === "restricted") {
|
|
249
|
+
if (allowedShips.length === 0) {
|
|
250
|
+
runtime.log?.(`[tlon] Access denied: ${senderShip} in ${channelNest} (no allowlist)`);
|
|
251
|
+
return;
|
|
252
|
+
}
|
|
253
|
+
const normalizedAllowed = allowedShips.map(normalizeShip);
|
|
254
|
+
if (!normalizedAllowed.includes(senderShip)) {
|
|
255
|
+
runtime.log?.(
|
|
256
|
+
`[tlon] Access denied: ${senderShip} in ${channelNest} (allowed: ${allowedShips.join(", ")})`,
|
|
257
|
+
);
|
|
258
|
+
return;
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
const seal = isThreadReply
|
|
263
|
+
? update?.response?.post?.["r-post"]?.reply?.["r-reply"]?.set?.seal
|
|
264
|
+
: update?.response?.post?.["r-post"]?.set?.seal;
|
|
265
|
+
|
|
266
|
+
const parentId = seal?.["parent-id"] || seal?.parent || null;
|
|
267
|
+
|
|
268
|
+
await processMessage({
|
|
269
|
+
messageId: messageId ?? "",
|
|
270
|
+
senderShip,
|
|
271
|
+
messageText,
|
|
272
|
+
isGroup: true,
|
|
273
|
+
groupChannel: channelNest,
|
|
274
|
+
groupName: `${parsed.hostShip}/${parsed.channelName}`,
|
|
275
|
+
timestamp: content.sent || Date.now(),
|
|
276
|
+
parentId,
|
|
277
|
+
});
|
|
278
|
+
} catch (error) {
|
|
279
|
+
runtime.error?.(`[tlon] Error handling group message: ${formatError(error)}`);
|
|
280
|
+
}
|
|
281
|
+
};
|
|
282
|
+
|
|
283
|
+
const processMessage = async (params: {
|
|
284
|
+
messageId: string;
|
|
285
|
+
senderShip: string;
|
|
286
|
+
messageText: string;
|
|
287
|
+
isGroup: boolean;
|
|
288
|
+
groupChannel?: string;
|
|
289
|
+
groupName?: string;
|
|
290
|
+
timestamp: number;
|
|
291
|
+
parentId?: string | null;
|
|
292
|
+
}) => {
|
|
293
|
+
const { messageId, senderShip, isGroup, groupChannel, groupName, timestamp, parentId } = params;
|
|
294
|
+
let messageText = params.messageText;
|
|
295
|
+
|
|
296
|
+
if (isGroup && groupChannel && isSummarizationRequest(messageText)) {
|
|
297
|
+
try {
|
|
298
|
+
const history = await getChannelHistory(api, groupChannel, 50, runtime);
|
|
299
|
+
if (history.length === 0) {
|
|
300
|
+
const noHistoryMsg =
|
|
301
|
+
"I couldn't fetch any messages for this channel. It might be empty or there might be a permissions issue.";
|
|
302
|
+
if (isGroup) {
|
|
303
|
+
const parsed = parseChannelNest(groupChannel);
|
|
304
|
+
if (parsed) {
|
|
305
|
+
await sendGroupMessage({
|
|
306
|
+
api: api,
|
|
307
|
+
fromShip: botShipName,
|
|
308
|
+
hostShip: parsed.hostShip,
|
|
309
|
+
channelName: parsed.channelName,
|
|
310
|
+
text: noHistoryMsg,
|
|
311
|
+
});
|
|
312
|
+
}
|
|
313
|
+
} else {
|
|
314
|
+
await sendDm({
|
|
315
|
+
api: api,
|
|
316
|
+
fromShip: botShipName,
|
|
317
|
+
toShip: senderShip,
|
|
318
|
+
text: noHistoryMsg,
|
|
319
|
+
});
|
|
320
|
+
}
|
|
321
|
+
return;
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
const historyText = history
|
|
325
|
+
.map(
|
|
326
|
+
(msg) => `[${new Date(msg.timestamp).toLocaleString()}] ${msg.author}: ${msg.content}`,
|
|
327
|
+
)
|
|
328
|
+
.join("\n");
|
|
329
|
+
|
|
330
|
+
messageText =
|
|
331
|
+
`Please summarize this channel conversation (${history.length} recent messages):\n\n${historyText}\n\n` +
|
|
332
|
+
"Provide a concise summary highlighting:\n" +
|
|
333
|
+
"1. Main topics discussed\n" +
|
|
334
|
+
"2. Key decisions or conclusions\n" +
|
|
335
|
+
"3. Action items if any\n" +
|
|
336
|
+
"4. Notable participants";
|
|
337
|
+
} catch (error) {
|
|
338
|
+
const errorMsg = `Sorry, I encountered an error while fetching the channel history: ${formatError(error)}`;
|
|
339
|
+
if (isGroup && groupChannel) {
|
|
340
|
+
const parsed = parseChannelNest(groupChannel);
|
|
341
|
+
if (parsed) {
|
|
342
|
+
await sendGroupMessage({
|
|
343
|
+
api: api,
|
|
344
|
+
fromShip: botShipName,
|
|
345
|
+
hostShip: parsed.hostShip,
|
|
346
|
+
channelName: parsed.channelName,
|
|
347
|
+
text: errorMsg,
|
|
348
|
+
});
|
|
349
|
+
}
|
|
350
|
+
} else {
|
|
351
|
+
await sendDm({ api: api, fromShip: botShipName, toShip: senderShip, text: errorMsg });
|
|
352
|
+
}
|
|
353
|
+
return;
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
const route = core.channel.routing.resolveAgentRoute({
|
|
358
|
+
cfg,
|
|
359
|
+
channel: "tlon",
|
|
360
|
+
accountId: opts.accountId ?? undefined,
|
|
361
|
+
peer: {
|
|
362
|
+
kind: isGroup ? "group" : "direct",
|
|
363
|
+
id: isGroup ? (groupChannel ?? senderShip) : senderShip,
|
|
364
|
+
},
|
|
365
|
+
});
|
|
366
|
+
|
|
367
|
+
const fromLabel = isGroup ? `${senderShip} in ${groupName}` : senderShip;
|
|
368
|
+
const body = core.channel.reply.formatAgentEnvelope({
|
|
369
|
+
channel: "Tlon",
|
|
370
|
+
from: fromLabel,
|
|
371
|
+
timestamp,
|
|
372
|
+
body: messageText,
|
|
373
|
+
});
|
|
374
|
+
|
|
375
|
+
const ctxPayload = core.channel.reply.finalizeInboundContext({
|
|
376
|
+
Body: body,
|
|
377
|
+
BodyForAgent: messageText,
|
|
378
|
+
RawBody: messageText,
|
|
379
|
+
CommandBody: messageText,
|
|
380
|
+
From: isGroup ? `tlon:group:${groupChannel}` : `tlon:${senderShip}`,
|
|
381
|
+
To: `tlon:${botShipName}`,
|
|
382
|
+
SessionKey: route.sessionKey,
|
|
383
|
+
AccountId: route.accountId,
|
|
384
|
+
ChatType: isGroup ? "group" : "direct",
|
|
385
|
+
ConversationLabel: fromLabel,
|
|
386
|
+
SenderName: senderShip,
|
|
387
|
+
SenderId: senderShip,
|
|
388
|
+
Provider: "tlon",
|
|
389
|
+
Surface: "tlon",
|
|
390
|
+
MessageSid: messageId,
|
|
391
|
+
OriginatingChannel: "tlon",
|
|
392
|
+
OriginatingTo: `tlon:${isGroup ? groupChannel : botShipName}`,
|
|
393
|
+
});
|
|
394
|
+
|
|
395
|
+
const dispatchStartTime = Date.now();
|
|
396
|
+
|
|
397
|
+
const { onModelSelected, ...prefixOptions } = createReplyPrefixOptions({
|
|
398
|
+
cfg,
|
|
399
|
+
agentId: route.agentId,
|
|
400
|
+
channel: "tlon",
|
|
401
|
+
accountId: route.accountId,
|
|
402
|
+
});
|
|
403
|
+
const humanDelay = core.channel.reply.resolveHumanDelayConfig(cfg, route.agentId);
|
|
404
|
+
|
|
405
|
+
await core.channel.reply.dispatchReplyWithBufferedBlockDispatcher({
|
|
406
|
+
ctx: ctxPayload,
|
|
407
|
+
cfg,
|
|
408
|
+
dispatcherOptions: {
|
|
409
|
+
...prefixOptions,
|
|
410
|
+
humanDelay,
|
|
411
|
+
deliver: async (payload: ReplyPayload) => {
|
|
412
|
+
let replyText = payload.text;
|
|
413
|
+
if (!replyText) {
|
|
414
|
+
return;
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
const showSignature =
|
|
418
|
+
account.showModelSignature ?? cfg.channels?.tlon?.showModelSignature ?? false;
|
|
419
|
+
if (showSignature) {
|
|
420
|
+
const extPayload = payload as ReplyPayload & {
|
|
421
|
+
metadata?: { model?: string };
|
|
422
|
+
model?: string;
|
|
423
|
+
};
|
|
424
|
+
const extRoute = route as typeof route & { model?: string };
|
|
425
|
+
const modelInfo =
|
|
426
|
+
extPayload.metadata?.model ||
|
|
427
|
+
extPayload.model ||
|
|
428
|
+
extRoute.model ||
|
|
429
|
+
cfg.agents?.defaults?.model?.primary;
|
|
430
|
+
replyText = `${replyText}\n\n_[Generated by ${formatModelName(modelInfo)}]_`;
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
if (isGroup && groupChannel) {
|
|
434
|
+
const parsed = parseChannelNest(groupChannel);
|
|
435
|
+
if (!parsed) {
|
|
436
|
+
return;
|
|
437
|
+
}
|
|
438
|
+
await sendGroupMessage({
|
|
439
|
+
api: api,
|
|
440
|
+
fromShip: botShipName,
|
|
441
|
+
hostShip: parsed.hostShip,
|
|
442
|
+
channelName: parsed.channelName,
|
|
443
|
+
text: replyText,
|
|
444
|
+
replyToId: parentId ?? undefined,
|
|
445
|
+
});
|
|
446
|
+
} else {
|
|
447
|
+
await sendDm({ api: api, fromShip: botShipName, toShip: senderShip, text: replyText });
|
|
448
|
+
}
|
|
449
|
+
},
|
|
450
|
+
onError: (err, info) => {
|
|
451
|
+
const dispatchDuration = Date.now() - dispatchStartTime;
|
|
452
|
+
runtime.error?.(
|
|
453
|
+
`[tlon] ${info.kind} reply failed after ${dispatchDuration}ms: ${String(err)}`,
|
|
454
|
+
);
|
|
455
|
+
},
|
|
456
|
+
},
|
|
457
|
+
replyOptions: {
|
|
458
|
+
onModelSelected,
|
|
459
|
+
},
|
|
460
|
+
});
|
|
461
|
+
};
|
|
462
|
+
|
|
463
|
+
const subscribedChannels = new Set<string>();
|
|
464
|
+
const subscribedDMs = new Set<string>();
|
|
465
|
+
|
|
466
|
+
async function subscribeToChannel(channelNest: string) {
|
|
467
|
+
if (subscribedChannels.has(channelNest)) {
|
|
468
|
+
return;
|
|
469
|
+
}
|
|
470
|
+
const parsed = parseChannelNest(channelNest);
|
|
471
|
+
if (!parsed) {
|
|
472
|
+
runtime.error?.(`[tlon] Invalid channel format: ${channelNest}`);
|
|
473
|
+
return;
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
try {
|
|
477
|
+
await api!.subscribe({
|
|
478
|
+
app: "channels",
|
|
479
|
+
path: `/${channelNest}`,
|
|
480
|
+
event: (data: unknown) => {
|
|
481
|
+
handleIncomingGroupMessage(channelNest)(data as UrbitUpdate);
|
|
482
|
+
},
|
|
483
|
+
err: (error) => {
|
|
484
|
+
runtime.error?.(`[tlon] Group subscription error for ${channelNest}: ${String(error)}`);
|
|
485
|
+
},
|
|
486
|
+
quit: () => {
|
|
487
|
+
runtime.log?.(`[tlon] Group subscription ended for ${channelNest}`);
|
|
488
|
+
subscribedChannels.delete(channelNest);
|
|
489
|
+
},
|
|
490
|
+
});
|
|
491
|
+
subscribedChannels.add(channelNest);
|
|
492
|
+
runtime.log?.(`[tlon] Subscribed to group channel: ${channelNest}`);
|
|
493
|
+
} catch (error) {
|
|
494
|
+
runtime.error?.(`[tlon] Failed to subscribe to ${channelNest}: ${formatError(error)}`);
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
async function subscribeToDM(dmShip: string) {
|
|
499
|
+
if (subscribedDMs.has(dmShip)) {
|
|
500
|
+
return;
|
|
501
|
+
}
|
|
502
|
+
try {
|
|
503
|
+
await api!.subscribe({
|
|
504
|
+
app: "chat",
|
|
505
|
+
path: `/dm/${dmShip}`,
|
|
506
|
+
event: (data: unknown) => {
|
|
507
|
+
handleIncomingDM(data as UrbitUpdate);
|
|
508
|
+
},
|
|
509
|
+
err: (error) => {
|
|
510
|
+
runtime.error?.(`[tlon] DM subscription error for ${dmShip}: ${String(error)}`);
|
|
511
|
+
},
|
|
512
|
+
quit: () => {
|
|
513
|
+
runtime.log?.(`[tlon] DM subscription ended for ${dmShip}`);
|
|
514
|
+
subscribedDMs.delete(dmShip);
|
|
515
|
+
},
|
|
516
|
+
});
|
|
517
|
+
subscribedDMs.add(dmShip);
|
|
518
|
+
runtime.log?.(`[tlon] Subscribed to DM with ${dmShip}`);
|
|
519
|
+
} catch (error) {
|
|
520
|
+
runtime.error?.(`[tlon] Failed to subscribe to DM with ${dmShip}: ${formatError(error)}`);
|
|
521
|
+
}
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
async function refreshChannelSubscriptions() {
|
|
525
|
+
try {
|
|
526
|
+
const dmShips = await api!.scry("/chat/dm.json");
|
|
527
|
+
if (Array.isArray(dmShips)) {
|
|
528
|
+
for (const dmShip of dmShips) {
|
|
529
|
+
await subscribeToDM(dmShip);
|
|
530
|
+
}
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
if (account.autoDiscoverChannels !== false) {
|
|
534
|
+
const discoveredChannels = await fetchAllChannels(api!, runtime);
|
|
535
|
+
for (const channelNest of discoveredChannels) {
|
|
536
|
+
await subscribeToChannel(channelNest);
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
} catch (error) {
|
|
540
|
+
runtime.error?.(`[tlon] Channel refresh failed: ${formatError(error)}`);
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
try {
|
|
545
|
+
runtime.log?.("[tlon] Subscribing to updates...");
|
|
546
|
+
|
|
547
|
+
let dmShips: string[] = [];
|
|
548
|
+
try {
|
|
549
|
+
const dmList = await api.scry("/chat/dm.json");
|
|
550
|
+
if (Array.isArray(dmList)) {
|
|
551
|
+
dmShips = dmList;
|
|
552
|
+
runtime.log?.(`[tlon] Found ${dmShips.length} DM conversation(s)`);
|
|
553
|
+
}
|
|
554
|
+
} catch (error) {
|
|
555
|
+
runtime.error?.(`[tlon] Failed to fetch DM list: ${formatError(error)}`);
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
for (const dmShip of dmShips) {
|
|
559
|
+
await subscribeToDM(dmShip);
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
for (const channelNest of groupChannels) {
|
|
563
|
+
await subscribeToChannel(channelNest);
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
runtime.log?.("[tlon] All subscriptions registered, connecting to SSE stream...");
|
|
567
|
+
await api.connect();
|
|
568
|
+
runtime.log?.("[tlon] Connected! All subscriptions active");
|
|
569
|
+
|
|
570
|
+
const pollInterval = setInterval(
|
|
571
|
+
() => {
|
|
572
|
+
if (!opts.abortSignal?.aborted) {
|
|
573
|
+
refreshChannelSubscriptions().catch((error) => {
|
|
574
|
+
runtime.error?.(`[tlon] Channel refresh error: ${formatError(error)}`);
|
|
575
|
+
});
|
|
576
|
+
}
|
|
577
|
+
},
|
|
578
|
+
2 * 60 * 1000,
|
|
579
|
+
);
|
|
580
|
+
|
|
581
|
+
if (opts.abortSignal) {
|
|
582
|
+
const signal = opts.abortSignal;
|
|
583
|
+
await new Promise((resolve) => {
|
|
584
|
+
signal.addEventListener(
|
|
585
|
+
"abort",
|
|
586
|
+
() => {
|
|
587
|
+
clearInterval(pollInterval);
|
|
588
|
+
resolve(null);
|
|
589
|
+
},
|
|
590
|
+
{ once: true },
|
|
591
|
+
);
|
|
592
|
+
});
|
|
593
|
+
} else {
|
|
594
|
+
await new Promise(() => {});
|
|
595
|
+
}
|
|
596
|
+
} finally {
|
|
597
|
+
try {
|
|
598
|
+
await api?.close();
|
|
599
|
+
} catch (error) {
|
|
600
|
+
runtime.error?.(`[tlon] Cleanup error: ${formatError(error)}`);
|
|
601
|
+
}
|
|
602
|
+
}
|
|
603
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { describe, expect, it } from "vitest";
|
|
2
|
+
import { createProcessedMessageTracker } from "./processed-messages.js";
|
|
3
|
+
|
|
4
|
+
describe("createProcessedMessageTracker", () => {
|
|
5
|
+
it("dedupes and evicts oldest entries", () => {
|
|
6
|
+
const tracker = createProcessedMessageTracker(3);
|
|
7
|
+
|
|
8
|
+
expect(tracker.mark("a")).toBe(true);
|
|
9
|
+
expect(tracker.mark("a")).toBe(false);
|
|
10
|
+
expect(tracker.has("a")).toBe(true);
|
|
11
|
+
|
|
12
|
+
tracker.mark("b");
|
|
13
|
+
tracker.mark("c");
|
|
14
|
+
expect(tracker.size()).toBe(3);
|
|
15
|
+
|
|
16
|
+
tracker.mark("d");
|
|
17
|
+
expect(tracker.size()).toBe(3);
|
|
18
|
+
expect(tracker.has("a")).toBe(false);
|
|
19
|
+
expect(tracker.has("b")).toBe(true);
|
|
20
|
+
expect(tracker.has("c")).toBe(true);
|
|
21
|
+
expect(tracker.has("d")).toBe(true);
|
|
22
|
+
});
|
|
23
|
+
});
|