@openclaw/tlon 2026.2.21 → 2026.5.2-beta.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 (63) hide show
  1. package/api.ts +16 -0
  2. package/channel-plugin-api.ts +1 -0
  3. package/doctor-contract-api.ts +1 -0
  4. package/index.ts +177 -11
  5. package/openclaw.plugin.json +194 -1
  6. package/package.json +57 -4
  7. package/runtime-api.ts +17 -0
  8. package/setup-api.ts +2 -0
  9. package/setup-entry.ts +9 -0
  10. package/src/account-fields.ts +9 -3
  11. package/src/channel.runtime.ts +248 -0
  12. package/src/channel.ts +153 -364
  13. package/src/config-schema.ts +22 -16
  14. package/src/core.test.ts +278 -0
  15. package/src/doctor-contract.ts +9 -0
  16. package/src/doctor.test.ts +40 -0
  17. package/src/doctor.ts +10 -0
  18. package/src/logger-runtime.ts +1 -0
  19. package/src/monitor/approval-runtime.ts +363 -0
  20. package/src/monitor/approval.test.ts +33 -0
  21. package/src/monitor/approval.ts +286 -0
  22. package/src/monitor/authorization.ts +30 -0
  23. package/src/monitor/cites.ts +54 -0
  24. package/src/monitor/discovery.ts +44 -54
  25. package/src/monitor/history.ts +155 -21
  26. package/src/monitor/index.ts +1290 -369
  27. package/src/monitor/media.test.ts +91 -0
  28. package/src/monitor/media.ts +172 -0
  29. package/src/monitor/processed-messages.test.ts +36 -1
  30. package/src/monitor/processed-messages.ts +62 -19
  31. package/src/monitor/settings-helpers.test.ts +113 -0
  32. package/src/monitor/settings-helpers.ts +158 -0
  33. package/src/monitor/utils.ts +311 -45
  34. package/src/runtime.ts +8 -13
  35. package/src/security.test.ts +622 -0
  36. package/src/session-route.ts +40 -0
  37. package/src/settings.ts +391 -0
  38. package/src/setup-core.ts +228 -0
  39. package/src/setup-surface.ts +103 -0
  40. package/src/targets.ts +29 -16
  41. package/src/tlon-api.test.ts +589 -0
  42. package/src/tlon-api.ts +402 -0
  43. package/src/types.ts +106 -45
  44. package/src/urbit/auth.ssrf.test.ts +3 -2
  45. package/src/urbit/auth.ts +2 -2
  46. package/src/urbit/base-url.test.ts +18 -11
  47. package/src/urbit/base-url.ts +9 -5
  48. package/src/urbit/channel-ops.ts +40 -59
  49. package/src/urbit/context.ts +13 -10
  50. package/src/urbit/errors.ts +2 -2
  51. package/src/urbit/fetch.ts +6 -3
  52. package/src/urbit/foreigns.ts +49 -0
  53. package/src/urbit/send.ts +53 -8
  54. package/src/urbit/sse-client.test.ts +184 -25
  55. package/src/urbit/sse-client.ts +123 -69
  56. package/src/urbit/story.ts +332 -0
  57. package/src/urbit/upload.test.ts +154 -0
  58. package/src/urbit/upload.ts +60 -0
  59. package/test-api.ts +1 -0
  60. package/tsconfig.json +16 -0
  61. package/src/config-schema.test.ts +0 -31
  62. package/src/onboarding.ts +0 -229
  63. package/src/urbit/channel-client.ts +0 -157
