@openclaw/tlon 2026.2.21 → 2026.5.1-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 +189 -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 +152 -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 +59 -2
  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,278 @@
1
+ import {
2
+ createPluginSetupWizardConfigure,
3
+ createPluginSetupWizardStatus,
4
+ createTestWizardPrompter,
5
+ runSetupWizardConfigure,
6
+ } from "openclaw/plugin-sdk/plugin-test-runtime";
7
+ import type { WizardPrompter } from "openclaw/plugin-sdk/plugin-test-runtime";
8
+ import { describe, expect, it, vi } from "vitest";
9
+ import type { OpenClawConfig } from "../api.js";
10
+ import { TlonAuthorizationSchema, TlonConfigSchema } from "./config-schema.js";
11
+ import { tlonSetupWizard } from "./setup-surface.js";
12
+ import { normalizeShip, resolveTlonOutboundTarget } from "./targets.js";
13
+ import { listTlonAccountIds, resolveTlonAccount } from "./types.js";
14
+
15
+ const tlonTestPlugin = {
16
+ id: "tlon",
17
+ meta: { label: "Tlon" },
18
+ setupWizard: tlonSetupWizard,
19
+ config: {
20
+ listAccountIds: listTlonAccountIds,
21
+ defaultAccountId: () => "default",
22
+ resolveAllowFrom: ({ cfg, accountId }: { cfg: OpenClawConfig; accountId?: string | null }) =>
23
+ resolveTlonAccount(cfg, accountId).dmAllowlist,
24
+ formatAllowFrom: ({
25
+ allowFrom,
26
+ }: {
27
+ cfg: OpenClawConfig;
28
+ allowFrom: Array<string | number> | undefined | null;
29
+ }) => (allowFrom ?? []).map((entry) => normalizeShip(String(entry))).filter(Boolean),
30
+ },
31
+ setup: {
32
+ resolveAccountId: ({ accountId }: { cfg: OpenClawConfig; accountId?: string | null }) =>
33
+ accountId ?? "default",
34
+ },
35
+ };
36
+
37
+ const tlonConfigure = createPluginSetupWizardConfigure(tlonTestPlugin);
38
+ const tlonStatus = createPluginSetupWizardStatus(tlonTestPlugin);
39
+
40
+ describe("tlon core", () => {
41
+ it("formats dm allowlist entries through the shared hybrid adapter", () => {
42
+ expect(
43
+ tlonTestPlugin.config.formatAllowFrom?.({
44
+ cfg: {} as OpenClawConfig,
45
+ allowFrom: ["zod", " ~nec "],
46
+ }),
47
+ ).toEqual(["~zod", "~nec"]);
48
+ });
49
+
50
+ it("returns an empty dm allowlist when the default account is unconfigured", () => {
51
+ expect(
52
+ tlonTestPlugin.config.resolveAllowFrom?.({
53
+ cfg: {} as OpenClawConfig,
54
+ accountId: "default",
55
+ }),
56
+ ).toEqual([]);
57
+ });
58
+
59
+ it("resolves dm allowlist from the default account", () => {
60
+ expect(
61
+ tlonTestPlugin.config.resolveAllowFrom?.({
62
+ cfg: {
63
+ channels: {
64
+ tlon: {
65
+ ship: "~sampel-palnet",
66
+ url: "https://urbit.example.com",
67
+ code: "lidlut-tabwed-pillex-ridrup",
68
+ dmAllowlist: ["~zod"],
69
+ },
70
+ },
71
+ } as OpenClawConfig,
72
+ accountId: "default",
73
+ }),
74
+ ).toEqual(["~zod"]);
75
+ });
76
+
77
+ it("accepts channelRules with string keys", () => {
78
+ const parsed = TlonAuthorizationSchema.parse({
79
+ channelRules: {
80
+ "chat/~zod/test": {
81
+ mode: "open",
82
+ allowedShips: ["~zod"],
83
+ },
84
+ },
85
+ });
86
+
87
+ expect(parsed.channelRules?.["chat/~zod/test"]?.mode).toBe("open");
88
+ });
89
+
90
+ it("accepts accounts with string keys", () => {
91
+ const parsed = TlonConfigSchema.parse({
92
+ accounts: {
93
+ primary: {
94
+ ship: "~zod",
95
+ url: "https://example.com",
96
+ code: "code-123",
97
+ },
98
+ },
99
+ });
100
+
101
+ expect(parsed.accounts?.primary?.ship).toBe("~zod");
102
+ });
103
+
104
+ it("configures ship, auth, and discovery settings", async () => {
105
+ const prompter = createTestWizardPrompter({
106
+ text: vi.fn(async ({ message }: { message: string }) => {
107
+ if (message === "Ship name") {
108
+ return "sampel-palnet";
109
+ }
110
+ if (message === "Ship URL") {
111
+ return "https://urbit.example.com";
112
+ }
113
+ if (message === "Login code") {
114
+ return "lidlut-tabwed-pillex-ridrup";
115
+ }
116
+ if (message === "Group channels (comma-separated)") {
117
+ return "chat/~host-ship/general, chat/~host-ship/support";
118
+ }
119
+ if (message === "DM allowlist (comma-separated ship names)") {
120
+ return "~zod, nec";
121
+ }
122
+ throw new Error(`Unexpected prompt: ${message}`);
123
+ }) as WizardPrompter["text"],
124
+ confirm: vi.fn(async ({ message }: { message: string }) => {
125
+ if (message === "Add group channels manually? (optional)") {
126
+ return true;
127
+ }
128
+ if (message === "Restrict DMs with an allowlist?") {
129
+ return true;
130
+ }
131
+ if (message === "Enable auto-discovery of group channels?") {
132
+ return true;
133
+ }
134
+ return false;
135
+ }),
136
+ });
137
+
138
+ const result = await runSetupWizardConfigure({
139
+ configure: tlonConfigure,
140
+ cfg: {} as OpenClawConfig,
141
+ prompter,
142
+ options: {},
143
+ });
144
+
145
+ expect(result.accountId).toBe("default");
146
+ expect(result.cfg.channels?.tlon?.enabled).toBe(true);
147
+ expect(result.cfg.channels?.tlon?.ship).toBe("~sampel-palnet");
148
+ expect(result.cfg.channels?.tlon?.url).toBe("https://urbit.example.com");
149
+ expect(result.cfg.channels?.tlon?.code).toBe("lidlut-tabwed-pillex-ridrup");
150
+ expect(result.cfg.channels?.tlon?.groupChannels).toEqual([
151
+ "chat/~host-ship/general",
152
+ "chat/~host-ship/support",
153
+ ]);
154
+ expect(result.cfg.channels?.tlon?.dmAllowlist).toEqual(["~zod", "~nec"]);
155
+ expect(result.cfg.channels?.tlon?.autoDiscoverChannels).toBe(true);
156
+ expect(result.cfg.channels?.tlon?.network?.dangerouslyAllowPrivateNetwork).toBe(false);
157
+ });
158
+
159
+ it("resolves dm targets to normalized ships", () => {
160
+ expect(resolveTlonOutboundTarget("dm/sampel-palnet")).toEqual({
161
+ ok: true,
162
+ to: "~sampel-palnet",
163
+ });
164
+ });
165
+
166
+ it("resolves group targets to canonical chat nests", () => {
167
+ expect(resolveTlonOutboundTarget("group:host-ship/general")).toEqual({
168
+ ok: true,
169
+ to: "chat/~host-ship/general",
170
+ });
171
+ });
172
+
173
+ it("returns a helpful error for invalid targets", () => {
174
+ const resolved = resolveTlonOutboundTarget("group:bad-target");
175
+ expect(resolved.ok).toBe(false);
176
+ if (resolved.ok) {
177
+ throw new Error("expected invalid target");
178
+ }
179
+ expect(resolved.error.message).toMatch(/invalid tlon target/i);
180
+ });
181
+
182
+ it("lists named accounts and the implicit default account", () => {
183
+ const cfg = {
184
+ channels: {
185
+ tlon: {
186
+ ship: "~zod",
187
+ accounts: {
188
+ Work: { ship: "~bus" },
189
+ alerts: { ship: "~nec" },
190
+ },
191
+ },
192
+ },
193
+ } as OpenClawConfig;
194
+
195
+ expect(listTlonAccountIds(cfg)).toEqual(["alerts", "default", "work"]);
196
+ });
197
+
198
+ it("merges named account config over channel defaults", () => {
199
+ const resolved = resolveTlonAccount(
200
+ {
201
+ channels: {
202
+ tlon: {
203
+ name: "Base",
204
+ ship: "~zod",
205
+ url: "https://urbit.example.com",
206
+ code: "base-code",
207
+ dmAllowlist: ["~nec"],
208
+ groupInviteAllowlist: ["~bus"],
209
+ defaultAuthorizedShips: ["~marzod"],
210
+ accounts: {
211
+ Work: {
212
+ name: "Work",
213
+ code: "work-code",
214
+ dmAllowlist: ["~rovnys"],
215
+ },
216
+ },
217
+ },
218
+ },
219
+ } as OpenClawConfig,
220
+ "work",
221
+ );
222
+
223
+ expect(resolved.accountId).toBe("work");
224
+ expect(resolved.name).toBe("Work");
225
+ expect(resolved.ship).toBe("~zod");
226
+ expect(resolved.url).toBe("https://urbit.example.com");
227
+ expect(resolved.code).toBe("work-code");
228
+ expect(resolved.dmAllowlist).toEqual(["~rovnys"]);
229
+ expect(resolved.groupInviteAllowlist).toEqual(["~bus"]);
230
+ expect(resolved.defaultAuthorizedShips).toEqual(["~marzod"]);
231
+ expect(resolved.configured).toBe(true);
232
+ });
233
+
234
+ it("keeps the default account on channel-level config only", () => {
235
+ const resolved = resolveTlonAccount(
236
+ {
237
+ channels: {
238
+ tlon: {
239
+ ship: "~zod",
240
+ url: "https://urbit.example.com",
241
+ code: "base-code",
242
+ accounts: {
243
+ default: {
244
+ ship: "~ignored",
245
+ code: "ignored-code",
246
+ },
247
+ },
248
+ },
249
+ },
250
+ } as OpenClawConfig,
251
+ "default",
252
+ );
253
+
254
+ expect(resolved.ship).toBe("~zod");
255
+ expect(resolved.code).toBe("base-code");
256
+ });
257
+
258
+ it("setup status labels the selected account", async () => {
259
+ const status = await tlonStatus({
260
+ cfg: {
261
+ channels: {
262
+ tlon: {
263
+ ship: "~zod",
264
+ url: "https://urbit.example.com",
265
+ code: "base-code",
266
+ accounts: {
267
+ work: {},
268
+ },
269
+ },
270
+ },
271
+ } as OpenClawConfig,
272
+ accountOverrides: { tlon: "work" },
273
+ });
274
+
275
+ expect(status.configured).toBe(true);
276
+ expect(status.statusLines).toEqual(["Tlon (work): configured"]);
277
+ });
278
+ });
@@ -0,0 +1,9 @@
1
+ import { createLegacyPrivateNetworkDoctorContract } from "openclaw/plugin-sdk/ssrf-runtime";
2
+
3
+ const contract = createLegacyPrivateNetworkDoctorContract({
4
+ channelKey: "tlon",
5
+ });
6
+
7
+ export const legacyConfigRules = contract.legacyConfigRules;
8
+
9
+ export const normalizeCompatibilityConfig = contract.normalizeCompatibilityConfig;
@@ -0,0 +1,40 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { tlonDoctor } from "./doctor.js";
3
+
4
+ describe("tlon doctor", () => {
5
+ it("normalizes legacy private-network aliases", () => {
6
+ const normalize = tlonDoctor.normalizeCompatibilityConfig;
7
+ expect(normalize).toBeDefined();
8
+ if (!normalize) {
9
+ return;
10
+ }
11
+
12
+ const result = normalize({
13
+ cfg: {
14
+ channels: {
15
+ tlon: {
16
+ allowPrivateNetwork: true,
17
+ accounts: {
18
+ alt: {
19
+ allowPrivateNetwork: false,
20
+ },
21
+ },
22
+ },
23
+ },
24
+ } as never,
25
+ });
26
+
27
+ expect(result.config.channels?.tlon?.network).toEqual({
28
+ dangerouslyAllowPrivateNetwork: true,
29
+ });
30
+ expect(
31
+ (
32
+ result.config.channels?.tlon?.accounts?.alt as
33
+ | { network?: Record<string, unknown> }
34
+ | undefined
35
+ )?.network,
36
+ ).toEqual({
37
+ dangerouslyAllowPrivateNetwork: false,
38
+ });
39
+ });
40
+ });
package/src/doctor.ts ADDED
@@ -0,0 +1,10 @@
1
+ import type { ChannelDoctorAdapter } from "openclaw/plugin-sdk/channel-contract";
2
+ import {
3
+ legacyConfigRules as TLON_LEGACY_CONFIG_RULES,
4
+ normalizeCompatibilityConfig as normalizeTlonCompatibilityConfig,
5
+ } from "./doctor-contract.js";
6
+
7
+ export const tlonDoctor: ChannelDoctorAdapter = {
8
+ legacyConfigRules: TLON_LEGACY_CONFIG_RULES,
9
+ normalizeCompatibilityConfig: normalizeTlonCompatibilityConfig,
10
+ };
@@ -0,0 +1 @@
1
+ export { createLoggerBackedRuntime } from "openclaw/plugin-sdk/runtime-logger";
@@ -0,0 +1,363 @@
1
+ import type { RuntimeEnv } from "openclaw/plugin-sdk/runtime";
2
+ import type { PendingApproval, TlonSettingsStore } from "../settings.js";
3
+ import { normalizeShip } from "../targets.js";
4
+ import { sendDm } from "../urbit/send.js";
5
+ import type { UrbitSSEClient } from "../urbit/sse-client.js";
6
+ import {
7
+ findPendingApproval,
8
+ formatApprovalConfirmation,
9
+ formatApprovalRequest,
10
+ formatBlockedList,
11
+ formatPendingList,
12
+ parseAdminCommand,
13
+ parseApprovalResponse,
14
+ removePendingApproval,
15
+ } from "./approval.js";
16
+
17
+ type TlonApprovalApi = Pick<UrbitSSEClient, "poke" | "scry">;
18
+
19
+ type ApprovedMessageProcessor = (approval: PendingApproval) => Promise<void>;
20
+
21
+ export function createTlonApprovalRuntime(params: {
22
+ api: TlonApprovalApi;
23
+ runtime: RuntimeEnv;
24
+ botShipName: string;
25
+ getPendingApprovals: () => PendingApproval[];
26
+ setPendingApprovals: (approvals: PendingApproval[]) => void;
27
+ getCurrentSettings: () => TlonSettingsStore;
28
+ setCurrentSettings: (settings: TlonSettingsStore) => void;
29
+ getEffectiveDmAllowlist: () => string[];
30
+ setEffectiveDmAllowlist: (ships: string[]) => void;
31
+ getEffectiveOwnerShip: () => string | null;
32
+ processApprovedMessage: ApprovedMessageProcessor;
33
+ refreshWatchedChannels: () => Promise<number>;
34
+ }) {
35
+ const {
36
+ api,
37
+ runtime,
38
+ botShipName,
39
+ getPendingApprovals,
40
+ setPendingApprovals,
41
+ getCurrentSettings,
42
+ setCurrentSettings,
43
+ getEffectiveDmAllowlist,
44
+ setEffectiveDmAllowlist,
45
+ getEffectiveOwnerShip,
46
+ processApprovedMessage,
47
+ refreshWatchedChannels,
48
+ } = params;
49
+
50
+ const savePendingApprovals = async (): Promise<void> => {
51
+ try {
52
+ await api.poke({
53
+ app: "settings",
54
+ mark: "settings-event",
55
+ json: {
56
+ "put-entry": {
57
+ desk: "moltbot",
58
+ "bucket-key": "tlon",
59
+ "entry-key": "pendingApprovals",
60
+ value: JSON.stringify(getPendingApprovals()),
61
+ },
62
+ },
63
+ });
64
+ } catch (err) {
65
+ runtime.error?.(`[tlon] Failed to save pending approvals: ${String(err)}`);
66
+ }
67
+ };
68
+
69
+ const addToDmAllowlist = async (ship: string): Promise<void> => {
70
+ const normalizedShip = normalizeShip(ship);
71
+ const nextAllowlist = getEffectiveDmAllowlist().includes(normalizedShip)
72
+ ? getEffectiveDmAllowlist()
73
+ : [...getEffectiveDmAllowlist(), normalizedShip];
74
+ setEffectiveDmAllowlist(nextAllowlist);
75
+ try {
76
+ await api.poke({
77
+ app: "settings",
78
+ mark: "settings-event",
79
+ json: {
80
+ "put-entry": {
81
+ desk: "moltbot",
82
+ "bucket-key": "tlon",
83
+ "entry-key": "dmAllowlist",
84
+ value: nextAllowlist,
85
+ },
86
+ },
87
+ });
88
+ runtime.log?.(`[tlon] Added ${normalizedShip} to dmAllowlist`);
89
+ } catch (err) {
90
+ runtime.error?.(`[tlon] Failed to update dmAllowlist: ${String(err)}`);
91
+ }
92
+ };
93
+
94
+ const addToChannelAllowlist = async (ship: string, channelNest: string): Promise<void> => {
95
+ const normalizedShip = normalizeShip(ship);
96
+ const currentSettings = getCurrentSettings();
97
+ const channelRules = currentSettings.channelRules ?? {};
98
+ const rule = channelRules[channelNest] ?? { mode: "restricted", allowedShips: [] };
99
+ const allowedShips = [...(rule.allowedShips ?? [])];
100
+
101
+ if (!allowedShips.includes(normalizedShip)) {
102
+ allowedShips.push(normalizedShip);
103
+ }
104
+
105
+ const updatedRules = {
106
+ ...channelRules,
107
+ [channelNest]: { ...rule, allowedShips },
108
+ };
109
+ setCurrentSettings({ ...currentSettings, channelRules: updatedRules });
110
+
111
+ try {
112
+ await api.poke({
113
+ app: "settings",
114
+ mark: "settings-event",
115
+ json: {
116
+ "put-entry": {
117
+ desk: "moltbot",
118
+ "bucket-key": "tlon",
119
+ "entry-key": "channelRules",
120
+ value: JSON.stringify(updatedRules),
121
+ },
122
+ },
123
+ });
124
+ runtime.log?.(`[tlon] Added ${normalizedShip} to ${channelNest} allowlist`);
125
+ } catch (err) {
126
+ runtime.error?.(`[tlon] Failed to update channelRules: ${String(err)}`);
127
+ }
128
+ };
129
+
130
+ const blockShip = async (ship: string): Promise<void> => {
131
+ const normalizedShip = normalizeShip(ship);
132
+ try {
133
+ await api.poke({
134
+ app: "chat",
135
+ mark: "chat-block-ship",
136
+ json: { ship: normalizedShip },
137
+ });
138
+ runtime.log?.(`[tlon] Blocked ship ${normalizedShip}`);
139
+ } catch (err) {
140
+ runtime.error?.(`[tlon] Failed to block ship ${normalizedShip}: ${String(err)}`);
141
+ }
142
+ };
143
+
144
+ const isShipBlocked = async (ship: string): Promise<boolean> => {
145
+ const normalizedShip = normalizeShip(ship);
146
+ try {
147
+ const blocked = (await api.scry("/chat/blocked.json")) as string[] | undefined;
148
+ return (
149
+ Array.isArray(blocked) && blocked.some((item) => normalizeShip(item) === normalizedShip)
150
+ );
151
+ } catch (err) {
152
+ runtime.log?.(`[tlon] Failed to check blocked list: ${String(err)}`);
153
+ return false;
154
+ }
155
+ };
156
+
157
+ const getBlockedShips = async (): Promise<string[]> => {
158
+ try {
159
+ const blocked = (await api.scry("/chat/blocked.json")) as string[] | undefined;
160
+ return Array.isArray(blocked) ? blocked : [];
161
+ } catch (err) {
162
+ runtime.log?.(`[tlon] Failed to get blocked list: ${String(err)}`);
163
+ return [];
164
+ }
165
+ };
166
+
167
+ const unblockShip = async (ship: string): Promise<boolean> => {
168
+ const normalizedShip = normalizeShip(ship);
169
+ try {
170
+ await api.poke({
171
+ app: "chat",
172
+ mark: "chat-unblock-ship",
173
+ json: { ship: normalizedShip },
174
+ });
175
+ runtime.log?.(`[tlon] Unblocked ship ${normalizedShip}`);
176
+ return true;
177
+ } catch (err) {
178
+ runtime.error?.(`[tlon] Failed to unblock ship ${normalizedShip}: ${String(err)}`);
179
+ return false;
180
+ }
181
+ };
182
+
183
+ const sendOwnerNotification = async (message: string): Promise<void> => {
184
+ const ownerShip = getEffectiveOwnerShip();
185
+ if (!ownerShip) {
186
+ runtime.log?.("[tlon] No ownerShip configured, cannot send notification");
187
+ return;
188
+ }
189
+ try {
190
+ await sendDm({
191
+ api,
192
+ fromShip: botShipName,
193
+ toShip: ownerShip,
194
+ text: message,
195
+ });
196
+ runtime.log?.(`[tlon] Sent notification to owner ${ownerShip}`);
197
+ } catch (err) {
198
+ runtime.error?.(`[tlon] Failed to send notification to owner: ${String(err)}`);
199
+ }
200
+ };
201
+
202
+ const queueApprovalRequest = async (approval: PendingApproval): Promise<void> => {
203
+ if (await isShipBlocked(approval.requestingShip)) {
204
+ runtime.log?.(`[tlon] Ignoring request from blocked ship ${approval.requestingShip}`);
205
+ return;
206
+ }
207
+
208
+ const approvals = getPendingApprovals();
209
+ const existingIndex = approvals.findIndex(
210
+ (item) =>
211
+ item.type === approval.type &&
212
+ item.requestingShip === approval.requestingShip &&
213
+ (approval.type !== "channel" || item.channelNest === approval.channelNest) &&
214
+ (approval.type !== "group" || item.groupFlag === approval.groupFlag),
215
+ );
216
+
217
+ if (existingIndex !== -1) {
218
+ const existing = approvals[existingIndex];
219
+ if (approval.originalMessage) {
220
+ existing.originalMessage = approval.originalMessage;
221
+ existing.messagePreview = approval.messagePreview;
222
+ }
223
+ runtime.log?.(
224
+ `[tlon] Updated existing approval for ${approval.requestingShip} (${approval.type}) - re-sending notification`,
225
+ );
226
+ await savePendingApprovals();
227
+ await sendOwnerNotification(formatApprovalRequest(existing));
228
+ return;
229
+ }
230
+
231
+ setPendingApprovals([...approvals, approval]);
232
+ await savePendingApprovals();
233
+ await sendOwnerNotification(formatApprovalRequest(approval));
234
+ runtime.log?.(
235
+ `[tlon] Queued approval request: ${approval.id} (${approval.type} from ${approval.requestingShip})`,
236
+ );
237
+ };
238
+
239
+ const handleApprovalResponse = async (text: string): Promise<boolean> => {
240
+ const parsed = parseApprovalResponse(text);
241
+ if (!parsed) {
242
+ return false;
243
+ }
244
+
245
+ const approval = findPendingApproval(getPendingApprovals(), parsed.id);
246
+ if (!approval) {
247
+ await sendOwnerNotification(
248
+ `No pending approval found${parsed.id ? ` for ID: ${parsed.id}` : ""}`,
249
+ );
250
+ return true;
251
+ }
252
+
253
+ if (parsed.action === "approve") {
254
+ switch (approval.type) {
255
+ case "dm":
256
+ await addToDmAllowlist(approval.requestingShip);
257
+ if (approval.originalMessage) {
258
+ runtime.log?.(
259
+ `[tlon] Processing original message from ${approval.requestingShip} after approval`,
260
+ );
261
+ await processApprovedMessage(approval);
262
+ }
263
+ break;
264
+ case "channel":
265
+ if (approval.channelNest) {
266
+ await addToChannelAllowlist(approval.requestingShip, approval.channelNest);
267
+ if (approval.originalMessage) {
268
+ runtime.log?.(
269
+ `[tlon] Processing original message from ${approval.requestingShip} in ${approval.channelNest} after approval`,
270
+ );
271
+ await processApprovedMessage(approval);
272
+ }
273
+ }
274
+ break;
275
+ case "group":
276
+ if (approval.groupFlag) {
277
+ try {
278
+ await api.poke({
279
+ app: "groups",
280
+ mark: "group-join",
281
+ json: {
282
+ flag: approval.groupFlag,
283
+ "join-all": true,
284
+ },
285
+ });
286
+ runtime.log?.(`[tlon] Joined group ${approval.groupFlag} after approval`);
287
+ setTimeout(() => {
288
+ void (async () => {
289
+ try {
290
+ const newCount = await refreshWatchedChannels();
291
+ if (newCount > 0) {
292
+ runtime.log?.(
293
+ `[tlon] Discovered ${newCount} new channel(s) after joining group`,
294
+ );
295
+ }
296
+ } catch (err) {
297
+ runtime.log?.(
298
+ `[tlon] Channel discovery after group join failed: ${String(err)}`,
299
+ );
300
+ }
301
+ })();
302
+ }, 2000);
303
+ } catch (err) {
304
+ runtime.error?.(`[tlon] Failed to join group ${approval.groupFlag}: ${String(err)}`);
305
+ }
306
+ }
307
+ break;
308
+ }
309
+
310
+ await sendOwnerNotification(formatApprovalConfirmation(approval, "approve"));
311
+ } else if (parsed.action === "block") {
312
+ await blockShip(approval.requestingShip);
313
+ await sendOwnerNotification(formatApprovalConfirmation(approval, "block"));
314
+ } else {
315
+ await sendOwnerNotification(formatApprovalConfirmation(approval, "deny"));
316
+ }
317
+
318
+ setPendingApprovals(removePendingApproval(getPendingApprovals(), approval.id));
319
+ await savePendingApprovals();
320
+ return true;
321
+ };
322
+
323
+ const handleAdminCommand = async (text: string): Promise<boolean> => {
324
+ const command = parseAdminCommand(text);
325
+ if (!command) {
326
+ return false;
327
+ }
328
+
329
+ switch (command.type) {
330
+ case "blocked": {
331
+ const blockedShips = await getBlockedShips();
332
+ await sendOwnerNotification(formatBlockedList(blockedShips));
333
+ runtime.log?.(`[tlon] Owner requested blocked ships list (${blockedShips.length} ships)`);
334
+ return true;
335
+ }
336
+ case "pending":
337
+ await sendOwnerNotification(formatPendingList(getPendingApprovals()));
338
+ runtime.log?.(
339
+ `[tlon] Owner requested pending approvals list (${getPendingApprovals().length} pending)`,
340
+ );
341
+ return true;
342
+ case "unblock": {
343
+ const shipToUnblock = command.ship;
344
+ if (!(await isShipBlocked(shipToUnblock))) {
345
+ await sendOwnerNotification(`${shipToUnblock} is not blocked.`);
346
+ return true;
347
+ }
348
+ const success = await unblockShip(shipToUnblock);
349
+ await sendOwnerNotification(
350
+ success ? `Unblocked ${shipToUnblock}.` : `Failed to unblock ${shipToUnblock}.`,
351
+ );
352
+ return true;
353
+ }
354
+ }
355
+ throw new Error("Unsupported Tlon admin command");
356
+ };
357
+
358
+ return {
359
+ queueApprovalRequest,
360
+ handleApprovalResponse,
361
+ handleAdminCommand,
362
+ };
363
+ }