@cored-im/openclaw-plugin 0.1.7 → 0.1.11
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/README.md +1 -5
- package/README.zh.md +1 -5
- package/dist/index.cjs +124 -143
- 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 +124 -143
- package/dist/index.js.map +1 -1
- package/dist/setup-entry.cjs +114 -117
- 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 +114 -117
- package/dist/setup-entry.js.map +1 -1
- package/dist/types-BEkT8vuK.d.cts +11 -0
- package/dist/types-BEkT8vuK.d.ts +11 -0
- package/openclaw.plugin.json +6 -53
- package/package.json +3 -2
- package/src/channel.ts +129 -134
- package/src/config.test.ts +4 -10
- package/src/config.ts +1 -11
- package/src/index.ts +15 -21
- package/src/messaging/inbound.test.ts +12 -160
- package/src/messaging/inbound.ts +12 -41
- package/src/setup-entry.ts +2 -2
- package/src/types.ts +3 -16
- package/src/typings/openclaw-plugin-sdk.d.ts +0 -162
package/dist/setup-entry.cjs.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":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAGA,IAAAA,eAAuC;;;ACAvC,kBAGO;;;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;A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A,YAC9C,oBAAoB,QAAQ,SAAS,UAAU;AAAA,UACjD;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF,CAAC;;;AD1MD,IAAO,0BAAQ,qCAAuB,WAAW;","names":["import_core"]}
|
|
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 { base } from \"./channel.js\";\n\nexport default defineSetupPluginEntry(base);\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\nexport const 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} 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\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 appId: raw?.appId ?? envConfig.appId ?? \"\",\n appSecret: raw?.appSecret ?? envConfig.appSecret ?? \"\",\n backendUrl: raw?.backendUrl ?? envConfig.backendUrl ?? \"\",\n enabled: raw?.enabled ?? true,\n enableEncryption:\n raw?.enableEncryption ?? envConfig.enableEncryption ?? DEFAULTS.enableEncryption,\n requestTimeout:\n raw?.requestTimeout ?? envConfig.requestTimeout ?? DEFAULTS.requestTimeout,\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":";;;;;;;;;;;;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MAAM;AAAA,MACJ,cAAc;AAAA,MACd,eAAe,CAAC,EAAE,GAAG,MAAM;AACzB,YAAI,CAAC,GAAI,QAAO,EAAE,IAAI,OAAgB,OAAO,IAAI,MAAM,0BAA0B,EAAE;AACnF,cAAM,SAAS,YAAY,EAAE;AAC7B,YAAI,CAAC,QAAQ;AACX,iBAAO;AAAA,YACL,IAAI;AAAA,YACJ,OAAO,IAAI;AAAA,cACT,+CAA+C,KAAK,UAAU,EAAE,CAAC;AAAA,YACnE;AAAA,UACF;AAAA,QACF;AACA,eAAO,EAAE,IAAI,MAAe,IAAI,GAAG,OAAO,IAAI,IAAI,OAAO,EAAE,GAAG;AAAA,MAChE;AAAA,IACF;AAAA,EACF;AACF,CAAC;;;ADrMD,IAAO,0BAAQ,qCAAuB,IAAI;","names":["import_core"]}
|
package/dist/setup-entry.d.cts
CHANGED
|
@@ -1,13 +1,8 @@
|
|
|
1
1
|
import * as openclaw_plugin_sdk_core from 'openclaw/plugin-sdk/core';
|
|
2
|
+
import { C as CoredAccountConfig } from './types-BEkT8vuK.cjs';
|
|
2
3
|
|
|
3
|
-
declare const _default:
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
appSecret: string;
|
|
7
|
-
backendUrl: string;
|
|
8
|
-
enableEncryption: boolean;
|
|
9
|
-
requestTimeout: number;
|
|
10
|
-
requireMention: boolean;
|
|
11
|
-
}>>;
|
|
4
|
+
declare const _default: {
|
|
5
|
+
plugin: Pick<openclaw_plugin_sdk_core.ChannelPlugin<CoredAccountConfig>, "id" | "meta" | "setup"> & Partial<Pick<openclaw_plugin_sdk_core.ChannelPlugin<CoredAccountConfig>, "capabilities" | "config" | "setupWizard" | "agentPrompt" | "streaming" | "reload" | "gatewayMethods" | "configSchema" | "security" | "groups">>;
|
|
6
|
+
};
|
|
12
7
|
|
|
13
8
|
export { _default as default };
|
package/dist/setup-entry.d.ts
CHANGED
|
@@ -1,13 +1,8 @@
|
|
|
1
1
|
import * as openclaw_plugin_sdk_core from 'openclaw/plugin-sdk/core';
|
|
2
|
+
import { C as CoredAccountConfig } from './types-BEkT8vuK.js';
|
|
2
3
|
|
|
3
|
-
declare const _default:
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
appSecret: string;
|
|
7
|
-
backendUrl: string;
|
|
8
|
-
enableEncryption: boolean;
|
|
9
|
-
requestTimeout: number;
|
|
10
|
-
requireMention: boolean;
|
|
11
|
-
}>>;
|
|
4
|
+
declare const _default: {
|
|
5
|
+
plugin: Pick<openclaw_plugin_sdk_core.ChannelPlugin<CoredAccountConfig>, "id" | "meta" | "setup"> & Partial<Pick<openclaw_plugin_sdk_core.ChannelPlugin<CoredAccountConfig>, "capabilities" | "config" | "setupWizard" | "agentPrompt" | "streaming" | "reload" | "gatewayMethods" | "configSchema" | "security" | "groups">>;
|
|
6
|
+
};
|
|
12
7
|
|
|
13
8
|
export { _default as default };
|
package/dist/setup-entry.js
CHANGED
|
@@ -10,9 +10,7 @@ import {
|
|
|
10
10
|
// src/config.ts
|
|
11
11
|
var DEFAULTS = {
|
|
12
12
|
enableEncryption: true,
|
|
13
|
-
requestTimeout: 3e4
|
|
14
|
-
requireMention: true,
|
|
15
|
-
inboundWhitelist: []
|
|
13
|
+
requestTimeout: 3e4
|
|
16
14
|
};
|
|
17
15
|
var ENV_PREFIX = "CORED_";
|
|
18
16
|
function getChannelConfig(cfg) {
|
|
@@ -31,10 +29,6 @@ function readEnvConfig() {
|
|
|
31
29
|
result.enableEncryption = env[`${ENV_PREFIX}ENABLE_ENCRYPTION`] !== "false";
|
|
32
30
|
if (env[`${ENV_PREFIX}REQUEST_TIMEOUT`])
|
|
33
31
|
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
32
|
return result;
|
|
39
33
|
}
|
|
40
34
|
function listAccountIds(cfg) {
|
|
@@ -55,15 +49,12 @@ function resolveAccountConfig(cfg, accountId) {
|
|
|
55
49
|
const raw = ch?.accounts?.[id] ?? ch;
|
|
56
50
|
return {
|
|
57
51
|
accountId: id,
|
|
58
|
-
enabled: raw?.enabled ?? true,
|
|
59
52
|
appId: raw?.appId ?? envConfig.appId ?? "",
|
|
60
53
|
appSecret: raw?.appSecret ?? envConfig.appSecret ?? "",
|
|
61
54
|
backendUrl: raw?.backendUrl ?? envConfig.backendUrl ?? "",
|
|
55
|
+
enabled: raw?.enabled ?? true,
|
|
62
56
|
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]
|
|
57
|
+
requestTimeout: raw?.requestTimeout ?? envConfig.requestTimeout ?? DEFAULTS.requestTimeout
|
|
67
58
|
};
|
|
68
59
|
}
|
|
69
60
|
|
|
@@ -150,174 +141,180 @@ function parseTarget(to) {
|
|
|
150
141
|
}
|
|
151
142
|
|
|
152
143
|
// src/channel.ts
|
|
153
|
-
|
|
154
|
-
|
|
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
|
|
144
|
+
var base = createChannelPluginBase({
|
|
145
|
+
id: "cored",
|
|
208
146
|
meta: {
|
|
209
147
|
id: "cored",
|
|
210
148
|
label: "Cored",
|
|
211
149
|
selectionLabel: "Cored",
|
|
212
150
|
docsPath: "/channels/cored",
|
|
213
151
|
blurb: "Connect OpenClaw to Cored",
|
|
214
|
-
aliases: ["
|
|
152
|
+
aliases: ["co"]
|
|
215
153
|
},
|
|
216
|
-
// Capabilities
|
|
217
154
|
capabilities: {
|
|
218
155
|
chatTypes: ["direct", "group"]
|
|
219
156
|
},
|
|
220
|
-
// Config
|
|
221
157
|
config: {
|
|
222
158
|
listAccountIds: (cfg) => listAccountIds(cfg),
|
|
223
|
-
resolveAccount: (cfg, accountId) => resolveAccountConfig(cfg, accountId)
|
|
159
|
+
resolveAccount: (cfg, accountId) => resolveAccountConfig(cfg, accountId ?? void 0),
|
|
160
|
+
inspectAccount(cfg, accountId) {
|
|
161
|
+
const resolved = resolveAccountConfig(cfg, accountId ?? void 0);
|
|
162
|
+
const hasConfig = Boolean(
|
|
163
|
+
resolved.appId && resolved.appSecret && resolved.backendUrl
|
|
164
|
+
);
|
|
165
|
+
return {
|
|
166
|
+
enabled: resolved.enabled,
|
|
167
|
+
configured: hasConfig,
|
|
168
|
+
tokenStatus: hasConfig ? "available" : "missing"
|
|
169
|
+
};
|
|
170
|
+
}
|
|
224
171
|
},
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
const
|
|
230
|
-
if (!
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
};
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
return {
|
|
248
|
-
ok: false,
|
|
249
|
-
error: new Error(`[cored] invalid send target: ${to}`)
|
|
250
|
-
};
|
|
172
|
+
setup: {
|
|
173
|
+
applyAccountConfig: ({ cfg, accountId, input }) => {
|
|
174
|
+
const updated = structuredClone(cfg);
|
|
175
|
+
if (!updated.channels) updated.channels = {};
|
|
176
|
+
const ch = updated.channels;
|
|
177
|
+
if (!ch["cored"]) ch["cored"] = {};
|
|
178
|
+
const section = ch["cored"];
|
|
179
|
+
const appId = input.appToken;
|
|
180
|
+
const appSecret = input.token;
|
|
181
|
+
const backendUrl = input.url;
|
|
182
|
+
if (accountId && accountId !== "default") {
|
|
183
|
+
if (!section.accounts) section.accounts = {};
|
|
184
|
+
const accounts = section.accounts;
|
|
185
|
+
if (!accounts[accountId]) accounts[accountId] = {};
|
|
186
|
+
const account = accounts[accountId];
|
|
187
|
+
if (appId) account.appId = appId;
|
|
188
|
+
if (appSecret) account.appSecret = appSecret;
|
|
189
|
+
if (backendUrl) account.backendUrl = backendUrl;
|
|
190
|
+
} else {
|
|
191
|
+
if (appId) section.appId = appId;
|
|
192
|
+
if (appSecret) section.appSecret = appSecret;
|
|
193
|
+
if (backendUrl) section.backendUrl = backendUrl;
|
|
251
194
|
}
|
|
252
|
-
return
|
|
195
|
+
return updated;
|
|
253
196
|
}
|
|
254
197
|
},
|
|
255
|
-
// Setup wizard for openclaw onboard
|
|
256
198
|
setupWizard: {
|
|
257
199
|
channel: "cored",
|
|
258
200
|
status: {
|
|
259
201
|
configuredLabel: "Connected",
|
|
260
202
|
unconfiguredLabel: "Not configured",
|
|
261
203
|
resolveConfigured: ({ cfg }) => {
|
|
262
|
-
const
|
|
263
|
-
return
|
|
204
|
+
const ids = listAccountIds(cfg);
|
|
205
|
+
return ids.some((id) => {
|
|
206
|
+
const resolved = resolveAccountConfig(cfg, id);
|
|
207
|
+
return Boolean(resolved.appId && resolved.appSecret && resolved.backendUrl);
|
|
208
|
+
});
|
|
264
209
|
}
|
|
265
210
|
},
|
|
266
211
|
credentials: [
|
|
267
212
|
{
|
|
268
|
-
inputKey: "
|
|
213
|
+
inputKey: "appToken",
|
|
269
214
|
providerHint: "cored",
|
|
270
215
|
credentialLabel: "App ID",
|
|
271
216
|
preferredEnvVar: "CORED_APP_ID",
|
|
272
217
|
envPrompt: "Use CORED_APP_ID from environment?",
|
|
273
218
|
keepPrompt: "Keep current App ID?",
|
|
274
219
|
inputPrompt: "Enter your Cored App ID:",
|
|
275
|
-
inspect: ({ cfg }) => {
|
|
276
|
-
const
|
|
220
|
+
inspect: ({ cfg, accountId }) => {
|
|
221
|
+
const resolved = resolveAccountConfig(cfg, accountId ?? void 0);
|
|
277
222
|
return {
|
|
278
|
-
accountConfigured: Boolean(
|
|
279
|
-
hasConfiguredValue: Boolean(
|
|
223
|
+
accountConfigured: Boolean(resolved.appId),
|
|
224
|
+
hasConfiguredValue: Boolean(resolved.appId)
|
|
280
225
|
};
|
|
281
226
|
}
|
|
282
227
|
},
|
|
283
228
|
{
|
|
284
|
-
inputKey: "
|
|
229
|
+
inputKey: "token",
|
|
285
230
|
providerHint: "cored",
|
|
286
231
|
credentialLabel: "App Secret",
|
|
287
232
|
preferredEnvVar: "CORED_APP_SECRET",
|
|
288
233
|
envPrompt: "Use CORED_APP_SECRET from environment?",
|
|
289
234
|
keepPrompt: "Keep current App Secret?",
|
|
290
235
|
inputPrompt: "Enter your Cored App Secret:",
|
|
291
|
-
inspect: ({ cfg }) => {
|
|
292
|
-
const
|
|
236
|
+
inspect: ({ cfg, accountId }) => {
|
|
237
|
+
const resolved = resolveAccountConfig(cfg, accountId ?? void 0);
|
|
293
238
|
return {
|
|
294
|
-
accountConfigured: Boolean(
|
|
295
|
-
hasConfiguredValue: Boolean(
|
|
239
|
+
accountConfigured: Boolean(resolved.appSecret),
|
|
240
|
+
hasConfiguredValue: Boolean(resolved.appSecret)
|
|
296
241
|
};
|
|
297
242
|
}
|
|
298
243
|
},
|
|
299
244
|
{
|
|
300
|
-
inputKey: "
|
|
245
|
+
inputKey: "url",
|
|
301
246
|
providerHint: "cored",
|
|
302
247
|
credentialLabel: "Backend URL",
|
|
303
248
|
preferredEnvVar: "CORED_BACKEND_URL",
|
|
304
249
|
envPrompt: "Use CORED_BACKEND_URL from environment?",
|
|
305
250
|
keepPrompt: "Keep current Backend URL?",
|
|
306
251
|
inputPrompt: "Enter your Cored backend server URL:",
|
|
307
|
-
inspect: ({ cfg }) => {
|
|
308
|
-
const
|
|
252
|
+
inspect: ({ cfg, accountId }) => {
|
|
253
|
+
const resolved = resolveAccountConfig(cfg, accountId ?? void 0);
|
|
309
254
|
return {
|
|
310
|
-
accountConfigured: Boolean(
|
|
311
|
-
hasConfiguredValue: Boolean(
|
|
255
|
+
accountConfigured: Boolean(resolved.backendUrl),
|
|
256
|
+
hasConfiguredValue: Boolean(resolved.backendUrl)
|
|
312
257
|
};
|
|
313
258
|
}
|
|
314
259
|
}
|
|
315
260
|
]
|
|
316
261
|
}
|
|
317
262
|
});
|
|
263
|
+
var coredPlugin = createChatChannelPlugin({
|
|
264
|
+
base,
|
|
265
|
+
// DM security: who can message the bot
|
|
266
|
+
security: {
|
|
267
|
+
dm: {
|
|
268
|
+
channelKey: "cored",
|
|
269
|
+
resolvePolicy: () => void 0,
|
|
270
|
+
resolveAllowFrom: () => [],
|
|
271
|
+
defaultPolicy: "allowlist"
|
|
272
|
+
}
|
|
273
|
+
},
|
|
274
|
+
// Threading: how replies are delivered
|
|
275
|
+
threading: { topLevelReplyToMode: "reply" },
|
|
276
|
+
// Outbound: send messages to the platform
|
|
277
|
+
outbound: {
|
|
278
|
+
attachedResults: {
|
|
279
|
+
channel: "cored",
|
|
280
|
+
sendText: async (ctx) => {
|
|
281
|
+
const target = parseTarget(ctx.to);
|
|
282
|
+
if (!target) {
|
|
283
|
+
throw new Error(`[cored] invalid send target: ${ctx.to}`);
|
|
284
|
+
}
|
|
285
|
+
const result = await sendText(
|
|
286
|
+
target.id,
|
|
287
|
+
ctx.text,
|
|
288
|
+
ctx.accountId ?? void 0,
|
|
289
|
+
ctx.replyToId ?? void 0
|
|
290
|
+
);
|
|
291
|
+
if (!result.ok) {
|
|
292
|
+
throw result.error ?? new Error("[cored] send failed");
|
|
293
|
+
}
|
|
294
|
+
return { messageId: result.messageId ?? "" };
|
|
295
|
+
}
|
|
296
|
+
},
|
|
297
|
+
base: {
|
|
298
|
+
deliveryMode: "direct",
|
|
299
|
+
resolveTarget: ({ to }) => {
|
|
300
|
+
if (!to) return { ok: false, error: new Error("[cored] --to is required") };
|
|
301
|
+
const target = parseTarget(to);
|
|
302
|
+
if (!target) {
|
|
303
|
+
return {
|
|
304
|
+
ok: false,
|
|
305
|
+
error: new Error(
|
|
306
|
+
`Cored requires --to <user:ID|chat:ID>, got: ${JSON.stringify(to)}`
|
|
307
|
+
)
|
|
308
|
+
};
|
|
309
|
+
}
|
|
310
|
+
return { ok: true, to: `${target.kind}:${target.id}` };
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
});
|
|
318
315
|
|
|
319
316
|
// src/setup-entry.ts
|
|
320
|
-
var setup_entry_default = defineSetupPluginEntry(
|
|
317
|
+
var setup_entry_default = defineSetupPluginEntry(base);
|
|
321
318
|
export {
|
|
322
319
|
setup_entry_default as default
|
|
323
320
|
};
|