@@ -0,0 +1,33 @@
1
+ import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
2
+
3
+ const cryptoMocks = vi.hoisted(() => ({
4
+ randomBytes: vi.fn(),
5
+ }));
6
+
7
+ vi.mock("node:crypto", () => ({
8
+ randomBytes: cryptoMocks.randomBytes,
9
+ }));
10
+
11
+ let generateApprovalId: typeof import("./approval.js").generateApprovalId;
12
+
13
+ beforeAll(async () => {
14
+ ({ generateApprovalId } = await import("./approval.js"));
15
+ });
16
+
17
+ beforeEach(() => {
18
+ cryptoMocks.randomBytes.mockReset();
19
+ });
20
+
21
+ describe("generateApprovalId", () => {
22
+ it("uses secure hex entropy while preserving the ID format", () => {
23
+ cryptoMocks.randomBytes.mockReturnValueOnce(Buffer.from("a1b2c3", "hex"));
24
+ const nowSpy = vi.spyOn(Date, "now").mockReturnValue(1_717_171_717_171);
25
+
26
+ try {
27
+ expect(generateApprovalId("dm")).toBe("dm-1717171717171-a1b2c3");
28
+ expect(cryptoMocks.randomBytes).toHaveBeenCalledWith(3);
29
+ } finally {
30
+ nowSpy.mockRestore();
31
+ }
32
+ });
33
+ });
@@ -0,0 +1,286 @@
1
+ /**
2
+ * Approval system for managing DM, channel mention, and group invite approvals.
3
+ *
4
+ * When an unknown ship tries to interact with the bot, the owner receives
5
+ * a notification and can approve or deny the request.
6
+ */
7
+
8
+ // Extensions cannot import core internals directly, so use node:crypto here.
9
+ import { randomBytes } from "node:crypto";
10
+ import type { PendingApproval } from "../settings.js";
11
+
12
+ export type { PendingApproval };
13
+
14
+ export type ApprovalType = "dm" | "channel" | "group";
15
+
16
+ function normalizeLowercaseStringOrEmpty(value: unknown): string {
17
+ return typeof value === "string" ? value.trim().toLowerCase() : "";
18
+ }
19
+
20
+ export type CreateApprovalParams = {
21
+ type: ApprovalType;
22
+ requestingShip: string;
23
+ channelNest?: string;
24
+ groupFlag?: string;
25
+ messagePreview?: string;
26
+ originalMessage?: {
27
+ messageId: string;
28
+ messageText: string;
29
+ messageContent: unknown;
30
+ timestamp: number;
31
+ parentId?: string;
32
+ isThreadReply?: boolean;
33
+ };
34
+ };
35
+
36
+ /**
37
+ * Generate a unique approval ID in the format: {type}-{timestamp}-{shortHash}
38
+ */
39
+ export function generateApprovalId(type: ApprovalType): string {
40
+ const timestamp = Date.now();
41
+ const randomPart = randomBytes(3).toString("hex");
42
+ return `${type}-${timestamp}-${randomPart}`;
43
+ }
44
+
45
+ /**
46
+ * Create a pending approval object.
47
+ */
48
+ export function createPendingApproval(params: CreateApprovalParams): PendingApproval {
49
+ return {
50
+ id: generateApprovalId(params.type),
51
+ type: params.type,
52
+ requestingShip: params.requestingShip,
53
+ channelNest: params.channelNest,
54
+ groupFlag: params.groupFlag,
55
+ messagePreview: params.messagePreview,
56
+ originalMessage: params.originalMessage,
57
+ timestamp: Date.now(),
58
+ };
59
+ }
60
+
61
+ /**
62
+ * Truncate text to a maximum length with ellipsis.
63
+ */
64
+ function truncate(text: string, maxLength: number): string {
65
+ if (text.length <= maxLength) {
66
+ return text;
67
+ }
68
+ return text.slice(0, maxLength - 3) + "...";
69
+ }
70
+
71
+ /**
72
+ * Format a notification message for the owner about a pending approval.
73
+ */
74
+ export function formatApprovalRequest(approval: PendingApproval): string {
75
+ const preview = approval.messagePreview ? `\n"${truncate(approval.messagePreview, 100)}"` : "";
76
+
77
+ switch (approval.type) {
78
+ case "dm":
79
+ return (
80
+ `New DM request from ${approval.requestingShip}:${preview}\n\n` +
81
+ `Reply "approve", "deny", or "block" (ID: ${approval.id})`
82
+ );
83
+
84
+ case "channel":
85
+ return (
86
+ `${approval.requestingShip} mentioned you in ${approval.channelNest}:${preview}\n\n` +
87
+ `Reply "approve", "deny", or "block"\n` +
88
+ `(ID: ${approval.id})`
89
+ );
90
+
91
+ case "group":
92
+ return (
93
+ `Group invite from ${approval.requestingShip} to join ${approval.groupFlag}\n\n` +
94
+ `Reply "approve", "deny", or "block"\n` +
95
+ `(ID: ${approval.id})`
96
+ );
97
+ }
98
+ throw new Error("Unsupported approval type");
99
+ }
100
+
101
+ export type ApprovalResponse = {
102
+ action: "approve" | "deny" | "block";
103
+ id?: string;
104
+ };
105
+
106
+ /**
107
+ * Parse an owner's response to an approval request.
108
+ * Supports formats:
109
+ * - "approve" / "deny" / "block" (applies to most recent pending)
110
+ * - "approve dm-1234567890-abc" / "deny dm-1234567890-abc" (specific ID)
111
+ * - "block" permanently blocks the ship via Tlon's native blocking
112
+ */
113
+ export function parseApprovalResponse(text: string): ApprovalResponse | null {
114
+ const trimmed = normalizeLowercaseStringOrEmpty(text);
115
+
116
+ // Match "approve", "deny", or "block" optionally followed by an ID
117
+ const match = trimmed.match(/^(approve|deny|block)(?:\s+(.+))?$/);
118
+ if (!match) {
119
+ return null;
120
+ }
121
+
122
+ const action = match[1] as "approve" | "deny" | "block";
123
+ const id = match[2]?.trim();
124
+
125
+ return { action, id };
126
+ }
127
+
128
+ /**
129
+ * Check if a message text looks like an approval response.
130
+ * Used to determine if we should intercept the message before normal processing.
131
+ */
132
+ export function isApprovalResponse(text: string): boolean {
133
+ const trimmed = normalizeLowercaseStringOrEmpty(text);
134
+ return trimmed.startsWith("approve") || trimmed.startsWith("deny") || trimmed.startsWith("block");
135
+ }
136
+
137
+ /**
138
+ * Find a pending approval by ID, or return the most recent if no ID specified.
139
+ */
140
+ export function findPendingApproval(
141
+ pendingApprovals: PendingApproval[],
142
+ id?: string,
143
+ ): PendingApproval | undefined {
144
+ if (id) {
145
+ return pendingApprovals.find((a) => a.id === id);
146
+ }
147
+ // Return most recent
148
+ return pendingApprovals[pendingApprovals.length - 1];
149
+ }
150
+
151
+ /**
152
+ * Check if there's already a pending approval for the same ship/channel/group combo.
153
+ * Used to avoid sending duplicate notifications.
154
+ */
155
+ export function hasDuplicatePending(
156
+ pendingApprovals: PendingApproval[],
157
+ type: ApprovalType,
158
+ requestingShip: string,
159
+ channelNest?: string,
160
+ groupFlag?: string,
161
+ ): boolean {
162
+ return pendingApprovals.some((approval) => {
163
+ if (approval.type !== type || approval.requestingShip !== requestingShip) {
164
+ return false;
165
+ }
166
+ if (type === "channel" && approval.channelNest !== channelNest) {
167
+ return false;
168
+ }
169
+ if (type === "group" && approval.groupFlag !== groupFlag) {
170
+ return false;
171
+ }
172
+ return true;
173
+ });
174
+ }
175
+
176
+ /**
177
+ * Remove a pending approval from the list by ID.
178
+ */
179
+ export function removePendingApproval(
180
+ pendingApprovals: PendingApproval[],
181
+ id: string,
182
+ ): PendingApproval[] {
183
+ return pendingApprovals.filter((a) => a.id !== id);
184
+ }
185
+
186
+ /**
187
+ * Format a confirmation message after an approval action.
188
+ */
189
+ export function formatApprovalConfirmation(
190
+ approval: PendingApproval,
191
+ action: "approve" | "deny" | "block",
192
+ ): string {
193
+ if (action === "block") {
194
+ return `Blocked ${approval.requestingShip}. They will no longer be able to contact the bot.`;
195
+ }
196
+
197
+ const actionText = action === "approve" ? "Approved" : "Denied";
198
+
199
+ switch (approval.type) {
200
+ case "dm":
201
+ if (action === "approve") {
202
+ return `${actionText} DM access for ${approval.requestingShip}. They can now message the bot.`;
203
+ }
204
+ return `${actionText} DM request from ${approval.requestingShip}.`;
205
+
206
+ case "channel":
207
+ if (action === "approve") {
208
+ return `${actionText} ${approval.requestingShip} for ${approval.channelNest}. They can now interact in this channel.`;
209
+ }
210
+ return `${actionText} ${approval.requestingShip} for ${approval.channelNest}.`;
211
+
212
+ case "group":
213
+ if (action === "approve") {
214
+ return `${actionText} group invite from ${approval.requestingShip} to ${approval.groupFlag}. Joining group...`;
215
+ }
216
+ return `${actionText} group invite from ${approval.requestingShip} to ${approval.groupFlag}.`;
217
+ }
218
+ throw new Error("Unsupported approval type");
219
+ }
220
+
221
+ // ============================================================================
222
+ // Admin Commands
223
+ // ============================================================================
224
+
225
+ export type AdminCommand =
226
+ | { type: "unblock"; ship: string }
227
+ | { type: "blocked" }
228
+ | { type: "pending" };
229
+
230
+ /**
231
+ * Parse an admin command from owner message.
232
+ * Supports:
233
+ * - "unblock ~ship" - unblock a specific ship
234
+ * - "blocked" - list all blocked ships
235
+ * - "pending" - list all pending approvals
236
+ */
237
+ export function parseAdminCommand(text: string): AdminCommand | null {
238
+ const trimmed = normalizeLowercaseStringOrEmpty(text);
239
+
240
+ // "blocked" - list blocked ships
241
+ if (trimmed === "blocked") {
242
+ return { type: "blocked" };
243
+ }
244
+
245
+ // "pending" - list pending approvals
246
+ if (trimmed === "pending") {
247
+ return { type: "pending" };
248
+ }
249
+
250
+ // "unblock ~ship" - unblock a specific ship
251
+ const unblockMatch = trimmed.match(/^unblock\s+(~[\w-]+)$/);
252
+ if (unblockMatch) {
253
+ return { type: "unblock", ship: unblockMatch[1] };
254
+ }
255
+
256
+ return null;
257
+ }
258
+
259
+ /**
260
+ * Check if a message text looks like an admin command.
261
+ */
262
+ export function isAdminCommand(text: string): boolean {
263
+ return parseAdminCommand(text) !== null;
264
+ }
265
+
266
+ /**
267
+ * Format the list of blocked ships for display to owner.
268
+ */
269
+ export function formatBlockedList(ships: string[]): string {
270
+ if (ships.length === 0) {
271
+ return "No ships are currently blocked.";
272
+ }
273
+ return `Blocked ships (${ships.length}):\n${ships.map((s) => `• ${s}`).join("\n")}`;
274
+ }
275
+
276
+ /**
277
+ * Format the list of pending approvals for display to owner.
278
+ */
279
+ export function formatPendingList(approvals: PendingApproval[]): string {
280
+ if (approvals.length === 0) {
281
+ return "No pending approval requests.";
282
+ }
283
+ return `Pending approvals (${approvals.length}):\n${approvals
284
+ .map((a) => `• ${a.id}: ${a.type} from ${a.requestingShip}`)
285
+ .join("\n")}`;
286
+ }
@@ -0,0 +1,30 @@
1
+ import type { OpenClawConfig } from "openclaw/plugin-sdk/config-types";
2
+ import type { TlonSettingsStore } from "../settings.js";
3
+
4
+ type ChannelAuthorization = {
5
+ mode?: "restricted" | "open";
6
+ allowedShips?: string[];
7
+ };
8
+
9
+ export function resolveChannelAuthorization(
10
+ cfg: OpenClawConfig,
11
+ channelNest: string,
12
+ settings?: TlonSettingsStore,
13
+ ): { mode: "restricted" | "open"; allowedShips: string[] } {
14
+ const tlonConfig = cfg.channels?.tlon as
15
+ | {
16
+ authorization?: { channelRules?: Record<string, ChannelAuthorization> };
17
+ defaultAuthorizedShips?: string[];
18
+ }
19
+ | undefined;
20
+
21
+ const fileRules = tlonConfig?.authorization?.channelRules ?? {};
22
+ const settingsRules = settings?.channelRules ?? {};
23
+ const rule = settingsRules[channelNest] ?? fileRules[channelNest];
24
+ const defaultShips = settings?.defaultAuthorizedShips ?? tlonConfig?.defaultAuthorizedShips ?? [];
25
+
26
+ return {
27
+ mode: rule?.mode ?? "restricted",
28
+ allowedShips: rule?.allowedShips ?? defaultShips,
29
+ };
30
+ }
@@ -0,0 +1,54 @@
1
+ import type { RuntimeEnv } from "openclaw/plugin-sdk/runtime";
2
+ import { asRecord, extractCites, extractMessageText, type ParsedCite } from "./utils.js";
3
+
4
+ type TlonScryApi = {
5
+ scry: (path: string) => Promise<unknown>;
6
+ };
7
+
8
+ export function createTlonCitationResolver(params: { api: TlonScryApi; runtime: RuntimeEnv }) {
9
+ const { api, runtime } = params;
10
+
11
+ const resolveCiteContent = async (cite: ParsedCite): Promise<string | null> => {
12
+ if (cite.type !== "chan" || !cite.nest || !cite.postId) {
13
+ return null;
14
+ }
15
+
16
+ try {
17
+ const scryPath = `/channels/v4/${cite.nest}/posts/post/${cite.postId}.json`;
18
+ runtime.log?.(`[tlon] Fetching cited post: ${scryPath}`);
19
+
20
+ const data = asRecord(await api.scry(scryPath));
21
+ const essay = asRecord(data?.essay);
22
+ if (essay?.content) {
23
+ return extractMessageText(essay.content) || null;
24
+ }
25
+
26
+ return null;
27
+ } catch (err) {
28
+ runtime.log?.(`[tlon] Failed to fetch cited post: ${String(err)}`);
29
+ return null;
30
+ }
31
+ };
32
+
33
+ const resolveAllCites = async (content: unknown): Promise<string> => {
34
+ const cites = extractCites(content);
35
+ if (cites.length === 0) {
36
+ return "";
37
+ }
38
+
39
+ const resolved: string[] = [];
40
+ for (const cite of cites) {
41
+ const text = await resolveCiteContent(cite);
42
+ if (text) {
43
+ resolved.push(`> ${cite.author || "unknown"} wrote: ${text}`);
44
+ }
45
+ }
46
+
47
+ return resolved.length > 0 ? `${resolved.join("\n")}\n\n` : "";
48
+ };
49
+
50
+ return {
51
+ resolveCiteContent,
52
+ resolveAllCites,
53
+ };
54
+ }
@@ -1,51 +1,32 @@
1
- import type { RuntimeEnv } from "openclaw/plugin-sdk";
2
- import { formatChangesDate } from "./utils.js";
1
+ import type { RuntimeEnv } from "openclaw/plugin-sdk/runtime";
2
+ import type { Foreigns } from "../urbit/foreigns.js";
3
+ import { asRecord, formatErrorMessage } from "./utils.js";
3
4
 
