@cored-im/openclaw-plugin 0.1.3 → 0.1.5
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/dist/index.cjs +196 -54
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +11 -60
- package/dist/index.d.ts +11 -60
- package/dist/index.js +201 -54
- package/dist/index.js.map +1 -1
- package/dist/setup-entry.cjs +311 -36
- package/dist/setup-entry.cjs.map +1 -1
- package/dist/setup-entry.d.cts +9 -1
- package/dist/setup-entry.d.ts +9 -1
- package/dist/setup-entry.js +314 -36
- package/dist/setup-entry.js.map +1 -1
- package/openclaw.plugin.json +2 -3
- package/package.json +3 -3
- package/src/channel.ts +152 -4
- package/src/index.test.ts +52 -26
- package/src/index.ts +56 -44
- package/src/messaging/inbound.ts +43 -11
- package/src/setup-entry.ts +2 -46
- package/src/types.ts +3 -33
- package/src/typings/openclaw-plugin-sdk.d.ts +152 -19
package/dist/setup-entry.js
CHANGED
|
@@ -1,45 +1,323 @@
|
|
|
1
1
|
// src/setup-entry.ts
|
|
2
2
|
import { defineSetupPluginEntry } from "openclaw/plugin-sdk/core";
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
3
|
+
|
|
4
|
+
// src/channel.ts
|
|
5
|
+
import {
|
|
6
|
+
createChatChannelPlugin,
|
|
7
|
+
createChannelPluginBase
|
|
8
|
+
} from "openclaw/plugin-sdk/core";
|
|
9
|
+
|
|
10
|
+
// src/config.ts
|
|
11
|
+
var DEFAULTS = {
|
|
12
|
+
enableEncryption: true,
|
|
13
|
+
requestTimeout: 3e4,
|
|
14
|
+
requireMention: true,
|
|
15
|
+
inboundWhitelist: []
|
|
16
|
+
};
|
|
17
|
+
var ENV_PREFIX = "CORED_";
|
|
18
|
+
function getChannelConfig(cfg) {
|
|
19
|
+
const root = cfg;
|
|
20
|
+
return root?.channels ? root.channels.cored : void 0;
|
|
21
|
+
}
|
|
22
|
+
function readEnvConfig() {
|
|
23
|
+
const env = process.env;
|
|
24
|
+
const result = {};
|
|
25
|
+
if (env[`${ENV_PREFIX}APP_ID`]) result.appId = env[`${ENV_PREFIX}APP_ID`];
|
|
26
|
+
if (env[`${ENV_PREFIX}APP_SECRET`])
|
|
27
|
+
result.appSecret = env[`${ENV_PREFIX}APP_SECRET`];
|
|
28
|
+
if (env[`${ENV_PREFIX}BACKEND_URL`])
|
|
29
|
+
result.backendUrl = env[`${ENV_PREFIX}BACKEND_URL`];
|
|
30
|
+
if (env[`${ENV_PREFIX}ENABLE_ENCRYPTION`] !== void 0)
|
|
31
|
+
result.enableEncryption = env[`${ENV_PREFIX}ENABLE_ENCRYPTION`] !== "false";
|
|
32
|
+
if (env[`${ENV_PREFIX}REQUEST_TIMEOUT`])
|
|
33
|
+
result.requestTimeout = Number(env[`${ENV_PREFIX}REQUEST_TIMEOUT`]);
|
|
34
|
+
if (env[`${ENV_PREFIX}REQUIRE_MENTION`] !== void 0)
|
|
35
|
+
result.requireMention = env[`${ENV_PREFIX}REQUIRE_MENTION`] !== "false";
|
|
36
|
+
if (env[`${ENV_PREFIX}BOT_USER_ID`])
|
|
37
|
+
result.botUserId = env[`${ENV_PREFIX}BOT_USER_ID`];
|
|
38
|
+
return result;
|
|
39
|
+
}
|
|
40
|
+
function listAccountIds(cfg) {
|
|
41
|
+
const ch = getChannelConfig(cfg);
|
|
42
|
+
if (!ch) {
|
|
43
|
+
if (process.env[`${ENV_PREFIX}APP_ID`]) return ["default"];
|
|
44
|
+
return [];
|
|
45
|
+
}
|
|
46
|
+
if (ch.accounts) return Object.keys(ch.accounts);
|
|
47
|
+
if (ch.appId) return ["default"];
|
|
48
|
+
if (process.env[`${ENV_PREFIX}APP_ID`]) return ["default"];
|
|
49
|
+
return [];
|
|
50
|
+
}
|
|
51
|
+
function resolveAccountConfig(cfg, accountId) {
|
|
52
|
+
const ch = getChannelConfig(cfg);
|
|
53
|
+
const id = accountId ?? "default";
|
|
54
|
+
const envConfig = readEnvConfig();
|
|
55
|
+
const raw = ch?.accounts?.[id] ?? ch;
|
|
56
|
+
return {
|
|
57
|
+
accountId: id,
|
|
58
|
+
enabled: raw?.enabled ?? true,
|
|
59
|
+
appId: raw?.appId ?? envConfig.appId ?? "",
|
|
60
|
+
appSecret: raw?.appSecret ?? envConfig.appSecret ?? "",
|
|
61
|
+
backendUrl: raw?.backendUrl ?? envConfig.backendUrl ?? "",
|
|
62
|
+
enableEncryption: raw?.enableEncryption ?? envConfig.enableEncryption ?? DEFAULTS.enableEncryption,
|
|
63
|
+
requestTimeout: raw?.requestTimeout ?? envConfig.requestTimeout ?? DEFAULTS.requestTimeout,
|
|
64
|
+
requireMention: raw?.requireMention ?? envConfig.requireMention ?? DEFAULTS.requireMention,
|
|
65
|
+
botUserId: raw?.botUserId ?? envConfig.botUserId,
|
|
66
|
+
inboundWhitelist: raw?.inboundWhitelist ?? [...DEFAULTS.inboundWhitelist]
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// src/core/cored-client.ts
|
|
71
|
+
import { CoredClient, LoggerLevel, ApiError } from "@cored-im/sdk";
|
|
72
|
+
var AUTH_ERROR_CODE = 40000006;
|
|
73
|
+
function isAuthError(err) {
|
|
74
|
+
return err instanceof ApiError && err.code === AUTH_ERROR_CODE;
|
|
75
|
+
}
|
|
76
|
+
var MessageType_TEXT = "text";
|
|
77
|
+
var clients = /* @__PURE__ */ new Map();
|
|
78
|
+
function getClient(accountId) {
|
|
79
|
+
if (accountId && clients.has(accountId)) return clients.get(accountId);
|
|
80
|
+
if (clients.size > 0) return clients.values().next().value;
|
|
81
|
+
return void 0;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// src/messaging/outbound.ts
|
|
85
|
+
async function sendText(chatId, text, accountId, replyMessageId, logWarn) {
|
|
86
|
+
const managed = getClient(accountId);
|
|
87
|
+
if (!managed) {
|
|
88
|
+
return {
|
|
89
|
+
ok: false,
|
|
90
|
+
error: new Error(
|
|
91
|
+
`[cored] no connected client for account=${accountId ?? "default"}`
|
|
92
|
+
)
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
const req = {
|
|
96
|
+
chat_id: chatId,
|
|
97
|
+
message_type: MessageType_TEXT,
|
|
98
|
+
message_content: {
|
|
99
|
+
text: { content: text }
|
|
100
|
+
},
|
|
101
|
+
reply_message_id: replyMessageId
|
|
102
|
+
};
|
|
103
|
+
try {
|
|
104
|
+
const resp = await managed.client.Im.v1.Message.sendMessage(req);
|
|
105
|
+
return { ok: true, messageId: resp.message_id, provider: "cored" };
|
|
106
|
+
} catch (err) {
|
|
107
|
+
if (!isAuthError(err)) {
|
|
108
|
+
return {
|
|
109
|
+
ok: false,
|
|
110
|
+
error: new Error(
|
|
111
|
+
`[cored] send failed for chat=${chatId}: ${err instanceof Error ? err.message : String(err)}`
|
|
112
|
+
)
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
logWarn?.(
|
|
116
|
+
`[cored] auth error on send (chat=${chatId}, account=${accountId ?? "default"}) \u2014 refreshing token and retrying`
|
|
117
|
+
);
|
|
118
|
+
try {
|
|
119
|
+
await managed.client.preheat();
|
|
120
|
+
const resp = await managed.client.Im.v1.Message.sendMessage(req);
|
|
121
|
+
logWarn?.(
|
|
122
|
+
`[cored] auth retry succeeded (chat=${chatId}, account=${accountId ?? "default"})`
|
|
123
|
+
);
|
|
124
|
+
return { ok: true, messageId: resp.message_id, provider: "cored" };
|
|
125
|
+
} catch (retryErr) {
|
|
126
|
+
return {
|
|
127
|
+
ok: false,
|
|
128
|
+
error: new Error(
|
|
129
|
+
`[cored] send failed after auth retry for chat=${chatId}: ${retryErr instanceof Error ? retryErr.message : String(retryErr)}`
|
|
130
|
+
)
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
// src/targets.ts
|
|
137
|
+
function parseTarget(to) {
|
|
138
|
+
const raw = String(to ?? "").trim();
|
|
139
|
+
if (!raw) return null;
|
|
140
|
+
const stripped = raw.replace(/^cored:/i, "");
|
|
141
|
+
if (stripped.startsWith("user:")) {
|
|
142
|
+
const id = stripped.slice("user:".length).trim();
|
|
143
|
+
return id ? { kind: "user", id } : null;
|
|
144
|
+
}
|
|
145
|
+
if (stripped.startsWith("chat:")) {
|
|
146
|
+
const id = stripped.slice("chat:".length).trim();
|
|
147
|
+
return id ? { kind: "chat", id } : null;
|
|
148
|
+
}
|
|
149
|
+
return stripped ? { kind: "chat", id: stripped } : null;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
// src/channel.ts
|
|
153
|
+
function resolveAccount(cfg, accountId) {
|
|
154
|
+
const section = cfg.channels?.["cored"];
|
|
155
|
+
const accounts = section?.accounts;
|
|
156
|
+
const defaultAccount = section?.defaultAccount;
|
|
157
|
+
if (accounts && Object.keys(accounts).length > 0) {
|
|
158
|
+
const targetId = accountId ?? defaultAccount ?? Object.keys(accounts)[0];
|
|
159
|
+
const account = accounts[targetId];
|
|
160
|
+
if (!account) {
|
|
161
|
+
throw new Error(`cored: account "${targetId}" not found`);
|
|
162
|
+
}
|
|
163
|
+
return {
|
|
164
|
+
accountId: targetId,
|
|
165
|
+
appId: account.appId,
|
|
166
|
+
appSecret: account.appSecret,
|
|
167
|
+
backendUrl: account.backendUrl,
|
|
168
|
+
enableEncryption: account.enableEncryption ?? section.enableEncryption ?? true,
|
|
169
|
+
requestTimeout: account.requestTimeout ?? section.requestTimeout ?? 3e4,
|
|
170
|
+
requireMention: account.requireMention ?? section.requireMention ?? true
|
|
171
|
+
};
|
|
172
|
+
}
|
|
173
|
+
const appId = section?.appId;
|
|
174
|
+
const appSecret = section?.appSecret;
|
|
175
|
+
const backendUrl = section?.backendUrl;
|
|
176
|
+
if (!appId || !appSecret || !backendUrl) {
|
|
177
|
+
throw new Error("cored: appId, appSecret, and backendUrl are required");
|
|
178
|
+
}
|
|
179
|
+
return {
|
|
180
|
+
accountId: null,
|
|
181
|
+
appId,
|
|
182
|
+
appSecret,
|
|
183
|
+
backendUrl,
|
|
184
|
+
enableEncryption: section?.enableEncryption ?? true,
|
|
185
|
+
requestTimeout: section?.requestTimeout ?? 3e4,
|
|
186
|
+
requireMention: section?.requireMention ?? true
|
|
187
|
+
};
|
|
188
|
+
}
|
|
189
|
+
var coredPlugin = createChatChannelPlugin({
|
|
190
|
+
base: createChannelPluginBase({
|
|
191
|
+
id: "cored",
|
|
192
|
+
setup: {
|
|
193
|
+
resolveAccount,
|
|
194
|
+
inspectAccount(cfg, accountId) {
|
|
195
|
+
const section = cfg.channels?.["cored"];
|
|
196
|
+
const hasConfig = Boolean(
|
|
197
|
+
section?.appId && section?.appSecret && section?.backendUrl
|
|
198
|
+
);
|
|
199
|
+
return {
|
|
200
|
+
enabled: Boolean(section?.enabled !== false),
|
|
201
|
+
configured: hasConfig,
|
|
202
|
+
tokenStatus: hasConfig ? "available" : "missing"
|
|
203
|
+
};
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
}),
|
|
207
|
+
// Plugin metadata
|
|
208
|
+
meta: {
|
|
209
|
+
id: "cored",
|
|
210
|
+
label: "Cored",
|
|
211
|
+
selectionLabel: "Cored",
|
|
212
|
+
docsPath: "/channels/cored",
|
|
213
|
+
blurb: "Connect OpenClaw to Cored",
|
|
214
|
+
aliases: ["cored", "co"]
|
|
215
|
+
},
|
|
216
|
+
// Capabilities
|
|
217
|
+
capabilities: {
|
|
218
|
+
chatTypes: ["direct", "group"]
|
|
219
|
+
},
|
|
220
|
+
// Config
|
|
221
|
+
config: {
|
|
222
|
+
listAccountIds: (cfg) => listAccountIds(cfg),
|
|
223
|
+
resolveAccount: (cfg, accountId) => resolveAccountConfig(cfg, accountId)
|
|
224
|
+
},
|
|
225
|
+
// Outbound messaging
|
|
226
|
+
outbound: {
|
|
227
|
+
deliveryMode: "direct",
|
|
228
|
+
resolveTarget: ({ to }) => {
|
|
229
|
+
const target = parseTarget(to);
|
|
230
|
+
if (!target) {
|
|
231
|
+
return {
|
|
232
|
+
ok: false,
|
|
233
|
+
error: new Error(
|
|
234
|
+
`Cored requires --to <user:ID|chat:ID>, got: ${JSON.stringify(to)}`
|
|
235
|
+
)
|
|
236
|
+
};
|
|
237
|
+
}
|
|
238
|
+
return { ok: true, to: `${target.kind}:${target.id}` };
|
|
239
|
+
},
|
|
240
|
+
sendText: async ({
|
|
241
|
+
to,
|
|
242
|
+
text,
|
|
243
|
+
accountId
|
|
244
|
+
}) => {
|
|
245
|
+
const target = parseTarget(to);
|
|
246
|
+
if (!target) {
|
|
247
|
+
return {
|
|
248
|
+
ok: false,
|
|
249
|
+
error: new Error(`[cored] invalid send target: ${to}`)
|
|
250
|
+
};
|
|
251
|
+
}
|
|
252
|
+
return sendText(target.id, text, accountId);
|
|
253
|
+
}
|
|
254
|
+
},
|
|
255
|
+
// Setup wizard for openclaw onboard
|
|
256
|
+
setupWizard: {
|
|
257
|
+
channel: "cored",
|
|
258
|
+
status: {
|
|
259
|
+
configuredLabel: "Connected",
|
|
260
|
+
unconfiguredLabel: "Not configured",
|
|
261
|
+
resolveConfigured: ({ cfg }) => {
|
|
262
|
+
const section = cfg.channels?.["cored"];
|
|
263
|
+
return Boolean(section?.appId && section?.appSecret && section?.backendUrl);
|
|
264
|
+
}
|
|
265
|
+
},
|
|
266
|
+
credentials: [
|
|
267
|
+
{
|
|
268
|
+
inputKey: "appId",
|
|
269
|
+
providerHint: "cored",
|
|
270
|
+
credentialLabel: "App ID",
|
|
271
|
+
preferredEnvVar: "CORED_APP_ID",
|
|
272
|
+
envPrompt: "Use CORED_APP_ID from environment?",
|
|
273
|
+
keepPrompt: "Keep current App ID?",
|
|
274
|
+
inputPrompt: "Enter your Cored App ID:",
|
|
275
|
+
inspect: ({ cfg }) => {
|
|
276
|
+
const section = cfg.channels?.["cored"];
|
|
277
|
+
return {
|
|
278
|
+
accountConfigured: Boolean(section?.appId),
|
|
279
|
+
hasConfiguredValue: Boolean(section?.appId)
|
|
280
|
+
};
|
|
281
|
+
}
|
|
282
|
+
},
|
|
283
|
+
{
|
|
284
|
+
inputKey: "appSecret",
|
|
285
|
+
providerHint: "cored",
|
|
286
|
+
credentialLabel: "App Secret",
|
|
287
|
+
preferredEnvVar: "CORED_APP_SECRET",
|
|
288
|
+
envPrompt: "Use CORED_APP_SECRET from environment?",
|
|
289
|
+
keepPrompt: "Keep current App Secret?",
|
|
290
|
+
inputPrompt: "Enter your Cored App Secret:",
|
|
291
|
+
inspect: ({ cfg }) => {
|
|
292
|
+
const section = cfg.channels?.["cored"];
|
|
293
|
+
return {
|
|
294
|
+
accountConfigured: Boolean(section?.appSecret),
|
|
295
|
+
hasConfiguredValue: Boolean(section?.appSecret)
|
|
296
|
+
};
|
|
297
|
+
}
|
|
298
|
+
},
|
|
299
|
+
{
|
|
300
|
+
inputKey: "backendUrl",
|
|
301
|
+
providerHint: "cored",
|
|
302
|
+
credentialLabel: "Backend URL",
|
|
303
|
+
preferredEnvVar: "CORED_BACKEND_URL",
|
|
304
|
+
envPrompt: "Use CORED_BACKEND_URL from environment?",
|
|
305
|
+
keepPrompt: "Keep current Backend URL?",
|
|
306
|
+
inputPrompt: "Enter your Cored backend server URL:",
|
|
307
|
+
inspect: ({ cfg }) => {
|
|
308
|
+
const section = cfg.channels?.["cored"];
|
|
309
|
+
return {
|
|
310
|
+
accountConfigured: Boolean(section?.backendUrl),
|
|
311
|
+
hasConfiguredValue: Boolean(section?.backendUrl)
|
|
312
|
+
};
|
|
25
313
|
}
|
|
26
314
|
}
|
|
27
|
-
|
|
28
|
-
const enableEncryption = await context.prompt({
|
|
29
|
-
type: "confirm",
|
|
30
|
-
message: "Enable message encryption?",
|
|
31
|
-
default: true
|
|
32
|
-
});
|
|
33
|
-
await context.updateConfig("channels.cored.appId", appId);
|
|
34
|
-
await context.updateConfig("channels.cored.appSecret", appSecret);
|
|
35
|
-
await context.updateConfig("channels.cored.backendUrl", backendUrl);
|
|
36
|
-
await context.updateConfig("channels.cored.enableEncryption", enableEncryption);
|
|
37
|
-
await context.updateConfig("channels.cored.enabled", true);
|
|
38
|
-
console.log("\u2705 Cored channel configuration saved successfully!");
|
|
39
|
-
console.log("\u{1F4C4} Config file: ~/.openclaw/openclaw.json");
|
|
40
|
-
console.log("\u{1F4D6} Deploy docs: https://coredim.com/docs/admin/bots/openclaw");
|
|
315
|
+
]
|
|
41
316
|
}
|
|
42
317
|
});
|
|
318
|
+
|
|
319
|
+
// src/setup-entry.ts
|
|
320
|
+
var setup_entry_default = defineSetupPluginEntry(coredPlugin);
|
|
43
321
|
export {
|
|
44
322
|
setup_entry_default as default
|
|
45
323
|
};
|
package/dist/setup-entry.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/setup-entry.ts"],"sourcesContent":["// Copyright (c) 2026 Cored Limited\n// SPDX-License-Identifier: Apache-2.0\n\nimport { defineSetupPluginEntry } from \"openclaw/plugin-sdk/core\";\n\nexport default defineSetupPluginEntry({\n async onSetup(context) {\n const appId = await context.prompt({\n type: \"text\",\n message: \"Enter your Cored App ID:\",\n validate: (val: string) => val.length > 0 || \"This field is required\",\n });\n\n const appSecret = await context.prompt({\n type: \"password\",\n message: \"Enter your Cored App Secret:\",\n validate: (val: string) => val.length > 0 || \"This field is required\",\n });\n\n const backendUrl = await context.prompt({\n type: \"text\",\n message: \"Enter Cored backend server URL:\",\n validate: (val: string) => {\n if (val.length === 0) return \"This field is required\";\n try {\n new URL(val);\n return true;\n } catch {\n return \"Please enter a valid URL\";\n }\n },\n });\n\n const enableEncryption = await context.prompt({\n type: \"confirm\",\n message: \"Enable message encryption?\",\n default: true,\n });\n\n // Write config to ~/.openclaw/openclaw.json\n await context.updateConfig(\"channels.cored.appId\", appId);\n await context.updateConfig(\"channels.cored.appSecret\", appSecret);\n await context.updateConfig(\"channels.cored.backendUrl\", backendUrl);\n await context.updateConfig(\"channels.cored.enableEncryption\", enableEncryption);\n await context.updateConfig(\"channels.cored.enabled\", true);\n\n console.log(\"✅ Cored channel configuration saved successfully!\");\n console.log(\"📄 Config file: ~/.openclaw/openclaw.json\");\n console.log(\"📖 Deploy docs: https://coredim.com/docs/admin/bots/openclaw\");\n },\n});\n"],"mappings":";AAGA,SAAS,8BAA8B;AAEvC,IAAO,sBAAQ,uBAAuB;AAAA,EACpC,MAAM,QAAQ,SAAS;AACrB,UAAM,QAAQ,MAAM,QAAQ,OAAO;AAAA,MACjC,MAAM;AAAA,MACN,SAAS;AAAA,MACT,UAAU,CAAC,QAAgB,IAAI,SAAS,KAAK;AAAA,IAC/C,CAAC;AAED,UAAM,YAAY,MAAM,QAAQ,OAAO;AAAA,MACrC,MAAM;AAAA,MACN,SAAS;AAAA,MACT,UAAU,CAAC,QAAgB,IAAI,SAAS,KAAK;AAAA,IAC/C,CAAC;AAED,UAAM,aAAa,MAAM,QAAQ,OAAO;AAAA,MACtC,MAAM;AAAA,MACN,SAAS;AAAA,MACT,UAAU,CAAC,QAAgB;AACzB,YAAI,IAAI,WAAW,EAAG,QAAO;AAC7B,YAAI;AACF,cAAI,IAAI,GAAG;AACX,iBAAO;AAAA,QACT,QAAQ;AACN,iBAAO;AAAA,QACT;AAAA,MACF;AAAA,IACF,CAAC;AAED,UAAM,mBAAmB,MAAM,QAAQ,OAAO;AAAA,MAC5C,MAAM;AAAA,MACN,SAAS;AAAA,MACT,SAAS;AAAA,IACX,CAAC;AAGD,UAAM,QAAQ,aAAa,wBAAwB,KAAK;AACxD,UAAM,QAAQ,aAAa,4BAA4B,SAAS;AAChE,UAAM,QAAQ,aAAa,6BAA6B,UAAU;AAClE,UAAM,QAAQ,aAAa,mCAAmC,gBAAgB;AAC9E,UAAM,QAAQ,aAAa,0BAA0B,IAAI;AAEzD,YAAQ,IAAI,wDAAmD;AAC/D,YAAQ,IAAI,kDAA2C;AACvD,YAAQ,IAAI,qEAA8D;AAAA,EAC5E;AACF,CAAC;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/setup-entry.ts","../src/channel.ts","../src/config.ts","../src/core/cored-client.ts","../src/messaging/outbound.ts","../src/targets.ts"],"sourcesContent":["// Copyright (c) 2026 Cored Limited\n// SPDX-License-Identifier: Apache-2.0\n\nimport { defineSetupPluginEntry } from \"openclaw/plugin-sdk/core\";\nimport { coredPlugin } from \"./channel.js\";\n\nexport default defineSetupPluginEntry(coredPlugin);\n","// Copyright (c) 2026 Cored Limited\n// SPDX-License-Identifier: Apache-2.0\n\nimport {\n createChatChannelPlugin,\n createChannelPluginBase,\n} from \"openclaw/plugin-sdk/core\";\nimport type { OpenClawConfig } from \"openclaw/plugin-sdk/core\";\nimport { listAccountIds, resolveAccountConfig } from \"./config.js\";\nimport { sendText } from \"./messaging/outbound.js\";\nimport { parseTarget } from \"./targets.js\";\n\ntype ResolvedAccount = {\n accountId: string | null;\n appId: string;\n appSecret: string;\n backendUrl: string;\n enableEncryption: boolean;\n requestTimeout: number;\n requireMention: boolean;\n};\n\nfunction resolveAccount(\n cfg: OpenClawConfig,\n accountId?: string | null,\n): ResolvedAccount {\n const section = (cfg.channels as Record<string, any>)?.[\"cored\"];\n const accounts = section?.accounts;\n const defaultAccount = section?.defaultAccount;\n\n // If multi-account mode, resolve the specific account\n if (accounts && Object.keys(accounts).length > 0) {\n const targetId = accountId ?? defaultAccount ?? Object.keys(accounts)[0];\n const account = accounts[targetId];\n if (!account) {\n throw new Error(`cored: account \"${targetId}\" not found`);\n }\n return {\n accountId: targetId,\n appId: account.appId,\n appSecret: account.appSecret,\n backendUrl: account.backendUrl,\n enableEncryption: account.enableEncryption ?? section.enableEncryption ?? true,\n requestTimeout: account.requestTimeout ?? section.requestTimeout ?? 30000,\n requireMention: account.requireMention ?? section.requireMention ?? true,\n };\n }\n\n // Single-account mode\n const appId = section?.appId;\n const appSecret = section?.appSecret;\n const backendUrl = section?.backendUrl;\n\n if (!appId || !appSecret || !backendUrl) {\n throw new Error(\"cored: appId, appSecret, and backendUrl are required\");\n }\n\n return {\n accountId: null,\n appId,\n appSecret,\n backendUrl,\n enableEncryption: section?.enableEncryption ?? true,\n requestTimeout: section?.requestTimeout ?? 30000,\n requireMention: section?.requireMention ?? true,\n };\n}\n\nexport const coredPlugin = createChatChannelPlugin<ResolvedAccount>({\n base: createChannelPluginBase({\n id: \"cored\",\n setup: {\n resolveAccount,\n inspectAccount(cfg, accountId) {\n const section = (cfg.channels as Record<string, any>)?.[\"cored\"];\n const hasConfig = Boolean(\n section?.appId && section?.appSecret && section?.backendUrl,\n );\n return {\n enabled: Boolean(section?.enabled !== false),\n configured: hasConfig,\n tokenStatus: hasConfig ? \"available\" : \"missing\",\n };\n },\n },\n }),\n\n // Plugin metadata\n meta: {\n id: \"cored\",\n label: \"Cored\",\n selectionLabel: \"Cored\",\n docsPath: \"/channels/cored\",\n blurb: \"Connect OpenClaw to Cored\",\n aliases: [\"cored\", \"co\"],\n },\n\n // Capabilities\n capabilities: {\n chatTypes: [\"direct\", \"group\"] as const,\n },\n\n // Config\n config: {\n listAccountIds: (cfg: unknown) => listAccountIds(cfg),\n resolveAccount: (cfg: unknown, accountId?: string) =>\n resolveAccountConfig(cfg, accountId),\n },\n\n // Outbound messaging\n outbound: {\n deliveryMode: \"direct\" as const,\n resolveTarget: ({ to }: { to?: string }) => {\n const target = parseTarget(to);\n if (!target) {\n return {\n ok: false as const,\n error: new Error(\n `Cored requires --to <user:ID|chat:ID>, got: ${JSON.stringify(to)}`,\n ),\n };\n }\n // Normalize to \"kind:id\" so sendText receives a consistent format\n return { ok: true as const, to: `${target.kind}:${target.id}` };\n },\n sendText: async ({\n to,\n text,\n accountId,\n }: {\n to: string;\n text: string;\n accountId?: string;\n }) => {\n // Re-parse the normalized target to extract the chat/user ID\n const target = parseTarget(to);\n if (!target) {\n return {\n ok: false,\n error: new Error(`[cored] invalid send target: ${to}`),\n };\n }\n return sendText(target.id, text, accountId);\n },\n },\n\n // Setup wizard for openclaw onboard\n setupWizard: {\n channel: \"cored\",\n status: {\n configuredLabel: \"Connected\",\n unconfiguredLabel: \"Not configured\",\n resolveConfigured: ({ cfg }: { cfg: OpenClawConfig }) => {\n const section = (cfg.channels as Record<string, any>)?.[\"cored\"];\n return Boolean(section?.appId && section?.appSecret && section?.backendUrl);\n },\n },\n credentials: [\n {\n inputKey: \"appId\",\n providerHint: \"cored\",\n credentialLabel: \"App ID\",\n preferredEnvVar: \"CORED_APP_ID\",\n envPrompt: \"Use CORED_APP_ID from environment?\",\n keepPrompt: \"Keep current App ID?\",\n inputPrompt: \"Enter your Cored App ID:\",\n inspect: ({ cfg }: { cfg: OpenClawConfig }) => {\n const section = (cfg.channels as Record<string, any>)?.[\"cored\"];\n return {\n accountConfigured: Boolean(section?.appId),\n hasConfiguredValue: Boolean(section?.appId),\n };\n },\n },\n {\n inputKey: \"appSecret\",\n providerHint: \"cored\",\n credentialLabel: \"App Secret\",\n preferredEnvVar: \"CORED_APP_SECRET\",\n envPrompt: \"Use CORED_APP_SECRET from environment?\",\n keepPrompt: \"Keep current App Secret?\",\n inputPrompt: \"Enter your Cored App Secret:\",\n inspect: ({ cfg }: { cfg: OpenClawConfig }) => {\n const section = (cfg.channels as Record<string, any>)?.[\"cored\"];\n return {\n accountConfigured: Boolean(section?.appSecret),\n hasConfiguredValue: Boolean(section?.appSecret),\n };\n },\n },\n {\n inputKey: \"backendUrl\",\n providerHint: \"cored\",\n credentialLabel: \"Backend URL\",\n preferredEnvVar: \"CORED_BACKEND_URL\",\n envPrompt: \"Use CORED_BACKEND_URL from environment?\",\n keepPrompt: \"Keep current Backend URL?\",\n inputPrompt: \"Enter your Cored backend server URL:\",\n inspect: ({ cfg }: { cfg: OpenClawConfig }) => {\n const section = (cfg.channels as Record<string, any>)?.[\"cored\"];\n return {\n accountConfigured: Boolean(section?.backendUrl),\n hasConfiguredValue: Boolean(section?.backendUrl),\n };\n },\n },\n ],\n },\n});\n","// Copyright (c) 2026 Cored Limited\n// SPDX-License-Identifier: Apache-2.0\n\nimport type { CoredChannelConfig, CoredAccountConfig } from \"./types.js\";\n\nconst DEFAULTS = {\n enableEncryption: true,\n requestTimeout: 30_000,\n requireMention: true,\n inboundWhitelist: [] as string[],\n} as const;\n\nconst ENV_PREFIX = \"CORED_\";\n\nfunction getChannelConfig(cfg: unknown): CoredChannelConfig | undefined {\n const root = cfg as Record<string, unknown> | undefined;\n return root?.channels\n ? ((root.channels as Record<string, unknown>).cored as\n | CoredChannelConfig\n | undefined)\n : undefined;\n}\n\nfunction readEnvConfig(): Partial<CoredAccountConfig> {\n const env = process.env;\n const result: Partial<CoredAccountConfig> = {};\n\n if (env[`${ENV_PREFIX}APP_ID`]) result.appId = env[`${ENV_PREFIX}APP_ID`];\n if (env[`${ENV_PREFIX}APP_SECRET`])\n result.appSecret = env[`${ENV_PREFIX}APP_SECRET`];\n if (env[`${ENV_PREFIX}BACKEND_URL`])\n result.backendUrl = env[`${ENV_PREFIX}BACKEND_URL`];\n if (env[`${ENV_PREFIX}ENABLE_ENCRYPTION`] !== undefined)\n result.enableEncryption =\n env[`${ENV_PREFIX}ENABLE_ENCRYPTION`] !== \"false\";\n if (env[`${ENV_PREFIX}REQUEST_TIMEOUT`])\n result.requestTimeout = Number(env[`${ENV_PREFIX}REQUEST_TIMEOUT`]);\n if (env[`${ENV_PREFIX}REQUIRE_MENTION`] !== undefined)\n result.requireMention = env[`${ENV_PREFIX}REQUIRE_MENTION`] !== \"false\";\n if (env[`${ENV_PREFIX}BOT_USER_ID`])\n result.botUserId = env[`${ENV_PREFIX}BOT_USER_ID`];\n\n return result;\n}\n\nexport function listAccountIds(cfg: unknown): string[] {\n const ch = getChannelConfig(cfg);\n if (!ch) {\n // Check env vars as fallback\n if (process.env[`${ENV_PREFIX}APP_ID`]) return [\"default\"];\n return [];\n }\n if (ch.accounts) return Object.keys(ch.accounts);\n if (ch.appId) return [\"default\"];\n // env var fallback\n if (process.env[`${ENV_PREFIX}APP_ID`]) return [\"default\"];\n return [];\n}\n\nexport function resolveAccountConfig(\n cfg: unknown,\n accountId?: string,\n): CoredAccountConfig {\n const ch = getChannelConfig(cfg);\n const id = accountId ?? \"default\";\n const envConfig = readEnvConfig();\n\n const raw = ch?.accounts?.[id] ?? ch;\n\n return {\n accountId: id,\n enabled: raw?.enabled ?? true,\n appId: raw?.appId ?? envConfig.appId ?? \"\",\n appSecret: raw?.appSecret ?? envConfig.appSecret ?? \"\",\n backendUrl: raw?.backendUrl ?? envConfig.backendUrl ?? \"\",\n enableEncryption:\n raw?.enableEncryption ?? envConfig.enableEncryption ?? DEFAULTS.enableEncryption,\n requestTimeout:\n raw?.requestTimeout ?? envConfig.requestTimeout ?? DEFAULTS.requestTimeout,\n requireMention:\n raw?.requireMention ?? envConfig.requireMention ?? DEFAULTS.requireMention,\n botUserId: raw?.botUserId ?? envConfig.botUserId,\n inboundWhitelist: raw?.inboundWhitelist ?? [...DEFAULTS.inboundWhitelist],\n };\n}\n\nexport interface ConfigValidationError {\n field: string;\n message: string;\n}\n\nexport function validateAccountConfig(\n config: CoredAccountConfig,\n): ConfigValidationError[] {\n const errors: ConfigValidationError[] = [];\n\n if (!config.appId) {\n errors.push({\n field: \"appId\",\n message: `Account \"${config.accountId}\": appId is required. Set it in channels.cored.appId or CORED_APP_ID env var.`,\n });\n }\n\n if (!config.appSecret) {\n errors.push({\n field: \"appSecret\",\n message: `Account \"${config.accountId}\": appSecret is required. Set it in channels.cored.appSecret or CORED_APP_SECRET env var.`,\n });\n }\n\n if (!config.backendUrl) {\n errors.push({\n field: \"backendUrl\",\n message: `Account \"${config.accountId}\": backendUrl is required. Set it in channels.cored.backendUrl or CORED_BACKEND_URL env var.`,\n });\n } else if (\n !config.backendUrl.startsWith(\"http://\") &&\n !config.backendUrl.startsWith(\"https://\")\n ) {\n errors.push({\n field: \"backendUrl\",\n message: `Account \"${config.accountId}\": backendUrl must start with http:// or https:// (got \"${config.backendUrl}\").`,\n });\n }\n\n if (\n typeof config.requestTimeout !== \"number\" ||\n !Number.isFinite(config.requestTimeout) ||\n config.requestTimeout <= 0\n ) {\n errors.push({\n field: \"requestTimeout\",\n message: `Account \"${config.accountId}\": requestTimeout must be a positive number in milliseconds (got ${config.requestTimeout}).`,\n });\n }\n\n return errors;\n}\n\nexport function resolveAndValidateAccountConfig(\n cfg: unknown,\n accountId?: string,\n): CoredAccountConfig {\n const config = resolveAccountConfig(cfg, accountId);\n const errors = validateAccountConfig(config);\n\n if (errors.length > 0) {\n const messages = errors.map((e) => ` - ${e.message}`).join(\"\\n\");\n throw new Error(\n `[cored] Invalid config for account \"${config.accountId}\":\\n${messages}`,\n );\n }\n\n return config;\n}\n\nexport function listEnabledAccountConfigs(cfg: unknown): CoredAccountConfig[] {\n const ids = listAccountIds(cfg);\n return ids\n .map((id) => resolveAccountConfig(cfg, id))\n .filter((account) => account.enabled);\n}\n","// Copyright (c) 2026 Cored Limited\n// SPDX-License-Identifier: Apache-2.0\n\n/**\n * Cored client manager — wraps the @cored-im/sdk\n * and provides per-account lifecycle management.\n *\n * This module bridges the SDK's snake_case API with the plugin's camelCase\n * conventions and manages client instances by account ID.\n */\n\nimport { CoredClient, LoggerLevel, ApiError } from \"@cored-im/sdk\";\nimport type { Logger } from \"@cored-im/sdk\";\nimport type { CoredAccountConfig, ConnectionState, CoredMessageEvent } from \"../types.js\";\n\n// ---------------------------------------------------------------------------\n// Auth error detection\n// ---------------------------------------------------------------------------\n\n/** Cored auth failure error code (鉴权失败). */\nconst AUTH_ERROR_CODE = 40000006;\n\n/**\n * Check whether an error is a Cored auth/token failure.\n * Returns true for ApiError with code 40000006, which indicates\n * the token has expired or is otherwise invalid.\n */\nexport function isAuthError(err: unknown): boolean {\n return err instanceof ApiError && err.code === AUTH_ERROR_CODE;\n}\n\n// ---------------------------------------------------------------------------\n// Constants — the new SDK doesn't re-export message type enums from its\n// top-level barrel, so we define the constant locally. The value matches\n// the SDK's MessageType_TEXT = 'text' in message_enum.ts.\n// ---------------------------------------------------------------------------\n\nexport const MessageType_TEXT = \"text\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/**\n * The SDK client instance returned by CoredClient.create().\n *\n * The new @cored-im/sdk uses:\n * - client.Im.v1.Message.sendMessage(req) — snake_case request fields\n * - client.Im.v1.Message.Event.onMessageReceive(handler) — sync, void return\n * - client.Im.v1.Chat.createTyping(req) — snake_case request fields\n * - client.preheat() / client.close() — camelCase lifecycle methods\n */\nexport type SdkClient = CoredClient;\n\n/**\n * Local send-message request shape matching the SDK's SendMessageReq.\n * Only text is used for now; add specific fields (image, card, etc.)\n * as outbound capabilities grow.\n */\nexport interface SendMessageReq {\n chat_id?: string;\n message_type?: string;\n message_content?: {\n text?: { content?: string };\n };\n reply_message_id?: string;\n}\n\n/**\n * Raw event shape from the SDK's onMessageReceive handler.\n *\n * The new SDK delivers typed events with shape:\n * { header: EventHeader, body: { message?: Message } }\n *\n * Message fields are snake_case. sender_id is a UserId object:\n * { user_id?, union_user_id?, open_user_id? }\n */\nexport interface SdkMessageEvent {\n header?: {\n event_id?: string;\n event_type?: string;\n event_created_at?: string;\n };\n body?: {\n message?: {\n message_id?: string;\n message_type?: string;\n message_status?: string;\n message_content?: unknown;\n message_created_at?: string | number;\n chat_id?: string;\n chat_seq_id?: string | number;\n sender_id?: {\n user_id?: string;\n union_user_id?: string;\n open_user_id?: string;\n } | string;\n // These may appear in group chats\n chat_type?: string;\n mention_user_list?: Array<{\n user_id?: {\n user_id?: string;\n union_user_id?: string;\n open_user_id?: string;\n };\n user_name?: string;\n }>;\n };\n };\n}\n\n// ---------------------------------------------------------------------------\n// Client state\n// ---------------------------------------------------------------------------\n\nexport interface ManagedClient {\n client: SdkClient;\n config: CoredAccountConfig;\n /** The raw handler reference, needed for offMessageReceive. */\n eventHandler?: (event: SdkMessageEvent) => void;\n /** Diagnostic connection state. Updated on create/destroy. */\n connectionState: ConnectionState;\n}\n\nconst clients = new Map<string, ManagedClient>();\n\n// ---------------------------------------------------------------------------\n// Logger adapter — bridge plugin's simple log callback to SDK's Logger interface\n// ---------------------------------------------------------------------------\n\nfunction makeLoggerAdapter(\n log?: (msg: string, ctx?: Record<string, unknown>) => void,\n): Logger {\n const emit = (level: string) => (msg: string, ...args: unknown[]) => {\n log?.(`[${level}] ${msg}${args.length ? \" \" + JSON.stringify(args) : \"\"}`);\n };\n return {\n debug: emit(\"debug\"),\n info: emit(\"info\"),\n warn: emit(\"warn\"),\n error: emit(\"error\"),\n };\n}\n\n// ---------------------------------------------------------------------------\n// Lifecycle\n// ---------------------------------------------------------------------------\n\nexport interface CreateClientOptions {\n config: CoredAccountConfig;\n onMessage?: (event: CoredMessageEvent, accountConfig: CoredAccountConfig) => void;\n log?: (msg: string, ctx?: Record<string, unknown>) => void;\n}\n\n/**\n * Create and connect a Cored SDK client for the given account.\n * Stores it in the client map for later retrieval.\n */\nexport async function createClient(opts: CreateClientOptions): Promise<ManagedClient> {\n const { config, onMessage, log } = opts;\n const accountId = config.accountId;\n\n // Tear down existing client for this account if any\n if (clients.has(accountId)) {\n await destroyClient(accountId);\n }\n\n const sdkClient = await CoredClient.create(\n config.backendUrl,\n config.appId,\n config.appSecret,\n {\n enableEncryption: config.enableEncryption,\n requestTimeout: config.requestTimeout,\n logger: log ? makeLoggerAdapter(log) : undefined,\n logLevel: log ? LoggerLevel.Debug : LoggerLevel.Info,\n },\n );\n\n // Preheat warms the token and verifies connectivity\n await sdkClient.preheat();\n\n const managed: ManagedClient = { client: sdkClient, config, connectionState: \"connected\" };\n\n // Subscribe to incoming messages if handler provided\n if (onMessage) {\n const handler = (sdkEvent: SdkMessageEvent) => {\n const normalized = normalizeSdkEvent(sdkEvent);\n if (normalized) {\n onMessage(normalized, config);\n }\n };\n\n // New SDK: onMessageReceive is synchronous, returns void.\n // Store handler reference for offMessageReceive on teardown.\n sdkClient.Im.v1.Message.Event.onMessageReceive(\n handler as Parameters<typeof sdkClient.Im.v1.Message.Event.onMessageReceive>[0],\n );\n managed.eventHandler = handler;\n }\n\n clients.set(accountId, managed);\n return managed;\n}\n\n/**\n * Destroy and disconnect a client by account ID.\n */\nexport async function destroyClient(accountId: string): Promise<void> {\n const managed = clients.get(accountId);\n if (!managed) return;\n\n managed.connectionState = \"disconnecting\";\n\n // Unsubscribe from events using offMessageReceive\n if (managed.eventHandler) {\n managed.client.Im.v1.Message.Event.offMessageReceive(\n managed.eventHandler as Parameters<typeof managed.client.Im.v1.Message.Event.offMessageReceive>[0],\n );\n }\n try {\n await managed.client.close();\n } catch {\n // Best-effort close\n }\n clients.delete(accountId);\n}\n\n/**\n * Destroy all managed clients.\n */\nexport async function destroyAllClients(): Promise<void> {\n const ids = [...clients.keys()];\n await Promise.allSettled(ids.map((id) => destroyClient(id)));\n}\n\n/**\n * Get a managed client by account ID. Falls back to the first available client.\n */\nexport function getClient(accountId?: string): ManagedClient | undefined {\n if (accountId && clients.has(accountId)) return clients.get(accountId);\n if (clients.size > 0) return clients.values().next().value as ManagedClient;\n return undefined;\n}\n\n/**\n * Number of currently connected clients.\n */\nexport function clientCount(): number {\n return clients.size;\n}\n\n/**\n * Get diagnostic state for all managed clients.\n */\nexport function getClientStates(): Array<{ accountId: string; connectionState: ConnectionState }> {\n return [...clients.entries()].map(([id, m]) => ({\n accountId: id,\n connectionState: m.connectionState,\n }));\n}\n\n// ---------------------------------------------------------------------------\n// Event normalization — SDK snake_case event -> plugin camelCase\n// ---------------------------------------------------------------------------\n\n/**\n * Convert a snake_case SDK event to the plugin's CoredMessageEvent format.\n * Returns null if the event is malformed.\n *\n * The new SDK delivers events with lowercase field names:\n * { header, body: { message: { message_id, sender_id: UserId, ... } } }\n *\n * sender_id is now a UserId object { user_id, union_user_id, open_user_id }\n * in the new SDK, but we keep backward compat with string for safety.\n */\nexport function normalizeSdkEvent(sdk: SdkMessageEvent): CoredMessageEvent | null {\n const msg = sdk.body?.message;\n if (!msg) return null;\n\n // Extract user ID from sender_id — may be UserId object or legacy string\n const senderId = msg.sender_id;\n let userId = \"\";\n if (typeof senderId === \"string\") {\n userId = senderId;\n } else if (senderId && typeof senderId === \"object\") {\n userId =\n senderId.user_id ??\n senderId.open_user_id ??\n senderId.union_user_id ??\n \"\";\n }\n\n // Extract mention user IDs from the new SDK's text mention format\n const mentionUsers = (msg.mention_user_list ?? []).map((u) => ({\n userId: u.user_id?.user_id ?? u.user_id?.open_user_id ?? u.user_id?.union_user_id ?? \"\",\n }));\n\n // message_created_at may be Int64 (string) in the new SDK\n const createdAt =\n typeof msg.message_created_at === \"string\"\n ? parseInt(msg.message_created_at, 10) || Date.now()\n : msg.message_created_at ?? Date.now();\n\n return {\n message: {\n messageId: msg.message_id ?? \"\",\n messageType: msg.message_type ?? \"\",\n messageContent: msg.message_content,\n chatId: msg.chat_id ?? \"\",\n chatType: msg.chat_type ?? \"direct\",\n sender: {\n userId,\n },\n createdAt,\n mentionUserList: mentionUsers,\n },\n };\n}\n","// Copyright (c) 2026 Cored Limited\n// SPDX-License-Identifier: Apache-2.0\n\n/**\n * Outbound message delivery — send text/typing/read to Cored chats.\n *\n * Pipeline: normalize target -> validate account/client -> send -> map errors\n *\n * Text-only for now; media/card/file delivery is follow-up (task 08).\n */\n\nimport {\n getClient,\n isAuthError,\n MessageType_TEXT,\n type ManagedClient,\n type SendMessageReq,\n} from \"../core/cored-client.js\";\n\n// ---------------------------------------------------------------------------\n// Send text\n// ---------------------------------------------------------------------------\n\nexport interface SendTextResult {\n ok: boolean;\n messageId?: string;\n error?: Error;\n provider?: string;\n}\n\n/**\n * Send a text message to a Cored chat.\n *\n * On auth error (code 40000006), forces a token refresh via preheat() and\n * retries once. This handles the SDK's token-refresh edge case without\n * requiring a gateway restart.\n */\nexport async function sendText(\n chatId: string,\n text: string,\n accountId?: string,\n replyMessageId?: string,\n logWarn?: (msg: string) => void,\n): Promise<SendTextResult> {\n const managed = getClient(accountId);\n if (!managed) {\n return {\n ok: false,\n error: new Error(\n `[cored] no connected client for account=${accountId ?? \"default\"}`,\n ),\n };\n }\n\n const req: SendMessageReq = {\n chat_id: chatId,\n message_type: MessageType_TEXT,\n message_content: {\n text: { content: text },\n },\n reply_message_id: replyMessageId,\n };\n\n try {\n const resp = await managed.client.Im.v1.Message.sendMessage(req);\n return { ok: true, messageId: resp.message_id, provider: \"cored\" };\n } catch (err) {\n if (!isAuthError(err)) {\n return {\n ok: false,\n error: new Error(\n `[cored] send failed for chat=${chatId}: ${err instanceof Error ? err.message : String(err)}`,\n ),\n };\n }\n\n // Auth token expired despite SDK auto-refresh — force refresh and retry once.\n // This avoids requiring a gateway restart when the SDK's background token\n // refresh hits an edge case (time sync drift, swallowed fetch failure, etc.).\n logWarn?.(\n `[cored] auth error on send (chat=${chatId}, account=${accountId ?? \"default\"}) — refreshing token and retrying`,\n );\n\n try {\n await managed.client.preheat();\n const resp = await managed.client.Im.v1.Message.sendMessage(req);\n logWarn?.(\n `[cored] auth retry succeeded (chat=${chatId}, account=${accountId ?? \"default\"})`,\n );\n return { ok: true, messageId: resp.message_id, provider: \"cored\" };\n } catch (retryErr) {\n return {\n ok: false,\n error: new Error(\n `[cored] send failed after auth retry for chat=${chatId}: ${retryErr instanceof Error ? retryErr.message : String(retryErr)}`,\n ),\n };\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// Typing indicator\n// ---------------------------------------------------------------------------\n\n/**\n * Set typing indicator in a chat. Cored typing lasts ~5s.\n */\nexport async function setTyping(\n chatId: string,\n accountId?: string,\n): Promise<void> {\n const managed = getClient(accountId);\n if (!managed) return;\n try {\n await managed.client.Im.v1.Chat.createTyping({ chat_id: chatId });\n } catch {\n // Typing is best-effort — don't fail the message flow\n }\n}\n\n/**\n * Clear typing indicator.\n */\nexport async function clearTyping(\n chatId: string,\n accountId?: string,\n): Promise<void> {\n const managed = getClient(accountId);\n if (!managed) return;\n try {\n await managed.client.Im.v1.Chat.deleteTyping({ chat_id: chatId });\n } catch {\n // Best-effort\n }\n}\n\n// ---------------------------------------------------------------------------\n// Read receipt\n// ---------------------------------------------------------------------------\n\n/**\n * Mark a message as read.\n */\nexport async function readMessage(\n messageId: string,\n accountId?: string,\n): Promise<void> {\n const managed = getClient(accountId);\n if (!managed) return;\n try {\n await managed.client.Im.v1.Message.readMessage({ message_id: messageId });\n } catch {\n // Best-effort\n }\n}\n\n// ---------------------------------------------------------------------------\n// Delivery callback for inbound dispatch\n// ---------------------------------------------------------------------------\n\n/**\n * Create a deliver function scoped to an account, suitable for passing\n * to processInboundMessage's InboundDispatchOptions.\n */\nexport function makeDeliver(\n accountId?: string,\n logWarn?: (msg: string) => void,\n): (chatId: string, text: string) => Promise<void> {\n return async (chatId: string, text: string) => {\n const result = await sendText(chatId, text, accountId, undefined, logWarn);\n if (!result.ok) {\n throw result.error ?? new Error(\"[cored] send failed\");\n }\n };\n}\n","// Copyright (c) 2026 Cored Limited\n// SPDX-License-Identifier: Apache-2.0\n\n/**\n * Target parsing & validation for the --to argument.\n *\n * Accepted formats:\n * \"chat:oc_abc123\" -> { kind: \"chat\", id: \"oc_abc123\" }\n * \"user:83870344313569283\" -> { kind: \"user\", id: \"83870344313569283\" }\n * \"cored:chat:oc_abc123\" -> { kind: \"chat\", id: \"oc_abc123\" } (prefix stripped)\n * \"oc_abc123\" -> { kind: \"chat\", id: \"oc_abc123\" } (bare ID defaults to chat)\n *\n * Returns null for empty, whitespace-only, or malformed targets (e.g. \"user:\" with no ID).\n */\n\nimport type { ParsedTarget } from \"./types.js\";\n\n/**\n * Parse a raw --to string into a structured target.\n * Returns null if the input is missing, empty, or has no usable ID.\n */\nexport function parseTarget(to?: string): ParsedTarget | null {\n const raw = String(to ?? \"\").trim();\n if (!raw) return null;\n\n // Strip optional \"cored:\" channel prefix (case-insensitive)\n const stripped = raw.replace(/^cored:/i, \"\");\n\n if (stripped.startsWith(\"user:\")) {\n const id = stripped.slice(\"user:\".length).trim();\n return id ? { kind: \"user\", id } : null;\n }\n\n if (stripped.startsWith(\"chat:\")) {\n const id = stripped.slice(\"chat:\".length).trim();\n return id ? { kind: \"chat\", id } : null;\n }\n\n // Bare ID — default to chat (Cored SDK uses ChatId for sending)\n return stripped ? { kind: \"chat\", id: stripped } : null;\n}\n"],"mappings":";AAGA,SAAS,8BAA8B;;;ACAvC;AAAA,EACE;AAAA,EACA;AAAA,OACK;;;ACDP,IAAM,WAAW;AAAA,EACf,kBAAkB;AAAA,EAClB,gBAAgB;AAAA,EAChB,gBAAgB;AAAA,EAChB,kBAAkB,CAAC;AACrB;AAEA,IAAM,aAAa;AAEnB,SAAS,iBAAiB,KAA8C;AACtE,QAAM,OAAO;AACb,SAAO,MAAM,WACP,KAAK,SAAqC,QAG5C;AACN;AAEA,SAAS,gBAA6C;AACpD,QAAM,MAAM,QAAQ;AACpB,QAAM,SAAsC,CAAC;AAE7C,MAAI,IAAI,GAAG,UAAU,QAAQ,EAAG,QAAO,QAAQ,IAAI,GAAG,UAAU,QAAQ;AACxE,MAAI,IAAI,GAAG,UAAU,YAAY;AAC/B,WAAO,YAAY,IAAI,GAAG,UAAU,YAAY;AAClD,MAAI,IAAI,GAAG,UAAU,aAAa;AAChC,WAAO,aAAa,IAAI,GAAG,UAAU,aAAa;AACpD,MAAI,IAAI,GAAG,UAAU,mBAAmB,MAAM;AAC5C,WAAO,mBACL,IAAI,GAAG,UAAU,mBAAmB,MAAM;AAC9C,MAAI,IAAI,GAAG,UAAU,iBAAiB;AACpC,WAAO,iBAAiB,OAAO,IAAI,GAAG,UAAU,iBAAiB,CAAC;AACpE,MAAI,IAAI,GAAG,UAAU,iBAAiB,MAAM;AAC1C,WAAO,iBAAiB,IAAI,GAAG,UAAU,iBAAiB,MAAM;AAClE,MAAI,IAAI,GAAG,UAAU,aAAa;AAChC,WAAO,YAAY,IAAI,GAAG,UAAU,aAAa;AAEnD,SAAO;AACT;AAEO,SAAS,eAAe,KAAwB;AACrD,QAAM,KAA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AAAA,QACd,iBAAiB;AAAA,QACjB,iBAAiB;AAAA,QACjB,WAAW;AAAA,QACX,YAAY;AAAA,QACZ,aAAa;AAAA,QACb,SAAS,CAAC,EAAE,IAAI,MAA+B;AAC7C,gBAAM,UAAW,IAAI,WAAmC,OAAO;AAC/D,iBAAO;AAAA,YACL,mBAAmB,QAAQ,SAAS,SAAS;AAAA,YAC7C,oBAAoB,QAAQ,SAAS,SAAS;AAAA,UAChD;AAAA,QACF;AAAA,MACF;AAAA,MACA;AAAA,QACE,UAAU;AAAA,QACV,cAAc;AAAA,QACd,iBAAiB;AAAA,QACjB,iBAAiB;AAAA,QACjB,WAAW;AAAA,QACX,YAAY;AAAA,QACZ,aAAa;AAAA,QACb,SAAS,CAAC,EAAE,IAAI,MAA+B;AAC7C,gBAAM,UAAW,IAAI,WAAmC,OAAO;AAC/D,iBAAO;AAAA,YACL,mBAAmB,QAAQ,SAAS,UAAU;AAAA,YAC9C,oBAAoB,QAAQ,SAAS,UAAU;AAAA,UACjD;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF,CAAC;;;AD1MD,IAAO,sBAAQ,uBAAuB,WAAW;","names":[]}
|
package/openclaw.plugin.json
CHANGED
|
@@ -1,10 +1,9 @@
|
|
|
1
1
|
{
|
|
2
2
|
"id": "cored",
|
|
3
|
-
"name": "Cored Channel",
|
|
4
|
-
"description": "Connect OpenClaw with Cored",
|
|
5
|
-
"version": "0.1.0",
|
|
6
3
|
"kind": "channel",
|
|
7
4
|
"channels": ["cored"],
|
|
5
|
+
"name": "Cored Channel",
|
|
6
|
+
"description": "Connect OpenClaw with Cored",
|
|
8
7
|
"configSchema": {
|
|
9
8
|
"type": "object",
|
|
10
9
|
"additionalProperties": false,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cored-im/openclaw-plugin",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.5",
|
|
4
4
|
"description": "Cored IM channel plugin for OpenClaw",
|
|
5
5
|
"author": "Cored Limited",
|
|
6
6
|
"type": "module",
|
|
@@ -26,16 +26,16 @@
|
|
|
26
26
|
"openclaw.plugin.json"
|
|
27
27
|
],
|
|
28
28
|
"openclaw": {
|
|
29
|
-
"setup": "./dist/src/setup-entry.js",
|
|
30
29
|
"extensions": [
|
|
31
30
|
"./dist/index.js"
|
|
32
31
|
],
|
|
32
|
+
"setupEntry": "./dist/setup-entry.js",
|
|
33
33
|
"channel": {
|
|
34
34
|
"id": "cored",
|
|
35
35
|
"label": "Cored",
|
|
36
36
|
"selectionLabel": "Cored",
|
|
37
37
|
"docsPath": "/channels/cored",
|
|
38
|
-
"blurb": "
|
|
38
|
+
"blurb": "Connect OpenClaw to Cored"
|
|
39
39
|
}
|
|
40
40
|
},
|
|
41
41
|
"scripts": {
|