@relaymessenger/openclaw-plugin 0.2.0
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/LICENSE +21 -0
- package/README.md +141 -0
- package/dist/index.js +11 -0
- package/dist/setup-entry.js +5 -0
- package/dist/src/account-lock.js +91 -0
- package/dist/src/accounts.js +67 -0
- package/dist/src/channel.js +606 -0
- package/dist/src/client.js +219 -0
- package/dist/src/cursor-store.js +136 -0
- package/dist/src/inbound-dedupe.js +175 -0
- package/dist/src/inbound.js +94 -0
- package/dist/src/lifecycle.js +35 -0
- package/dist/src/outbound.js +98 -0
- package/dist/src/poll-loop.js +125 -0
- package/dist/src/runtime.js +8 -0
- package/dist/src/security.js +26 -0
- package/dist/src/state-files.js +167 -0
- package/dist/src/types.js +4 -0
- package/index.ts +12 -0
- package/openclaw.plugin.json +101 -0
- package/package.json +97 -0
- package/setup-entry.ts +6 -0
- package/src/account-lock.ts +108 -0
- package/src/accounts.ts +98 -0
- package/src/channel.ts +669 -0
- package/src/client.ts +313 -0
- package/src/cursor-store.ts +186 -0
- package/src/inbound-dedupe.ts +241 -0
- package/src/inbound.ts +128 -0
- package/src/lifecycle.ts +42 -0
- package/src/outbound.ts +136 -0
- package/src/poll-loop.ts +161 -0
- package/src/runtime.ts +13 -0
- package/src/security.ts +36 -0
- package/src/state-files.ts +212 -0
- package/src/types.ts +173 -0
package/src/channel.ts
ADDED
|
@@ -0,0 +1,669 @@
|
|
|
1
|
+
// Relay channel plugin assembly: config/multi-account resolution,
|
|
2
|
+
// gateway long-poll lifecycle, durable message adapter, and inbound dispatch
|
|
3
|
+
// wiring. Transport logic lives in client/poll-loop/inbound/outbound modules;
|
|
4
|
+
// this file owns the OpenClaw adapter surfaces.
|
|
5
|
+
import { createChatChannelPlugin } from "openclaw/plugin-sdk/channel-core";
|
|
6
|
+
import type { ChannelPlugin, OpenClawConfig } from "openclaw/plugin-sdk/channel-core";
|
|
7
|
+
import type { ChannelGatewayContext } from "openclaw/plugin-sdk/channel-contract";
|
|
8
|
+
import { resolveStableChannelMessageIngress } from "openclaw/plugin-sdk/channel-ingress-runtime";
|
|
9
|
+
import {
|
|
10
|
+
createMessageReceiptFromOutboundResults,
|
|
11
|
+
defineChannelMessageAdapter,
|
|
12
|
+
} from "openclaw/plugin-sdk/channel-outbound";
|
|
13
|
+
import { resolveInboundRouteEnvelopeBuilderWithRuntime } from "openclaw/plugin-sdk/inbound-envelope";
|
|
14
|
+
import { chunkText } from "openclaw/plugin-sdk/reply-chunking";
|
|
15
|
+
import {
|
|
16
|
+
DEFAULT_ACCOUNT_ID,
|
|
17
|
+
listRelayAccountIds,
|
|
18
|
+
resolveDefaultRelayAccountId,
|
|
19
|
+
resolveRelayAccount,
|
|
20
|
+
} from "./accounts.js";
|
|
21
|
+
import { RelayAccountLock } from "./account-lock.js";
|
|
22
|
+
import {
|
|
23
|
+
createRelayClient,
|
|
24
|
+
isAbortError,
|
|
25
|
+
isRelayWebhookConflict,
|
|
26
|
+
RelayApiError,
|
|
27
|
+
} from "./client.js";
|
|
28
|
+
import type { RelayClient } from "./client.js";
|
|
29
|
+
import { createRelayCursorStore, openRelayCursorStateStore } from "./cursor-store.js";
|
|
30
|
+
import { createRelayInboundDedupeGuard, createRelayInboundDeduper } from "./inbound-dedupe.js";
|
|
31
|
+
import { buildRelayInboundFacts } from "./inbound.js";
|
|
32
|
+
import type { RelayInboundFacts } from "./inbound.js";
|
|
33
|
+
import { createRelayAccountLifecycleRegistry } from "./lifecycle.js";
|
|
34
|
+
import {
|
|
35
|
+
deriveRelayIdempotencyKey,
|
|
36
|
+
RELAY_TEXT_CHUNK_LIMIT,
|
|
37
|
+
reconcileRelayUnknownSend,
|
|
38
|
+
sendRelayText,
|
|
39
|
+
} from "./outbound.js";
|
|
40
|
+
import { runRelayPollLoop } from "./poll-loop.js";
|
|
41
|
+
import { getRelayRuntime } from "./runtime.js";
|
|
42
|
+
import { relaySenderIsAllowed, resolveRelayAllowedSenderIds } from "./security.js";
|
|
43
|
+
import type { RelayCoreConfig, ResolvedRelayAccount } from "./types.js";
|
|
44
|
+
|
|
45
|
+
export const RELAY_CHANNEL_ID = "relay" as const;
|
|
46
|
+
|
|
47
|
+
const relayMeta = {
|
|
48
|
+
id: RELAY_CHANNEL_ID,
|
|
49
|
+
label: "Relay",
|
|
50
|
+
selectionLabel: "Relay",
|
|
51
|
+
detailLabel: "Relay",
|
|
52
|
+
docsPath: "https://docs.relayapp.im/integrations/openclaw",
|
|
53
|
+
blurb: "Text your OpenClaw like a friend.",
|
|
54
|
+
systemImage: "message",
|
|
55
|
+
// Relay renders plain text plus typed parts; no markdown dialect, so core
|
|
56
|
+
// strips formatting instead of leaking `**`.
|
|
57
|
+
markdownCapable: false,
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
function relayClientForAccount(account: ResolvedRelayAccount): RelayClient {
|
|
61
|
+
return createRelayClient({ baseUrl: account.baseUrl, token: account.token });
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// ---------------------------------------------------------------------------
|
|
65
|
+
// Outbound: durable message adapter.
|
|
66
|
+
// ---------------------------------------------------------------------------
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Reconciliation can only prove sends whose idempotency key it can rebuild
|
|
70
|
+
* exactly: one payload, one text, short enough that the renderer produced a
|
|
71
|
+
* single platform send (partIndex 0). Anything else (multi-payload,
|
|
72
|
+
* chunk-split, media) returns null so core keeps the intent unresolved
|
|
73
|
+
* instead of replaying a body that differs from the original.
|
|
74
|
+
*/
|
|
75
|
+
function resolveSingleReconcilableText(ctx: {
|
|
76
|
+
payloads: ReadonlyArray<unknown>;
|
|
77
|
+
renderedBatchPlan?: { textCount: number; mediaCount: number; payloadCount: number };
|
|
78
|
+
}): string | null {
|
|
79
|
+
if (ctx.payloads.length !== 1) {
|
|
80
|
+
return null;
|
|
81
|
+
}
|
|
82
|
+
const payload = ctx.payloads[0];
|
|
83
|
+
if (!payload || typeof payload !== "object" || !("text" in payload)) {
|
|
84
|
+
return null;
|
|
85
|
+
}
|
|
86
|
+
const text = (payload as { text?: unknown }).text;
|
|
87
|
+
if (typeof text !== "string" || !text.trim()) {
|
|
88
|
+
return null;
|
|
89
|
+
}
|
|
90
|
+
if (text.length > RELAY_TEXT_CHUNK_LIMIT) {
|
|
91
|
+
return null;
|
|
92
|
+
}
|
|
93
|
+
const plan = ctx.renderedBatchPlan;
|
|
94
|
+
if (plan && (plan.payloadCount !== 1 || plan.textCount > 1 || plan.mediaCount > 0)) {
|
|
95
|
+
return null;
|
|
96
|
+
}
|
|
97
|
+
return text;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
const relayMessageAdapter = defineChannelMessageAdapter({
|
|
101
|
+
id: RELAY_CHANNEL_ID,
|
|
102
|
+
durableFinal: {
|
|
103
|
+
capabilities: {
|
|
104
|
+
text: true,
|
|
105
|
+
replyTo: true,
|
|
106
|
+
// Plain per-send adapter functions: core's message-sending hooks run
|
|
107
|
+
// around every send, which the default durable requirement derivation
|
|
108
|
+
// demands (capabilities.ts requires it unless explicitly waived).
|
|
109
|
+
messageSendingHooks: true,
|
|
110
|
+
reconcileUnknownSend: true,
|
|
111
|
+
},
|
|
112
|
+
// Only single-part text sends: that is what replaying one idempotency key
|
|
113
|
+
// actually proves (multi-chunk sends have per-part keys and stay with the
|
|
114
|
+
// normal retry path).
|
|
115
|
+
reconcileUnknownSendKinds: { text: true },
|
|
116
|
+
reconcileUnknownSend: async (ctx) => {
|
|
117
|
+
const account = resolveRelayAccount({
|
|
118
|
+
cfg: ctx.cfg as RelayCoreConfig,
|
|
119
|
+
accountId: ctx.accountId,
|
|
120
|
+
});
|
|
121
|
+
if (!account.configured) {
|
|
122
|
+
return { status: "unresolved", error: "relay account not configured", retryable: false };
|
|
123
|
+
}
|
|
124
|
+
const text = resolveSingleReconcilableText(ctx);
|
|
125
|
+
if (text === null) {
|
|
126
|
+
return null;
|
|
127
|
+
}
|
|
128
|
+
const verdict = await reconcileRelayUnknownSend({
|
|
129
|
+
client: relayClientForAccount(account),
|
|
130
|
+
conversationId: ctx.to,
|
|
131
|
+
text,
|
|
132
|
+
replyToId: ctx.effectiveReplyToId ?? ctx.replyToId ?? null,
|
|
133
|
+
idempotencyKey: deriveRelayIdempotencyKey({ deliveryQueueId: ctx.queueId }),
|
|
134
|
+
});
|
|
135
|
+
if (verdict.status === "sent") {
|
|
136
|
+
return {
|
|
137
|
+
status: "sent",
|
|
138
|
+
messageId: verdict.messageId,
|
|
139
|
+
// The 202 is an array: name every message the send committed.
|
|
140
|
+
receipt: createMessageReceiptFromOutboundResults({
|
|
141
|
+
results: verdict.messages.map((message) => ({
|
|
142
|
+
channel: RELAY_CHANNEL_ID,
|
|
143
|
+
messageId: message.id,
|
|
144
|
+
})),
|
|
145
|
+
kind: "text",
|
|
146
|
+
}),
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
return verdict;
|
|
150
|
+
},
|
|
151
|
+
},
|
|
152
|
+
send: {
|
|
153
|
+
text: async (ctx) => {
|
|
154
|
+
const account = resolveRelayAccount({
|
|
155
|
+
cfg: ctx.cfg as RelayCoreConfig,
|
|
156
|
+
accountId: ctx.accountId,
|
|
157
|
+
});
|
|
158
|
+
if (!account.configured) {
|
|
159
|
+
throw new Error(`relay: account "${account.accountId}" has no Agent Token configured`);
|
|
160
|
+
}
|
|
161
|
+
const result = await sendRelayText({
|
|
162
|
+
client: relayClientForAccount(account),
|
|
163
|
+
conversationId: ctx.to,
|
|
164
|
+
text: ctx.text,
|
|
165
|
+
replyToId: ctx.replyToId ?? null,
|
|
166
|
+
// Stable per (queueId, partIndex): internal retries replay the same
|
|
167
|
+
// key, so the server-side idempotent commit makes duplicates
|
|
168
|
+
// impossible by contract.
|
|
169
|
+
idempotencyKey: deriveRelayIdempotencyKey({
|
|
170
|
+
deliveryQueueId: ctx.deliveryQueueId,
|
|
171
|
+
deliveryPartIndex: ctx.deliveryPartIndex,
|
|
172
|
+
}),
|
|
173
|
+
...(ctx.signal ? { signal: ctx.signal } : {}),
|
|
174
|
+
});
|
|
175
|
+
return {
|
|
176
|
+
messageId: result.messageId,
|
|
177
|
+
// The 202 is an array: name every message the send committed.
|
|
178
|
+
receipt: createMessageReceiptFromOutboundResults({
|
|
179
|
+
results: result.messages.map((message) => ({
|
|
180
|
+
channel: RELAY_CHANNEL_ID,
|
|
181
|
+
messageId: message.id,
|
|
182
|
+
})),
|
|
183
|
+
replyToId: ctx.replyToId ?? undefined,
|
|
184
|
+
kind: "text",
|
|
185
|
+
}),
|
|
186
|
+
};
|
|
187
|
+
},
|
|
188
|
+
},
|
|
189
|
+
receive: {
|
|
190
|
+
// Cursor acks after a durable at-most-once attempt marker is written.
|
|
191
|
+
defaultAckPolicy: "after_agent_dispatch",
|
|
192
|
+
supportedAckPolicies: ["after_receive_record", "after_agent_dispatch"],
|
|
193
|
+
},
|
|
194
|
+
});
|
|
195
|
+
|
|
196
|
+
// ---------------------------------------------------------------------------
|
|
197
|
+
// Inbound dispatch — qa-channel-shaped runtime wiring.
|
|
198
|
+
// ---------------------------------------------------------------------------
|
|
199
|
+
|
|
200
|
+
async function dispatchRelayInbound(params: {
|
|
201
|
+
cfg: OpenClawConfig;
|
|
202
|
+
account: ResolvedRelayAccount;
|
|
203
|
+
facts: RelayInboundFacts;
|
|
204
|
+
client: RelayClient;
|
|
205
|
+
allowedSenderIds: readonly string[];
|
|
206
|
+
markAttempt: () => Promise<void>;
|
|
207
|
+
}): Promise<void> {
|
|
208
|
+
const { account, facts } = params;
|
|
209
|
+
// Public Relay agents are discoverable, so contact membership is not an
|
|
210
|
+
// authorization boundary. Only the API-pinned owner and explicit operator
|
|
211
|
+
// allowlist entries may start an OpenClaw turn.
|
|
212
|
+
const dmPolicy = "allowlist" as const;
|
|
213
|
+
const allowFrom = [...params.allowedSenderIds];
|
|
214
|
+
const access = await resolveStableChannelMessageIngress({
|
|
215
|
+
channelId: RELAY_CHANNEL_ID,
|
|
216
|
+
accountId: account.accountId,
|
|
217
|
+
identity: { key: "sender", entryIdPrefix: "relay-entry" },
|
|
218
|
+
subject: { stableId: facts.senderId },
|
|
219
|
+
conversation: { kind: "direct", id: facts.conversationId },
|
|
220
|
+
dmPolicy,
|
|
221
|
+
allowFrom,
|
|
222
|
+
});
|
|
223
|
+
if (access.ingress.admission !== "dispatch") {
|
|
224
|
+
return;
|
|
225
|
+
}
|
|
226
|
+
const runtime = getRelayRuntime();
|
|
227
|
+
const { route, buildEnvelope } = resolveInboundRouteEnvelopeBuilderWithRuntime({
|
|
228
|
+
cfg: params.cfg,
|
|
229
|
+
channel: RELAY_CHANNEL_ID,
|
|
230
|
+
accountId: account.accountId,
|
|
231
|
+
peer: { kind: "direct", id: facts.conversationId },
|
|
232
|
+
runtime: runtime.channel,
|
|
233
|
+
sessionStore: (params.cfg as RelayCoreConfig).session?.store,
|
|
234
|
+
});
|
|
235
|
+
const commandAuthorized = relaySenderIsAllowed(params.allowedSenderIds, facts.senderId);
|
|
236
|
+
const { storePath, body } = buildEnvelope({
|
|
237
|
+
channel: relayMeta.label,
|
|
238
|
+
from: facts.senderId,
|
|
239
|
+
...(facts.timestamp ? { timestamp: facts.timestamp } : {}),
|
|
240
|
+
body: facts.text,
|
|
241
|
+
});
|
|
242
|
+
const ctxPayload = runtime.channel.reply.finalizeInboundContext({
|
|
243
|
+
Body: body,
|
|
244
|
+
BodyForAgent: facts.text,
|
|
245
|
+
RawBody: facts.text,
|
|
246
|
+
CommandBody: facts.text,
|
|
247
|
+
From: facts.conversationId,
|
|
248
|
+
To: facts.conversationId,
|
|
249
|
+
SessionKey: route.sessionKey,
|
|
250
|
+
AccountId: route.accountId ?? account.accountId,
|
|
251
|
+
ChatType: "direct",
|
|
252
|
+
ConversationLabel: facts.conversationId,
|
|
253
|
+
SenderId: facts.senderId,
|
|
254
|
+
SenderName: facts.senderId,
|
|
255
|
+
Provider: RELAY_CHANNEL_ID,
|
|
256
|
+
Surface: RELAY_CHANNEL_ID,
|
|
257
|
+
MessageSid: facts.messageId,
|
|
258
|
+
MessageSidFull: facts.messageId,
|
|
259
|
+
...(facts.replyToId ? { ReplyToId: facts.replyToId } : {}),
|
|
260
|
+
...(facts.timestamp ? { Timestamp: facts.timestamp } : {}),
|
|
261
|
+
OriginatingChannel: RELAY_CHANNEL_ID,
|
|
262
|
+
OriginatingTo: facts.conversationId,
|
|
263
|
+
CommandAuthorized: commandAuthorized,
|
|
264
|
+
});
|
|
265
|
+
// A consumed inbound message with a silently lost reply is the worst
|
|
266
|
+
// outcome. Delivery failures are surfaced, but the inbound attempt marker
|
|
267
|
+
// prevents replaying an agent turn whose tools may already have run.
|
|
268
|
+
let deliveryError: unknown;
|
|
269
|
+
let fallbackDeliveryIndex = 0;
|
|
270
|
+
const recordDeliveryError = (error: unknown) => {
|
|
271
|
+
deliveryError ??= error;
|
|
272
|
+
};
|
|
273
|
+
// Admission, runtime resolution, route/session lookup, envelope building,
|
|
274
|
+
// and context finalization above are replay-safe. The durable attempt starts
|
|
275
|
+
// immediately before OpenClaw can invoke the agent or its tools.
|
|
276
|
+
await params.markAttempt();
|
|
277
|
+
await runtime.channel.inbound.dispatchReply({
|
|
278
|
+
cfg: params.cfg,
|
|
279
|
+
channel: RELAY_CHANNEL_ID,
|
|
280
|
+
accountId: account.accountId,
|
|
281
|
+
agentId: route.agentId,
|
|
282
|
+
routeSessionKey: route.sessionKey,
|
|
283
|
+
storePath,
|
|
284
|
+
ctxPayload,
|
|
285
|
+
recordInboundSession: runtime.channel.session.recordInboundSession,
|
|
286
|
+
dispatchReplyWithBufferedBlockDispatcher:
|
|
287
|
+
runtime.channel.reply.dispatchReplyWithBufferedBlockDispatcher,
|
|
288
|
+
delivery: {
|
|
289
|
+
// Final replies go through the durable message adapter: core renders
|
|
290
|
+
// and chunks them (chunker + textChunkLimit) and tracks the send as a
|
|
291
|
+
// durable queue intent. Requiring reconcileUnknownSend forces
|
|
292
|
+
// `durability: "required"`, so single-payload finals carry a stable
|
|
293
|
+
// deliveryQueueId into send.text (stable idempotency key + exact
|
|
294
|
+
// replay), and multi-chunk finals get core's queue-level crash
|
|
295
|
+
// recovery. Replies land as plain messages, not quotes
|
|
296
|
+
// (`replyToId: null`).
|
|
297
|
+
durable: {
|
|
298
|
+
to: facts.conversationId,
|
|
299
|
+
replyToId: null,
|
|
300
|
+
requiredCapabilities: { reconcileUnknownSend: true },
|
|
301
|
+
},
|
|
302
|
+
// Fallback for payloads the durable path does not carry (non-final
|
|
303
|
+
// visible blocks). The event id + block/chunk ordinals identify each
|
|
304
|
+
// logical send: retries reuse it while identical intentional blocks and
|
|
305
|
+
// chunks remain distinct.
|
|
306
|
+
deliver: async (payload) => {
|
|
307
|
+
const text =
|
|
308
|
+
payload && typeof payload === "object" && "text" in payload
|
|
309
|
+
? ((payload as { text?: string }).text ?? "")
|
|
310
|
+
: "";
|
|
311
|
+
if (!text.trim()) {
|
|
312
|
+
return;
|
|
313
|
+
}
|
|
314
|
+
const logicalBlockId = `${facts.eventId}:block:${fallbackDeliveryIndex}`;
|
|
315
|
+
fallbackDeliveryIndex += 1;
|
|
316
|
+
try {
|
|
317
|
+
let chunkIndex = 0;
|
|
318
|
+
for (const chunk of chunkText(text, RELAY_TEXT_CHUNK_LIMIT)) {
|
|
319
|
+
await sendRelayText({
|
|
320
|
+
client: params.client,
|
|
321
|
+
conversationId: facts.conversationId,
|
|
322
|
+
text: chunk,
|
|
323
|
+
idempotencyKey: deriveRelayIdempotencyKey({
|
|
324
|
+
deliveryQueueId: logicalBlockId,
|
|
325
|
+
deliveryPartIndex: chunkIndex,
|
|
326
|
+
}),
|
|
327
|
+
});
|
|
328
|
+
chunkIndex += 1;
|
|
329
|
+
}
|
|
330
|
+
} catch (error) {
|
|
331
|
+
recordDeliveryError(error);
|
|
332
|
+
throw error;
|
|
333
|
+
}
|
|
334
|
+
},
|
|
335
|
+
onError: recordDeliveryError,
|
|
336
|
+
},
|
|
337
|
+
replyPipeline: {},
|
|
338
|
+
});
|
|
339
|
+
if (deliveryError) {
|
|
340
|
+
throw deliveryError instanceof Error
|
|
341
|
+
? deliveryError
|
|
342
|
+
: new Error(`relay reply delivery failed: ${String(deliveryError)}`);
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
// ---------------------------------------------------------------------------
|
|
347
|
+
// Gateway lifecycle.
|
|
348
|
+
// ---------------------------------------------------------------------------
|
|
349
|
+
|
|
350
|
+
/**
|
|
351
|
+
* One long-poll consumer per agent token: two configured
|
|
352
|
+
* accounts sharing a token would otherwise fight over the server's consumer
|
|
353
|
+
* slot in an endless 409 loop. Keyed by (baseUrl, agentId) from getMe.
|
|
354
|
+
*/
|
|
355
|
+
const runningRelayAgentAccounts = new Map<string, string>();
|
|
356
|
+
const relayAccountLifecycles = createRelayAccountLifecycleRegistry();
|
|
357
|
+
|
|
358
|
+
export function relayAgentAccountKey(baseUrl: string, agentId: string): string {
|
|
359
|
+
return `${baseUrl}\0${agentId}`;
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
async function startRelayAccount(ctx: ChannelGatewayContext<ResolvedRelayAccount>): Promise<void> {
|
|
363
|
+
const account = ctx.account;
|
|
364
|
+
if (!account.configured) {
|
|
365
|
+
throw new Error(
|
|
366
|
+
`Relay is not configured for account "${account.accountId}" (set channels.relay.token or ${account.accountId === DEFAULT_ACCOUNT_ID ? "RELAY_AGENT_TOKEN" : `channels.relay.accounts.${account.accountId}.token`}).`,
|
|
367
|
+
);
|
|
368
|
+
}
|
|
369
|
+
const log = (line: string) => ctx.log?.info?.(line);
|
|
370
|
+
const warn = (line: string) => ctx.log?.warn?.(line);
|
|
371
|
+
const client = relayClientForAccount(account);
|
|
372
|
+
const lifecycle = relayAccountLifecycles.acquire(account.accountId, ctx.abortSignal);
|
|
373
|
+
const abortSignal = lifecycle.signal;
|
|
374
|
+
let agentKey: string | undefined;
|
|
375
|
+
let accountLock: RelayAccountLock | undefined;
|
|
376
|
+
|
|
377
|
+
const markTerminalDisconnect = (error: Error) => {
|
|
378
|
+
// Operator action required: flag terminalDisconnect so the supervisor
|
|
379
|
+
// does not auto-restart (server-channels.ts:718).
|
|
380
|
+
ctx.setStatus({
|
|
381
|
+
accountId: account.accountId,
|
|
382
|
+
running: false,
|
|
383
|
+
connected: false,
|
|
384
|
+
terminalDisconnect: true,
|
|
385
|
+
lastError: error.message,
|
|
386
|
+
});
|
|
387
|
+
};
|
|
388
|
+
|
|
389
|
+
try {
|
|
390
|
+
const me = await client.getMe({ signal: abortSignal });
|
|
391
|
+
const allowedSenderIds = resolveRelayAllowedSenderIds({
|
|
392
|
+
profile: me,
|
|
393
|
+
allowFrom: account.config.allowFrom,
|
|
394
|
+
});
|
|
395
|
+
if (allowedSenderIds.length === 0) {
|
|
396
|
+
const error = new Error(
|
|
397
|
+
`relay: account "${account.accountId}" has no owner pin. ` +
|
|
398
|
+
"The Relay API did not return owner_user_id and channels.relay.allowFrom is empty.",
|
|
399
|
+
);
|
|
400
|
+
markTerminalDisconnect(error);
|
|
401
|
+
throw error;
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
// Two accounts configured with the same token would fight over the
|
|
405
|
+
// server's single consumer slot forever; keep the second one down until
|
|
406
|
+
// the operator fixes the config. account.baseUrl is already canonical.
|
|
407
|
+
agentKey = relayAgentAccountKey(account.baseUrl, me.id);
|
|
408
|
+
const owner = runningRelayAgentAccounts.get(agentKey);
|
|
409
|
+
if (owner !== undefined) {
|
|
410
|
+
const error = new Error(
|
|
411
|
+
`relay: agent ${me.id} is already polled by account "${owner}"; account "${account.accountId}" appears to reuse the same Agent Token. Give each account its own token.`,
|
|
412
|
+
);
|
|
413
|
+
markTerminalDisconnect(error);
|
|
414
|
+
throw error;
|
|
415
|
+
}
|
|
416
|
+
accountLock = new RelayAccountLock(account.baseUrl, me.id, account.accountId);
|
|
417
|
+
try {
|
|
418
|
+
accountLock.acquire();
|
|
419
|
+
} catch (error) {
|
|
420
|
+
const lockError = error instanceof Error ? error : new Error(String(error));
|
|
421
|
+
markTerminalDisconnect(lockError);
|
|
422
|
+
throw lockError;
|
|
423
|
+
}
|
|
424
|
+
runningRelayAgentAccounts.set(agentKey, account.accountId);
|
|
425
|
+
|
|
426
|
+
ctx.setStatus({
|
|
427
|
+
accountId: account.accountId,
|
|
428
|
+
running: true,
|
|
429
|
+
connected: true,
|
|
430
|
+
configured: true,
|
|
431
|
+
enabled: account.enabled,
|
|
432
|
+
});
|
|
433
|
+
|
|
434
|
+
const cursorStore = createRelayCursorStore({
|
|
435
|
+
store: openRelayCursorStateStore(warn),
|
|
436
|
+
baseUrl: account.baseUrl,
|
|
437
|
+
agentId: me.id,
|
|
438
|
+
onPersistError: (error) => warn(`[relay] cursor persistence failed: ${String(error)}`),
|
|
439
|
+
});
|
|
440
|
+
await cursorStore.load();
|
|
441
|
+
const deduper = createRelayInboundDeduper({
|
|
442
|
+
guard: createRelayInboundDedupeGuard({
|
|
443
|
+
onDiskError: (error) => warn(`[relay] inbound dedupe persistence failed: ${String(error)}`),
|
|
444
|
+
}),
|
|
445
|
+
baseUrl: account.baseUrl,
|
|
446
|
+
agentId: me.id,
|
|
447
|
+
});
|
|
448
|
+
|
|
449
|
+
await runRelayPollLoop({
|
|
450
|
+
client,
|
|
451
|
+
cursorStore,
|
|
452
|
+
deduper,
|
|
453
|
+
abortSignal,
|
|
454
|
+
timeoutSeconds: account.pollTimeoutSeconds,
|
|
455
|
+
limit: 100,
|
|
456
|
+
log,
|
|
457
|
+
// Receipts, reactions, and echoes are acked without a dedupe row or a
|
|
458
|
+
// dispatch: reaction.* is observe-only at v1, delivered/read
|
|
459
|
+
// are bookkeeping.
|
|
460
|
+
shouldProcess: (event) => buildRelayInboundFacts(event, { agentId: me.id }) !== null,
|
|
461
|
+
onBatch: () => {
|
|
462
|
+
ctx.setStatus({
|
|
463
|
+
accountId: account.accountId,
|
|
464
|
+
running: true,
|
|
465
|
+
connected: true,
|
|
466
|
+
lastInboundAt: Date.now(),
|
|
467
|
+
});
|
|
468
|
+
},
|
|
469
|
+
handleEvent: async (event, markAttempt) => {
|
|
470
|
+
const facts = buildRelayInboundFacts(event, { agentId: me.id });
|
|
471
|
+
if (!facts) {
|
|
472
|
+
return;
|
|
473
|
+
}
|
|
474
|
+
await dispatchRelayInbound({
|
|
475
|
+
cfg: ctx.cfg,
|
|
476
|
+
account,
|
|
477
|
+
facts,
|
|
478
|
+
client,
|
|
479
|
+
allowedSenderIds,
|
|
480
|
+
markAttempt,
|
|
481
|
+
});
|
|
482
|
+
// Read watermark after the turn is handled: read implies delivered;
|
|
483
|
+
// best effort — a failed receipt must not replay the event.
|
|
484
|
+
await client
|
|
485
|
+
.markRead({ conversationId: facts.conversationId, messageId: facts.messageId })
|
|
486
|
+
.catch((error) => log(`[relay] markRead failed: ${String(error)}`));
|
|
487
|
+
},
|
|
488
|
+
});
|
|
489
|
+
} catch (error) {
|
|
490
|
+
if (abortSignal.aborted || isAbortError(error)) {
|
|
491
|
+
return;
|
|
492
|
+
}
|
|
493
|
+
if (error instanceof RelayApiError && error.terminal) {
|
|
494
|
+
markTerminalDisconnect(error);
|
|
495
|
+
} else if (isRelayWebhookConflict(error)) {
|
|
496
|
+
// Webhook XOR: long polling stays 409 until the operator
|
|
497
|
+
// disables the webhook endpoint — restarting cannot fix it.
|
|
498
|
+
// `terminated_by_other_consumer` intentionally falls through to the
|
|
499
|
+
// supervisor's normal restart/backoff arbitration.
|
|
500
|
+
markTerminalDisconnect(error);
|
|
501
|
+
}
|
|
502
|
+
throw error;
|
|
503
|
+
} finally {
|
|
504
|
+
if (agentKey && runningRelayAgentAccounts.get(agentKey) === account.accountId) {
|
|
505
|
+
runningRelayAgentAccounts.delete(agentKey);
|
|
506
|
+
}
|
|
507
|
+
accountLock?.release();
|
|
508
|
+
lifecycle.release();
|
|
509
|
+
ctx.setStatus({
|
|
510
|
+
accountId: account.accountId,
|
|
511
|
+
running: false,
|
|
512
|
+
connected: false,
|
|
513
|
+
});
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
async function stopRelayAccount(
|
|
518
|
+
ctx: ChannelGatewayContext<ResolvedRelayAccount>,
|
|
519
|
+
): Promise<void> {
|
|
520
|
+
relayAccountLifecycles.stop(ctx.accountId);
|
|
521
|
+
ctx.setStatus({
|
|
522
|
+
accountId: ctx.accountId,
|
|
523
|
+
running: false,
|
|
524
|
+
connected: false,
|
|
525
|
+
});
|
|
526
|
+
ctx.log?.info?.(`[relay] stopped account "${ctx.accountId}"`);
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
// ---------------------------------------------------------------------------
|
|
530
|
+
// Plugin object.
|
|
531
|
+
// ---------------------------------------------------------------------------
|
|
532
|
+
|
|
533
|
+
export const relayChannelPlugin: ChannelPlugin<ResolvedRelayAccount> = createChatChannelPlugin({
|
|
534
|
+
base: {
|
|
535
|
+
id: RELAY_CHANNEL_ID,
|
|
536
|
+
meta: relayMeta,
|
|
537
|
+
capabilities: {
|
|
538
|
+
// v1: direct conversations only; media flips on when the agent
|
|
539
|
+
// attachment path ships. Reactions are observe-only.
|
|
540
|
+
chatTypes: ["direct"],
|
|
541
|
+
reply: true,
|
|
542
|
+
threads: false,
|
|
543
|
+
media: false,
|
|
544
|
+
reactions: false,
|
|
545
|
+
},
|
|
546
|
+
reload: { configPrefixes: ["channels.relay"] },
|
|
547
|
+
setup: {
|
|
548
|
+
applyAccountConfig: ({ cfg, accountId, input }) => {
|
|
549
|
+
const coreCfg = cfg as RelayCoreConfig;
|
|
550
|
+
const channelSection = { ...coreCfg.channels?.relay };
|
|
551
|
+
const patch = input as Record<string, unknown>;
|
|
552
|
+
const next =
|
|
553
|
+
!accountId || accountId === DEFAULT_ACCOUNT_ID
|
|
554
|
+
? { ...channelSection, ...patch }
|
|
555
|
+
: {
|
|
556
|
+
...channelSection,
|
|
557
|
+
accounts: {
|
|
558
|
+
...channelSection.accounts,
|
|
559
|
+
[accountId]: {
|
|
560
|
+
...channelSection.accounts?.[accountId],
|
|
561
|
+
...patch,
|
|
562
|
+
},
|
|
563
|
+
},
|
|
564
|
+
};
|
|
565
|
+
return {
|
|
566
|
+
...cfg,
|
|
567
|
+
channels: {
|
|
568
|
+
...coreCfg.channels,
|
|
569
|
+
relay: next,
|
|
570
|
+
},
|
|
571
|
+
} as OpenClawConfig;
|
|
572
|
+
},
|
|
573
|
+
},
|
|
574
|
+
config: {
|
|
575
|
+
listAccountIds: (cfg) => listRelayAccountIds(cfg as RelayCoreConfig),
|
|
576
|
+
resolveAccount: (cfg, accountId) =>
|
|
577
|
+
resolveRelayAccount({ cfg: cfg as RelayCoreConfig, accountId }),
|
|
578
|
+
defaultAccountId: (cfg) => resolveDefaultRelayAccountId(cfg as RelayCoreConfig),
|
|
579
|
+
isConfigured: (account) => account.configured,
|
|
580
|
+
inspectAccount: (cfg, accountId) => {
|
|
581
|
+
const account = resolveRelayAccount({ cfg: cfg as RelayCoreConfig, accountId });
|
|
582
|
+
return {
|
|
583
|
+
enabled: account.enabled,
|
|
584
|
+
configured: account.configured,
|
|
585
|
+
tokenStatus: account.configured ? "available" : "missing",
|
|
586
|
+
baseUrl: account.baseUrl,
|
|
587
|
+
};
|
|
588
|
+
},
|
|
589
|
+
resolveAllowFrom: ({ cfg, accountId }) =>
|
|
590
|
+
resolveRelayAllowedSenderIds({
|
|
591
|
+
profile: {},
|
|
592
|
+
allowFrom: resolveRelayAccount({ cfg: cfg as RelayCoreConfig, accountId }).config
|
|
593
|
+
.allowFrom,
|
|
594
|
+
}),
|
|
595
|
+
},
|
|
596
|
+
messaging: {
|
|
597
|
+
targetResolver: {
|
|
598
|
+
looksLikeId: (raw) => /^cnv_[A-Za-z0-9]+$/.test(raw.trim()),
|
|
599
|
+
hint: "<cnv_…> (Relay conversation id from message.received)",
|
|
600
|
+
},
|
|
601
|
+
},
|
|
602
|
+
gateway: {
|
|
603
|
+
startAccount: startRelayAccount,
|
|
604
|
+
stopAccount: stopRelayAccount,
|
|
605
|
+
},
|
|
606
|
+
heartbeat: {
|
|
607
|
+
// Ephemeral typing indicator: POST typing start/stop.
|
|
608
|
+
sendTyping: async ({ cfg, to, accountId }) => {
|
|
609
|
+
const account = resolveRelayAccount({ cfg: cfg as RelayCoreConfig, accountId });
|
|
610
|
+
if (!account.configured) {
|
|
611
|
+
return;
|
|
612
|
+
}
|
|
613
|
+
await relayClientForAccount(account).setTyping({ conversationId: to, started: true });
|
|
614
|
+
},
|
|
615
|
+
clearTyping: async ({ cfg, to, accountId }) => {
|
|
616
|
+
const account = resolveRelayAccount({ cfg: cfg as RelayCoreConfig, accountId });
|
|
617
|
+
if (!account.configured) {
|
|
618
|
+
return;
|
|
619
|
+
}
|
|
620
|
+
await relayClientForAccount(account).setTyping({ conversationId: to, started: false });
|
|
621
|
+
},
|
|
622
|
+
},
|
|
623
|
+
message: relayMessageAdapter,
|
|
624
|
+
},
|
|
625
|
+
security: {
|
|
626
|
+
dm: {
|
|
627
|
+
channelKey: RELAY_CHANNEL_ID,
|
|
628
|
+
resolvePolicy: () => "allowlist",
|
|
629
|
+
resolveAllowFrom: (account) =>
|
|
630
|
+
resolveRelayAllowedSenderIds({ profile: {}, allowFrom: account.config.allowFrom }),
|
|
631
|
+
defaultPolicy: "allowlist",
|
|
632
|
+
},
|
|
633
|
+
},
|
|
634
|
+
outbound: {
|
|
635
|
+
base: {
|
|
636
|
+
deliveryMode: "direct",
|
|
637
|
+
// Core's renderer splits long replies before the adapter sees them
|
|
638
|
+
// without a chunker the plan falls back to one oversized
|
|
639
|
+
// unit, which the server 422s at its 8 KiB per-part cap.
|
|
640
|
+
chunker: (text, limit) => chunkText(text, limit),
|
|
641
|
+
chunkerMode: "text",
|
|
642
|
+
textChunkLimit: RELAY_TEXT_CHUNK_LIMIT,
|
|
643
|
+
},
|
|
644
|
+
attachedResults: {
|
|
645
|
+
channel: RELAY_CHANNEL_ID,
|
|
646
|
+
sendText: async (ctx) => {
|
|
647
|
+
const { cfg, to, text, accountId, replyToId } = ctx;
|
|
648
|
+
const account = resolveRelayAccount({ cfg: cfg as RelayCoreConfig, accountId });
|
|
649
|
+
if (!account.configured) {
|
|
650
|
+
throw new Error(`relay: account "${account.accountId}" has no Agent Token configured`);
|
|
651
|
+
}
|
|
652
|
+
const normalizedReplyToId = replyToId == null ? null : String(replyToId);
|
|
653
|
+
const result = await sendRelayText({
|
|
654
|
+
client: relayClientForAccount(account),
|
|
655
|
+
conversationId: to,
|
|
656
|
+
text,
|
|
657
|
+
replyToId: normalizedReplyToId,
|
|
658
|
+
// Stable when core supplies a logical queue id; otherwise fresh for
|
|
659
|
+
// this invocation so two intentional identical sends remain two.
|
|
660
|
+
idempotencyKey: deriveRelayIdempotencyKey({
|
|
661
|
+
deliveryQueueId: ctx.deliveryQueueId,
|
|
662
|
+
deliveryPartIndex: ctx.deliveryPartIndex,
|
|
663
|
+
}),
|
|
664
|
+
});
|
|
665
|
+
return { messageId: result.messageId };
|
|
666
|
+
},
|
|
667
|
+
},
|
|
668
|
+
},
|
|
669
|
+
});
|