4
- export async function fetchGroupChanges(
5
- api: { scry: (path: string) => Promise<unknown> },
6
- runtime: RuntimeEnv,
7
- daysAgo = 5,
8
- ) {
9
- try {
10
- const changeDate = formatChangesDate(daysAgo);
11
- runtime.log?.(`[tlon] Fetching group changes since ${daysAgo} days ago (${changeDate})...`);
12
- const changes = await api.scry(`/groups-ui/v5/changes/${changeDate}.json`);
13
- if (changes) {
14
- runtime.log?.("[tlon] Successfully fetched changes data");
15
- return changes;
16
- }
17
- return null;
18
- } catch (error) {
19
- runtime.log?.(
20
- `[tlon] Failed to fetch changes (falling back to full init): ${(error as { message?: string })?.message ?? String(error)}`,
21
- );
22
- return null;
23
- }
5
+ interface InitData {
6
+ channels: string[];
7
+ foreigns: Foreigns | null;
24
8
  }
25
9
 
26
- export async function fetchAllChannels(
10
+ /**
11
+ * Fetch groups-ui init data, returning channels and foreigns.
12
+ * This is a single scry that provides both channel discovery and pending invites.
13
+ */
14
+ export async function fetchInitData(
27
15
  api: { scry: (path: string) => Promise<unknown> },
28
16
  runtime: RuntimeEnv,
29
- ): Promise<string[]> {
17
+ ): Promise<InitData> {
30
18
  try {
31
- runtime.log?.("[tlon] Attempting auto-discovery of group channels...");
32
- const changes = await fetchGroupChanges(api, runtime, 5);
33
-
34
- // oxlint-disable-next-line typescript/no-explicit-any
35
- let initData: any;
36
- if (changes) {
37
- runtime.log?.("[tlon] Changes data received, using full init for channel extraction");
38
- initData = await api.scry("/groups-ui/v6/init.json");
39
- } else {
40
- initData = await api.scry("/groups-ui/v6/init.json");
41
- }
19
+ runtime.log?.("[tlon] Fetching groups-ui init data...");
20
+ const initData = asRecord(await api.scry("/groups-ui/v6/init.json"));
42
21
 
43
22
  const channels: string[] = [];
44
- if (initData && initData.groups) {
45
- // oxlint-disable-next-line typescript/no-explicit-any
46
- for (const groupData of Object.values(initData.groups as Record<string, any>)) {
47
- if (groupData && typeof groupData === "object" && groupData.channels) {
48
- for (const channelNest of Object.keys(groupData.channels)) {
23
+ const groups = asRecord(initData?.groups);
24
+ if (groups) {
25
+ for (const groupData of Object.values(groups)) {
26
+ const typedGroupData = asRecord(groupData);
27
+ const groupChannels = asRecord(typedGroupData?.channels);
28
+ if (groupChannels) {
29
+ for (const channelNest of Object.keys(groupChannels)) {
49
30
  if (channelNest.startsWith("chat/")) {
50
31
  channels.push(channelNest);
51
32
  }
@@ -56,23 +37,32 @@ export async function fetchAllChannels(
56
37
 
57
38
  if (channels.length > 0) {
58
39
  runtime.log?.(`[tlon] Auto-discovered ${channels.length} chat channel(s)`);
59
- runtime.log?.(
60
- `[tlon] Channels: ${channels.slice(0, 5).join(", ")}${channels.length > 5 ? "..." : ""}`,
61
- );
62
40
  } else {
63
41
  runtime.log?.("[tlon] No chat channels found via auto-discovery");
64
- runtime.log?.("[tlon] Add channels manually to config: channels.tlon.groupChannels");
65
42
  }
66
43
 
67
- return channels;
68
- } catch (error) {
69
- runtime.log?.(
70
- `[tlon] Auto-discovery failed: ${(error as { message?: string })?.message ?? String(error)}`,
71
- );
72
- runtime.log?.(
73
- "[tlon] To monitor group channels, add them to config: channels.tlon.groupChannels",
74
- );
75
- runtime.log?.('[tlon] Example: ["chat/~host-ship/channel-name"]');
76
- return [];
44
+ const foreignsValue = asRecord(initData?.foreigns);
45
+ const foreigns = foreignsValue ? (foreignsValue as Foreigns) : null;
46
+ if (foreigns) {
47
+ const pendingCount = Object.values(foreigns).filter((f) =>
48
+ f.invites?.some((i) => i.valid),
49
+ ).length;
50
+ if (pendingCount > 0) {
51
+ runtime.log?.(`[tlon] Found ${pendingCount} pending group invite(s)`);
52
+ }
53
+ }
54
+
55
+ return { channels, foreigns };
56
+ } catch (error: unknown) {
57
+ runtime.log?.(`[tlon] Init data fetch failed: ${formatErrorMessage(error)}`);
58
+ return { channels: [], foreigns: null };
77
59
  }
78
60
  }
61
+
62
+ export async function fetchAllChannels(
63
+ api: { scry: (path: string) => Promise<unknown> },
64
+ runtime: RuntimeEnv,
65
+ ): Promise<string[]> {
66
+ const { channels } = await fetchInitData(api, runtime);
67
+ return channels;
68
+ }