@cored-im/openclaw-plugin 0.1.7 → 0.1.10
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 +120 -115
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +11 -9
- package/dist/index.d.ts +11 -9
- package/dist/index.js +120 -115
- package/dist/index.js.map +1 -1
- package/dist/setup-entry.cjs +110 -104
- package/dist/setup-entry.cjs.map +1 -1
- package/dist/setup-entry.d.cts +4 -9
- package/dist/setup-entry.d.ts +4 -9
- package/dist/setup-entry.js +110 -104
- package/dist/setup-entry.js.map +1 -1
- package/dist/types-C6n4PnbR.d.cts +14 -0
- package/dist/types-C6n4PnbR.d.ts +14 -0
- package/openclaw.plugin.json +2 -51
- package/package.json +3 -2
- package/src/channel.ts +129 -134
- package/src/index.ts +15 -21
- package/src/messaging/inbound.test.ts +2 -2
- package/src/messaging/inbound.ts +11 -8
- package/src/types.ts +0 -4
- package/src/typings/openclaw-plugin-sdk.d.ts +0 -162
package/dist/setup-entry.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
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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1MD,IAAO,sBAAQ,uBAAuB,WAAW;","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\";\nimport type { CoredAccountConfig } from \"./types.js\";\n\nconst base = createChannelPluginBase<CoredAccountConfig>({\n id: \"cored\",\n\n meta: {\n id: \"cored\",\n label: \"Cored\",\n selectionLabel: \"Cored\",\n docsPath: \"/channels/cored\",\n blurb: \"Connect OpenClaw to Cored\",\n aliases: [\"co\"],\n },\n\n capabilities: {\n chatTypes: [\"direct\", \"group\"],\n },\n\n config: {\n listAccountIds: (cfg: OpenClawConfig) => listAccountIds(cfg),\n resolveAccount: (cfg: OpenClawConfig, accountId?: string | null) =>\n resolveAccountConfig(cfg, accountId ?? undefined),\n inspectAccount(cfg: OpenClawConfig, accountId?: string | null) {\n const resolved = resolveAccountConfig(cfg, accountId ?? undefined);\n const hasConfig = Boolean(\n resolved.appId && resolved.appSecret && resolved.backendUrl,\n );\n return {\n enabled: resolved.enabled,\n configured: hasConfig,\n tokenStatus: hasConfig ? \"available\" : \"missing\",\n };\n },\n },\n\n setup: {\n applyAccountConfig: ({ cfg, accountId, input }) => {\n const updated = structuredClone(cfg) as Record<string, unknown>;\n if (!updated.channels) updated.channels = {};\n const ch = updated.channels as Record<string, Record<string, unknown>>;\n if (!ch[\"cored\"]) ch[\"cored\"] = {};\n const section = ch[\"cored\"];\n\n // Map ChannelSetupInput keys to our config shape:\n // appToken → appId, token → appSecret, url → backendUrl\n const appId = input.appToken;\n const appSecret = input.token;\n const backendUrl = input.url;\n\n if (accountId && accountId !== \"default\") {\n // Multi-account: write under accounts.<accountId>\n if (!section.accounts) section.accounts = {};\n const accounts = section.accounts as Record<string, Record<string, unknown>>;\n if (!accounts[accountId]) accounts[accountId] = {};\n const account = accounts[accountId];\n if (appId) account.appId = appId;\n if (appSecret) account.appSecret = appSecret;\n if (backendUrl) account.backendUrl = backendUrl;\n } else {\n // Single-account: write at top level\n if (appId) section.appId = appId;\n if (appSecret) section.appSecret = appSecret;\n if (backendUrl) section.backendUrl = backendUrl;\n }\n\n return updated as OpenClawConfig;\n },\n },\n\n setupWizard: {\n channel: \"cored\",\n status: {\n configuredLabel: \"Connected\",\n unconfiguredLabel: \"Not configured\",\n resolveConfigured: ({ cfg }) => {\n const ids = listAccountIds(cfg);\n return ids.some((id) => {\n const resolved = resolveAccountConfig(cfg, id);\n return Boolean(resolved.appId && resolved.appSecret && resolved.backendUrl);\n });\n },\n },\n credentials: [\n {\n inputKey: \"appToken\",\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, accountId }) => {\n const resolved = resolveAccountConfig(cfg, accountId ?? undefined);\n return {\n accountConfigured: Boolean(resolved.appId),\n hasConfiguredValue: Boolean(resolved.appId),\n };\n },\n },\n {\n inputKey: \"token\",\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, accountId }) => {\n const resolved = resolveAccountConfig(cfg, accountId ?? undefined);\n return {\n accountConfigured: Boolean(resolved.appSecret),\n hasConfiguredValue: Boolean(resolved.appSecret),\n };\n },\n },\n {\n inputKey: \"url\",\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, accountId }) => {\n const resolved = resolveAccountConfig(cfg, accountId ?? undefined);\n return {\n accountConfigured: Boolean(resolved.backendUrl),\n hasConfiguredValue: Boolean(resolved.backendUrl),\n };\n },\n },\n ],\n },\n});\n\n// Cast needed: createChannelPluginBase returns Partial<config> but\n// createChatChannelPlugin requires config to be defined. We always\n// provide config above so the cast is safe.\nexport const coredPlugin = createChatChannelPlugin<CoredAccountConfig>({\n base: base as Parameters<typeof createChatChannelPlugin<CoredAccountConfig>>[0][\"base\"],\n\n // DM security: who can message the bot\n security: {\n dm: {\n channelKey: \"cored\",\n resolvePolicy: () => undefined,\n resolveAllowFrom: () => [],\n defaultPolicy: \"allowlist\",\n },\n },\n\n // Threading: how replies are delivered\n threading: { topLevelReplyToMode: \"reply\" },\n\n // Outbound: send messages to the platform\n outbound: {\n attachedResults: {\n channel: \"cored\",\n sendText: async (ctx) => {\n const target = parseTarget(ctx.to);\n if (!target) {\n throw new Error(`[cored] invalid send target: ${ctx.to}`);\n }\n const result = await sendText(\n target.id,\n ctx.text,\n ctx.accountId ?? undefined,\n ctx.replyToId ?? undefined,\n );\n if (!result.ok) {\n throw result.error ?? new Error(\"[cored] send failed\");\n }\n return { messageId: result.messageId ?? \"\" };\n },\n },\n base: {\n deliveryMode: \"direct\",\n resolveTarget: ({ to }) => {\n if (!to) return { ok: false as const, error: new Error(\"[cored] --to is required\") };\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 return { ok: true as const, to: `${target.kind}:${target.id}` };\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,e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
|
+
appSecret: string;
|
|
6
|
+
backendUrl: string;
|
|
7
|
+
enableEncryption: boolean;
|
|
8
|
+
requestTimeout: number;
|
|
9
|
+
requireMention: boolean;
|
|
10
|
+
botUserId?: string;
|
|
11
|
+
inboundWhitelist: string[];
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export type { CoredAccountConfig as C };
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
interface CoredAccountConfig {
|
|
2
|
+
accountId: string;
|
|
3
|
+
enabled: boolean;
|
|
4
|
+
appId: string;
|
|
5
|
+
appSecret: string;
|
|
6
|
+
backendUrl: string;
|
|
7
|
+
enableEncryption: boolean;
|
|
8
|
+
requestTimeout: number;
|
|
9
|
+
requireMention: boolean;
|
|
10
|
+
botUserId?: string;
|
|
11
|
+
inboundWhitelist: string[];
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export type { CoredAccountConfig as C };
|
package/openclaw.plugin.json
CHANGED
|
@@ -4,60 +4,11 @@
|
|
|
4
4
|
"channels": ["cored"],
|
|
5
5
|
"name": "Cored Channel",
|
|
6
6
|
"description": "Connect OpenClaw with Cored",
|
|
7
|
+
"setupEntry": "./dist/setup-entry.js",
|
|
7
8
|
"configSchema": {
|
|
8
9
|
"type": "object",
|
|
9
10
|
"additionalProperties": false,
|
|
10
|
-
"properties": {
|
|
11
|
-
"enabled": {
|
|
12
|
-
"type": "boolean",
|
|
13
|
-
"description": "Enable this channel",
|
|
14
|
-
"default": true
|
|
15
|
-
},
|
|
16
|
-
"appId": {
|
|
17
|
-
"type": "string",
|
|
18
|
-
"description": "Cored application ID"
|
|
19
|
-
},
|
|
20
|
-
"appSecret": {
|
|
21
|
-
"type": "string",
|
|
22
|
-
"description": "Cored application secret"
|
|
23
|
-
},
|
|
24
|
-
"backendUrl": {
|
|
25
|
-
"type": "string",
|
|
26
|
-
"description": "Cored backend URL (e.g., https://your-backend-url.com)"
|
|
27
|
-
},
|
|
28
|
-
"enableEncryption": {
|
|
29
|
-
"type": "boolean",
|
|
30
|
-
"description": "Enable message encryption",
|
|
31
|
-
"default": true
|
|
32
|
-
},
|
|
33
|
-
"requestTimeout": {
|
|
34
|
-
"type": "number",
|
|
35
|
-
"description": "Request timeout in milliseconds",
|
|
36
|
-
"default": 30000
|
|
37
|
-
},
|
|
38
|
-
"requireMention": {
|
|
39
|
-
"type": "boolean",
|
|
40
|
-
"description": "Require @mention in group chats before responding",
|
|
41
|
-
"default": true
|
|
42
|
-
},
|
|
43
|
-
"accounts": {
|
|
44
|
-
"type": "object",
|
|
45
|
-
"description": "Multi-account configuration",
|
|
46
|
-
"additionalProperties": {
|
|
47
|
-
"type": "object",
|
|
48
|
-
"properties": {
|
|
49
|
-
"enabled": { "type": "boolean", "default": true },
|
|
50
|
-
"appId": { "type": "string" },
|
|
51
|
-
"appSecret": { "type": "string" },
|
|
52
|
-
"backendUrl": { "type": "string" },
|
|
53
|
-
"enableEncryption": { "type": "boolean" },
|
|
54
|
-
"requestTimeout": { "type": "number" },
|
|
55
|
-
"requireMention": { "type": "boolean" }
|
|
56
|
-
},
|
|
57
|
-
"required": ["appId", "appSecret", "backendUrl"]
|
|
58
|
-
}
|
|
59
|
-
}
|
|
60
|
-
}
|
|
11
|
+
"properties": {}
|
|
61
12
|
},
|
|
62
13
|
"uiHints": {
|
|
63
14
|
"appId": { "label": "App ID" },
|
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.10",
|
|
4
4
|
"description": "Cored IM channel plugin for OpenClaw",
|
|
5
5
|
"author": "Cored Limited",
|
|
6
6
|
"type": "module",
|
|
@@ -35,7 +35,8 @@
|
|
|
35
35
|
"label": "Cored",
|
|
36
36
|
"selectionLabel": "Cored",
|
|
37
37
|
"docsPath": "/channels/cored",
|
|
38
|
-
"blurb": "Connect OpenClaw to Cored"
|
|
38
|
+
"blurb": "Connect OpenClaw to Cored",
|
|
39
|
+
"aliases": ["co"]
|
|
39
40
|
}
|
|
40
41
|
},
|
|
41
42
|
"scripts": {
|
package/src/channel.ts
CHANGED
|
@@ -9,201 +9,196 @@ import type { OpenClawConfig } from "openclaw/plugin-sdk/core";
|
|
|
9
9
|
import { listAccountIds, resolveAccountConfig } from "./config.js";
|
|
10
10
|
import { sendText } from "./messaging/outbound.js";
|
|
11
11
|
import { parseTarget } from "./targets.js";
|
|
12
|
+
import type { CoredAccountConfig } from "./types.js";
|
|
12
13
|
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
appId: string;
|
|
16
|
-
appSecret: string;
|
|
17
|
-
backendUrl: string;
|
|
18
|
-
enableEncryption: boolean;
|
|
19
|
-
requestTimeout: number;
|
|
20
|
-
requireMention: boolean;
|
|
21
|
-
};
|
|
14
|
+
const base = createChannelPluginBase<CoredAccountConfig>({
|
|
15
|
+
id: "cored",
|
|
22
16
|
|
|
23
|
-
function resolveAccount(
|
|
24
|
-
cfg: OpenClawConfig,
|
|
25
|
-
accountId?: string | null,
|
|
26
|
-
): ResolvedAccount {
|
|
27
|
-
const section = (cfg.channels as Record<string, any>)?.["cored"];
|
|
28
|
-
const accounts = section?.accounts;
|
|
29
|
-
const defaultAccount = section?.defaultAccount;
|
|
30
|
-
|
|
31
|
-
// If multi-account mode, resolve the specific account
|
|
32
|
-
if (accounts && Object.keys(accounts).length > 0) {
|
|
33
|
-
const targetId = accountId ?? defaultAccount ?? Object.keys(accounts)[0];
|
|
34
|
-
const account = accounts[targetId];
|
|
35
|
-
if (!account) {
|
|
36
|
-
throw new Error(`cored: account "${targetId}" not found`);
|
|
37
|
-
}
|
|
38
|
-
return {
|
|
39
|
-
accountId: targetId,
|
|
40
|
-
appId: account.appId,
|
|
41
|
-
appSecret: account.appSecret,
|
|
42
|
-
backendUrl: account.backendUrl,
|
|
43
|
-
enableEncryption: account.enableEncryption ?? section.enableEncryption ?? true,
|
|
44
|
-
requestTimeout: account.requestTimeout ?? section.requestTimeout ?? 30000,
|
|
45
|
-
requireMention: account.requireMention ?? section.requireMention ?? true,
|
|
46
|
-
};
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
// Single-account mode
|
|
50
|
-
const appId = section?.appId;
|
|
51
|
-
const appSecret = section?.appSecret;
|
|
52
|
-
const backendUrl = section?.backendUrl;
|
|
53
|
-
|
|
54
|
-
if (!appId || !appSecret || !backendUrl) {
|
|
55
|
-
throw new Error("cored: appId, appSecret, and backendUrl are required");
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
return {
|
|
59
|
-
accountId: null,
|
|
60
|
-
appId,
|
|
61
|
-
appSecret,
|
|
62
|
-
backendUrl,
|
|
63
|
-
enableEncryption: section?.enableEncryption ?? true,
|
|
64
|
-
requestTimeout: section?.requestTimeout ?? 30000,
|
|
65
|
-
requireMention: section?.requireMention ?? true,
|
|
66
|
-
};
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
export const coredPlugin = createChatChannelPlugin<ResolvedAccount>({
|
|
70
|
-
base: createChannelPluginBase({
|
|
71
|
-
id: "cored",
|
|
72
|
-
setup: {
|
|
73
|
-
resolveAccount,
|
|
74
|
-
inspectAccount(cfg, accountId) {
|
|
75
|
-
const section = (cfg.channels as Record<string, any>)?.["cored"];
|
|
76
|
-
const hasConfig = Boolean(
|
|
77
|
-
section?.appId && section?.appSecret && section?.backendUrl,
|
|
78
|
-
);
|
|
79
|
-
return {
|
|
80
|
-
enabled: Boolean(section?.enabled !== false),
|
|
81
|
-
configured: hasConfig,
|
|
82
|
-
tokenStatus: hasConfig ? "available" : "missing",
|
|
83
|
-
};
|
|
84
|
-
},
|
|
85
|
-
},
|
|
86
|
-
}),
|
|
87
|
-
|
|
88
|
-
// Plugin metadata
|
|
89
17
|
meta: {
|
|
90
18
|
id: "cored",
|
|
91
19
|
label: "Cored",
|
|
92
20
|
selectionLabel: "Cored",
|
|
93
21
|
docsPath: "/channels/cored",
|
|
94
22
|
blurb: "Connect OpenClaw to Cored",
|
|
95
|
-
aliases: ["
|
|
23
|
+
aliases: ["co"],
|
|
96
24
|
},
|
|
97
25
|
|
|
98
|
-
// Capabilities
|
|
99
26
|
capabilities: {
|
|
100
|
-
chatTypes: ["direct", "group"]
|
|
27
|
+
chatTypes: ["direct", "group"],
|
|
101
28
|
},
|
|
102
29
|
|
|
103
|
-
// Config
|
|
104
30
|
config: {
|
|
105
|
-
listAccountIds: (cfg:
|
|
106
|
-
resolveAccount: (cfg:
|
|
107
|
-
resolveAccountConfig(cfg, accountId),
|
|
31
|
+
listAccountIds: (cfg: OpenClawConfig) => listAccountIds(cfg),
|
|
32
|
+
resolveAccount: (cfg: OpenClawConfig, accountId?: string | null) =>
|
|
33
|
+
resolveAccountConfig(cfg, accountId ?? undefined),
|
|
34
|
+
inspectAccount(cfg: OpenClawConfig, accountId?: string | null) {
|
|
35
|
+
const resolved = resolveAccountConfig(cfg, accountId ?? undefined);
|
|
36
|
+
const hasConfig = Boolean(
|
|
37
|
+
resolved.appId && resolved.appSecret && resolved.backendUrl,
|
|
38
|
+
);
|
|
39
|
+
return {
|
|
40
|
+
enabled: resolved.enabled,
|
|
41
|
+
configured: hasConfig,
|
|
42
|
+
tokenStatus: hasConfig ? "available" : "missing",
|
|
43
|
+
};
|
|
44
|
+
},
|
|
108
45
|
},
|
|
109
46
|
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
const
|
|
115
|
-
if (!
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
return {
|
|
139
|
-
ok: false,
|
|
140
|
-
error: new Error(`[cored] invalid send target: ${to}`),
|
|
141
|
-
};
|
|
47
|
+
setup: {
|
|
48
|
+
applyAccountConfig: ({ cfg, accountId, input }) => {
|
|
49
|
+
const updated = structuredClone(cfg) as Record<string, unknown>;
|
|
50
|
+
if (!updated.channels) updated.channels = {};
|
|
51
|
+
const ch = updated.channels as Record<string, Record<string, unknown>>;
|
|
52
|
+
if (!ch["cored"]) ch["cored"] = {};
|
|
53
|
+
const section = ch["cored"];
|
|
54
|
+
|
|
55
|
+
// Map ChannelSetupInput keys to our config shape:
|
|
56
|
+
// appToken → appId, token → appSecret, url → backendUrl
|
|
57
|
+
const appId = input.appToken;
|
|
58
|
+
const appSecret = input.token;
|
|
59
|
+
const backendUrl = input.url;
|
|
60
|
+
|
|
61
|
+
if (accountId && accountId !== "default") {
|
|
62
|
+
// Multi-account: write under accounts.<accountId>
|
|
63
|
+
if (!section.accounts) section.accounts = {};
|
|
64
|
+
const accounts = section.accounts as Record<string, Record<string, unknown>>;
|
|
65
|
+
if (!accounts[accountId]) accounts[accountId] = {};
|
|
66
|
+
const account = accounts[accountId];
|
|
67
|
+
if (appId) account.appId = appId;
|
|
68
|
+
if (appSecret) account.appSecret = appSecret;
|
|
69
|
+
if (backendUrl) account.backendUrl = backendUrl;
|
|
70
|
+
} else {
|
|
71
|
+
// Single-account: write at top level
|
|
72
|
+
if (appId) section.appId = appId;
|
|
73
|
+
if (appSecret) section.appSecret = appSecret;
|
|
74
|
+
if (backendUrl) section.backendUrl = backendUrl;
|
|
142
75
|
}
|
|
143
|
-
|
|
76
|
+
|
|
77
|
+
return updated as OpenClawConfig;
|
|
144
78
|
},
|
|
145
79
|
},
|
|
146
80
|
|
|
147
|
-
// Setup wizard for openclaw onboard
|
|
148
81
|
setupWizard: {
|
|
149
82
|
channel: "cored",
|
|
150
83
|
status: {
|
|
151
84
|
configuredLabel: "Connected",
|
|
152
85
|
unconfiguredLabel: "Not configured",
|
|
153
|
-
resolveConfigured: ({ cfg }
|
|
154
|
-
const
|
|
155
|
-
return
|
|
86
|
+
resolveConfigured: ({ cfg }) => {
|
|
87
|
+
const ids = listAccountIds(cfg);
|
|
88
|
+
return ids.some((id) => {
|
|
89
|
+
const resolved = resolveAccountConfig(cfg, id);
|
|
90
|
+
return Boolean(resolved.appId && resolved.appSecret && resolved.backendUrl);
|
|
91
|
+
});
|
|
156
92
|
},
|
|
157
93
|
},
|
|
158
94
|
credentials: [
|
|
159
95
|
{
|
|
160
|
-
inputKey: "
|
|
96
|
+
inputKey: "appToken",
|
|
161
97
|
providerHint: "cored",
|
|
162
98
|
credentialLabel: "App ID",
|
|
163
99
|
preferredEnvVar: "CORED_APP_ID",
|
|
164
100
|
envPrompt: "Use CORED_APP_ID from environment?",
|
|
165
101
|
keepPrompt: "Keep current App ID?",
|
|
166
102
|
inputPrompt: "Enter your Cored App ID:",
|
|
167
|
-
inspect: ({ cfg
|
|
168
|
-
const
|
|
103
|
+
inspect: ({ cfg, accountId }) => {
|
|
104
|
+
const resolved = resolveAccountConfig(cfg, accountId ?? undefined);
|
|
169
105
|
return {
|
|
170
|
-
accountConfigured: Boolean(
|
|
171
|
-
hasConfiguredValue: Boolean(
|
|
106
|
+
accountConfigured: Boolean(resolved.appId),
|
|
107
|
+
hasConfiguredValue: Boolean(resolved.appId),
|
|
172
108
|
};
|
|
173
109
|
},
|
|
174
110
|
},
|
|
175
111
|
{
|
|
176
|
-
inputKey: "
|
|
112
|
+
inputKey: "token",
|
|
177
113
|
providerHint: "cored",
|
|
178
114
|
credentialLabel: "App Secret",
|
|
179
115
|
preferredEnvVar: "CORED_APP_SECRET",
|
|
180
116
|
envPrompt: "Use CORED_APP_SECRET from environment?",
|
|
181
117
|
keepPrompt: "Keep current App Secret?",
|
|
182
118
|
inputPrompt: "Enter your Cored App Secret:",
|
|
183
|
-
inspect: ({ cfg
|
|
184
|
-
const
|
|
119
|
+
inspect: ({ cfg, accountId }) => {
|
|
120
|
+
const resolved = resolveAccountConfig(cfg, accountId ?? undefined);
|
|
185
121
|
return {
|
|
186
|
-
accountConfigured: Boolean(
|
|
187
|
-
hasConfiguredValue: Boolean(
|
|
122
|
+
accountConfigured: Boolean(resolved.appSecret),
|
|
123
|
+
hasConfiguredValue: Boolean(resolved.appSecret),
|
|
188
124
|
};
|
|
189
125
|
},
|
|
190
126
|
},
|
|
191
127
|
{
|
|
192
|
-
inputKey: "
|
|
128
|
+
inputKey: "url",
|
|
193
129
|
providerHint: "cored",
|
|
194
130
|
credentialLabel: "Backend URL",
|
|
195
131
|
preferredEnvVar: "CORED_BACKEND_URL",
|
|
196
132
|
envPrompt: "Use CORED_BACKEND_URL from environment?",
|
|
197
133
|
keepPrompt: "Keep current Backend URL?",
|
|
198
134
|
inputPrompt: "Enter your Cored backend server URL:",
|
|
199
|
-
inspect: ({ cfg
|
|
200
|
-
const
|
|
135
|
+
inspect: ({ cfg, accountId }) => {
|
|
136
|
+
const resolved = resolveAccountConfig(cfg, accountId ?? undefined);
|
|
201
137
|
return {
|
|
202
|
-
accountConfigured: Boolean(
|
|
203
|
-
hasConfiguredValue: Boolean(
|
|
138
|
+
accountConfigured: Boolean(resolved.backendUrl),
|
|
139
|
+
hasConfiguredValue: Boolean(resolved.backendUrl),
|
|
204
140
|
};
|
|
205
141
|
},
|
|
206
142
|
},
|
|
207
143
|
],
|
|
208
144
|
},
|
|
209
145
|
});
|
|
146
|
+
|
|
147
|
+
// Cast needed: createChannelPluginBase returns Partial<config> but
|
|
148
|
+
// createChatChannelPlugin requires config to be defined. We always
|
|
149
|
+
// provide config above so the cast is safe.
|
|
150
|
+
export const coredPlugin = createChatChannelPlugin<CoredAccountConfig>({
|
|
151
|
+
base: base as Parameters<typeof createChatChannelPlugin<CoredAccountConfig>>[0]["base"],
|
|
152
|
+
|
|
153
|
+
// DM security: who can message the bot
|
|
154
|
+
security: {
|
|
155
|
+
dm: {
|
|
156
|
+
channelKey: "cored",
|
|
157
|
+
resolvePolicy: () => undefined,
|
|
158
|
+
resolveAllowFrom: () => [],
|
|
159
|
+
defaultPolicy: "allowlist",
|
|
160
|
+
},
|
|
161
|
+
},
|
|
162
|
+
|
|
163
|
+
// Threading: how replies are delivered
|
|
164
|
+
threading: { topLevelReplyToMode: "reply" },
|
|
165
|
+
|
|
166
|
+
// Outbound: send messages to the platform
|
|
167
|
+
outbound: {
|
|
168
|
+
attachedResults: {
|
|
169
|
+
channel: "cored",
|
|
170
|
+
sendText: async (ctx) => {
|
|
171
|
+
const target = parseTarget(ctx.to);
|
|
172
|
+
if (!target) {
|
|
173
|
+
throw new Error(`[cored] invalid send target: ${ctx.to}`);
|
|
174
|
+
}
|
|
175
|
+
const result = await sendText(
|
|
176
|
+
target.id,
|
|
177
|
+
ctx.text,
|
|
178
|
+
ctx.accountId ?? undefined,
|
|
179
|
+
ctx.replyToId ?? undefined,
|
|
180
|
+
);
|
|
181
|
+
if (!result.ok) {
|
|
182
|
+
throw result.error ?? new Error("[cored] send failed");
|
|
183
|
+
}
|
|
184
|
+
return { messageId: result.messageId ?? "" };
|
|
185
|
+
},
|
|
186
|
+
},
|
|
187
|
+
base: {
|
|
188
|
+
deliveryMode: "direct",
|
|
189
|
+
resolveTarget: ({ to }) => {
|
|
190
|
+
if (!to) return { ok: false as const, error: new Error("[cored] --to is required") };
|
|
191
|
+
const target = parseTarget(to);
|
|
192
|
+
if (!target) {
|
|
193
|
+
return {
|
|
194
|
+
ok: false as const,
|
|
195
|
+
error: new Error(
|
|
196
|
+
`Cored requires --to <user:ID|chat:ID>, got: ${JSON.stringify(to)}`,
|
|
197
|
+
),
|
|
198
|
+
};
|
|
199
|
+
}
|
|
200
|
+
return { ok: true as const, to: `${target.kind}:${target.id}` };
|
|
201
|
+
},
|
|
202
|
+
},
|
|
203
|
+
},
|
|
204
|
+
});
|