@agentchatme/openclaw 0.9.1 → 0.9.2
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/CHANGELOG.md +9 -1
- package/README.md +4 -4
- package/RUNBOOK.md +1 -1
- package/dist/index.cjs +36 -2
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +7 -5
- package/dist/index.d.ts +7 -5
- package/dist/index.js +36 -2
- package/dist/index.js.map +1 -1
- package/dist/{setup-entry-Dh6dRH2F.d.cts → setup-entry-sXnwmV8K.d.cts} +20 -1
- package/dist/{setup-entry-Dh6dRH2F.d.ts → setup-entry-sXnwmV8K.d.ts} +20 -1
- package/dist/setup-entry.cjs +36 -2
- package/dist/setup-entry.cjs.map +1 -1
- package/dist/setup-entry.d.cts +1 -1
- package/dist/setup-entry.d.ts +1 -1
- package/dist/setup-entry.js +36 -2
- package/dist/setup-entry.js.map +1 -1
- package/openclaw.plugin.json +1 -1
- package/package.json +1 -1
- package/skills/agentchat/SKILL.md +75 -79
package/dist/setup-entry.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/channel-account.ts","../src/version.ts","../src/client-identity.ts","../src/setup-client.ts","../src/integration/turn.ts","../src/integration/mcp.ts","../src/integration/runtime-holder.ts","../src/integration/model.ts","../src/integration/placement.ts","../src/integration/state.ts","../src/integration/texts.ts","../src/binding/sdk-client.ts","../src/channel.wizard.ts","../src/config-schema.ts","../src/log.ts","../src/metrics.ts","../src/integration/invites.ts","../src/integration/socket.ts","../src/binding/runtime-registry.ts","../src/integration/wake.ts","../src/integration/invoker.ts","../src/binding/gateway.ts","../src/binding/status.ts","../src/binding/doctor.ts","../src/channel.ts","../src/channel.setup.ts"],"names":["path","API_KEY_ENV","DEFAULT_API_BASE","resolveOpenClawStateDir","fs","resolveBoundAgentId","resolveOpenClawDefaultAgentId","removeAgentsAnchor","agentsAnchorPath","hasAgentsAnchorFor","writeAgentsAnchor","readAgentsAnchor","path2","fs2","path3","describe","AgentChatClient","HANDLE_PATTERN","isValidHandleShape","current","patched","WizardCancelledError","readApiKeyFromEnv","setSetupChannelEnabled","z","pino","path4","RealtimeClient","gate","readWakeModeFromEnv","LEGACY_WAKE_MODE_ENV","WAKE_MODE_ENV","readLegacyReplyGateFailOpenFromEnv","LEGACY_REPLY_GATE_FAIL_OPEN_ENV","readReplyGateTimeoutMsFromEnv","readReplyGateEnabledFromEnv","setAccountEnabledInConfigSection","deleteAccountFromConfigSection","buildChannelConfigSchema","defineChannelPluginEntry","defineSetupPluginEntry"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqBO,IAAM,oBAAA,GAAuB,WAAA;AAC7B,IAAM,4BAAA,GAA+B,SAAA;AAErC,IAAM,kBAAA,GAAqB,EAAA;AAU3B,SAAS,mBAAmB,GAAA,EAAgE;AACjG,EAAA,MAAM,WAAY,GAAA,EAA4D,QAAA;AAC9E,EAAA,MAAM,OAAA,GAAU,WAAW,oBAAoB,CAAA;AAC/C,EAAA,OAAO,OAAA,IAAW,OAAO,OAAA,KAAY,QAAA,IAAY,CAAC,KAAA,CAAM,OAAA,CAAQ,OAAO,CAAA,GAClE,OAAA,GACD,MAAA;AACN;AAEO,SAAS,cAAA,CACd,SACA,SAAA,EACqC;AACrC,EAAA,IAAI,CAAC,SAAS,OAAO,MAAA;AACrB,EAAA,MAAM,EAAE,UAAS,GAAI,OAAA;AACrB,EAAA,IAAI,QAAA,IAAY,OAAO,QAAA,KAAa,QAAA,IAAY,CAAC,KAAA,CAAM,OAAA,CAAQ,QAAQ,CAAA,EAAG;AACxE,IAAA,MAAM,KAAA,GAAS,SAAqC,SAAS,CAAA;AAC7D,IAAA,IAAI,KAAA,IAAS,OAAO,KAAA,KAAU,QAAA,EAAU,OAAO,KAAA;AAAA,EACjD;AAIA,EAAA,IAAI,cAAc,4BAAA,EAA8B;AAC9C,IAAA,MAAM,EAAE,QAAA,EAAU,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,IAAI,KAAA,IAAS,OAAO,KAAA,KAAU,QAAA,EAAU;AACtC,YAAA,MAAM,YAAa,KAAA,CAAkC,MAAA;AACrD,YAAA,IAAI,eAAA,CAAgB,SAAS,CAAA,EAAG,OAAO,IAAA;AAAA,UACzC;AAAA,QACF;AAAA,MACF;AACA,MAAA,OAAO,eAAA,CAAgB,QAAQ,MAAM,CAAA;AAAA,IACvC,CAAA;AAAA,IAEA,gBAAgB,OAAA,EAAS;AACvB,MAAA,OAAO;AAAA,QACL,WAAW,OAAA,CAAQ,SAAA;AAAA,QACnB,SAAS,OAAA,CAAQ,OAAA;AAAA,QACjB,YAAY,OAAA,CAAQ,UAAA;AAAA,QACpB,QAAQ,OAAA,CAAQ;AAAA,OAClB;AAAA,IACF;AAAA,GACF;AAAA,EAEA,KAAA,EAAO,qBAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAcP,OAAA,EAAS,uBAAA;AAAA,EACT,MAAA,EAAQ,sBAAA;AAAA,EACR,MAAA,EAAQ,sBAAA;AAAA,EACR,SAAA,EAAW;AACb;AAcIG,oCAAA,CAAyB;AAAA,EAC3B,EAAA,EAAI,oBAAA;AAAA,EACJ,IAAA,EAAM,WAAA;AAAA,EACN,WAAA,EAAa,iHAAA;AAAA,EACb,MAAA,EAAQ,eAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAKR,UAAA,EAAY,CAAC,OAAA,KAAY,gBAAA,CAAiB,OAAO;AACnD,CAAC;;;AC/hBM,IAAM,mBAAA,GAAsBC,mCAAuB,eAAe","file":"setup-entry.cjs","sourcesContent":["/**\n * Account-config primitives for the AgentChat channel plugin.\n *\n * This module owns the smallest set of shared pieces that both the plugin\n * definition (`channel.ts`) and the interactive setup wizard\n * (`channel.wizard.ts`) need to read or mutate the `channels.agentchat.*`\n * section of the OpenClaw config. Keeping them in a leaf file (no imports\n * from other channel-* modules) breaks the channel.ts ↔ channel.wizard.ts\n * import cycle — without it, the wizard literal's `channel:` field resolves\n * to the temporal-dead-zone value of `AGENTCHAT_CHANNEL_ID` at module-init\n * time, which bundlers emit as `undefined`.\n *\n * Invariants:\n * - Flat form (`channels.agentchat.{apiKey,...}`) is the default-account\n * layout when no `accounts` key is present. Once a named account is\n * written, flat form is never used again for the default account.\n * - The `enabled` flag is section-level (not per-account) and is kept out\n * of the Zod-parsed account shape because the schema is `.strict()`.\n */\nimport type { OpenClawConfig } from 'openclaw/plugin-sdk/channel-core'\n\nexport const AGENTCHAT_CHANNEL_ID = 'agentchat' as const\nexport const AGENTCHAT_DEFAULT_ACCOUNT_ID = 'default'\n\nexport const MIN_API_KEY_LENGTH = 20\n\nexport type ChannelSectionRaw = Record<string, unknown> & {\n accounts?: Record<string, unknown>\n enabled?: unknown\n apiKey?: unknown\n apiBase?: unknown\n agentHandle?: unknown\n}\n\nexport function readChannelSection(cfg: OpenClawConfig | undefined): ChannelSectionRaw | undefined {\n const channels = (cfg as { channels?: Record<string, unknown> } | undefined)?.channels\n const section = channels?.[AGENTCHAT_CHANNEL_ID]\n return section && typeof section === 'object' && !Array.isArray(section)\n ? (section as ChannelSectionRaw)\n : undefined\n}\n\nexport function readAccountRaw(\n section: ChannelSectionRaw | undefined,\n accountId: string,\n): Record<string, unknown> | undefined {\n if (!section) return undefined\n const { accounts } = section\n if (accounts && typeof accounts === 'object' && !Array.isArray(accounts)) {\n const entry = (accounts as Record<string, unknown>)[accountId]\n if (entry && typeof entry === 'object') return entry as Record<string, unknown>\n }\n // Single-account fallback: treat section-level fields as the 'default' account,\n // stripping the `accounts` subsection (but preserving `enabled`, which the\n // caller extracts before Zod parsing).\n if (accountId === AGENTCHAT_DEFAULT_ACCOUNT_ID) {\n const { accounts: _accounts, ...rest } = section\n void _accounts\n return rest as Record<string, unknown>\n }\n return undefined\n}\n\n/**\n * Pulls the `enabled` flag out of a raw account record and returns a copy\n * safe to feed into `parseChannelConfig` (which enforces `.strict()` — an\n * unknown `enabled` key would otherwise reject).\n */\nexport function splitEnabledFromRaw(\n raw: Record<string, unknown> | undefined,\n): { enabled: boolean; forParse: Record<string, unknown> | undefined } {\n if (!raw) return { enabled: true, forParse: undefined }\n const { enabled, ...rest } = raw\n return { enabled: enabled !== false, forParse: rest }\n}\n\n/**\n * Whether OpenClaw treats this account as enabled: neither the section-level\n * `channels.agentchat.enabled` nor the account's own `enabled` is `false`.\n * (For the flat default account the two are the same field.)\n */\nexport function isAgentchatAccountEnabled(cfg: OpenClawConfig | undefined, accountId: string): boolean {\n const section = readChannelSection(cfg)\n if (!section) return true\n if (section.enabled === false) return false\n const raw = readAccountRaw(section, accountId)\n return raw?.enabled !== false\n}\n\n/**\n * The config path whose `false` keeps this account disabled — the one\n * `openclaw config set <path> true` must flip. The section-level flag\n * first: while it is `false` OpenClaw does not load the plugin at all.\n */\nexport function agentchatEnabledConfigPath(cfg: OpenClawConfig | undefined, accountId: string): string {\n const section = readChannelSection(cfg)\n const sectionPath = `channels.${AGENTCHAT_CHANNEL_ID}.enabled`\n if (!section || section.enabled === false) return sectionPath\n const { accounts } = section\n const entry = accounts && typeof accounts === 'object' && !Array.isArray(accounts) ? (accounts as Record<string, unknown>)[accountId] : undefined\n if (entry && typeof entry === 'object') return `channels.${AGENTCHAT_CHANNEL_ID}.accounts.${accountId}.enabled`\n return sectionPath\n}\n\n/**\n * The remedy for anything missing on a DISABLED account. Never\n * `channels add`: OpenClaw (2026.10.9) does not load a disabled channel's\n * plugin, so `channels add` treats AgentChat as a missing plugin, downloads\n * `@agentchatme/openclaw` from npm and asks to install it over this one.\n * `config set … true` re-enables in place (\"applies without restarting the\n * gateway\"); `doctor --fix` then restores the hosted tools entry and the\n * identity line.\n */\nexport function agentchatReenableHint(cfg: OpenClawConfig | undefined, accountId: string): string {\n return (\n `the account is disabled — re-enable it with \\`openclaw config set ${agentchatEnabledConfigPath(cfg, accountId)} true\\`, then run \\`openclaw doctor --fix\\` ` +\n '(not `openclaw channels add`: OpenClaw does not load a disabled channel\\'s plugin and would install @agentchatme/openclaw from npm over this one)'\n )\n}\n\n/**\n * Every account id the config declares: the keys of `accounts.*` when\n * present, else `default` when the flat section carries an `apiKey`. Shared\n * by the config adapter, the gateway's single-account check and the doctor.\n */\nexport function listConfiguredAccountIds(cfg: OpenClawConfig | undefined): string[] {\n const section = readChannelSection(cfg)\n if (!section) return []\n const { accounts } = section\n if (accounts && typeof accounts === 'object' && !Array.isArray(accounts)) {\n const ids = Object.keys(accounts as Record<string, unknown>)\n if (ids.length > 0) return ids\n }\n return typeof section.apiKey === 'string' ? [AGENTCHAT_DEFAULT_ACCOUNT_ID] : []\n}\n\n/**\n * This release runs ONE AgentChat account per gateway. The hosted tools are\n * one `mcp.servers.agentchat` entry whose bearer header is a template on one\n * environment variable (`AGENTCHAT_API_KEY`), so a second account's turn\n * would call the tools as the first account. The integration refuses to start\n * when more than one account is configured, and `channels status` says so.\n *\n * TODO (per-account integrations): one MCP entry per account\n * (`mcp.servers.agentchat-<accountId>`, bearer template on\n * `AGENTCHAT_API_KEY_<ACCOUNT>`), the turn prompt naming that account's tool\n * prefix (`agentchat-<accountId>__…`), the identity line per agent workspace,\n * and the key placed under its own variable name in `.env`.\n */\nexport function multiAccountRefusal(cfg: OpenClawConfig | undefined): string | null {\n const ids = listConfiguredAccountIds(cfg)\n if (ids.length <= 1) return null\n return (\n `${ids.length} AgentChat accounts are configured (${ids.join(', ')}); this release runs one account per gateway ` +\n '— the hosted tools are one mcp.servers.agentchat entry on one AGENTCHAT_API_KEY, so a second account would act as the first. ' +\n 'Keep one account under channels.agentchat (or run a second gateway) until per-account integrations ship.'\n )\n}\n\nexport function isApiKeyPresent(value: unknown): value is string {\n return typeof value === 'string' && value.length >= MIN_API_KEY_LENGTH\n}\n\n/**\n * Read a string-valued field from the resolved account record. Mirrors the\n * fallback logic of `resolveAccount` — accounts.<id>.<field> when present,\n * falling back to the flat section for the default account.\n *\n * Used by the setup wizard so it can render live config state without\n * re-running the Zod parser (which would reject partial work-in-progress\n * inputs during the interactive flow).\n */\nexport function readAgentchatConfigField(\n cfg: OpenClawConfig | undefined,\n accountId: string,\n field: 'apiKey' | 'apiBase' | 'agentHandle',\n): string | undefined {\n const section = readChannelSection(cfg)\n const raw = readAccountRaw(section, accountId)\n if (!raw) return undefined\n const value = raw[field]\n return typeof value === 'string' && value.length > 0 ? value : undefined\n}\n\n/**\n * Shared writer for both the non-interactive `setup.applyAccountConfig`\n * adapter and the interactive wizard. Maintains the same flat-vs-accounts\n * invariant: default account uses flat form iff no `accounts` key is present;\n * named accounts always nest under `accounts.<id>`.\n */\nexport function applyAgentchatAccountPatch(\n cfg: OpenClawConfig | undefined,\n accountId: string,\n patch: Record<string, unknown>,\n): OpenClawConfig {\n const channels: Record<string, unknown> = {\n ...((cfg as { channels?: Record<string, unknown> } | undefined)?.channels ?? {}),\n }\n const currentSection = channels[AGENTCHAT_CHANNEL_ID]\n const section: ChannelSectionRaw =\n currentSection && typeof currentSection === 'object' && !Array.isArray(currentSection)\n ? { ...(currentSection as ChannelSectionRaw) }\n : {}\n\n if (accountId === AGENTCHAT_DEFAULT_ACCOUNT_ID && !section.accounts) {\n Object.assign(section, patch)\n } else {\n const accounts: Record<string, unknown> = {\n ...((section.accounts as Record<string, unknown> | undefined) ?? {}),\n }\n const prevAccount =\n typeof accounts[accountId] === 'object' && accounts[accountId] !== null\n ? (accounts[accountId] as Record<string, unknown>)\n : {}\n accounts[accountId] = { ...prevAccount, ...patch }\n section.accounts = accounts\n }\n\n channels[AGENTCHAT_CHANNEL_ID] = section\n return { ...(cfg ?? {}), channels } as OpenClawConfig\n}\n","/**\n * Single source of truth for the package version string.\n *\n * Kept as a hand-edited constant (not an `import ... from '../package.json'`)\n * so that tsup can bundle ESM/CJS without requiring `resolveJsonModule` +\n * runtime filesystem access from inside the published dist. A unit test\n * (`tests/version.test.ts`) pins this against `package.json` so bumping one\n * without the other fails CI.\n */\nexport const PACKAGE_VERSION = '0.9.1'\n","import type { AgentChatClientIdentity } from 'agentchatme'\n\nimport { PACKAGE_VERSION } from './version.js'\n\n/** The server's low-cardinality client taxonomy names this plugin `openclaw`. */\nexport const AGENTCHAT_CLIENT_NAME = 'openclaw'\n\n/** What the SDK client and the realtime client announce on every request and HELLO. */\nexport const AGENTCHAT_CLIENT_IDENTITY: Readonly<AgentChatClientIdentity> = {\n name: AGENTCHAT_CLIENT_NAME,\n version: PACKAGE_VERSION,\n}\n\n/** The same identity as headers, for the plugin's own `fetch` calls (setup, the hosted-MCP probe). */\nexport const AGENTCHAT_CLIENT_HEADERS: Readonly<Record<string, string>> = {\n 'X-AgentChat-Client': AGENTCHAT_CLIENT_NAME,\n 'X-AgentChat-Client-Version': PACKAGE_VERSION,\n}\n","/**\n * Minimal HTTP client used by the setup plugin (P7) to:\n * - verify an API key is live before finalizing setup (`validateApiKey`)\n * - drive the email-OTP self-registration flow for agents without a key yet\n * (`registerAgentStart` → `registerAgentVerify`)\n * - drive the email-OTP recovery flow that re-issues a lost API key\n * (`recoverAgentStart` → `recoverAgentVerify`)\n *\n * Why this lives separately from `outbound.ts`:\n * - `outbound.ts` is the hot-path message sender. It wants retries, a circuit\n * breaker, metrics, and a long-lived `fetch`. Setup is one-shot, low-rate,\n * user-interactive — a 200ms validation call doesn't need any of that.\n * - Setup runs before the runtime exists; coupling it to `OutboundAdapter`\n * (which expects a parsed `AgentchatChannelConfig`) would force an odd\n * partial-config path during registration.\n *\n * The server endpoints this module targets are stable AgentChat REST calls:\n * - `GET /v1/agents/me` → 200 OK when the key authenticates\n * - `POST /v1/register` → 200 with `{ pending_id }`\n * - `POST /v1/register/verify` → 201 with `{ agent, api_key }` on success\n * - `POST /v1/agents/recover` → 200 with `{ pending_id, message }` — always,\n * whether or not the email + handle match\n * a live agent (no existence leak)\n * - `POST /v1/agents/recover/verify` → 200 with `{ handle, api_key }` on success\n *\n * Registration and recovery deliberately bypass the `agentchatme` SDK: the\n * SDK's `recover(email)` predates the handle + email recovery contract and\n * has no way to send `handle`, and the pinned SDK floor cannot move until a\n * compatible SDK is published. Owning these four calls here keeps the plugin\n * on the current server contract regardless of which SDK version resolves.\n *\n * Per-email policy (server-enforced, the numbers live in the server's\n * `agent_email_policy` row and are NOT hard-coded here): an email can back\n * up to `max_active` live agents and `max_lifetime` registrations overall.\n * The server quotes the number that applies in `details.limit`; every\n * user-facing string built from these results must quote that value rather\n * than assume one.\n *\n * All methods return strongly-typed result unions — setup UIs can `switch` on\n * the discriminant without guessing at HTTP status codes.\n */\n\nimport { AgentChatChannelError } from './errors.js'\nimport { AGENTCHAT_CLIENT_HEADERS } from './client-identity.js'\n\nconst DEFAULT_API_BASE = 'https://api.agentchat.me'\nconst DEFAULT_TIMEOUT_MS = 10_000\n\n/** Subset of the AgentChat agent row the setup surface needs to show the user. */\nexport interface AgentchatAgentIdentity {\n readonly handle: string\n readonly displayName: string | null\n readonly email: string\n readonly createdAt: string\n}\n\nexport type ValidateApiKeyResult =\n | { readonly ok: true; readonly agent: AgentchatAgentIdentity }\n | {\n readonly ok: false\n /** High-level reason code the UI can map to a localized message. */\n readonly reason:\n | 'unauthorized'\n | 'forbidden'\n | 'deleted'\n | 'network-error'\n | 'unreachable'\n | 'server-error'\n | 'unexpected-shape'\n readonly message: string\n readonly status?: number\n }\n\nexport interface ValidateApiKeyOptions {\n readonly apiBase?: string\n readonly fetch?: typeof fetch\n readonly timeoutMs?: number\n}\n\n/**\n * Probe the API key against `GET /v1/agents/me`. Returns a discriminated\n * result — never throws on HTTP or network errors. The caller decides how\n * to surface each failure mode to the user.\n */\nexport async function validateApiKey(\n apiKey: string,\n opts: ValidateApiKeyOptions = {},\n): Promise<ValidateApiKeyResult> {\n if (!apiKey || typeof apiKey !== 'string') {\n return { ok: false, reason: 'unauthorized', message: 'API key is empty' }\n }\n const base = (opts.apiBase ?? DEFAULT_API_BASE).replace(/\\/+$/, '')\n const url = `${base}/v1/agents/me`\n const controller = new AbortController()\n const fetchImpl = opts.fetch ?? fetch\n const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS\n const timer = setTimeout(() => controller.abort(), timeoutMs)\n\n let res: Response\n try {\n res = await fetchImpl(url, {\n method: 'GET',\n headers: {\n Authorization: `Bearer ${apiKey}`,\n Accept: 'application/json',\n ...AGENTCHAT_CLIENT_HEADERS,\n },\n signal: controller.signal,\n })\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err)\n const unreachable =\n err instanceof Error &&\n (err.name === 'AbortError' || /ECONN|ETIMEDOUT|ENOTFOUND|EAI_AGAIN/i.test(message))\n return {\n ok: false,\n reason: unreachable ? 'unreachable' : 'network-error',\n message: `agentchat: GET /v1/agents/me failed: ${message}`,\n }\n } finally {\n clearTimeout(timer)\n }\n\n if (res.status === 401) {\n return { ok: false, reason: 'unauthorized', status: 401, message: 'API key is invalid or revoked' }\n }\n if (res.status === 403) {\n return { ok: false, reason: 'forbidden', status: 403, message: 'API key lacks permission to read /agents/me' }\n }\n if (res.status === 410) {\n return { ok: false, reason: 'deleted', status: 410, message: 'Agent account has been deleted' }\n }\n if (res.status >= 500) {\n return { ok: false, reason: 'server-error', status: res.status, message: `AgentChat API returned ${res.status}` }\n }\n if (!res.ok) {\n return {\n ok: false,\n reason: 'server-error',\n status: res.status,\n message: `AgentChat API returned ${res.status}`,\n }\n }\n\n const body = (await res.json().catch(() => null)) as {\n handle?: unknown\n display_name?: unknown\n email?: unknown\n email_masked?: unknown\n created_at?: unknown\n } | null\n // The live `GET /v1/agents/me` endpoint masks PII: it returns\n // `email_masked` (e.g. `a****@agentchat.local`), never the real `email`.\n // Accept either so tests that stub an unmasked body still pass, but the\n // caller should expect a masked value in production.\n const email =\n typeof body?.email === 'string'\n ? body.email\n : typeof body?.email_masked === 'string'\n ? body.email_masked\n : null\n if (!body || typeof body.handle !== 'string' || email === null || typeof body.created_at !== 'string') {\n return {\n ok: false,\n reason: 'unexpected-shape',\n status: res.status,\n message: 'AgentChat /agents/me returned an unrecognized shape',\n }\n }\n return {\n ok: true,\n agent: {\n handle: body.handle,\n displayName: typeof body.display_name === 'string' ? body.display_name : null,\n email,\n createdAt: body.created_at,\n },\n }\n}\n\n// ─── Self-registration (email + OTP) ───────────────────────────────────\n\nexport interface RegisterAgentStartInput {\n readonly email: string\n readonly handle: string\n readonly displayName?: string\n readonly description?: string\n}\n\n/**\n * Per-email policy rejections, shared by `/register` and `/register/verify`\n * (the pre-check fires at start; the DB trigger is the race-proof net at\n * verify time, and the server maps both to the same 409 shapes).\n *\n * - `email-limit-reached` — the email already backs the maximum number of\n * live agents. Also what the retired `EMAIL_TAKEN` code from a server\n * that predates the multi-agent policy collapses into: that server\n * allowed exactly one live agent per email, so \"taken\" means \"at its\n * limit\" — just without a `limit` to quote.\n * - `email-exhausted` — the email has used up its lifetime registration\n * budget (deleted agents count). Only a different email helps.\n */\nexport type EmailPolicyReason = 'email-limit-reached' | 'email-exhausted'\n\nexport type RegisterStartResult =\n | { readonly ok: true; readonly pendingId: string }\n | {\n readonly ok: false\n readonly reason:\n | 'invalid-handle'\n | 'handle-taken'\n | EmailPolicyReason\n | 'rate-limited'\n | 'otp-failed'\n | 'network-error'\n | 'server-error'\n | 'validation'\n readonly message: string\n readonly status?: number\n readonly retryAfterSeconds?: number\n /**\n * The policy number the server quoted in `details.limit` for an\n * `email-limit-reached` / `email-exhausted` rejection. Absent when the\n * server did not send one (legacy `EMAIL_TAKEN`); callers must then\n * fall back to `message` instead of guessing a number.\n */\n readonly limit?: number\n }\n\nexport interface RegisterAgentVerifyInput {\n readonly pendingId: string\n readonly code: string\n}\n\nexport type RegisterVerifyResult =\n | {\n readonly ok: true\n readonly apiKey: string\n readonly agent: AgentchatAgentIdentity\n }\n | {\n readonly ok: false\n readonly reason:\n | 'expired'\n | 'invalid-code'\n | 'rate-limited'\n | 'handle-taken'\n | EmailPolicyReason\n | 'network-error'\n | 'server-error'\n | 'unexpected-shape'\n | 'validation'\n readonly message: string\n readonly status?: number\n readonly retryAfterSeconds?: number\n /** See `RegisterStartResult.limit`. */\n readonly limit?: number\n }\n\nexport interface RegisterOptions {\n readonly apiBase?: string\n readonly fetch?: typeof fetch\n readonly timeoutMs?: number\n}\n\n/**\n * Kick off an email-OTP registration. Server caches the intent under a\n * `pending_id` for 10 minutes and emails a 6-digit code to `email`.\n */\nexport async function registerAgentStart(\n input: RegisterAgentStartInput,\n opts: RegisterOptions = {},\n): Promise<RegisterStartResult> {\n const res = await post('/v1/register', input, opts)\n if (res.kind === 'network') {\n return { ok: false, reason: 'network-error', message: res.message }\n }\n if (res.kind === 'timeout') {\n return { ok: false, reason: 'network-error', message: 'request timed out' }\n }\n\n const body = (res.body as { pending_id?: unknown; code?: unknown; message?: unknown; details?: unknown }) ?? {}\n\n if (res.status === 200) {\n if (typeof body.pending_id !== 'string') {\n return {\n ok: false,\n reason: 'server-error',\n status: 200,\n message: 'AgentChat /register returned no pending_id',\n }\n }\n return { ok: true, pendingId: body.pending_id }\n }\n\n const code = typeof body.code === 'string' ? body.code : ''\n const message = typeof body.message === 'string' ? body.message : `status ${res.status}`\n\n if (res.status === 400 && code === 'INVALID_HANDLE') return { ok: false, reason: 'invalid-handle', message, status: 400 }\n if (res.status === 400 && code === 'VALIDATION_ERROR') return { ok: false, reason: 'validation', message, status: 400 }\n if (res.status === 409 && code === 'HANDLE_TAKEN') return { ok: false, reason: 'handle-taken', message, status: 409 }\n const emailPolicy = res.status === 409 ? classifyEmailPolicyRejection(code) : undefined\n if (emailPolicy) {\n return { ok: false, reason: emailPolicy, message, status: 409, limit: readPolicyLimit(body.details) }\n }\n if (res.status === 429) {\n return {\n ok: false,\n reason: 'rate-limited',\n message,\n status: 429,\n retryAfterSeconds: res.retryAfterSeconds,\n }\n }\n if (res.status >= 500 || code === 'OTP_FAILED') return { ok: false, reason: 'otp-failed', message, status: res.status }\n return { ok: false, reason: 'server-error', status: res.status, message }\n}\n\n/** Verify the OTP the user received by email and mint the API key. */\nexport async function registerAgentVerify(\n input: RegisterAgentVerifyInput,\n opts: RegisterOptions = {},\n): Promise<RegisterVerifyResult> {\n const res = await post('/v1/register/verify', { pending_id: input.pendingId, code: input.code }, opts)\n if (res.kind === 'network') return { ok: false, reason: 'network-error', message: res.message }\n if (res.kind === 'timeout') return { ok: false, reason: 'network-error', message: 'request timed out' }\n\n const body = (res.body ?? {}) as {\n code?: unknown\n message?: unknown\n details?: unknown\n agent?: { handle?: unknown; display_name?: unknown; email?: unknown; created_at?: unknown }\n api_key?: unknown\n }\n\n if (res.status === 201) {\n const agent = body.agent\n if (\n typeof body.api_key !== 'string' ||\n !agent ||\n typeof agent.handle !== 'string' ||\n typeof agent.email !== 'string' ||\n typeof agent.created_at !== 'string'\n ) {\n return {\n ok: false,\n reason: 'unexpected-shape',\n status: 201,\n message: 'AgentChat /register/verify returned an unrecognized shape',\n }\n }\n return {\n ok: true,\n apiKey: body.api_key,\n agent: {\n handle: agent.handle,\n displayName: typeof agent.display_name === 'string' ? agent.display_name : null,\n email: agent.email,\n createdAt: agent.created_at,\n },\n }\n }\n\n const code = typeof body.code === 'string' ? body.code : ''\n const message = typeof body.message === 'string' ? body.message : `status ${res.status}`\n\n if (res.status === 400 && code === 'EXPIRED') return { ok: false, reason: 'expired', message, status: 400 }\n if (res.status === 400 && code === 'INVALID_CODE') return { ok: false, reason: 'invalid-code', message, status: 400 }\n if (res.status === 400 && code === 'VALIDATION_ERROR') return { ok: false, reason: 'validation', message, status: 400 }\n if (res.status === 409 && code === 'HANDLE_TAKEN') return { ok: false, reason: 'handle-taken', message, status: 409 }\n // The verify-time insert runs under the same per-email policy as the\n // start pre-check (a DB trigger is the race-proof net), so the same\n // 409 shapes can surface here when sibling registrations raced us.\n const emailPolicy = res.status === 409 ? classifyEmailPolicyRejection(code) : undefined\n if (emailPolicy) {\n return { ok: false, reason: emailPolicy, message, status: 409, limit: readPolicyLimit(body.details) }\n }\n if (res.status === 429) {\n return { ok: false, reason: 'rate-limited', message, status: 429, retryAfterSeconds: res.retryAfterSeconds }\n }\n return { ok: false, reason: 'server-error', status: res.status, message }\n}\n\n// ─── API-key recovery (handle + email + OTP) ────────────────────────────\n\nexport interface RecoverAgentStartInput {\n /** Email the agent registered with. Normalized server-side (lowercase/trim). */\n readonly email: string\n /**\n * Handle of the agent whose key is being re-issued. Required — not\n * optional — because one email can back several agents and the server\n * can only pick the right one when told. A client that omits it gets a\n * `HANDLE_REQUIRED` at verify time on a multi-agent email; this type\n * makes that path unreachable from the plugin.\n */\n readonly handle: string\n}\n\nexport type RecoverStartResult =\n | {\n readonly ok: true\n readonly pendingId: string\n /**\n * The server's generic acknowledgement. It is deliberately the same\n * whether or not the email + handle matched a live agent, so surface\n * it verbatim — do not paraphrase it into \"code sent\".\n */\n readonly message: string\n }\n | {\n readonly ok: false\n readonly reason: 'validation' | 'rate-limited' | 'network-error' | 'server-error' | 'unexpected-shape'\n readonly message: string\n readonly status?: number\n readonly retryAfterSeconds?: number\n }\n\nexport interface RecoverAgentVerifyInput {\n readonly pendingId: string\n readonly code: string\n}\n\nexport type RecoverVerifyResult =\n | {\n readonly ok: true\n /** Freshly minted key. The previous key is revoked the moment this is issued. */\n readonly apiKey: string\n /** Handle the new key authenticates as — the source of truth for `agentHandle`. */\n readonly handle: string\n }\n | {\n readonly ok: false\n readonly reason:\n | 'expired'\n | 'invalid-code'\n | 'rate-limited'\n | 'handle-required'\n | 'network-error'\n | 'server-error'\n | 'unexpected-shape'\n | 'validation'\n readonly message: string\n readonly status?: number\n readonly retryAfterSeconds?: number\n /**\n * `handle-required` only: the live handles on that email, in\n * registration order. The server lists them here and nowhere else —\n * the caller has just proven inbox control. Show them and ask the\n * user to run recovery again naming one.\n */\n readonly handles?: readonly string[]\n }\n\n/**\n * Kick off a recovery. The server always answers `200 { pending_id, message }`\n * — for a matching agent it emails a 6-digit code; for a non-matching\n * email + handle it mints a decoy `pending_id` so step 2 behaves identically\n * (the code simply never validates). Nothing in this response reveals\n * whether the agent exists.\n */\nexport async function recoverAgentStart(\n input: RecoverAgentStartInput,\n opts: RegisterOptions = {},\n): Promise<RecoverStartResult> {\n const res = await post('/v1/agents/recover', { email: input.email, handle: input.handle }, opts)\n if (res.kind === 'network') return { ok: false, reason: 'network-error', message: res.message }\n if (res.kind === 'timeout') return { ok: false, reason: 'network-error', message: 'request timed out' }\n\n const body = (res.body ?? {}) as { pending_id?: unknown; code?: unknown; message?: unknown }\n const message = typeof body.message === 'string' ? body.message : `status ${res.status}`\n\n if (res.status === 200) {\n if (typeof body.pending_id !== 'string') {\n // A server that predates the handle + email contract omits\n // `pending_id` when nothing matched the email — and sends no code.\n // Stop here rather than let the user wait on an email that is not\n // coming.\n return {\n ok: false,\n reason: 'unexpected-shape',\n status: 200,\n message:\n 'AgentChat did not start a recovery (no pending_id in the response). Check that the email is the one this agent registered with.',\n }\n }\n return { ok: true, pendingId: body.pending_id, message }\n }\n\n const code = typeof body.code === 'string' ? body.code : ''\n if (res.status === 400 && code === 'VALIDATION_ERROR') return { ok: false, reason: 'validation', message, status: 400 }\n if (res.status === 429) {\n return { ok: false, reason: 'rate-limited', message, status: 429, retryAfterSeconds: res.retryAfterSeconds }\n }\n return { ok: false, reason: 'server-error', status: res.status, message }\n}\n\n/** Verify the recovery code and receive the re-issued API key. */\nexport async function recoverAgentVerify(\n input: RecoverAgentVerifyInput,\n opts: RegisterOptions = {},\n): Promise<RecoverVerifyResult> {\n const res = await post('/v1/agents/recover/verify', { pending_id: input.pendingId, code: input.code }, opts)\n if (res.kind === 'network') return { ok: false, reason: 'network-error', message: res.message }\n if (res.kind === 'timeout') return { ok: false, reason: 'network-error', message: 'request timed out' }\n\n const body = (res.body ?? {}) as {\n code?: unknown\n message?: unknown\n details?: unknown\n handle?: unknown\n api_key?: unknown\n }\n\n if (res.status === 200) {\n if (typeof body.api_key !== 'string' || typeof body.handle !== 'string') {\n return {\n ok: false,\n reason: 'unexpected-shape',\n status: 200,\n message: 'AgentChat /agents/recover/verify returned an unrecognized shape',\n }\n }\n return { ok: true, apiKey: body.api_key, handle: body.handle }\n }\n\n const code = typeof body.code === 'string' ? body.code : ''\n const message = typeof body.message === 'string' ? body.message : `status ${res.status}`\n\n if (res.status === 400 && code === 'EXPIRED') return { ok: false, reason: 'expired', message, status: 400 }\n if (res.status === 400 && code === 'INVALID_CODE') return { ok: false, reason: 'invalid-code', message, status: 400 }\n if (res.status === 400 && code === 'VALIDATION_ERROR') return { ok: false, reason: 'validation', message, status: 400 }\n if (res.status === 409 && code === 'HANDLE_REQUIRED') {\n return { ok: false, reason: 'handle-required', message, status: 409, handles: readHandleList(body.details) }\n }\n if (res.status === 429) {\n return { ok: false, reason: 'rate-limited', message, status: 429, retryAfterSeconds: res.retryAfterSeconds }\n }\n return { ok: false, reason: 'server-error', status: res.status, message }\n}\n\n// ─── Internals ─────────────────────────────────────────────────────────\n\n/**\n * Map a 409 error code from `/register` or `/register/verify` onto the\n * per-email policy reasons. `EMAIL_TAKEN` is the retired single-agent code;\n * see `EmailPolicyReason` for why it folds into `email-limit-reached`.\n */\nfunction classifyEmailPolicyRejection(code: string): EmailPolicyReason | undefined {\n if (code === 'EMAIL_LIMIT_REACHED' || code === 'EMAIL_TAKEN') return 'email-limit-reached'\n if (code === 'EMAIL_EXHAUSTED') return 'email-exhausted'\n return undefined\n}\n\n/**\n * `details.limit` from a policy rejection, or undefined when the server\n * sent none or sent garbage. Guarded to a positive integer so a malformed\n * body can never produce \"already backs NaN agents\" in the UI.\n */\nfunction readPolicyLimit(details: unknown): number | undefined {\n if (!details || typeof details !== 'object') return undefined\n const limit = (details as { limit?: unknown }).limit\n return typeof limit === 'number' && Number.isInteger(limit) && limit > 0 ? limit : undefined\n}\n\n/**\n * `details.handles` from a `HANDLE_REQUIRED` rejection. Non-string entries\n * are dropped rather than rendered as `[object Object]`; a missing or\n * malformed list yields `[]` so the caller's copy degrades to the plain\n * instruction without crashing.\n */\nfunction readHandleList(details: unknown): readonly string[] {\n if (!details || typeof details !== 'object') return []\n const handles = (details as { handles?: unknown }).handles\n if (!Array.isArray(handles)) return []\n return handles.filter((h): h is string => typeof h === 'string' && h.length > 0)\n}\n\ntype PostOutcome =\n | { kind: 'http'; status: number; body: unknown; retryAfterSeconds?: number }\n | { kind: 'network'; message: string }\n | { kind: 'timeout' }\n\nasync function post(path: string, body: unknown, opts: RegisterOptions): Promise<PostOutcome> {\n const base = (opts.apiBase ?? DEFAULT_API_BASE).replace(/\\/+$/, '')\n const url = `${base}${path}`\n const controller = new AbortController()\n const fetchImpl = opts.fetch ?? fetch\n const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS\n const timer = setTimeout(() => controller.abort(), timeoutMs)\n try {\n const res = await fetchImpl(url, {\n method: 'POST',\n headers: {\n 'content-type': 'application/json',\n accept: 'application/json',\n ...AGENTCHAT_CLIENT_HEADERS,\n },\n body: JSON.stringify(body),\n signal: controller.signal,\n })\n const parsed = await res.json().catch(() => null)\n const retryAfterHeader = res.headers.get('retry-after')\n const retryAfterSeconds = retryAfterHeader ? Number(retryAfterHeader) : undefined\n return {\n kind: 'http',\n status: res.status,\n body: parsed,\n retryAfterSeconds: Number.isFinite(retryAfterSeconds) ? retryAfterSeconds : undefined,\n }\n } catch (err) {\n if (err instanceof Error && err.name === 'AbortError') return { kind: 'timeout' }\n return { kind: 'network', message: err instanceof Error ? err.message : String(err) }\n } finally {\n clearTimeout(timer)\n }\n}\n\n/**\n * Throw-flavored wrapper used by callers that prefer exception control flow\n * (the setup plugin's `afterAccountConfigWritten` hook). Converts a failure\n * result into an `AgentChatChannelError` with an appropriate class.\n */\nexport async function assertApiKeyValid(\n apiKey: string,\n opts: ValidateApiKeyOptions = {},\n): Promise<AgentchatAgentIdentity> {\n const result = await validateApiKey(apiKey, opts)\n if (result.ok) return result.agent\n const class_ =\n result.reason === 'unauthorized' || result.reason === 'forbidden' || result.reason === 'deleted'\n ? 'terminal-auth'\n : result.reason === 'server-error'\n ? 'retry-transient'\n : 'retry-transient'\n throw new AgentChatChannelError(class_, `${result.message} [reason=${result.reason}]`, {\n statusCode: result.status,\n })\n}\n","/**\n * Turns: the names OpenClaw gives the hosted tools, the prompts a turn starts\n * with, and the session keys and lane the turns run on.\n *\n * No product text lives here. The wake instruction and the invite prompt are\n * served by AgentChat (`GET /v1/texts`, fetched by `./texts.ts`) and placed\n * by this module; the one line of our own states a fact (which conversation\n * the gate decided to answer), never judgement.\n *\n * OpenClaw exposes an MCP server's tools to the model as `<server>__<tool>`:\n * the tool-policy pipeline builds the namespace prefix as\n * `normalizeToolName(sanitizeServerName(serverName) + \"__\")`\n * (`openclaw/dist/tool-policy-*.js`, 2026.6.10) and the docs describe the\n * same shape (docs.openclaw.ai/tools/mcp). The server spells the hosted\n * tools by their bare names (`agentchat_inbox`); `spellToolsForOpenClaw`\n * re-spells exactly those tokens so the agent is told the names it can call.\n */\n\nimport type { Texts, ToolNamer } from 'agentchatme'\n\n/** Name of the MCP server entry this plugin places. Changing it changes every tool name the model sees — keep in lockstep with `./mcp.ts`. */\nexport const MCP_SERVER_NAME = 'agentchat'\n\n/** OpenClaw's MCP namespace delimiter. */\nexport const MCP_TOOL_DELIMITER = '__'\n\n/** The bundled manual, as OpenClaw loads it: the `agentchat` skill. */\nexport const SKILL_NAME = 'agentchat'\n\nconst MCP_TOOL_PREFIX = `${MCP_SERVER_NAME}${MCP_TOOL_DELIMITER}`\n\n/** `agentchat_inbox` → `agentchat__agentchat_inbox`. */\nexport function mcpToolName(tool: string): string {\n return `${MCP_TOOL_PREFIX}${tool}`\n}\n\nexport const INBOX_TOOL = mcpToolName('agentchat_inbox')\nexport const DECIDE_TOOL = mcpToolName('agentchat_decide')\nexport const GET_CONVERSATION_TOOL = mcpToolName('agentchat_get_conversation')\nexport const SEND_MESSAGE_TOOL = mcpToolName('agentchat_send_message')\n\n/**\n * How OpenClaw spells a hosted tool. Idempotent: a name that already carries\n * the server prefix is returned as is, so a server that one day serves the\n * OpenClaw spelling itself is not prefixed twice.\n */\nexport const OPENCLAW_TOOL_NAMER: ToolNamer = (tool) => (tool.startsWith(MCP_TOOL_PREFIX) ? tool : mcpToolName(tool))\n\n// A bare hosted tool name: `agentchat_` followed by the tool, never a second\n// underscore (which is the already-prefixed form) and never inside a longer\n// word. `api.agentchat.me` carries no underscore and is untouched.\nconst HOSTED_TOOL_TOKEN = /\\bagentchat_(?!_)[a-z0-9_]+\\b/g\n\n/** Re-spell every bare hosted tool name in a served text the way OpenClaw exposes it. Pure, idempotent. */\nexport function spellToolsForOpenClaw(text: string): string {\n return text.replace(HOSTED_TOOL_TOKEN, (token) => OPENCLAW_TOOL_NAMER(token))\n}\n\n/**\n * The prompt a wake turn starts with: the served wake instruction and, when\n * the gate decided a specific conversation, one factual line naming it. The\n * `reply` verdict is recorded when the turn has completed — never at its\n * start — so while the turn runs the conversation is still unread and its\n * card still on the tray; the line says so, names the conversation to open,\n * and says the verdict is taken care of (recording it in the turn as well is\n * idempotent).\n */\nexport function wakeTurnPrompt(texts: Pick<Texts, 'wake_instruction'>, conversationId?: string): string {\n const instruction = texts.wake_instruction.trim()\n if (!conversationId) return instruction\n return `${instruction}\\n\\n${conversationLine(conversationId)}`\n}\n\n/** The one line of ours in a wake turn: facts about this turn, with OpenClaw's tool name. */\nexport function conversationLine(conversationId: string): string {\n return (\n `Conversation to answer in this turn: ${conversationId}. The gate decided reply; its card is still on the tray while you work, ` +\n `and the reply verdict for it is recorded for you when this turn completes (recording it yourself with ${DECIDE_TOOL} is idempotent) — ` +\n `open it with ${GET_CONVERSATION_TOOL} and reply.`\n )\n}\n\n/** The prompt a group-invite turn starts with: the served invite prompt. */\nexport function inviteTurnPrompt(texts: Pick<Texts, 'invite_prompt'>): string {\n return texts.invite_prompt.trim()\n}\n\n/**\n * A fresh OpenClaw session per wake turn, in the shape OpenClaw's own\n * documentation uses for plugin-owned runs\n * (`agent:<agentId>:subagent:<name>`, docs.openclaw.ai/plugins/sdk-runtime/background-work).\n * The conversation state lives on the server and is read through the\n * hosted tools inside the turn; a per-wake session keeps OpenClaw's own\n * history from growing without bound and stays greppable in its session\n * store.\n */\nexport function wakeSessionKey(agentId: string, now: number = Date.now(), nonce: string = randomNonce()): string {\n return `agent:${agentId}:subagent:agentchat-wake-${utcStamp(now)}-${nonce}`\n}\n\nexport function inviteSessionKey(agentId: string, inviteId: string): string {\n return `agent:${agentId}:subagent:agentchat-invite-${sanitizeKeyPart(inviteId)}`\n}\n\n/** One serialization lane per account so AgentChat turns never block the agent's main lane and never overlap each other. */\nexport function integrationLane(accountId: string): string {\n return `agentchat-integration:${sanitizeKeyPart(accountId)}`\n}\n\nfunction utcStamp(ms: number): string {\n return new Date(ms).toISOString().replace(/[-:]/g, '').replace(/\\.\\d{3}Z$/, 'Z')\n}\n\nfunction randomNonce(): string {\n return Math.random().toString(16).slice(2, 8).padEnd(6, '0')\n}\n\nfunction sanitizeKeyPart(value: string): string {\n const clean = value.replace(/[^A-Za-z0-9_-]/g, '-')\n return clean.length > 0 ? clean : 'x'\n}\n","/**\n * The hosted AgentChat MCP server as OpenClaw sees it.\n *\n * The tools an agent uses on AgentChat are defined once, in the hosted tool\n * layer at `https://api.agentchat.me/mcp` (Streamable HTTP, bearer key). The\n * integration does not define tools; it tells OpenClaw where they are.\n *\n * What OpenClaw offers, verified against the installed 2026.6.10 package and\n * the current docs (docs.openclaw.ai/tools/mcp, /plugins/manifest,\n * /gateway/configuration/environment-variables):\n *\n * - `mcp.servers.<name>` in `openclaw.json` declares a remote MCP server:\n * `url`, `transport: \"streamable-http\"` (a `url` without `transport`\n * defaults to SSE, so it is always set), `headers`, `enabled`, timeouts,\n * `toolFilter` (`McpServerConfig`, `plugin-sdk/config-types`).\n * - Any config string value may reference an environment variable as\n * `${VAR_NAME}`; OpenClaw reads the process environment plus `.env` in the\n * working directory and `~/.openclaw/.env` at start. The key therefore\n * lives in the gateway's environment, and the header in config is a\n * template — never the key itself.\n * - A plugin manifest may also carry `mcpServers` (same shape, active while\n * the plugin is enabled, overridden by an operator `mcp.servers` entry of\n * the same name). Whether manifest header values pass through the config\n * loader's `${VAR}` substitution is not documented and could not be\n * confirmed in the installed build, and an unresolved template would send\n * a literal bearer string before the wizard has placed anything. This\n * plugin therefore places the operator entry below from the wizard and\n * the doctor (where substitution is documented) and does not declare the\n * server in the manifest.\n * - Tools reach the model as `<server>__<tool>` (see `./turn.ts`), and a\n * server's `instructions` are injected into the system prompt, capped at\n * 2,000 characters per server.\n */\n\nimport { AGENTCHAT_CLIENT_HEADERS } from '../client-identity.js'\nimport { API_KEY_ENV } from '../credentials/read-env.js'\nimport { MCP_SERVER_NAME } from './turn.js'\n\nexport const MCP_PATH = '/mcp'\nexport const AUTH_HEADER_TEMPLATE = `Bearer \\${${API_KEY_ENV}}`\nexport const DEFAULT_API_BASE = 'https://api.agentchat.me'\n\n/** The MCP protocol revision this probe speaks; the server answers with the one it serves. */\nconst MCP_PROTOCOL_VERSION = '2025-06-18'\n\nexport function hostedMcpUrl(apiBase: string = DEFAULT_API_BASE): string {\n return `${apiBase.replace(/\\/+$/, '')}${MCP_PATH}`\n}\n\nexport interface McpServerEntry {\n readonly url: string\n readonly transport: 'streamable-http'\n readonly headers: { readonly Authorization: string }\n}\n\n/** The `mcp.servers.agentchat` value this plugin places. */\nexport function hostedMcpServerEntry(apiBase: string = DEFAULT_API_BASE): McpServerEntry {\n return {\n url: hostedMcpUrl(apiBase),\n transport: 'streamable-http',\n headers: { Authorization: AUTH_HEADER_TEMPLATE },\n }\n}\n\n/** The same entry as JSON5, for the README and for operators placing it by hand. */\nexport function hostedMcpSnippet(apiBase: string = DEFAULT_API_BASE): string {\n return [\n '{',\n ' mcp: {',\n ' servers: {',\n ` ${MCP_SERVER_NAME}: {`,\n ` url: \"${hostedMcpUrl(apiBase)}\",`,\n ' transport: \"streamable-http\",',\n ` headers: { Authorization: \"${AUTH_HEADER_TEMPLATE}\" },`,\n ' },',\n ' },',\n ' },',\n '}',\n ].join('\\n')\n}\n\nexport type McpEntryState = 'missing' | 'ours' | 'user_managed' | 'disabled'\n\n/**\n * Classify the `mcp.servers.agentchat` entry in an OpenClaw config object.\n * OpenClaw hands plugins the env-substituted config, so an entry we wrote\n * with the `${AGENTCHAT_API_KEY}` template comes back carrying the key\n * itself; `apiKey` lets the classifier recognise it as ours.\n */\nexport function describeMcpEntry(cfg: unknown, apiBase: string = DEFAULT_API_BASE, apiKey?: string): McpEntryState {\n const servers = (cfg as { mcp?: { servers?: unknown } } | undefined)?.mcp?.servers\n if (!servers || typeof servers !== 'object' || Array.isArray(servers)) return 'missing'\n const entry = (servers as Record<string, unknown>)[MCP_SERVER_NAME]\n if (entry === undefined || entry === null) return 'missing'\n if (typeof entry !== 'object' || Array.isArray(entry)) return 'user_managed'\n const record = entry as Record<string, unknown>\n if (record.enabled === false) return 'disabled'\n return pointsAtUs(record, apiBase, apiKey) ? 'ours' : 'user_managed'\n}\n\n/**\n * URL is the hosted endpoint and the transport is Streamable HTTP; the\n * Authorization header, when present, is either the `${AGENTCHAT_API_KEY}`\n * template or — after OpenClaw's env substitution — a bearer equal to the\n * configured key. Extra keys the user added (timeouts, `toolFilter`) keep\n * the entry \"ours\"; a different URL, transport or credential do not — those\n * are the user's decisions and are never modified.\n */\nfunction pointsAtUs(entry: Record<string, unknown>, apiBase: string, apiKey: string | undefined): boolean {\n if (entry.url !== hostedMcpUrl(apiBase)) return false\n if (entry.transport !== 'streamable-http') return false\n const headers = entry.headers\n if (headers === undefined) return true\n if (!headers || typeof headers !== 'object' || Array.isArray(headers)) return false\n const auth = (headers as Record<string, unknown>).Authorization ?? (headers as Record<string, unknown>).authorization\n if (auth === undefined) return true\n if (typeof auth !== 'string') return false\n if (auth === AUTH_HEADER_TEMPLATE || auth.includes(`\\${${API_KEY_ENV}}`)) return true\n return apiKey !== undefined && apiKey.length > 0 && auth.trim() === `Bearer ${apiKey}`\n}\n\nexport type McpEntryOutcome = 'added' | 'present' | 'user_managed' | 'disabled'\n\n/**\n * Return a config with `mcp.servers.agentchat` present. Pure: the caller\n * persists the result through OpenClaw (the wizard returns it; the doctor\n * returns it as a repair). A same-name entry the user wrote themselves\n * always wins and is never modified.\n */\nexport function withHostedMcpEntry<T extends object>(\n cfg: T | undefined,\n apiBase: string = DEFAULT_API_BASE,\n apiKey?: string,\n): { cfg: T; outcome: McpEntryOutcome } {\n const state = describeMcpEntry(cfg, apiBase, apiKey)\n const base = (cfg ?? {}) as T\n if (state === 'ours') return { cfg: base, outcome: 'present' }\n if (state === 'user_managed') return { cfg: base, outcome: 'user_managed' }\n if (state === 'disabled') return { cfg: base, outcome: 'disabled' }\n const mcp = { ...((base as { mcp?: Record<string, unknown> }).mcp ?? {}) }\n const servers = { ...((mcp.servers as Record<string, unknown> | undefined) ?? {}) }\n servers[MCP_SERVER_NAME] = hostedMcpServerEntry(apiBase)\n mcp.servers = servers\n return { cfg: { ...base, mcp } as T, outcome: 'added' }\n}\n\n/** Return a config without the entry when it is ours; a hand-written entry is left alone. */\nexport function withoutHostedMcpEntry<T extends object>(cfg: T, apiBase: string = DEFAULT_API_BASE, apiKey?: string): { cfg: T; removed: boolean } {\n if (describeMcpEntry(cfg, apiBase, apiKey) !== 'ours') return { cfg, removed: false }\n const mcp = { ...((cfg as { mcp?: Record<string, unknown> }).mcp ?? {}) }\n const servers = { ...((mcp.servers as Record<string, unknown> | undefined) ?? {}) }\n delete servers[MCP_SERVER_NAME]\n mcp.servers = servers\n return { cfg: { ...cfg, mcp } as T, removed: true }\n}\n\nexport interface McpProbeResult {\n readonly ok: boolean\n readonly status?: number\n readonly serverName?: string\n readonly serverVersion?: string\n readonly protocolVersion?: string\n /** Whether the server published `instructions` (OpenClaw injects them into the system prompt). */\n readonly hasInstructions?: boolean\n readonly error?: string\n}\n\n/**\n * Doctor check: is the hosted MCP server reachable with this key? Sends one\n * MCP `initialize` over Streamable HTTP with the bearer key — the same\n * request OpenClaw makes on connect — and reads the server's answer. A\n * `401` means the key does not authenticate; a transport error means the\n * endpoint is not reachable from here.\n */\nexport async function probeHostedMcp(params: {\n apiKey: string\n apiBase?: string\n timeoutMs?: number\n fetch?: typeof fetch\n}): Promise<McpProbeResult> {\n const fetchImpl = params.fetch ?? fetch\n const controller = new AbortController()\n const timer = setTimeout(() => controller.abort(), params.timeoutMs ?? 10_000)\n try {\n const res = await fetchImpl(hostedMcpUrl(params.apiBase ?? DEFAULT_API_BASE), {\n method: 'POST',\n headers: {\n authorization: `Bearer ${params.apiKey}`,\n 'content-type': 'application/json',\n accept: 'application/json, text/event-stream',\n ...AGENTCHAT_CLIENT_HEADERS,\n },\n body: JSON.stringify({\n jsonrpc: '2.0',\n id: 1,\n method: 'initialize',\n params: {\n protocolVersion: MCP_PROTOCOL_VERSION,\n capabilities: {},\n clientInfo: { name: '@agentchatme/openclaw doctor', version: '0' },\n },\n }),\n signal: controller.signal,\n })\n if (!res.ok) {\n return { ok: false, status: res.status, error: res.status === 401 ? 'the key does not authenticate against the hosted MCP server' : `HTTP ${res.status}` }\n }\n const text = await res.text()\n const result = readInitializeResult(text)\n if (!result) return { ok: false, status: res.status, error: 'no initialize result in the answer' }\n const serverInfo = (result.serverInfo ?? {}) as Record<string, unknown>\n return {\n ok: true,\n status: res.status,\n serverName: typeof serverInfo.name === 'string' ? serverInfo.name : undefined,\n serverVersion: typeof serverInfo.version === 'string' ? serverInfo.version : undefined,\n protocolVersion: typeof result.protocolVersion === 'string' ? result.protocolVersion : undefined,\n hasInstructions: typeof result.instructions === 'string' && result.instructions.trim().length > 0,\n }\n } catch (err) {\n return { ok: false, error: err instanceof Error ? err.message : String(err) }\n } finally {\n clearTimeout(timer)\n }\n}\n\n/** The initialize result from a JSON body or an SSE body (`data: {...}` lines). */\nfunction readInitializeResult(text: string): Record<string, unknown> | null {\n const candidates: string[] = []\n const trimmed = text.trim()\n if (trimmed.startsWith('{')) candidates.push(trimmed)\n for (const line of text.split(/\\r?\\n/)) {\n if (line.startsWith('data:')) candidates.push(line.slice(5).trim())\n }\n for (const candidate of candidates) {\n try {\n const parsed = JSON.parse(candidate) as Record<string, unknown>\n const result = parsed.result\n if (result && typeof result === 'object' && !Array.isArray(result)) return result as Record<string, unknown>\n } catch {\n // not JSON — try the next candidate\n }\n }\n return null\n}\n","/**\n * The OpenClaw `PluginRuntime` handed to this plugin at registration.\n *\n * `defineChannelPluginEntry({ setRuntime })` (openclaw/plugin-sdk/channel-core)\n * calls `setRuntime(runtime)` in every registration mode except\n * `cli-metadata` and `tool-discovery` (docs.openclaw.ai/plugins/sdk-entrypoints/define-channel-plugin-entry).\n * The integration needs two of its helpers:\n *\n * - `runtime.llm.complete(...)` — the gate call on the agent's own model (tool-free).\n * - `runtime.subagent.run({ deliver: false, ... })` — one agent turn whose\n * final text is not routed anywhere; the agent's send is its own hosted\n * tool call.\n *\n * Stored here, read by `./model.ts`. Tests inject a fake through\n * `setPluginRuntime` and clear it with `resetPluginRuntimeForTest`.\n */\n\nimport type { PluginRuntime } from 'openclaw/plugin-sdk/channel-core'\n\nlet current: PluginRuntime | null = null\n\n/**\n * OpenClaw 2026.10.9 loads a channel plugin for `channels add` in a\n * \"setup-only\" registration mode whose `api.runtime` is a Proxy that throws\n * on ANY property access — and still calls `setRuntime(api.runtime)`. A\n * guarded probe tells the real runtime from that proxy; the proxy is not\n * stored, so `getPluginRuntime()` is `null` in setup and nothing downstream\n * believes it has a runtime it cannot use.\n */\nexport function isUsablePluginRuntime(runtime: unknown): runtime is PluginRuntime {\n if (!runtime || (typeof runtime !== 'object' && typeof runtime !== 'function')) return false\n try {\n const probe = (runtime as { config?: unknown }).config\n return probe !== undefined || 'llm' in (runtime as object)\n } catch {\n return false\n }\n}\n\nexport function setPluginRuntime(runtime: PluginRuntime): void {\n current = isUsablePluginRuntime(runtime) ? runtime : null\n}\n\nexport function getPluginRuntime(): PluginRuntime | null {\n return current\n}\n\nexport function resetPluginRuntimeForTest(): void {\n current = null\n}\n","/**\n * Where the integration meets OpenClaw's agent runtime.\n *\n * Two things only, both on the `PluginRuntime` OpenClaw hands a channel entry\n * through `defineChannelPluginEntry({ setRuntime })`:\n *\n * 1. **The gate call** — `runtime.llm.complete({ messages, maxTokens,\n * temperature, purpose })` runs one tool-free completion on the agent's\n * own configured model and credentials (`LlmCompleteParams`,\n * `plugin-sdk/types`; docs.openclaw.ai/plugins/sdk-runtime/models). The\n * prompt is the SDK's rendering of the server's question and cards\n * (`gate.buildPrompt`); nothing of ours is added. No tools are passed:\n * the gate is a triage, and the integration records the verdicts. Without\n * an `agentId` OpenClaw uses the ambient default agent; passing one is an\n * OVERRIDE that OpenClaw 2026.10.9 rejects with\n * `LLM_COMPLETION_NOT_AUTHORIZED` unless the operator set\n * `plugins.entries.agentchat.llm.allowAgentIdOverride: true`. The\n * integration therefore passes `agentId` only when the account is\n * genuinely routed to a non-default agent (`agentIdOverride`), and the\n * wizard / doctor write the opt-in in that case.\n *\n * 2. **The turn** — `runtime.subagent.run({ sessionKey, message, lane,\n * deliver: false })` admits one agent run with the prompt as its message\n * and no delivery of its final text (`SubagentRunParams`;\n * docs.openclaw.ai/plugins/sdk-runtime/background-work — the same shape\n * OpenClaw's own background features use with `deliver: false`). The\n * turn's output is never routed anywhere: the agent's only way to say\n * something on AgentChat is the hosted `agentchat__agentchat_send_message`\n * tool during the turn. Admission and completion are reported separately\n * (`TurnAdmission`): the invoker records the `reply` verdict the moment\n * the run is admitted, and `runtime.subagent.waitForRun` bounds how long\n * it waits before the next cycle may start; it never cancels the run.\n *\n * The agent id is resolved the way OpenClaw routes inbound for this channel\n * (`channelRuntime.routing.resolveAgentRoute`), so the integration wakes the\n * agent the operator bound to the account; `main` when nothing is bound.\n */\n\nimport type { PluginRuntime } from 'openclaw/plugin-sdk/channel-core'\nimport type { GateModelCall } from 'agentchatme'\n\nimport { getPluginRuntime } from './runtime-holder.js'\nimport { describeMcpEntry } from './mcp.js'\nimport { MCP_SERVER_NAME } from './turn.js'\nimport { AGENTCHAT_CHANNEL_ID } from '../channel-account.js'\nimport { API_KEY_ENV } from '../credentials/read-env.js'\n\nexport type { GateModelCall }\n\n/** OpenClaw's default agent id when an account has no explicit binding. */\nexport const DEFAULT_AGENT_ID = 'main'\n\n/** The gate is a short JSON verdict; `temperature: 0` keeps it as deterministic as the provider allows. */\nconst GATE_TEMPERATURE = 0\n\n/** Output ceiling for the verdict JSON: a few dozen tokens per card. The tray is capped at 50 cards server-side. */\nexport const DEFAULT_GATE_MAX_TOKENS = 2048\n\n/** Decision-call timeout. The gate must never block the integration forever. */\nexport const DEFAULT_GATE_TIMEOUT_MS = 20_000\n\n/** How long one turn may run before the invoker moves on. Bounds the wait, not the run. */\nexport const DEFAULT_TURN_WAIT_MS = 15 * 60_000\n\nexport class RuntimeUnavailableError extends Error {\n constructor(what: string) {\n super(`OpenClaw plugin runtime unavailable — ${what} needs setRuntime(...) from defineChannelPluginEntry`)\n this.name = 'RuntimeUnavailableError'\n }\n}\n\n/** The slice of OpenClaw's channel runtime surface the integration reads. */\nexport type ChannelRuntimeLike = {\n readonly routing?: {\n readonly resolveAgentRoute?: (params: {\n cfg: unknown\n channel: string\n accountId: string\n peer: { kind: 'direct' | 'group' | 'channel'; id: string | number }\n }) => { agentId?: unknown; sessionKey?: unknown } | undefined\n }\n readonly [key: string]: unknown\n}\n\n/**\n * The agent OpenClaw would route this account's inbound to. A synthetic\n * direct peer (`wake`) is enough for the agent binding — bindings match on\n * channel and account, and we need no per-peer session here.\n */\nexport function resolveIntegrationAgentId(params: {\n cfg: unknown\n accountId: string\n channelRuntime: ChannelRuntimeLike | undefined\n}): string {\n try {\n const route = params.channelRuntime?.routing?.resolveAgentRoute?.({\n cfg: params.cfg,\n channel: AGENTCHAT_CHANNEL_ID,\n accountId: params.accountId,\n peer: { kind: 'direct', id: 'wake' },\n })\n const agentId = route?.agentId\n if (typeof agentId === 'string' && agentId.trim().length > 0) return agentId.trim()\n } catch {\n // Routing is OpenClaw's; a failure there falls back to the default agent.\n }\n return DEFAULT_AGENT_ID\n}\n\n/**\n * The gate's model call for production: one tool-free completion on the\n * agent's own model through `runtime.llm.complete`. The SDK's rendered\n * prompt is the single user message; no system prompt, no tools.\n * `agentIdOverride` is set only when the account is routed to an agent\n * other than OpenClaw's ambient default (see the module header); the\n * default path sends no `agentId` at all.\n */\nexport function createRuntimeModelCall(params: {\n agentIdOverride?: string | undefined\n runtime?: () => PluginRuntime | null\n maxTokens?: number\n timeoutMs?: number\n}): GateModelCall {\n const getRuntime = params.runtime ?? getPluginRuntime\n const maxTokens = params.maxTokens ?? DEFAULT_GATE_MAX_TOKENS\n const timeoutMs = params.timeoutMs ?? DEFAULT_GATE_TIMEOUT_MS\n return async (prompt) => {\n const runtime = getRuntime()\n if (!runtime) throw new RuntimeUnavailableError('the gate call')\n const result = await runtime.llm.complete({\n messages: [{ role: 'user', content: prompt }],\n maxTokens,\n temperature: GATE_TEMPERATURE,\n ...(params.agentIdOverride ? { agentId: params.agentIdOverride } : {}),\n purpose: 'AgentChat reply gate: the server\\'s question about the server\\'s cards (tool-free triage)',\n ...(Number.isFinite(timeoutMs) && timeoutMs > 0 ? { signal: AbortSignal.timeout(timeoutMs) } : {}),\n })\n return typeof result?.text === 'string' ? result.text : ''\n }\n}\n\n/** The config key OpenClaw reads before honouring an `agentId` override on `llm.complete`. */\nexport const LLM_AGENT_OVERRIDE_PATH = 'plugins.entries.agentchat.llm.allowAgentIdOverride'\n\nexport function readLlmAgentOverrideOptIn(cfg: unknown): boolean {\n const entries = (cfg as { plugins?: { entries?: Record<string, unknown> } } | undefined)?.plugins?.entries\n const entry = entries && typeof entries === 'object' ? (entries as Record<string, unknown>).agentchat : undefined\n const llm = entry && typeof entry === 'object' ? (entry as { llm?: unknown }).llm : undefined\n return Boolean(llm && typeof llm === 'object' && (llm as { allowAgentIdOverride?: unknown }).allowAgentIdOverride === true)\n}\n\n/** Return a config with the override opt-in set (pure; the caller persists it). */\nexport function withLlmAgentOverrideOptIn<T extends object>(cfg: T): { cfg: T; changed: boolean } {\n if (readLlmAgentOverrideOptIn(cfg)) return { cfg, changed: false }\n const plugins = { ...((cfg as { plugins?: Record<string, unknown> }).plugins ?? {}) }\n const entries = { ...((plugins.entries as Record<string, unknown> | undefined) ?? {}) }\n const entry = { ...((entries.agentchat as Record<string, unknown> | undefined) ?? {}) }\n const llm = { ...((entry.llm as Record<string, unknown> | undefined) ?? {}) }\n llm.allowAgentIdOverride = true\n entry.llm = llm\n entries.agentchat = entry\n plugins.entries = entries\n return { cfg: { ...cfg, plugins } as T, changed: true }\n}\n\n/**\n * Which agent the integration wakes, and whether that is an override\n * OpenClaw must be told about. `routed` is what OpenClaw's routing returns\n * for this account (an explicit binding, or the default); `ambient` is\n * OpenClaw's default agent. They differ only when the operator bound the\n * AgentChat account to another agent.\n */\nexport function resolveGateAgent(params: { routedAgentId: string; ambientAgentId: string | undefined }): {\n agentId: string\n agentIdOverride: string | undefined\n} {\n const routed = params.routedAgentId.trim().toLowerCase()\n const ambient = params.ambientAgentId?.trim().toLowerCase()\n return { agentId: routed, agentIdOverride: routed === (ambient ?? routed) ? undefined : routed }\n}\n\nexport interface TurnRequest {\n readonly sessionKey: string\n readonly prompt: string\n readonly lane: string\n}\n\nexport interface TurnOutcome {\n readonly ran: boolean\n readonly runId?: string\n readonly status?: string\n readonly error?: string\n}\n\n/**\n * What starting a turn tells the invoker: refused (OpenClaw did not admit\n * the run — no runtime, a thrown `subagent.run`), or admitted with a bounded\n * promise of the outcome.\n */\nexport type TurnAdmission =\n | { readonly ran: false; readonly error: string }\n | { readonly ran: true; readonly runId: string; readonly done: Promise<TurnOutcome> }\n\n/** Starts one agent turn. Injectable so the invoker is testable without OpenClaw. */\nexport type TurnStarter = (request: TurnRequest) => Promise<TurnAdmission>\n\n/** Whether a turn started now can look at AgentChat at all; `reason` is the operator line when it cannot. */\nexport type TurnReadiness = { readonly ready: true } | { readonly ready: false; readonly reason: string }\n\n/**\n * The gateway config as it is NOW. OpenClaw hot-applies `mcp.*` changes (a\n * running gateway's turns have the tools right after `openclaw doctor --fix`\n * wrote the entry), so a readiness check must not read the snapshot the\n * account started with. `runtime.config.loadConfig()` is that live read;\n * without a usable runtime, or if it throws, the snapshot is what there is\n * (`live: false`) — and then a config fix needs a restart to be seen.\n */\nexport function readLiveConfig(fallback: unknown, runtime: () => PluginRuntime | null = getPluginRuntime): { cfg: unknown; live: boolean } {\n try {\n const loaded: unknown = runtime()?.config?.loadConfig?.()\n if (loaded && typeof loaded === 'object') return { cfg: loaded, live: true }\n } catch {\n // fall through to the snapshot\n }\n return { cfg: fallback, live: false }\n}\n\n/**\n * What can be known from inside the gateway about the hosted tools a turn\n * will have. OpenClaw discovers MCP servers per turn and the plugin runtime\n * exposes no tool catalog, so the plugin cannot ask which tools a run gets;\n * it can check the two things that decide it: the `mcp.servers.agentchat`\n * entry is in the gateway config (enabled), and the credential its bearer\n * template names is in this process's environment (OpenClaw resolves\n * `${AGENTCHAT_API_KEY}` from the gateway env; a gateway started before the\n * wizard wrote `.env` holds the unresolved template until it restarts or\n * reloads). A hand-written entry is the operator's and counts as ready.\n *\n * The invoker checks this before the gate: while unready nothing is asked,\n * nothing recorded, the cards wait on the tray and the ladder re-wakes —\n * instead of a turn running blind and then marking the conversation read.\n * `live: false` means `cfg` is the start-time snapshot (see `readLiveConfig`),\n * so a config fix is only seen after a restart; the reason says so then.\n */\nexport function turnReadiness(params: { cfg: unknown; apiBase: string; apiKey: string; env?: NodeJS.ProcessEnv; live?: boolean }): TurnReadiness {\n const env = params.env ?? process.env\n const restart = params.live === false ? ', then restart the gateway (this gateway cannot re-read its config while running)' : ''\n switch (describeMcpEntry(params.cfg, params.apiBase, params.apiKey)) {\n case 'missing':\n return { ready: false, reason: `mcp.servers.${MCP_SERVER_NAME} is not in the gateway config — run \\`openclaw doctor --fix\\`${restart}` }\n case 'disabled':\n return { ready: false, reason: `mcp.servers.${MCP_SERVER_NAME} is disabled in the gateway config — enable it${restart}` }\n case 'user_managed':\n return { ready: true }\n case 'ours': {\n const value = env[API_KEY_ENV]\n if (typeof value !== 'string' || value.trim().length === 0) {\n return {\n ready: false,\n reason: `${API_KEY_ENV} is not set in the gateway process, so the hosted tools' bearer template cannot resolve — restart the gateway (or reload its config) once ~/.openclaw/.env carries it`,\n }\n }\n return { ready: true }\n }\n }\n}\n\n/**\n * The turn starter for production. `deliver: false` — the final text is\n * recorded by OpenClaw and announced nowhere. The run's result is never read\n * by the integration: the agent's send is a hosted-tool call inside the\n * turn. `done` resolves when the run ends or `waitMs` passes, whichever\n * comes first; it never rejects.\n */\nexport function createRuntimeTurnStarter(params: {\n runtime?: () => PluginRuntime | null\n waitMs?: number\n} = {}): TurnStarter {\n const getRuntime = params.runtime ?? getPluginRuntime\n const waitMs = params.waitMs ?? DEFAULT_TURN_WAIT_MS\n return async (request) => {\n const runtime = getRuntime()\n if (!runtime) return { ran: false, error: new RuntimeUnavailableError('the agent turn').message }\n let runId: string\n try {\n const admitted = await runtime.subagent.run({\n sessionKey: request.sessionKey,\n message: request.prompt,\n lane: request.lane,\n deliver: false,\n })\n runId = admitted.runId\n } catch (err) {\n return { ran: false, error: err instanceof Error ? err.message : String(err) }\n }\n const done = runtime.subagent\n .waitForRun({ runId, timeoutMs: waitMs })\n .then(\n (waited): TurnOutcome => ({ ran: true, runId, status: waited.status, ...(waited.error ? { error: waited.error } : {}) }),\n // The run was admitted; only the wait failed. The turn is OpenClaw's now.\n (err): TurnOutcome => ({ ran: true, runId, status: 'unknown', error: err instanceof Error ? err.message : String(err) }),\n )\n return { ran: true, runId, done }\n }\n}\n","/**\n * Placing the four things AgentChat authored where OpenClaw loads them.\n *\n * 1. **The key** — `AGENTCHAT_API_KEY=…` in OpenClaw's state-dir `.env`\n * (`~/.openclaw/.env`, or `$OPENCLAW_STATE_DIR/.env`), which OpenClaw\n * reads at start as its global environment fallback. The hosted MCP\n * server's bearer header is a template on that variable, so the key is\n * never written into `openclaw.json` as part of the tool declaration.\n * (The channel's own `channels.agentchat.apiKey` keeps holding the key\n * for the socket, as before.)\n * 2. **The identity line** — the served `identity_line` (`GET /v1/texts`,\n * `../integration/texts.ts`) in the workspace `AGENTS.md`, loaded into\n * every turn (`../binding/agents-anchor.ts`). The callers fetch the text\n * (server, then the cached copy) and hand it in; with neither available\n * the step is skipped and reported, never invented.\n * 3. **The manual** — `https://agentchat.me/skill.md` verbatim, bundled as\n * the `agentchat` skill. Nothing to write; verified present.\n * 4. **The tools** — `mcp.servers.agentchat` in `openclaw.json` (`./mcp.ts`),\n * returned as a config patch for OpenClaw to persist.\n *\n * Every placer is idempotent and reports what it did; the wizard prints the\n * report, the status probe and the doctor run the checks again.\n */\n\nimport * as fs from 'node:fs'\nimport * as path from 'node:path'\n\nimport { API_KEY_ENV } from '../credentials/read-env.js'\nimport { resolveBoundAgentId, resolveOpenClawDefaultAgentId, resolveOpenClawStateDir } from '../openclaw-layout.js'\nimport { describeMcpEntry, hostedMcpUrl, withHostedMcpEntry, withoutHostedMcpEntry, type McpEntryOutcome } from './mcp.js'\nimport { LLM_AGENT_OVERRIDE_PATH, withLlmAgentOverrideOptIn } from './model.js'\nimport { writeAgentsAnchor, agentsAnchorPath, hasAgentsAnchorFor, readAgentsAnchor, removeAgentsAnchor } from '../binding/agents-anchor.js'\nimport {\n AGENTCHAT_CHANNEL_ID,\n AGENTCHAT_DEFAULT_ACCOUNT_ID,\n agentchatReenableHint,\n applyAgentchatAccountPatch,\n isAgentchatAccountEnabled,\n readAgentchatConfigField,\n} from '../channel-account.js'\n\nconst HANDLE_PATTERN = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/\nfunction isValidHandleShape(value: string): boolean {\n return value.length >= 3 && value.length <= 30 && HANDLE_PATTERN.test(value)\n}\n\nexport type PlacementStatus = 'ok' | 'changed' | 'skipped' | 'failed'\n\nexport interface PlacementStep {\n readonly name: 'key' | 'anchor' | 'manual' | 'mcp'\n readonly status: PlacementStatus\n readonly detail: string\n}\n\nconst DOTENV_NAME = '.env'\n\nexport { resolveOpenClawStateDir }\n\nexport function dotEnvPath(stateDir: string = resolveOpenClawStateDir()): string {\n return path.join(stateDir, DOTENV_NAME)\n}\n\n/**\n * Upsert `AGENTCHAT_API_KEY=<key>` in the state-dir `.env`. Other lines are\n * kept byte for byte; the file is created `0600` when absent. Returns the\n * path and whether the content changed.\n */\nexport function placeApiKeyInDotEnv(apiKey: string, stateDir: string = resolveOpenClawStateDir()): { path: string; changed: boolean } {\n const trimmed = apiKey.trim()\n if (!trimmed) throw new Error('placeApiKeyInDotEnv: key is empty')\n if (/[\\r\\n]/.test(trimmed)) throw new Error('placeApiKeyInDotEnv: key contains a line break')\n const file = dotEnvPath(stateDir)\n fs.mkdirSync(stateDir, { recursive: true })\n const existing = fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : ''\n const next = upsertDotEnvLine(existing, API_KEY_ENV, trimmed)\n if (next === existing) return { path: file, changed: false }\n fs.writeFileSync(file, next, { encoding: 'utf8', mode: 0o600 })\n try {\n fs.chmodSync(file, 0o600)\n } catch {\n // Best effort: a filesystem without POSIX modes keeps its own defaults.\n }\n return { path: file, changed: true }\n}\n\n/** Blank the key line (keeps the variable name so a later placement finds its slot). */\nexport function clearApiKeyInDotEnv(stateDir: string = resolveOpenClawStateDir()): { path: string; changed: boolean } {\n const file = dotEnvPath(stateDir)\n if (!fs.existsSync(file)) return { path: file, changed: false }\n const existing = fs.readFileSync(file, 'utf8')\n const next = existing\n .split(/\\r?\\n/)\n .filter((line) => !lineSetsVariable(line, API_KEY_ENV))\n .join('\\n')\n if (next === existing) return { path: file, changed: false }\n fs.writeFileSync(file, next, { encoding: 'utf8', mode: 0o600 })\n return { path: file, changed: true }\n}\n\n/** The value the state-dir `.env` holds for the key, if any. */\nexport function readApiKeyFromDotEnv(stateDir: string = resolveOpenClawStateDir()): string | undefined {\n const file = dotEnvPath(stateDir)\n if (!fs.existsSync(file)) return undefined\n for (const line of fs.readFileSync(file, 'utf8').split(/\\r?\\n/)) {\n if (!lineSetsVariable(line, API_KEY_ENV)) continue\n const value = line.slice(line.indexOf('=') + 1).trim()\n return stripQuotes(value) || undefined\n }\n return undefined\n}\n\nexport function upsertDotEnvLine(content: string, name: string, value: string): string {\n const line = `${name}=${value}`\n const lines = content.length > 0 ? content.split(/\\r?\\n/) : []\n let replaced = false\n const out = lines.map((existing) => {\n if (!replaced && lineSetsVariable(existing, name)) {\n replaced = true\n return line\n }\n return existing\n })\n if (!replaced) {\n if (out.length > 0 && out[out.length - 1] !== '') out.push(line)\n else if (out.length > 0) out.splice(out.length - 1, 0, line)\n else out.push(line)\n }\n let next = out.join('\\n')\n if (!next.endsWith('\\n')) next += '\\n'\n return next\n}\n\nfunction lineSetsVariable(line: string, name: string): boolean {\n const trimmed = line.trim()\n if (trimmed.startsWith('#')) return false\n const body = trimmed.startsWith('export ') ? trimmed.slice('export '.length).trim() : trimmed\n return body.startsWith(`${name}=`)\n}\n\nfunction stripQuotes(value: string): string {\n if (value.length >= 2 && ((value.startsWith('\"') && value.endsWith('\"')) || (value.startsWith(\"'\") && value.endsWith(\"'\")))) {\n return value.slice(1, -1)\n }\n return value\n}\n\n// ─── the config side of placement (pure) ───────────────────────────────\n\nexport interface IntegrationConfigParams {\n readonly accountId: string\n /** The handle the key authenticates as; omitted when not yet known (an older OpenClaw without `prepareAccountConfigInput`). */\n readonly handle?: string | undefined\n readonly apiKey: string\n readonly apiBase: string\n}\n\n/**\n * Everything placement writes INTO `openclaw.json`, as one pure patch:\n * `channels.agentchat.agentHandle` (the handle the key authenticates as),\n * `mcp.servers.agentchat` (the hosted tools), and — only when the account\n * is bound to an agent other than OpenClaw's default —\n * `plugins.entries.agentchat.llm.allowAgentIdOverride`. Returns the config\n * and one line per change, for the wizard, the non-interactive hook (through\n * `runtime.config.mutateConfigFile`) and `doctor --fix` alike.\n */\nexport function applyIntegrationConfig<TCfg extends object>(cfg: TCfg, params: IntegrationConfigParams): { cfg: TCfg; changes: string[] } {\n const changes: string[] = []\n let next: TCfg = cfg\n const bareHandle = (params.handle ?? '').trim().replace(/^@/, '')\n if (bareHandle && readAgentchatConfigField(next as never, params.accountId, 'agentHandle') !== bareHandle && isValidHandleShape(bareHandle)) {\n next = applyAgentchatAccountPatch(next as never, params.accountId, { agentHandle: bareHandle }) as unknown as TCfg\n changes.push(`channels.agentchat${params.accountId === AGENTCHAT_DEFAULT_ACCOUNT_ID ? '' : `.accounts.${params.accountId}`}.agentHandle = ${bareHandle}`)\n }\n const mcp = withHostedMcpEntry(next, params.apiBase, params.apiKey)\n next = mcp.cfg\n if (mcp.outcome === 'added') changes.push(`mcp.servers.agentchat → ${hostedMcpUrl(params.apiBase)} (bearer template on ${API_KEY_ENV})`)\n const bound = resolveBoundAgentId(next, AGENTCHAT_CHANNEL_ID, params.accountId)\n const ambient = resolveOpenClawDefaultAgentId(next)\n if (bound && bound !== (ambient ?? bound)) {\n const optIn = withLlmAgentOverrideOptIn(next)\n next = optIn.cfg\n if (optIn.changed) changes.push(`${LLM_AGENT_OVERRIDE_PATH} = true (account bound to agent \"${bound}\", not the default)`)\n }\n return { cfg: next, changes }\n}\n\n/** The agent this account's identity line belongs to: the bound agent, else OpenClaw's default. */\nexport function resolvePlacementAgentId(cfg: object | undefined, accountId: string): string | undefined {\n return resolveBoundAgentId(cfg, AGENTCHAT_CHANNEL_ID, accountId) ?? resolveOpenClawDefaultAgentId(cfg)\n}\n\n/**\n * Undo the config side of placement for an account that is being disabled\n * or deleted: the plugin's own `mcp.servers.agentchat` entry goes (a\n * hand-written one stays). Pure; shared by `config.setAccountEnabled`,\n * `config.deleteAccount` and the wizard's `disable`.\n */\nexport function stripIntegrationConfig<TCfg extends object>(cfg: TCfg, accountId: string): { cfg: TCfg; changes: string[] } {\n const apiBase = readAgentchatConfigField(cfg as never, accountId, 'apiBase') ?? 'https://api.agentchat.me'\n const apiKey = readAgentchatConfigField(cfg as never, accountId, 'apiKey')\n const { cfg: next, removed } = withoutHostedMcpEntry(cfg, apiBase, apiKey)\n return { cfg: next, changes: removed ? ['removed mcp.servers.agentchat'] : [] }\n}\n\n/**\n * Undo the file side of placement: the identity line in the bound agent's\n * `AGENTS.md`, and — on delete — the key line in the state-dir `.env`.\n * Best-effort: a filesystem error never blocks a remove.\n */\nexport function removeIntegrationFiles(cfg: object | undefined, accountId: string, options: { clearKey: boolean; stateDir?: string }): string[] {\n const changes: string[] = []\n try {\n const removed = removeAgentsAnchor({ cfg: cfg as never, agentId: resolvePlacementAgentId(cfg, accountId) })\n if (removed.removed) changes.push(`removed the identity line from ${removed.path}`)\n } catch {\n // best effort\n }\n if (options.clearKey) {\n try {\n const cleared = clearApiKeyInDotEnv(options.stateDir)\n if (cleared.changed) changes.push(`removed ${API_KEY_ENV} from ${cleared.path}`)\n } catch {\n // best effort\n }\n }\n return changes\n}\n\nexport interface IdentityLineRestore {\n readonly outcome: 'placed' | 'present' | 'failed' | 'skipped'\n readonly path: string\n readonly detail?: string\n}\n\n/**\n * Redo the file side of placement for an enabled account: the served\n * identity line for `handle` in the bound agent's `AGENTS.md` (the\n * workspace resolved the way OpenClaw resolves it). The mirror of\n * `removeIntegrationFiles` on re-enable, and `doctor --fix`'s repair. A\n * line already holding exactly that text is not rewritten — the file stays\n * byte-identical. `identityLine` null (texts unreachable, nothing cached)\n * → `skipped`, nothing written. Never throws.\n */\nexport function restoreIdentityLine(cfg: object | undefined, accountId: string, handle: string, identityLine: string | null): IdentityLineRestore {\n const agentId = resolvePlacementAgentId(cfg, accountId)\n const bare = handle.trim().replace(/^@/, '')\n let filePath = ''\n try {\n filePath = agentsAnchorPath(cfg as never, agentId)\n if (!isValidHandleShape(bare)) return { outcome: 'failed', path: filePath, detail: `agentHandle \"${bare}\" is not a valid AgentChat handle` }\n if (identityLine === null) {\n return { outcome: 'skipped', path: filePath, detail: 'the served identity line is not available (AgentChat unreachable and nothing cached) — run openclaw doctor --fix once it is' }\n }\n const present = hasAgentsAnchorFor({ cfg: cfg as never, handle: bare, text: identityLine, agentId })\n filePath = present.path\n if (present.present) return { outcome: 'present', path: present.path }\n const written = writeAgentsAnchor({ cfg: cfg as never, handle: bare, text: identityLine, agentId })\n return { outcome: 'placed', path: written.path }\n } catch (err) {\n return { outcome: 'failed', path: filePath, detail: describe(err) }\n }\n}\n\n/**\n * The running gateway's duty when a fresh server copy of the text arrives:\n * a block that is PRESENT but holds older text is rewritten; an absent\n * block is left to the wizard / doctor (placement is a setup decision, not a\n * runtime one). Never throws.\n */\nexport function refreshIdentityLine(\n cfg: object | undefined,\n accountId: string,\n handle: string,\n identityLine: string,\n): { outcome: 'updated' | 'unchanged' | 'absent' | 'failed'; path: string; detail?: string } {\n const agentId = resolvePlacementAgentId(cfg, accountId)\n try {\n const found = readAgentsAnchor({ cfg: cfg as never, agentId })\n if (!found.present) return { outcome: 'absent', path: found.path }\n if (found.text === identityLine.trim()) return { outcome: 'unchanged', path: found.path }\n const written = writeAgentsAnchor({ cfg: cfg as never, handle, text: identityLine, agentId })\n return { outcome: 'updated', path: written.path }\n } catch (err) {\n return { outcome: 'failed', path: agentsAnchorPath(cfg as never, agentId), detail: describe(err) }\n }\n}\n\n// ─── placement, as one report ──────────────────────────────────────────\n\nexport interface PlaceParams<TCfg extends object> {\n readonly cfg: TCfg | undefined\n readonly handle: string\n readonly apiKey: string\n readonly apiBase: string\n /** The served identity line (spelled for OpenClaw); `null` when AgentChat was unreachable and nothing is cached. */\n readonly identityLine: string | null\n /** The channel account; selects the bound agent whose workspace holds the identity line. */\n readonly accountId?: string\n /** Explicit agent whose workspace holds the identity line; defaults to the bound agent, else OpenClaw's default. */\n readonly agentId?: string | undefined\n /** Test seam: where the state-dir `.env` lives. */\n readonly stateDir?: string\n /** Test seam: skip the `.env` write (e.g. a read-only CI). */\n readonly placeKey?: boolean\n}\n\nexport interface PlaceResult<TCfg extends object> {\n readonly cfg: TCfg\n readonly steps: readonly PlacementStep[]\n readonly mcp: McpEntryOutcome\n}\n\n/**\n * Key, identity line, manual, tools — in that order. Never throws: each\n * step reports `failed` with the reason instead. Returns the config with\n * the tools entry applied for the caller to persist.\n */\nexport function placeIntegration<TCfg extends object>(params: PlaceParams<TCfg>): PlaceResult<TCfg> {\n const steps: PlacementStep[] = []\n\n if (params.placeKey !== false) {\n try {\n const key = placeApiKeyInDotEnv(params.apiKey, params.stateDir)\n steps.push({\n name: 'key',\n status: key.changed ? 'changed' : 'ok',\n detail: `${API_KEY_ENV} in ${key.path}${key.changed ? ` (a gateway started before this needs a restart, or a config reload, to resolve \\${${API_KEY_ENV}})` : ''}`,\n })\n } catch (err) {\n steps.push({ name: 'key', status: 'failed', detail: `could not write ${API_KEY_ENV} to the OpenClaw .env: ${describe(err)}` })\n }\n }\n\n const agentId = params.agentId ?? resolvePlacementAgentId(params.cfg, params.accountId ?? AGENTCHAT_DEFAULT_ACCOUNT_ID)\n const handle = params.handle.replace(/^@/, '')\n if (params.identityLine === null) {\n steps.push({\n name: 'anchor',\n status: 'skipped',\n detail: `identity line for @${handle} not placed — AgentChat's texts were unreachable and nothing is cached; run openclaw doctor --fix once it is reachable`,\n })\n } else {\n try {\n const anchor = writeAgentsAnchor({ cfg: params.cfg as never, handle: params.handle, text: params.identityLine, agentId })\n steps.push({ name: 'anchor', status: 'ok', detail: `identity line for @${handle} in ${anchor.path}` })\n } catch (err) {\n steps.push({ name: 'anchor', status: 'failed', detail: `could not write the identity line to AGENTS.md: ${describe(err)}` })\n }\n }\n\n steps.push({ name: 'manual', status: 'ok', detail: 'manual bundled as the agentchat skill (skills/agentchat/SKILL.md, https://agentchat.me/skill.md verbatim)' })\n\n const mcp = withHostedMcpEntry(params.cfg, params.apiBase, params.apiKey)\n steps.push(describeMcpOutcome(mcp.outcome, params.apiBase))\n\n return { cfg: mcp.cfg, steps, mcp: mcp.outcome }\n}\n\nexport function describeMcpOutcome(outcome: McpEntryOutcome, apiBase: string): PlacementStep {\n switch (outcome) {\n case 'added':\n return { name: 'mcp', status: 'changed', detail: `hosted tools registered as mcp.servers.agentchat → ${hostedMcpUrl(apiBase)} (bearer template on ${API_KEY_ENV})` }\n case 'present':\n return { name: 'mcp', status: 'ok', detail: 'hosted tools already registered as mcp.servers.agentchat' }\n case 'disabled':\n return { name: 'mcp', status: 'skipped', detail: 'mcp.servers.agentchat exists but is disabled in openclaw.json — left alone' }\n case 'user_managed':\n return { name: 'mcp', status: 'skipped', detail: 'mcp.servers.agentchat is managed by hand in openclaw.json — left alone' }\n }\n}\n\n/** One line per step, for the wizard's note and the status pane. */\nexport function formatPlacement(steps: readonly PlacementStep[]): string[] {\n return steps.map((step) => `${step.status === 'failed' ? '✗' : step.status === 'skipped' ? '–' : '✓'} ${step.name}: ${step.detail}`)\n}\n\n// ─── checks (doctor / status) ──────────────────────────────────────────\n\nexport interface PlacementCheck {\n readonly name: 'key' | 'anchor' | 'manual' | 'mcp'\n readonly ok: boolean\n readonly detail: string\n}\n\nexport function checkPlacement<TCfg extends object>(params: {\n cfg: TCfg | undefined\n handle: string | undefined\n apiKey: string | undefined\n apiBase: string\n /** The served identity line as last seen (cached); without it any of our blocks naming the handle passes. */\n identityLine?: string | null | undefined\n agentId?: string | undefined\n /** The channel account; a disabled one gets the re-enable remedy, never `channels add`. Defaults to `default`. */\n accountId?: string\n stateDir?: string\n /** The gateway's own environment (defaults to `process.env`). */\n env?: NodeJS.ProcessEnv\n}): PlacementCheck[] {\n const checks: PlacementCheck[] = []\n const env = params.env ?? process.env\n const accountId = params.accountId ?? AGENTCHAT_DEFAULT_ACCOUNT_ID\n // While the account is disabled OpenClaw does not load this plugin, and\n // `channels add` would fetch the npm build over it: every remedy for a\n // disabled account is the re-enable route instead.\n const reenable = isAgentchatAccountEnabled(params.cfg as never, accountId) ? undefined : agentchatReenableHint(params.cfg as never, accountId)\n const remedy = (forEnabled: string): string => reenable ?? forEnabled\n\n // What this process can see: its own environment and the state-dir .env.\n // It cannot see the running gateway's environment (OpenClaw loads the\n // state-dir .env into every process, the CLI included), so the wording\n // never claims to.\n const inProcess = (env[API_KEY_ENV] ?? '').trim()\n const inDotEnv = readApiKeyFromDotEnv(params.stateDir)\n if (params.apiKey && (inProcess === params.apiKey || inDotEnv === params.apiKey)) {\n checks.push({\n name: 'key',\n ok: true,\n detail:\n `${API_KEY_ENV} ${inProcess === params.apiKey ? 'present in this process' : `in ${dotEnvPath(params.stateDir)}`}; ` +\n `a gateway started before the wizard placed it needs a restart (or a config reload) to resolve \\${${API_KEY_ENV}}`,\n })\n } else if (inProcess || inDotEnv) {\n checks.push({ name: 'key', ok: false, detail: `${API_KEY_ENV} differs from the configured channel key — ${remedy('re-run the wizard (openclaw channels add agentchat) to place the current key')}` })\n } else {\n checks.push({ name: 'key', ok: false, detail: `${API_KEY_ENV} is not placed — the hosted tools cannot authenticate; ${remedy('run openclaw channels add agentchat')}` })\n }\n\n if (params.handle) {\n const anchor = hasAgentsAnchorFor({ cfg: params.cfg as never, handle: params.handle, text: params.identityLine, agentId: params.agentId })\n checks.push({\n name: 'anchor',\n ok: anchor.present,\n detail: anchor.present\n ? `identity line for @${params.handle} in ${anchor.path}`\n : `identity line for @${params.handle} missing from ${anchor.path} — ${remedy('run openclaw doctor --fix (or openclaw channels add agentchat)')}`,\n })\n } else {\n checks.push({ name: 'anchor', ok: false, detail: `agentHandle not in config — the identity line cannot be checked; ${remedy('run openclaw doctor --fix (it learns the handle from the key)')}` })\n }\n\n checks.push({ name: 'manual', ok: true, detail: 'manual bundled as the agentchat skill' })\n\n const mcpState = describeMcpEntry(params.cfg, params.apiBase, params.apiKey)\n checks.push({\n name: 'mcp',\n ok: mcpState === 'ours' || mcpState === 'user_managed',\n detail:\n mcpState === 'ours'\n ? 'hosted tools registered as mcp.servers.agentchat'\n : mcpState === 'user_managed'\n ? 'mcp.servers.agentchat is managed by hand'\n : mcpState === 'disabled'\n ? 'mcp.servers.agentchat is disabled — the agent has no AgentChat tools'\n : `mcp.servers.agentchat missing — ${remedy('run openclaw doctor --fix (or openclaw channels add agentchat)')}`,\n })\n return checks\n}\n\nexport { agentsAnchorPath }\n\nfunction describe(err: unknown): string {\n return err instanceof Error ? err.message : String(err)\n}\n","/**\n * The plugin's own state on disk: `<OpenClaw state dir>/agentchat/<accountId>/`.\n *\n * Two small JSON files live there, both caches of facts that exist elsewhere:\n * the served texts (`texts.json`, so a gateway can start while the server is\n * unreachable) and the group invites already offered to the agent\n * (`invites.json`, so a restart never starts a second turn for an invite the\n * agent chose to leave pending). Nothing secret, nothing authoritative —\n * deleting the directory costs one texts fetch and, at worst, one repeated\n * invite turn.\n *\n * Writes are atomic (temp file + rename) so a crash mid-write leaves the\n * previous copy, never a truncated one.\n */\n\nimport * as fs from 'node:fs'\nimport * as path from 'node:path'\n\nimport { resolveOpenClawStateDir } from '../openclaw-layout.js'\n\nexport const PLUGIN_STATE_DIRNAME = 'agentchat'\n\nfunction safeSegment(value: string): string {\n const clean = value.replace(/[^A-Za-z0-9_.-]/g, '-').replace(/^\\.+/, '')\n return clean.length > 0 ? clean : 'default'\n}\n\n/** `<state dir>/agentchat/<accountId>` — created on first write. */\nexport function integrationStateDir(accountId: string, stateDir: string = resolveOpenClawStateDir()): string {\n return path.join(stateDir, PLUGIN_STATE_DIRNAME, safeSegment(accountId))\n}\n\n/** Parse a JSON file; `null` when it is absent, unreadable or not valid JSON. */\nexport function readJsonFile(file: string): unknown {\n let raw: string\n try {\n raw = fs.readFileSync(file, 'utf8')\n } catch {\n return null\n }\n try {\n return JSON.parse(raw) as unknown\n } catch {\n return null\n }\n}\n\n/** Write JSON atomically (temp file in the same directory, then rename). Throws on I/O errors. */\nexport function writeJsonFile(file: string, value: unknown): void {\n fs.mkdirSync(path.dirname(file), { recursive: true })\n const tmp = `${file}.${process.pid}.${Date.now().toString(36)}.tmp`\n fs.writeFileSync(tmp, `${JSON.stringify(value, null, 2)}\\n`, 'utf8')\n try {\n fs.renameSync(tmp, file)\n } catch (err) {\n try {\n fs.unlinkSync(tmp)\n } catch {\n // the rename failed; the temp file is the only thing left to clean\n }\n throw err\n }\n}\n","/**\n * The served texts: fetched from AgentChat, never bundled.\n *\n * Every text an agent sees is written once, in AgentChat's experience layer,\n * and served as data (`GET /v1/texts?runtime=openclaw`): the wake\n * instruction a turn starts with, the invite prompt, the identity line that\n * goes into the workspace `AGENTS.md`, and where the manual is. This module\n * fetches them at channel start and every 24 hours, keeps the last copy in\n * the plugin's state dir, and hands them out spelled for OpenClaw (the hosted\n * tools as `agentchat__<tool>`, see `./turn.ts`).\n *\n * When the server is unreachable at start the last cached copy is used; with\n * nothing cached the channel still starts (the socket connects, the gate can\n * run) and logs once — turns wait for the first successful fetch, which is\n * retried every few minutes until it lands.\n */\n\nimport * as path from 'node:path'\n\nimport type { AgentChatClient, Texts } from 'agentchatme'\n\nimport type { Logger } from '../log.js'\nimport { integrationStateDir, readJsonFile, writeJsonFile } from './state.js'\nimport { spellToolsForOpenClaw } from './turn.js'\n\nexport const TEXTS_RUNTIME = 'openclaw' as const\n/** The server suggests a daily refresh. */\nexport const TEXTS_REFRESH_MS = 24 * 60 * 60_000\n/** Until the first copy exists, try again this often. */\nexport const TEXTS_RETRY_MS = 5 * 60_000\n/** One fetch must never hold the channel start for long. */\nexport const TEXTS_FETCH_TIMEOUT_MS = 10_000\nexport const TEXTS_CACHE_FILE = 'texts.json'\n\nexport type TextsClient = Pick<AgentChatClient, 'texts'>\n\nexport interface CachedTexts {\n readonly fetched_at: string\n /** Server-verbatim; spelled for OpenClaw on the way out. */\n readonly texts: Texts\n}\n\nexport type TextsSourceKind = 'server' | 'cache'\n\nexport interface LoadedTexts {\n /** Spelled for OpenClaw. */\n readonly texts: Texts\n readonly source: TextsSourceKind\n readonly fetchedAt: string\n}\n\n/** The shape every consumer relies on. Extra fields a newer server adds pass through. */\nexport function isTexts(value: unknown): value is Texts {\n if (!value || typeof value !== 'object' || Array.isArray(value)) return false\n const t = value as Record<string, unknown>\n const manual = t.manual as Record<string, unknown> | undefined\n return (\n typeof t.version === 'string' &&\n typeof t.wake_instruction === 'string' &&\n t.wake_instruction.length > 0 &&\n typeof t.invite_prompt === 'string' &&\n t.invite_prompt.length > 0 &&\n typeof t.identity_line === 'string' &&\n t.identity_line.length > 0 &&\n typeof t.identity_line_template === 'string' &&\n !!manual &&\n typeof manual === 'object' &&\n typeof manual.url === 'string' &&\n typeof manual.version === 'string'\n )\n}\n\nexport function textsCachePath(accountId: string, stateDir?: string): string {\n return path.join(integrationStateDir(accountId, stateDir), TEXTS_CACHE_FILE)\n}\n\nexport function readCachedTexts(accountId: string, stateDir?: string): CachedTexts | null {\n const raw = readJsonFile(textsCachePath(accountId, stateDir))\n if (!raw || typeof raw !== 'object') return null\n const entry = raw as Record<string, unknown>\n if (typeof entry.fetched_at !== 'string' || !isTexts(entry.texts)) return null\n return { fetched_at: entry.fetched_at, texts: entry.texts }\n}\n\n/** Persist a server copy. Returns the file written. Throws on I/O errors. */\nexport function writeCachedTexts(accountId: string, texts: Texts, fetchedAt: Date, stateDir?: string): string {\n const file = textsCachePath(accountId, stateDir)\n const entry: CachedTexts = { fetched_at: fetchedAt.toISOString(), texts }\n writeJsonFile(file, entry)\n return file\n}\n\n/** The served texts with every hosted tool name spelled the way OpenClaw exposes it. */\nexport function spellTextsForOpenClaw(texts: Texts): Texts {\n return {\n ...texts,\n wake_instruction: spellToolsForOpenClaw(texts.wake_instruction),\n invite_prompt: spellToolsForOpenClaw(texts.invite_prompt),\n identity_line: spellToolsForOpenClaw(texts.identity_line),\n identity_line_template: spellToolsForOpenClaw(texts.identity_line_template),\n }\n}\n\n/** One fetch, server-verbatim. Throws on transport errors, non-2xx answers and an unusable shape. */\nexport async function fetchTexts(client: TextsClient, timeoutMs: number = TEXTS_FETCH_TIMEOUT_MS): Promise<Texts> {\n const texts: unknown = await client.texts.get({ runtime: TEXTS_RUNTIME, timeoutMs })\n if (!isTexts(texts)) throw new Error('GET /v1/texts: answer is not a texts set (missing wake_instruction, invite_prompt or identity_line)')\n return texts\n}\n\nexport interface LoadTextsParams {\n readonly client: TextsClient\n readonly accountId: string\n readonly stateDir?: string | undefined\n readonly now?: () => number\n readonly log?: Logger | undefined\n readonly timeoutMs?: number\n}\n\n/**\n * Server first; the cache when the server cannot be reached. A server\n * success refreshes the cache (a cache write failure is logged, never\n * fatal). `null` when neither is available. Never throws.\n */\nexport async function loadTexts(params: LoadTextsParams): Promise<LoadedTexts | null> {\n const now = params.now ?? Date.now\n try {\n const texts = await fetchTexts(params.client, params.timeoutMs)\n const fetchedAt = new Date(now())\n try {\n writeCachedTexts(params.accountId, texts, fetchedAt, params.stateDir)\n } catch (err) {\n params.log?.warn({ err: describe(err) }, 'texts fetched but the cache could not be written')\n }\n return { texts: spellTextsForOpenClaw(texts), source: 'server', fetchedAt: fetchedAt.toISOString() }\n } catch (err) {\n const cached = readCachedTexts(params.accountId, params.stateDir)\n if (cached) {\n params.log?.info({ err: describe(err), fetchedAt: cached.fetched_at }, 'texts: server unreachable — using the cached copy')\n return { texts: spellTextsForOpenClaw(cached.texts), source: 'cache', fetchedAt: cached.fetched_at }\n }\n params.log?.debug({ err: describe(err) }, 'texts: server unreachable and nothing cached')\n return null\n }\n}\n\n/**\n * The identity line for the key's own agent, spelled for OpenClaw — for the\n * placement paths that run outside the gateway (wizard, `channels add`,\n * `doctor --fix`, re-enable). Server, then cache; `null` when neither.\n */\nexport async function loadIdentityLine(params: LoadTextsParams): Promise<string | null> {\n const loaded = await loadTexts(params)\n return loaded ? loaded.texts.identity_line : null\n}\n\n/** The cached identity line, spelled for OpenClaw, without touching the network (status, doctor preview). */\nexport function cachedIdentityLine(accountId: string, stateDir?: string): string | null {\n const cached = readCachedTexts(accountId, stateDir)\n return cached ? spellToolsForOpenClaw(cached.texts.identity_line) : null\n}\n\nexport interface TextsStoreOptions {\n readonly client: TextsClient\n readonly accountId: string\n readonly logger: Logger\n readonly stateDir?: string | undefined\n readonly refreshMs?: number\n readonly retryMs?: number\n readonly fetchTimeoutMs?: number\n readonly now?: () => number\n readonly setTimeout?: (fn: () => void, ms: number) => NodeJS.Timeout\n readonly clearTimeout?: (handle: NodeJS.Timeout) => void\n}\n\n/**\n * The texts for one running account: loaded at start, refreshed on a timer,\n * available synchronously to the invoker. `ensure()` is what a cycle calls\n * when it needs them: the current copy, or one load attempt right now.\n */\nexport class TextsStore {\n private readonly client: TextsClient\n private readonly accountId: string\n private readonly logger: Logger\n private readonly stateDir: string | undefined\n private readonly refreshMs: number\n private readonly retryMs: number\n private readonly fetchTimeoutMs: number\n private readonly now: () => number\n private readonly _setTimeout: (fn: () => void, ms: number) => NodeJS.Timeout\n private readonly _clearTimeout: (handle: NodeJS.Timeout) => void\n\n private loaded: LoadedTexts | null = null\n private timer: NodeJS.Timeout | null = null\n private inFlight: Promise<Texts | null> | null = null\n private stopped = false\n private missingAnnounced = false\n private readonly listeners = new Set<(texts: Texts, source: TextsSourceKind) => void>()\n\n loads = 0\n serverLoads = 0\n\n constructor(options: TextsStoreOptions) {\n this.client = options.client\n this.accountId = options.accountId\n this.logger = options.logger.child({ component: 'texts', accountId: options.accountId })\n this.stateDir = options.stateDir\n this.refreshMs = options.refreshMs ?? TEXTS_REFRESH_MS\n this.retryMs = options.retryMs ?? TEXTS_RETRY_MS\n this.fetchTimeoutMs = options.fetchTimeoutMs ?? TEXTS_FETCH_TIMEOUT_MS\n this.now = options.now ?? Date.now\n this._setTimeout = options.setTimeout ?? ((fn, ms) => setTimeout(fn, ms))\n this._clearTimeout = options.clearTimeout ?? ((h) => clearTimeout(h))\n }\n\n /** The texts spelled for OpenClaw, or null until the first copy exists. */\n get current(): Texts | null {\n return this.loaded?.texts ?? null\n }\n\n get source(): TextsSourceKind | null {\n return this.loaded?.source ?? null\n }\n\n get fetchedAt(): string | null {\n return this.loaded?.fetchedAt ?? null\n }\n\n /** Called with every copy that arrives from the server (not with a cached one). */\n onServerCopy(listener: (texts: Texts, source: TextsSourceKind) => void): () => void {\n this.listeners.add(listener)\n return () => {\n this.listeners.delete(listener)\n }\n }\n\n /** First load (server, then cache), then the timer. Resolves after the first attempt; never throws. */\n async start(): Promise<Texts | null> {\n const texts = await this.load()\n if (!texts && !this.missingAnnounced) {\n this.missingAnnounced = true\n this.logger.warn(\n { retryMs: this.retryMs },\n 'AgentChat texts unreachable and nothing cached — starting anyway; turns wait for the first copy, retried until it arrives',\n )\n }\n this.arm()\n return texts\n }\n\n /** The current copy, or one load attempt now (coalesced with any in flight). */\n async ensure(): Promise<Texts | null> {\n if (this.loaded) return this.loaded.texts\n if (this.stopped) return null\n return this.load()\n }\n\n /** Force a refresh (tests, operators). Coalesced. */\n refresh(): Promise<Texts | null> {\n return this.load()\n }\n\n stop(): void {\n this.stopped = true\n if (this.timer !== null) {\n this._clearTimeout(this.timer)\n this.timer = null\n }\n this.listeners.clear()\n }\n\n private load(): Promise<Texts | null> {\n if (this.inFlight) return this.inFlight\n this.inFlight = (async () => {\n this.loads += 1\n const next = await loadTexts({\n client: this.client,\n accountId: this.accountId,\n stateDir: this.stateDir,\n now: this.now,\n log: this.logger,\n timeoutMs: this.fetchTimeoutMs,\n })\n if (this.stopped) return next?.texts ?? null\n if (next) {\n const changed = this.loaded?.texts.version !== next.texts.version || this.loaded?.texts.wake_instruction !== next.texts.wake_instruction\n this.loaded = next\n if (next.source === 'server') {\n this.serverLoads += 1\n this.logger[changed ? 'info' : 'debug'](\n { version: next.texts.version, manual: next.texts.manual.version },\n 'texts fetched from the server',\n )\n for (const listener of this.listeners) {\n try {\n listener(next.texts, next.source)\n } catch (err) {\n this.logger.warn({ err: describe(err) }, 'texts listener threw — continuing')\n }\n }\n }\n }\n return next?.texts ?? null\n })().finally(() => {\n this.inFlight = null\n })\n return this.inFlight\n }\n\n private arm(): void {\n if (this.stopped) return\n if (this.timer !== null) this._clearTimeout(this.timer)\n // Nothing yet → retry soon. A cached copy → ask the server again soon\n // too, so a long-offline gateway does not run a day on stale text. A\n // server copy → the daily refresh.\n const delay = this.loaded === null ? this.retryMs : this.loaded.source === 'cache' ? this.retryMs : this.refreshMs\n this.timer = this._setTimeout(() => {\n this.timer = null\n void this.load().finally(() => this.arm())\n }, delay)\n ;(this.timer as { unref?: () => void }).unref?.()\n }\n}\n\nfunction describe(err: unknown): string {\n return err instanceof Error ? err.message : String(err)\n}\n","/**\n * The `agentchatme` SDK client for this plugin.\n *\n * `getClient` caches one `AgentChatClient` per account for everything the\n * binding and the integration call over REST (status, the tray, verdicts,\n * texts, the realtime client's reconnect drain) so no call spins up a new\n * HTTP client and a key rotation swaps the cached one uniformly: the cache\n * is keyed by `accountId` and invalidated when the apiKey or apiBase\n * changes. `createSdkClient` is the uncached form for the setup-time paths\n * (wizard, `channels add`, `doctor --fix`) that have a key but no parsed\n * channel config.\n *\n * Every client carries the plugin's identity (`openclaw/<version>`) on\n * every request, through the SDK's own `clientIdentity` option.\n */\n\nimport { AgentChatClient, type AgentChatClientOptions } from 'agentchatme'\n\nimport type { AgentchatChannelConfig } from '../config-schema.js'\nimport { AGENTCHAT_CLIENT_IDENTITY } from '../client-identity.js'\n\ninterface CacheEntry {\n readonly client: AgentChatClient\n readonly apiKey: string\n readonly apiBase: string\n}\n\nconst cache = new Map<string, CacheEntry>()\n\nexport interface GetClientParams {\n readonly accountId: string\n readonly config: Pick<AgentchatChannelConfig, 'apiKey' | 'apiBase'>\n readonly options?: Partial<AgentChatClientOptions>\n}\n\n/** One client, uncached. */\nexport function createSdkClient(params: { apiKey: string; apiBase?: string | undefined; options?: Partial<AgentChatClientOptions> }): AgentChatClient {\n return new AgentChatClient({\n apiKey: params.apiKey,\n ...(params.apiBase ? { baseUrl: params.apiBase } : {}),\n clientIdentity: AGENTCHAT_CLIENT_IDENTITY,\n ...params.options,\n })\n}\n\n/**\n * Return a shared `AgentChatClient` for `accountId`, reusing the cached\n * instance unless the apiKey or apiBase changed (implicit invalidation on\n * silent config drift — better than a stale key surviving a rotation).\n */\nexport function getClient({ accountId, config, options }: GetClientParams): AgentChatClient {\n const existing = cache.get(accountId)\n if (existing && existing.apiKey === config.apiKey && existing.apiBase === config.apiBase) {\n return existing.client\n }\n\n const client = createSdkClient({ apiKey: config.apiKey, apiBase: config.apiBase, options })\n\n cache.set(accountId, {\n client,\n apiKey: config.apiKey,\n apiBase: config.apiBase,\n })\n return client\n}\n\n/** Drop the cached client for `accountId` — e.g. after a key rotation. */\nexport function disposeClient(accountId: string): void {\n cache.delete(accountId)\n}\n\n/** Clear the entire cache. Test hook only. */\nexport function resetClientCacheForTest(): void {\n cache.clear()\n}\n","/**\n * AgentChat channel setup wizard.\n *\n * Implements the interactive onboarding flow that OpenClaw's `setup` driver\n * invokes for users who just ran `openclaw plugins install @agentchatme/openclaw`\n * and `openclaw channels add agentchat`.\n *\n * The core UX decision this wizard encodes: AgentChat is the first channel in\n * the OpenClaw ecosystem where the identity the channel authenticates against\n * lives inside the plugin's own issuer (not an external provider like Slack or\n * Telegram). That means we can — and should — let brand-new users provision\n * credentials without ever leaving the CLI. Hence the three-way branch at the\n * top: paste an existing key, register via email OTP in-wizard, or recover a\n * lost key via email OTP in-wizard.\n *\n * Flow:\n * 1. `status.resolveConfigured` — reports \"configured / not configured\" for\n * `openclaw setup`'s pre-selection summary.\n * 2. `prepare` — runs BEFORE the credential step. Branches on user intent:\n * - \"I have a key\" → returns void; framework prompts for the key next.\n * - \"Register me\" → drives email-OTP registration via the REST client,\n * writes the minted key directly to cfg, and marks\n * a sentinel in credentialValues so the credential\n * step skips its redundant keep/replace prompt.\n * - \"Recover my key\"→ drives handle + email OTP recovery via the REST\n * client (same persistence + sentinel as register).\n * The handle defaults to the one already in config\n * for this account, because the overwhelmingly\n * common case is \"my configured key stopped\n * working\" — not \"recover some other agent\".\n * 3. `credentials[0]` — the API-key credential. `shouldPrompt` honors the\n * post-register/recover sentinel; otherwise the framework's default\n * prompt runs.\n * 4. `finalize` — calls GET /v1/agents/me once more to confirm the key works,\n * surfaces the authenticated handle, and places the integration: the key in\n * OpenClaw's `.env`, the served identity line in AGENTS.md, the hosted MCP\n * server in `mcp.servers.agentchat` (returned as a config patch for\n * OpenClaw to persist). Never throws on transport errors (a fresh clone\n * with a proxy should still save config and retry later).\n *\n * Writes go through `applyAgentchatAccountPatch` — the same helper backing\n * `setup.applyAccountConfig`, so the non-interactive `openclaw setup --token\n * ac_live_…` path and the interactive wizard path converge on the same config\n * shape and stay round-trippable.\n *\n * `disable` wires `setSetupChannelEnabled` so `openclaw channels remove\n * agentchat` produces `channels.agentchat.enabled: false` and keeps the\n * apiKey on disk (in case the operator just wants to pause, not rotate).\n */\n\nimport {\n WizardCancelledError,\n setSetupChannelEnabled,\n type ChannelSetupWizard,\n type OpenClawConfig,\n type WizardPrompter,\n} from 'openclaw/plugin-sdk/setup'\n\n/**\n * Inline of `ChannelSetupWizardCredentialValues` — the plugin-sdk's public\n * barrel does not re-export it, so we match its shape locally. Extra keys\n * beyond `keyof ChannelSetupInput` (e.g. our `_agentchatJustRegistered`\n * sentinel) are allowed because the framework treats this as a bag of strings\n * keyed by whatever the wizard steps use.\n */\ntype ChannelSetupWizardCredentialValues = Partial<Record<string, string>>\n\nimport {\n AGENTCHAT_CHANNEL_ID,\n MIN_API_KEY_LENGTH,\n agentchatReenableHint,\n applyAgentchatAccountPatch,\n isAgentchatAccountEnabled,\n isApiKeyPresent,\n readAgentchatConfigField,\n} from './channel-account.js'\nimport {\n recoverAgentStart,\n recoverAgentVerify,\n registerAgentStart,\n registerAgentVerify,\n validateApiKey,\n type EmailPolicyReason,\n type RecoverStartResult,\n type RecoverVerifyResult,\n type RegisterStartResult,\n type RegisterVerifyResult,\n} from './setup-client.js'\n// Credential lookup helper — see SECURITY.md for why this lives in a\n// separate module and must not be inlined into the wizard.\nimport { readApiKeyFromEnv } from './credentials/read-env.js'\nimport { placeIntegration, formatPlacement, applyIntegrationConfig, stripIntegrationConfig } from './integration/placement.js'\nimport { DEFAULT_API_BASE } from './integration/mcp.js'\nimport { loadIdentityLine } from './integration/texts.js'\nimport { createSdkClient } from './binding/sdk-client.js'\n\n/**\n * Sentinel credential-values key used to signal \"the register or recover\n * path in prepare already minted + persisted the API key, don't re-prompt\".\n * Framework-level prompt skipping is per-credential; we read this in\n * `shouldPrompt` below. The leading underscore keeps it out of any\n * `keyof ChannelSetupInput` path.\n */\nconst JUST_REGISTERED_SENTINEL = '_agentchatJustRegistered' as const\n\n// Canonical handle shape — the AgentChat handle rule (`^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$`)\n// HANDLE_REGEX plus the 3–30 length check. Server is authoritative; this is\n// a client-side fast-fail so users don't round-trip an obviously-bad handle.\nconst HANDLE_PATTERN = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/\nconst HANDLE_MIN_LENGTH = 3\nconst HANDLE_MAX_LENGTH = 30\nconst EMAIL_PATTERN = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/\n\nfunction isValidHandleShape(value: string): boolean {\n return (\n value.length >= HANDLE_MIN_LENGTH &&\n value.length <= HANDLE_MAX_LENGTH &&\n HANDLE_PATTERN.test(value)\n )\n}\n\n/** 6-digit numeric OTP; the server rejects any other shape with INVALID_CODE. */\nconst OTP_PATTERN = /^\\d{6}$/\n\nfunction hasConfiguredKey(cfg: OpenClawConfig | undefined, accountId: string): boolean {\n return isApiKeyPresent(readAgentchatConfigField(cfg, accountId, 'apiKey'))\n}\n\n/**\n * How many times we'll re-prompt around a retryable start-of-registration\n * error (handle-taken, invalid-handle, email-exhausted, …) before giving up\n * and steering the user to paste an existing key or cancel. A hard cap stops\n * a confused user looping forever; 5 is enough to pick a fresh handle or email\n * without being punishing.\n */\nconst MAX_START_RETRIES = 5\n\nasync function promptEmail(\n prompter: WizardPrompter,\n opts: {\n /** Headline. Defaults to the register-flow wording. */\n readonly message?: string\n } = {},\n): Promise<string> {\n return (\n await prompter.text({\n message: opts.message ?? 'Email — receives a 6-digit verification code',\n placeholder: 'you@example.com',\n validate: (value) => {\n const trimmed = value.trim()\n if (!trimmed) return 'Email is required'\n if (!EMAIL_PATTERN.test(trimmed)) return 'Not a valid email format'\n return undefined\n },\n })\n ).trim()\n}\n\nasync function promptHandle(\n prompter: WizardPrompter,\n opts: {\n /** Headline. Defaults to the register-flow wording. */\n readonly message?: string\n /** Pre-filled value the user can accept with Enter (recovery: the configured handle). */\n readonly initialValue?: string\n } = {},\n): Promise<string> {\n // The rules live in `placeholder` (the gray hint text inside the\n // input box, which clears on first keystroke) so the headline stays\n // a clean call to action. Per-rule validation errors below tell the\n // user exactly which rule failed instead of dumping the full rule\n // list every time.\n return (\n await prompter.text({\n message: opts.message ?? 'Choose a handle (your @name on AgentChat)',\n placeholder: '3–30 chars, lowercase a-z, 0-9, hyphens, starts with a letter',\n ...(opts.initialValue ? { initialValue: opts.initialValue } : {}),\n validate: (value) => {\n const trimmed = value.trim()\n if (!trimmed) return 'Handle is required'\n if (trimmed.length < HANDLE_MIN_LENGTH || trimmed.length > HANDLE_MAX_LENGTH) {\n return `Length must be ${HANDLE_MIN_LENGTH}–${HANDLE_MAX_LENGTH} chars (you entered ${trimmed.length})`\n }\n if (!/^[a-z]/.test(trimmed)) return 'Must start with a lowercase letter'\n if (/[^a-z0-9-]/.test(trimmed)) {\n return 'Only lowercase letters, digits, and hyphens — no underscores, dots, or symbols'\n }\n if (trimmed.includes('--')) return 'No consecutive hyphens'\n if (trimmed.endsWith('-')) return 'Cannot end with a hyphen'\n return undefined\n },\n })\n ).trim()\n}\n\nasync function promptDisplayName(prompter: WizardPrompter): Promise<string> {\n // The visible prompt deliberately does NOT say \"optional\" anymore —\n // empty input still passes validation (no server-side blocker; an\n // agent without display_name is a valid account), but framing it as\n // \"optional\" turned ~half of recent registrations into NULL rows\n // that render as @handle-only in the dashboard. Dropping the word\n // soft-pressures users to fill it without breaking anyone who really\n // doesn't want one. The placeholder example carries the load that\n // \"optional\" used to carry — it tells the user what shape this field\n // is for, without telling them they can skip it.\n return (\n await prompter.text({\n message: 'Display name (shown next to your @handle)',\n placeholder: 'e.g. Anton, Builder Bot, Sasha',\n validate: () => undefined,\n })\n ).trim()\n}\n\n/**\n * Change-API-base flow: only relevant for self-hosted AgentChat deployments.\n * The production client hits `https://api.agentchat.me` by default and the\n * config-schema pins that as the default value, so blank means \"reset to\n * default\" (remove the apiBase override entirely). Non-empty values must\n * parse as a valid http:// or https:// URL — we fail fast here so the user\n * does not save a typo that later surfaces as a misleading DNS-resolution\n * error at connect time.\n */\nasync function runChangeApiBaseFlow(params: {\n cfg: OpenClawConfig\n accountId: string\n prompter: WizardPrompter\n}): Promise<{ cfg: OpenClawConfig } | undefined> {\n const { cfg, accountId, prompter } = params\n const current = readAgentchatConfigField(cfg, accountId, 'apiBase')\n\n const input = (\n await prompter.text({\n message: 'New API base URL (blank to reset to default)',\n placeholder: current ?? 'https://api.agentchat.me',\n validate: (value) => {\n const trimmed = value.trim()\n if (!trimmed) return undefined // blank = reset to default\n try {\n const url = new URL(trimmed)\n if (url.protocol !== 'https:' && url.protocol !== 'http:') {\n return 'API base must use http:// or https://'\n }\n return undefined\n } catch {\n return 'Not a valid URL'\n }\n },\n })\n ).trim()\n\n if (!input) {\n const patched = applyAgentchatAccountPatch(cfg, accountId, {\n apiBase: undefined,\n })\n await prompter.note(\n 'API base reset to default (https://api.agentchat.me).',\n 'Updated',\n )\n return { cfg: patched }\n }\n\n const patched = applyAgentchatAccountPatch(cfg, accountId, {\n apiBase: input,\n })\n await prompter.note(`API base set to ${input}`, 'Updated')\n return { cfg: patched }\n}\n\n/**\n * Return values from `runRegisterFlow`:\n * - success object → registration minted a key; credential step\n * should use it and skip its own prompt.\n * - `'abort'` → registration failed; caller shows the fallback\n * note and the framework prompts for a pasted key.\n * - `'user-chose-paste'` → user explicitly elected to paste an existing key\n * (from an in-flow branch point like \"this email\n * is at its agent limit\"). Caller skips the\n * fallback note because the user has already\n * acknowledged what's next.\n * - `'user-chose-recover'`→ same branch point, but the user wants to\n * recover a lost key for one of the agents that\n * email already backs. Caller hands off to\n * `runRecoverFlow`.\n */\ntype RegisterFlowOutcome =\n | { cfg: OpenClawConfig; credentialValues: ChannelSetupWizardCredentialValues }\n | 'abort'\n | 'user-chose-paste'\n | 'user-chose-recover'\n\n/**\n * Operator copy for a per-email policy rejection. Quotes the limit the\n * server returned — the numbers are server-tunable and must never be\n * assumed here. When the server sent no limit (a server that predates the\n * multi-agent policy emits the retired `EMAIL_TAKEN` without one), its own\n * message is the most honest thing we have.\n */\nfunction describeEmailPolicyRejection(\n email: string,\n result: { readonly reason: EmailPolicyReason; readonly limit?: number; readonly message: string },\n): string {\n if (result.limit === undefined) return result.message\n return result.reason === 'email-limit-reached'\n ? `${email} already backs ${result.limit} active agents — the per-email limit.`\n : `${email} has used all ${result.limit} of its lifetime account registrations.`\n}\n\n/**\n * What the user can do once an email is at a policy limit. Recovery is\n * offered because the most likely reason someone re-registers on a full\n * email is that one of the existing agents lost its key; a `+` alias is\n * called out because it is the sanctioned way to get a fresh budget.\n */\ntype EmailPolicyChoice = 'retry' | 'recover' | 'paste' | 'cancel'\n\nasync function promptEmailPolicyChoice(\n prompter: WizardPrompter,\n email: string,\n result: { readonly reason: EmailPolicyReason; readonly limit?: number; readonly message: string },\n): Promise<EmailPolicyChoice> {\n return prompter.select<EmailPolicyChoice>({\n message: `${describeEmailPolicyRejection(email, result)} What next?`,\n options: [\n {\n value: 'retry',\n label: 'Use a different email address',\n hint: 'a +alias like you+agent2@example.com counts as a separate email',\n },\n {\n value: 'recover',\n label: 'Recover the API key of an agent this email already backs',\n hint: 'needs that agent’s handle — a code goes to this email',\n },\n { value: 'paste', label: 'Paste a key from an existing agent' },\n { value: 'cancel', label: 'Cancel registration' },\n ],\n initialValue: 'retry',\n })\n}\n\nasync function runRegisterFlow(params: {\n cfg: OpenClawConfig\n accountId: string\n prompter: WizardPrompter\n apiBase: string | undefined\n}): Promise<RegisterFlowOutcome> {\n const { cfg, accountId, prompter, apiBase } = params\n\n await prompter.note(\n [\n 'Registration mints a new AgentChat agent identity tied to your email.',\n 'One email can back several agents (the server enforces the limit);',\n 'each one registers and verifies separately.',\n 'You will receive a 6-digit code to verify — check your inbox (and spam).',\n ].join('\\n'),\n 'AgentChat: register a new agent',\n )\n\n // Collect all three fields up front. If the server rejects on one specific\n // field (handle / email), we loop back and re-prompt ONLY that field below\n // — keeping the already-correct state so the user isn't punished for a\n // partial collision.\n let email = await promptEmail(prompter)\n let handle = await promptHandle(prompter)\n const displayName = await promptDisplayName(prompter)\n\n // ─── Start: request OTP, with field-specific retry ──────────────────\n // Retry semantics:\n // invalid-handle / handle-taken → re-prompt handle, keep email+displayName\n // email-limit-reached /\n // email-exhausted → branch: pick new email, recover a key\n // for an agent on this email, paste an\n // existing key, or cancel\n // rate-limited / otp-failed /\n // network / server / validation → abort with a clear message\n let startResult: RegisterStartResult | undefined\n let startedOk = false\n for (let attempt = 1; attempt <= MAX_START_RETRIES; attempt += 1) {\n const startSpinner = prompter.progress(\n attempt === 1 ? 'Sending verification code…' : 'Retrying…',\n )\n try {\n startResult = await registerAgentStart(\n {\n email,\n handle,\n ...(displayName ? { displayName } : {}),\n },\n { apiBase },\n )\n } catch (err) {\n startSpinner.stop('Could not reach AgentChat')\n await prompter.note(\n `${err instanceof Error ? err.message : String(err)}. Try again when the network is available, or paste an existing key instead.`,\n 'Registration failed',\n )\n return 'abort'\n }\n\n if (startResult.ok) {\n startSpinner.stop(`Verification code sent to ${email}`)\n startedOk = true\n break\n }\n\n startSpinner.stop('Registration rejected')\n\n switch (startResult.reason) {\n case 'invalid-handle':\n case 'handle-taken': {\n const detail =\n startResult.reason === 'handle-taken'\n ? `Handle @${handle} is already taken.`\n : 'That handle is not acceptable (3–30 chars — lowercase letters/digits/hyphens; must start with a letter).'\n await prompter.note(`${detail} Pick a different handle and we'll try again.`, 'Pick a different handle')\n handle = await promptHandle(prompter)\n continue\n }\n case 'email-limit-reached':\n case 'email-exhausted': {\n const choice = await promptEmailPolicyChoice(prompter, email, {\n reason: startResult.reason,\n limit: startResult.limit,\n message: startResult.message,\n })\n if (choice === 'paste') return 'user-chose-paste'\n if (choice === 'recover') return 'user-chose-recover'\n if (choice === 'cancel') return 'abort'\n email = await promptEmail(prompter)\n continue\n }\n case 'rate-limited': {\n const wait = startResult.retryAfterSeconds\n ? ` Try again in ${startResult.retryAfterSeconds}s.`\n : ''\n await prompter.note(`Too many registration attempts.${wait}`, 'Rate limited')\n return 'abort'\n }\n case 'otp-failed': {\n await prompter.note(\n 'The verification-code email could not be sent. Try again in a minute, or paste an existing key instead.',\n 'OTP delivery failed',\n )\n return 'abort'\n }\n case 'network-error':\n case 'server-error':\n case 'validation':\n default: {\n await prompter.note(describeRegisterStartError(startResult), 'Could not start registration')\n return 'abort'\n }\n }\n }\n\n if (!startedOk || !startResult || !startResult.ok) {\n await prompter.note(\n 'Too many attempts. Restart the wizard to try again, or paste an existing key at the next prompt.',\n 'Registration failed',\n )\n return 'abort'\n }\n\n // ─── Verify: collect OTP, retry on mistyped codes ───────────────────\n const maxCodeAttempts = 3\n let verifyResult: RegisterVerifyResult | null = null\n for (let attempt = 1; attempt <= maxCodeAttempts; attempt += 1) {\n const code = (\n await prompter.text({\n message:\n attempt === 1\n ? 'Enter the 6-digit verification code from your email'\n : `Verification code (attempt ${attempt}/${maxCodeAttempts})`,\n placeholder: '123456',\n validate: (value) => {\n const trimmed = value.trim()\n if (!trimmed) return 'Code is required'\n if (!OTP_PATTERN.test(trimmed)) return 'Code is 6 digits'\n return undefined\n },\n })\n ).trim()\n\n const verifySpinner = prompter.progress('Verifying code…')\n try {\n verifyResult = await registerAgentVerify({ pendingId: startResult.pendingId, code }, { apiBase })\n } catch (err) {\n verifySpinner.stop('Could not reach AgentChat')\n await prompter.note(\n `${err instanceof Error ? err.message : String(err)}. Try again, or paste an existing key instead.`,\n 'Verification failed',\n )\n return 'abort'\n }\n\n if (verifyResult.ok) {\n verifySpinner.stop(`Registered as @${verifyResult.agent.handle}`)\n break\n }\n\n verifySpinner.stop('Verification failed')\n\n // Retryable: bad code. Other failure modes are terminal for this flow.\n if (verifyResult.reason === 'invalid-code' && attempt < maxCodeAttempts) {\n await prompter.note(\n 'That code did not match. Check your email and try again.',\n 'Invalid verification code',\n )\n continue\n }\n\n await prompter.note(describeRegisterVerifyError(verifyResult), 'Registration failed')\n return 'abort'\n }\n\n if (!verifyResult || !verifyResult.ok) {\n await prompter.note(\n 'Too many incorrect codes. Restart the wizard to receive a new code.',\n 'Registration failed',\n )\n return 'abort'\n }\n\n // ─── Persist: write minted key to cfg, advertise handle in config ───\n const patch: Record<string, unknown> = { apiKey: verifyResult.apiKey }\n if (isValidHandleShape(verifyResult.agent.handle)) {\n patch.agentHandle = verifyResult.agent.handle\n }\n const nextCfg = applyAgentchatAccountPatch(cfg, accountId, patch)\n\n await prompter.note(\n [\n `Handle: @${verifyResult.agent.handle}`,\n `Email: ${verifyResult.agent.email}`,\n `API key: ${redactKey(verifyResult.apiKey)} (saved to your OpenClaw config)`,\n ].join('\\n'),\n 'AgentChat account created',\n )\n\n return {\n cfg: nextCfg,\n credentialValues: {\n token: verifyResult.apiKey,\n [JUST_REGISTERED_SENTINEL]: '1',\n },\n }\n}\n\nfunction describeRegisterStartError(result: Extract<RegisterStartResult, { ok: false }>): string {\n switch (result.reason) {\n case 'invalid-handle':\n return 'That handle is not acceptable. Try a different one (3–30 chars — lowercase letters/digits/hyphens; must start with a letter).'\n case 'handle-taken':\n return 'That handle is already taken. Try a different one.'\n case 'email-limit-reached':\n return `${result.limit === undefined ? result.message : `This email already backs ${result.limit} active agents — the per-email limit.`} Use a different email (a +alias works), recover a key for one of its agents, or paste an existing key.`\n case 'email-exhausted':\n return `${result.limit === undefined ? result.message : `This email has used all ${result.limit} of its lifetime account registrations.`} Use a different email (a +alias works), or paste a key from an existing agent.`\n case 'rate-limited': {\n const wait = result.retryAfterSeconds ? ` Try again in ${result.retryAfterSeconds}s.` : ''\n return `Rate limited.${wait}`\n }\n case 'otp-failed':\n return 'The verification-code email could not be sent. Try again in a minute.'\n case 'network-error':\n case 'server-error':\n case 'validation':\n default:\n return result.message\n }\n}\n\nfunction describeRegisterVerifyError(result: Extract<RegisterVerifyResult, { ok: false }>): string {\n switch (result.reason) {\n case 'expired':\n return 'This code expired. Restart the wizard to receive a new one.'\n case 'invalid-code':\n return 'Too many incorrect codes. Restart the wizard to receive a new one.'\n case 'handle-taken':\n return 'Your chosen handle was claimed by another registration in the meantime. Restart with a different handle.'\n case 'email-limit-reached':\n // Another registration on this email landed between our start and\n // verify and took the last live slot.\n return `${result.limit === undefined ? result.message : `This email reached its limit of ${result.limit} active agents while you were verifying.`} Restart with a different email (a +alias works), or paste an existing key.`\n case 'email-exhausted':\n return `${result.limit === undefined ? result.message : `This email used all ${result.limit} of its lifetime account registrations while you were verifying.`} Restart with a different email (a +alias works), or paste an existing key.`\n case 'rate-limited': {\n const wait = result.retryAfterSeconds ? ` Try again in ${result.retryAfterSeconds}s.` : ''\n return `Rate limited.${wait}`\n }\n case 'network-error':\n case 'server-error':\n case 'unexpected-shape':\n case 'validation':\n default:\n return result.message\n }\n}\n\n// ─── Recovery (handle + email + OTP) ───────────────────────────────────\n\n/**\n * Return values from `runRecoverFlow`:\n * - success object → recovery minted a key; credential step should use it\n * and skip its own prompt.\n * - `'abort'` → recovery did not complete; the user was told why and\n * what to do next. Caller falls through to the\n * framework's paste-a-key prompt.\n */\ntype RecoverFlowOutcome =\n | { cfg: OpenClawConfig; credentialValues: ChannelSetupWizardCredentialValues }\n | 'abort'\n\n/**\n * Re-issue a lost API key. Always sends handle + email: one email can back\n * several agents, and the server can only pick the right one when told.\n *\n * Handle default: the `agentHandle` already in config for this account,\n * pre-filled so Enter accepts it. That is the case this flow exists for —\n * \"the key I have configured stopped working\" — while still letting the\n * user type a different handle (an agent set up elsewhere, or a sibling on\n * the same email). The email is always asked: the plugin never stores it\n * and `/agents/me` only ever returns it masked.\n *\n * Attempt budget is deliberately tight. `POST /agents/recover` is\n * rate-limited per IP far more strictly than registration (it sends OTPs\n * to arbitrary addresses), so there is no start-retry loop here — a\n * rejected start ends the flow with a clear note.\n */\nasync function runRecoverFlow(params: {\n cfg: OpenClawConfig\n accountId: string\n prompter: WizardPrompter\n apiBase: string | undefined\n}): Promise<RecoverFlowOutcome> {\n const { cfg, accountId, prompter, apiBase } = params\n\n const storedHandle = readAgentchatConfigField(cfg, accountId, 'agentHandle')\n const defaultHandle = storedHandle && isValidHandleShape(storedHandle) ? storedHandle : undefined\n\n await prompter.note(\n [\n 'Recovery re-issues the API key for ONE agent — the handle you name below.',\n 'You need that handle and the email it registered with; a 6-digit code',\n 'goes to that email. The old key stops working the moment the new one',\n 'is minted.',\n ...(defaultHandle\n ? ['', `@${defaultHandle} is configured here — press Enter at the handle prompt to recover it.`]\n : []),\n ].join('\\n'),\n 'AgentChat: recover a lost API key',\n )\n\n const handle = await promptHandle(prompter, {\n message: 'Handle of the agent to recover (its @name on AgentChat)',\n ...(defaultHandle ? { initialValue: defaultHandle } : {}),\n })\n const email = await promptEmail(prompter, {\n message: `Email @${handle} registered with — receives a 6-digit recovery code`,\n })\n\n // ─── Start: request OTP ────────────────────────────────────────────\n const startSpinner = prompter.progress('Requesting recovery code…')\n let startResult: RecoverStartResult\n try {\n startResult = await recoverAgentStart({ email, handle }, { apiBase })\n } catch (err) {\n startSpinner.stop('Could not reach AgentChat')\n await prompter.note(\n `${err instanceof Error ? err.message : String(err)}. Try again when the network is available, or paste an existing key instead.`,\n 'Recovery failed',\n )\n return 'abort'\n }\n\n if (!startResult.ok) {\n startSpinner.stop('Recovery rejected')\n await prompter.note(describeRecoverStartError(startResult), 'Could not start recovery')\n return 'abort'\n }\n // The server's acknowledgement is intentionally the same whether or not\n // the email + handle matched an agent — echo it rather than promising a\n // code that may not be coming.\n startSpinner.stop(startResult.message)\n\n // ─── Verify: collect OTP, retry on mistyped codes ───────────────────\n const maxCodeAttempts = 3\n let verifyResult: RecoverVerifyResult | null = null\n for (let attempt = 1; attempt <= maxCodeAttempts; attempt += 1) {\n const code = (\n await prompter.text({\n message:\n attempt === 1\n ? `Enter the 6-digit recovery code (check ${email}, including spam)`\n : `Recovery code (attempt ${attempt}/${maxCodeAttempts})`,\n placeholder: '123456',\n validate: (value) => {\n const trimmed = value.trim()\n if (!trimmed) return 'Code is required'\n if (!OTP_PATTERN.test(trimmed)) return 'Code is 6 digits'\n return undefined\n },\n })\n ).trim()\n\n const verifySpinner = prompter.progress('Verifying code…')\n try {\n verifyResult = await recoverAgentVerify({ pendingId: startResult.pendingId, code }, { apiBase })\n } catch (err) {\n verifySpinner.stop('Could not reach AgentChat')\n await prompter.note(\n `${err instanceof Error ? err.message : String(err)}. Try again, or paste an existing key instead.`,\n 'Recovery failed',\n )\n return 'abort'\n }\n\n if (verifyResult.ok) {\n verifySpinner.stop(`Recovered @${verifyResult.handle}`)\n break\n }\n\n verifySpinner.stop('Verification failed')\n\n // Retryable: bad code. Other failure modes are terminal for this flow.\n // Note a decoy pending (email + handle matched nothing) also lands\n // here as invalid-code — by design the server does not distinguish.\n if (verifyResult.reason === 'invalid-code' && attempt < maxCodeAttempts) {\n await prompter.note(\n 'That code did not match. Check your email and try again — if no code arrived, the handle and email may not belong to the same agent.',\n 'Invalid recovery code',\n )\n continue\n }\n\n await prompter.note(describeRecoverVerifyError(verifyResult), 'Recovery failed')\n return 'abort'\n }\n\n if (!verifyResult || !verifyResult.ok) {\n await prompter.note(\n 'Too many incorrect codes. Restart the wizard to request a new one — and double-check the handle and email belong to the same agent.',\n 'Recovery failed',\n )\n return 'abort'\n }\n\n // ─── Persist: the new key now authenticates as the recovered handle ──\n // `agentHandle` is overwritten with the server's answer, not what the\n // user typed: the key is the identity, and the config must describe the\n // key it holds.\n const patch: Record<string, unknown> = { apiKey: verifyResult.apiKey }\n if (isValidHandleShape(verifyResult.handle)) {\n patch.agentHandle = verifyResult.handle\n }\n const nextCfg = applyAgentchatAccountPatch(cfg, accountId, patch)\n\n await prompter.note(\n [\n `Handle: @${verifyResult.handle}`,\n `API key: ${redactKey(verifyResult.apiKey)} (saved to your OpenClaw config)`,\n '',\n 'The previous key for this agent has been revoked.',\n ].join('\\n'),\n 'AgentChat API key recovered',\n )\n\n return {\n cfg: nextCfg,\n credentialValues: {\n token: verifyResult.apiKey,\n [JUST_REGISTERED_SENTINEL]: '1',\n },\n }\n}\n\nfunction describeRecoverStartError(result: Extract<RecoverStartResult, { ok: false }>): string {\n switch (result.reason) {\n case 'rate-limited': {\n const wait = result.retryAfterSeconds ? ` Try again in ${result.retryAfterSeconds}s.` : ''\n return `Too many recovery attempts from this network.${wait}`\n }\n case 'validation':\n return `AgentChat rejected the request: ${result.message}`\n case 'network-error':\n case 'server-error':\n case 'unexpected-shape':\n default:\n return result.message\n }\n}\n\nfunction describeRecoverVerifyError(result: Extract<RecoverVerifyResult, { ok: false }>): string {\n switch (result.reason) {\n case 'expired':\n return 'This recovery code expired. Restart the wizard to request a new one.'\n case 'invalid-code':\n return 'Too many incorrect codes. Restart the wizard to request a new one.'\n case 'handle-required': {\n // Defensive: this plugin always sends a handle, so a compliant server\n // never answers HANDLE_REQUIRED to it. If one does, the server has\n // just confirmed inbox control and listed the live handles — show\n // them so the re-run is a straight pick instead of a guess.\n const handles = result.handles ?? []\n const list = handles.length > 0 ? `\\n\\nAgents on this email:\\n${handles.map((h) => ` @${h}`).join('\\n')}` : ''\n return `This email backs more than one agent. Run recovery again and enter the handle you want to recover.${list}`\n }\n case 'rate-limited': {\n const wait = result.retryAfterSeconds ? ` Try again in ${result.retryAfterSeconds}s.` : ''\n return `Rate limited.${wait}`\n }\n case 'network-error':\n case 'server-error':\n case 'unexpected-shape':\n case 'validation':\n default:\n return result.message\n }\n}\n\nfunction redactKey(apiKey: string): string {\n if (apiKey.length < 12) return '••••'\n return `${apiKey.slice(0, 8)}…${apiKey.slice(-4)}`\n}\n\nexport const agentchatSetupWizard: ChannelSetupWizard = {\n channel: AGENTCHAT_CHANNEL_ID,\n\n // AgentChat is one-agent-per-account by product design — the agent IS the\n // account, identity is its handle. The default OpenClaw `promptAccountId`\n // helper is built for channels like Telegram/Slack where one workspace\n // can host multiple bot accounts; it forces every user through an\n // \"Add a new account\" → \"Set account id\" prompt that doesn't map to\n // anything meaningful here.\n //\n // Override the resolver to silently use the default account id, so the\n // wizard goes straight from channel selection into the register-or-paste\n // step. An explicit `--account` override still wins so power users who\n // genuinely want a second agent on the same machine can scope their\n // config that way (rare, by intent).\n resolveAccountIdForConfigure: async ({ accountOverride }) => {\n const trimmed = accountOverride?.trim()\n return trimmed ? trimmed : 'default'\n },\n\n status: {\n configuredLabel: 'configured',\n unconfiguredLabel: 'not configured',\n configuredHint: 'AgentChat agent is ready to receive messages',\n unconfiguredHint: 'connect your agent to the AgentChat messaging platform',\n configuredScore: 90,\n unconfiguredScore: 30,\n resolveConfigured: ({ cfg, accountId }) => {\n return hasConfiguredKey(cfg, accountId ?? 'default')\n },\n resolveStatusLines: ({ cfg, accountId, configured }) => {\n const id = accountId ?? 'default'\n if (!configured) {\n return ['AgentChat: not configured — the wizard will register you, accept an existing key, or recover a lost one.']\n }\n const handle = readAgentchatConfigField(cfg, id, 'agentHandle')\n if (!isAgentchatAccountEnabled(cfg, id)) return [`AgentChat: configured${handle ? ` (@${handle})` : ''}; ${agentchatReenableHint(cfg, id)}`]\n return [`AgentChat: configured${handle ? ` (@${handle})` : ''}`]\n },\n },\n\n introNote: {\n title: 'AgentChat',\n lines: [\n 'AgentChat is a messaging platform for AI agents — direct messages,',\n 'groups, presence, attachments. Registration is free.',\n '',\n 'This wizard will mint a new account via email OTP, accept an existing',\n 'API key, or recover a lost key (handle + email OTP) — your choice in',\n 'the next prompt.',\n ],\n },\n\n prepare: async ({ cfg, accountId, credentialValues, prompter }) => {\n // Re-run against an already-configured account: offer the edit menu\n // (keep / change-base / replace-key). `change-base` is the only action\n // that cannot be driven through the framework's credential UX — it has\n // to mutate `apiBase`, which is not a credential field. `keep` and\n // `replace-key` both fall through to the framework's keep/replace prompt\n // on the credential step; the only difference is that `replace-key`\n // surfaces the register-or-paste menu below so the user gets the\n // in-wizard register path instead of just a paste box.\n if (hasConfiguredKey(cfg, accountId) && typeof credentialValues.token === 'string') {\n const editChoice = await prompter.select<'keep' | 'change-base' | 'replace-key'>({\n message: 'AgentChat is already configured. What would you like to do?',\n options: [\n {\n value: 'keep',\n label: 'Keep current config',\n hint: 'the credential step will still re-validate on the next run',\n },\n {\n value: 'change-base',\n label: 'Change API base URL',\n hint: 'only for self-hosted AgentChat deployments',\n },\n {\n value: 'replace-key',\n label: 'Replace the API key',\n hint: 'paste a new key, register a new agent, or recover a lost key',\n },\n ],\n initialValue: 'keep',\n })\n\n if (editChoice === 'keep') return\n if (editChoice === 'change-base') {\n return await runChangeApiBaseFlow({ cfg, accountId, prompter })\n }\n // 'replace-key' falls through to the register / paste / recover menu below.\n }\n\n const choice = await prompter.select<'register' | 'paste' | 'recover'>({\n message: 'How would you like to configure AgentChat?',\n options: [\n {\n value: 'register',\n label: 'Register a new agent (email OTP)',\n hint: 'no account yet — the wizard creates one',\n },\n {\n value: 'paste',\n label: 'I already have an API key',\n hint: 'paste ac_live_… on the next prompt',\n },\n {\n value: 'recover',\n label: 'Recover a lost API key (handle + email OTP)',\n hint: 'an agent exists but its key is gone — re-issue it',\n },\n ],\n initialValue: 'register',\n })\n\n if (choice === 'paste') {\n return\n }\n\n const apiBase = readAgentchatConfigField(cfg, accountId, 'apiBase')\n\n // Recovery tail, shared by the menu entry and the hand-off from the\n // register flow: a minted key is returned as-is; an abort tells the\n // user they can still paste a key at the next prompt. Unexpected\n // throws are reported under their own title so a failure inside\n // recovery is never misattributed to registration.\n const recover = async () => {\n try {\n const result = await runRecoverFlow({ cfg, accountId, prompter, apiBase })\n if (result === 'abort') {\n await prompter.note(\n 'Recovery was not completed. You can still paste an existing API key at the next prompt, or cancel the wizard.',\n 'Falling back to credential entry',\n )\n return\n }\n return result\n } catch (err) {\n if (err instanceof WizardCancelledError) throw err\n await prompter.note(\n `${err instanceof Error ? err.message : String(err)}`,\n 'Recovery flow failed',\n )\n return\n }\n }\n\n if (choice === 'recover') {\n return await recover()\n }\n\n let registerOutcome: RegisterFlowOutcome\n try {\n registerOutcome = await runRegisterFlow({ cfg, accountId, prompter, apiBase })\n } catch (err) {\n if (err instanceof WizardCancelledError) throw err\n await prompter.note(\n `${err instanceof Error ? err.message : String(err)}`,\n 'Registration flow failed',\n )\n return\n }\n\n if (registerOutcome === 'abort') {\n // User can still paste an existing key at the credential step.\n await prompter.note(\n 'Registration was not completed. You can still paste an existing API key at the next prompt, or cancel the wizard.',\n 'Falling back to credential entry',\n )\n return\n }\n if (registerOutcome === 'user-chose-paste') {\n // User picked the \"paste my existing key\" branch from inside the\n // register flow — they already acknowledged what's next, so don't\n // re-surface the generic fallback note. Fall through to the\n // credential step which will prompt for the key.\n return\n }\n if (registerOutcome === 'user-chose-recover') {\n // The email is at its agent limit and the user wants the key of one\n // of the agents it already backs. Hand off to recovery; it asks for\n // the handle and the email again — the register flow's email is a\n // reasonable guess but not necessarily the one that agent registered\n // with, so it is not pre-filled.\n return await recover()\n }\n return registerOutcome\n },\n\n credentials: [\n {\n inputKey: 'token',\n providerHint: 'agentchat',\n credentialLabel: 'API key',\n preferredEnvVar: 'AGENTCHAT_API_KEY',\n envPrompt: 'AGENTCHAT_API_KEY detected in env. Use it?',\n keepPrompt: 'AgentChat API key already configured. Keep it?',\n inputPrompt: 'Paste your AgentChat API key (ac_live_…)',\n helpTitle: 'AgentChat API key',\n helpLines: [\n 'Format: ac_live_<base64>, ≥20 chars. Validated against',\n 'GET /v1/agents/me during this wizard — bad keys fail fast instead',\n 'of flapping reconnects at runtime.',\n ],\n allowEnv: () => true,\n shouldPrompt: ({ credentialValues, currentValue }) => {\n // Post-register: we already minted + persisted the key in prepare.\n if (credentialValues[JUST_REGISTERED_SENTINEL] === '1') return false\n // No key yet: always prompt.\n if (!currentValue) return true\n // Existing key + user didn't choose register: show keep/replace.\n return true\n },\n inspect: ({ cfg, accountId }) => {\n const apiKey = readAgentchatConfigField(cfg, accountId, 'apiKey')\n const configured = isApiKeyPresent(apiKey)\n // Delegated to the credential helper — see SECURITY.md.\n const envValue = readApiKeyFromEnv(MIN_API_KEY_LENGTH)\n return {\n accountConfigured: configured,\n hasConfiguredValue: configured,\n resolvedValue: configured ? apiKey : undefined,\n envValue,\n }\n },\n },\n ],\n\n finalize: async ({ cfg, accountId, credentialValues, prompter }) => {\n const apiKey =\n typeof credentialValues.token === 'string' && credentialValues.token.length >= MIN_API_KEY_LENGTH\n ? credentialValues.token\n : readAgentchatConfigField(cfg, accountId, 'apiKey')\n\n if (!apiKey || !isApiKeyPresent(apiKey)) {\n // Nothing to validate — prepare aborted and credential step got skipped\n // or the user bailed mid-flow. The `configure` call above will still\n // write whatever cfg we return; nothing more to do here.\n return\n }\n\n const apiBase = readAgentchatConfigField(cfg, accountId, 'apiBase')\n const spinner = prompter.progress('Validating API key against AgentChat…')\n try {\n const result = await validateApiKey(apiKey, { apiBase })\n if (result.ok) {\n spinner.stop(`Authenticated as @${result.agent.handle}`)\n\n // Place the integration: the key in OpenClaw's state-dir `.env` (the\n // hosted tools' bearer header is a template on it), the served\n // identity line in AGENTS.md (loaded every turn), the manual\n // (bundled), and the hosted MCP server in `mcp.servers.agentchat`.\n // Best-effort by intent: a read-only workspace must NOT bounce the\n // wizard — the key and config are saved; the report says what to\n // repair.\n const handle = result.agent.handle\n const resolvedBase = apiBase ?? DEFAULT_API_BASE\n const identityLine = await loadIdentityLine({ client: createSdkClient({ apiKey, apiBase: resolvedBase }), accountId })\n const placed = placeIntegration({ cfg, handle, apiKey, apiBase: resolvedBase, identityLine, accountId })\n const failed = placed.steps.filter((s) => s.status === 'failed')\n const skipped = placed.steps.filter((s) => s.status === 'skipped' && s.name === 'anchor')\n await prompter.note(\n [\n ...formatPlacement(placed.steps),\n '',\n placed.mcp === 'added' || placed.steps.some((s) => s.name === 'key' && s.status === 'changed')\n ? 'Restart the gateway once so its environment carries the key and it connects the hosted tools. Then `openclaw channels status` shows the integration and the tools.'\n : 'The agent is reachable: a peer\\'s message wakes it; the agent decides with its own model; it answers through the hosted AgentChat tools.',\n ...(failed.length > 0\n ? ['', 'Some placement failed (above). Your account is configured; re-run `openclaw channels add agentchat` after fixing the path, or `openclaw doctor --fix` for the config entry.']\n : []),\n ...(skipped.length > 0 ? ['', 'The identity line waits for AgentChat to be reachable: run `openclaw doctor --fix` then.'] : []),\n ].join('\\n'),\n 'AgentChat integration placed',\n )\n\n // The config side of placement: the handle the key authenticates as\n // (configured-state, doctor and the own-echo filter need it), the\n // hosted tools entry, and the llm override opt-in when this account\n // is bound to an agent other than OpenClaw's default.\n const applied = applyIntegrationConfig(placed.cfg, { accountId, handle, apiKey, apiBase: resolvedBase })\n return { cfg: applied.cfg }\n }\n\n spinner.stop(`API key did not pass the live check (${result.reason})`)\n await prompter.note(\n [\n result.message,\n '',\n 'The config was saved — you can re-run `openclaw channels add agentchat`',\n 'to replace the key, or edit ~/.openclaw/config.yaml directly.',\n ].join('\\n'),\n 'AgentChat validation warning',\n )\n } catch (err) {\n spinner.stop('Could not reach AgentChat for validation')\n await prompter.note(\n [\n err instanceof Error ? err.message : String(err),\n '',\n 'The config was saved — the runtime will retry on startup.',\n ].join('\\n'),\n 'AgentChat API unreachable',\n )\n }\n return\n },\n\n completionNote: {\n title: 'AgentChat is ready',\n // After our wizard returns, OpenClaw's setupChannels keeps running\n // its own outer flow (a Select-a-channel loop, then optional\n // follow-up prompts for display names and channel→agent binding).\n // None of that is suppressible from a channel plugin — there's no\n // field on ChannelSetupWizard that hides those prompts. So this\n // note keeps to the only thing the user actually needs to know:\n // pick Finished. The earlier \"or pick another channel\" copy read\n // as a vague alt-branch and produced the \"did this break?\"\n // reaction; one direct sentence is the cure.\n lines: ['On the next prompt, choose \"Finished\" to exit.'],\n },\n\n // `disable` fires on `openclaw channels remove agentchat`. We strip the\n // AGENTS.md identity line and our own `mcp.servers.agentchat` entry so the\n // agent stops being told it is @handle on AgentChat and stops seeing the\n // hosted tools the moment the channel is removed. The key stays in the\n // channel config and in `.env` (a remove is a pause, not a rotation).\n // Best-effort: FS errors never block the channel-remove. Plugin uninstall\n // (`openclaw plugins uninstall`) fires no plugin hook, so this only runs\n // when the user explicitly removes the channel; orphans are documented in\n // RUNBOOK.md.\n disable: (cfg) => {\n // The config side only, same as `config.setAccountEnabled(false)`: the\n // plugin's own mcp.servers.agentchat entry goes (matched by URL +\n // transport on the env-substituted config), the key stays — a remove is\n // a pause, not a rotation. Files (the identity line) are removed by the\n // lifecycle hook after the patch is checked, never from a pure adapter.\n return setSetupChannelEnabled(stripIntegrationConfig(cfg, 'default').cfg, AGENTCHAT_CHANNEL_ID, false)\n },\n}\n","/**\n * Zod schema for AgentChat channel config.\n *\n * Source of truth: this file. The JSON Schema inlined in `openclaw.plugin.json`\n * MUST stay in sync (P1 adds a build step that emits it via zod-to-json-schema).\n *\n * `.strict()` rejects unknown keys — a common source of \"the config silently\n * ignored my setting\" bugs.\n */\n\nimport { z } from 'zod'\n\n/**\n * Socket reconnect backoff, handed to the SDK's `RealtimeClient`:\n * `initialBackoffMs` → `reconnectInterval`, `maxBackoffMs` →\n * `maxReconnectInterval`. `jitterRatio` is accepted for configuration\n * compatibility and unused: the SDK applies its own ±25 % jitter.\n */\nexport const reconnectConfigSchema = z\n .object({\n initialBackoffMs: z.number().int().min(100).max(10_000).default(1_000),\n maxBackoffMs: z.number().int().min(1_000).max(300_000).default(30_000),\n jitterRatio: z.number().min(0).max(1).default(0.2),\n })\n .strict()\n\n/**\n * Accepted for configuration compatibility with releases that ran their own\n * socket and unused: the SDK's realtime client has no client-side ping; the\n * server's heartbeat keeps the session alive. Kept so an existing\n * `channels.agentchat.ping` block still parses under the strict schema.\n */\nexport const pingConfigSchema = z\n .object({\n intervalMs: z.number().int().min(5_000).max(120_000).default(45_000),\n timeoutMs: z.number().int().min(1_000).max(60_000).default(30_000),\n })\n .strict()\n\n/**\n * Accepted for configuration compatibility with releases before the\n * integration and otherwise unused: the integration sends nothing itself\n * (the agent's send is a hosted-tool call), so there is no outbound to tune.\n * Kept so an existing `channels.agentchat.outbound` block still parses\n * under the strict schema.\n */\nexport const outboundConfigSchema = z\n .object({\n maxInFlight: z.number().int().min(1).max(10_000).default(256),\n sendTimeoutMs: z.number().int().min(1_000).max(60_000).default(15_000),\n })\n .strict()\n\nexport const observabilityConfigSchema = z\n .object({\n logLevel: z.enum(['trace', 'debug', 'info', 'warn', 'error']).default('info'),\n redactKeys: z\n .array(z.string())\n .default(['apiKey', 'authorization', 'cookie', 'set-cookie']),\n })\n .strict()\n\nexport const agentHandleSchema = z\n .string()\n .regex(\n /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,\n 'handle must be lowercase letters/digits/hyphens; start with a letter; no trailing or doubled hyphens',\n )\n .min(3, 'handle must be at least 3 characters')\n .max(30, 'handle must be at most 30 characters')\n\nexport const agentchatChannelConfigSchema = z\n .object({\n /**\n * Written by OpenClaw on `channels remove` (disable) / re-enable through\n * `config.setAccountEnabled`, and validated by OpenClaw against the JSON\n * schema emitted from this object before the write is persisted — so the\n * strict schema must know it. At runtime `splitEnabledFromRaw` lifts it\n * out before the account is parsed; it is never read from the parsed\n * config.\n */\n enabled: z.boolean().optional(),\n apiBase: z.string().url().default('https://api.agentchat.me'),\n apiKey: z.string().min(20, 'apiKey looks too short for an AgentChat API key'),\n agentHandle: agentHandleSchema.optional(),\n // `.prefault({})` — Zod 4 idiom: when the key is missing from input, parse\n // `{}` through the inner schema so its own per-field defaults kick in.\n // Using `.default({})` here fails in Zod 4 because the output type's fields\n // are non-optional once the inner schema has defaults.\n reconnect: reconnectConfigSchema.prefault({}),\n ping: pingConfigSchema.prefault({}),\n outbound: outboundConfigSchema.prefault({}),\n observability: observabilityConfigSchema.prefault({}),\n })\n .strict()\n\nexport type AgentchatChannelConfig = z.infer<typeof agentchatChannelConfigSchema>\nexport type AgentchatChannelConfigInput = z.input<typeof agentchatChannelConfigSchema>\n\n/**\n * Parse + validate config at plugin startup.\n *\n * Strict on `apiKey` and the four nested groups — `parseChannelConfig` is\n * called only AFTER `resolveAgentchatAccount` has confirmed that the\n * persisted config block is non-empty (see `channel.ts`), so an empty\n * install-time config never reaches Zod. The runtime-time strictness here\n * surfaces typos and out-of-range values fast. The OpenClaw install-time\n * JSON Schema (emitted by `scripts/emit-manifest-schema.mjs`) is more\n * permissive — see that script's post-process step for the rationale —\n * so a freshly-installed plugin can pass install validation against an\n * empty config block before the setup wizard fills in credentials.\n *\n * `AgentChatChannelError` wraps validation failures so the gateway can\n * classify them (`terminal-user` — operator fix required).\n */\nexport function parseChannelConfig(input: unknown): AgentchatChannelConfig {\n return agentchatChannelConfigSchema.parse(input)\n}\n","/**\n * Structured logger for the channel plugin.\n *\n * Wraps pino with:\n * - Secret redaction (`apiKey`, `authorization`, `cookie`, `set-cookie` by default)\n * - A `child({ correlationId })` helper for per-operation logs\n * - Graceful integration: when OpenClaw's channel runtime context provides\n * a logger, we delegate to it so logs stream through the gateway's sink.\n *\n * Never logs the API key. Never logs message bodies above `debug` level.\n */\n\nimport pino from 'pino'\n\nexport type LogLevel = 'trace' | 'debug' | 'info' | 'warn' | 'error'\n\nexport interface Logger {\n trace(obj: object, msg?: string): void\n debug(obj: object, msg?: string): void\n info(obj: object, msg?: string): void\n warn(obj: object, msg?: string): void\n error(obj: object, msg?: string): void\n child(bindings: Record<string, unknown>): Logger\n}\n\nexport interface CreateLoggerOptions {\n level: LogLevel\n redactKeys: readonly string[]\n /** If provided, delegates to the gateway's logger instead of creating our own. */\n delegate?: Logger | undefined\n}\n\nexport function createLogger(options: CreateLoggerOptions): Logger {\n if (options.delegate) {\n return options.delegate\n }\n\n const pinoLogger = pino({\n level: options.level,\n base: { plugin: '@agentchatme/openclaw' },\n redact: {\n paths: buildRedactPaths(options.redactKeys),\n censor: '[REDACTED]',\n },\n timestamp: pino.stdTimeFunctions.isoTime,\n })\n\n return wrapPino(pinoLogger)\n}\n\nfunction buildRedactPaths(keys: readonly string[]): string[] {\n // Cover common shapes: top-level, nested under `config.*`, nested under\n // `headers.*`, nested under `context.*`. Pino redact paths are JSON-path-ish.\n const prefixes = ['', 'config.', 'headers.', 'context.', 'req.headers.', 'res.headers.']\n const paths: string[] = []\n for (const key of keys) {\n for (const prefix of prefixes) {\n paths.push(`${prefix}${key}`)\n }\n }\n // Also redact under `*` wildcard at top level for deeply nested cases.\n paths.push(...keys.map((k) => `*.${k}`))\n return paths\n}\n\nfunction wrapPino(p: pino.Logger): Logger {\n return {\n trace: (obj, msg) => p.trace(obj, msg),\n debug: (obj, msg) => p.debug(obj, msg),\n info: (obj, msg) => p.info(obj, msg),\n warn: (obj, msg) => p.warn(obj, msg),\n error: (obj, msg) => p.error(obj, msg),\n child: (bindings) => wrapPino(p.child(bindings)),\n }\n}\n\n/**\n * Redact a string for display in logs — shows first 8 and last 4 chars,\n * masks the middle. Useful for surfacing \"which key\" without leaking it.\n */\nexport function maskSecret(value: string): string {\n if (value.length <= 12) return '[REDACTED]'\n return `${value.slice(0, 8)}••••${value.slice(-4)}`\n}\n","/**\n * Counters for the integration: the socket's state, its closes and the\n * notices the SDK surfaces, and the wakes handed to the invoker. The\n * integration sends nothing, so there are no outbound metrics.\n *\n * Where they can be read. OpenClaw gives a plugin no Prometheus registry:\n * its `/api/diagnostics/prometheus` (the `diagnostics-prometheus` plugin)\n * renders a fixed catalog of `openclaw_*` families from trusted or\n * dispatcher-owned diagnostic events, and a third-party plugin's\n * `emitDiagnosticEvent` is untrusted by definition and dropped by that\n * exporter. So inside the gateway these counters are kept in memory\n * (`createInMemoryMetrics`) and shown by the status probe\n * (`openclaw channels capabilities --channel agentchat`, the `socket —`\n * line). `createMetrics` registers the same counters into a `prom-client`\n * registry for a host that runs the plugin's classes in its own process and\n * owns a scrape endpoint; `createNoopMetrics` is the zero-cost default.\n *\n * Names are prefixed with `agentchat_channel_` (dashboards: see CHANGELOG):\n * agentchat_channel_wake_total{source} — message | connect | reminder | retry | other\n * agentchat_channel_disconnect_total{code,initiator} — initiator = server (the wire) | client (the SDK's own watchdog)\n * agentchat_channel_connection_state{kind} — the SDK's state: idle | connecting | ready | backoff | blocked | stopped\n * agentchat_channel_error_total{errorClass} — auth (one per rejected HELLO) | transport | handler | protocol | other\n */\n\n/** The counters so far, as the in-memory recorder keeps them. */\nexport interface MetricsSnapshot {\n /** The connection state last set (the gauge's active kind). */\n readonly state: string\n /** Wakes by source. */\n readonly wakes: Readonly<Record<string, number>>\n /** Socket closes by `<code>/<initiator>`, e.g. `1006/server`, `4000/client`. */\n readonly disconnects: Readonly<Record<string, number>>\n /** Rejected HELLOs (`auth`) and the SDK's other notices, by class. */\n readonly errors: Readonly<Record<string, number>>\n}\n\nexport interface MetricsRecorder {\n /** Incremented on every socket close the SDK reports; `initiator` is `server` (the wire) or `client` (the SDK's own watchdog). */\n incDisconnect(labels: { code: string; initiator: string }): void\n /** Incremented on every rejected HELLO (`auth`) and every other notice the SDK surfaces, labeled by class. */\n incError(labels: { errorClass: string }): void\n /** Set the current connection state (cardinality bounded by state kinds). */\n setConnectionState(kind: string): void\n /** Incremented on every wake handed to the invoker (message frames, connects, server wake frames, the ladder's retries). */\n incWake(labels: { source: string }): void\n /** The counters so far, when the recorder keeps them (the in-memory one does; a prom-client registry is read by scraping). */\n snapshot?(): MetricsSnapshot\n}\n\n/** Minimal contract for a prom-client-compatible registry. */\nexport interface PromRegistryLike {\n registerMetric(metric: unknown): void\n}\n\n/** Minimal contract for a prom-client factory; avoids a hard dep on `prom-client`. */\nexport interface PromFactory {\n Counter: new (cfg: MetricConfig) => {\n inc(labels?: Record<string, string>, value?: number): void\n }\n Gauge: new (cfg: MetricConfig) => {\n set(labelsOrValue: Record<string, string> | number, value?: number): void\n }\n}\n\ninterface MetricConfig {\n name: string\n help: string\n labelNames?: readonly string[]\n registers?: readonly unknown[]\n}\n\nexport interface CreateMetricsOptions {\n registry: PromRegistryLike\n factory: PromFactory\n}\n\n/** The recorder for a host with a `prom-client` registry and a scrape endpoint of its own. */\nexport function createMetrics(options: CreateMetricsOptions): MetricsRecorder {\n const { registry, factory } = options\n\n const disconnects = new factory.Counter({\n name: 'agentchat_channel_disconnect_total',\n help: 'WebSocket closes reported by the SDK, by close code and initiator (server | client).',\n labelNames: ['code', 'initiator'],\n registers: [registry],\n })\n\n const errors = new factory.Counter({\n name: 'agentchat_channel_error_total',\n help: 'Rejected HELLOs (auth) and the other notices the SDK surfaced, labeled by error class.',\n labelNames: ['errorClass'],\n registers: [registry],\n })\n\n const connectionState = new factory.Gauge({\n name: 'agentchat_channel_connection_state',\n help: 'Current connection state (1 = active kind, 0 = otherwise).',\n labelNames: ['kind'],\n registers: [registry],\n })\n\n const wakes = new factory.Counter({\n name: 'agentchat_channel_wake_total',\n help: 'Wakes handed to the integration (message frames, connects, server wake frames).',\n labelNames: ['source'],\n registers: [registry],\n })\n\n return {\n incDisconnect: ({ code, initiator }) => disconnects.inc({ code, initiator }),\n incError: ({ errorClass }) => errors.inc({ errorClass }),\n setConnectionState: (kind) => connectionState.set({ kind }, 1),\n incWake: ({ source }) => wakes.inc({ source }),\n }\n}\n\n/**\n * The recorder the gateway binding uses: the same counters, kept in memory\n * and read by the status probe. Label sets are bounded by construction\n * (fixed source / class / state vocabularies, close codes from the wire).\n */\nexport function createInMemoryMetrics(): MetricsRecorder & { snapshot(): MetricsSnapshot } {\n let state = 'idle'\n const wakes = new Map<string, number>()\n const disconnects = new Map<string, number>()\n const errors = new Map<string, number>()\n const bump = (map: Map<string, number>, key: string): void => {\n map.set(key, (map.get(key) ?? 0) + 1)\n }\n const plain = (map: Map<string, number>): Record<string, number> => Object.fromEntries([...map.entries()].sort(([a], [b]) => a.localeCompare(b)))\n return {\n incDisconnect: ({ code, initiator }) => bump(disconnects, `${code}/${initiator}`),\n incError: ({ errorClass }) => bump(errors, errorClass),\n setConnectionState: (kind) => {\n state = kind\n },\n incWake: ({ source }) => bump(wakes, source),\n snapshot: () => ({ state, wakes: plain(wakes), disconnects: plain(disconnects), errors: plain(errors) }),\n }\n}\n\n/** No-op recorder — zero overhead when nothing reads the counters. */\nexport function createNoopMetrics(): MetricsRecorder {\n return {\n incDisconnect: () => undefined,\n incError: () => undefined,\n setConnectionState: () => undefined,\n incWake: () => undefined,\n }\n}\n","/**\n * Group invites: the second wake kind, and the ledger of invites already\n * offered to the agent.\n *\n * An invite is not on the tray and is not gated: the agent gets one turn\n * with the served invite prompt and decides for itself through the hosted\n * tools (accept, decline, or leave it pending). Invites arrive live\n * (`group.invite.received` frame) and are listed again on every connect\n * (`GET /v1/groups/invites`), so the same invite is seen many times over\n * the life of an account. The ledger remembers which invites were offered —\n * on disk, so a gateway restart never starts one more turn for an invite\n * the agent chose to leave pending. An invite whose turn could not start is\n * NOT marked offered: it stays pending in the invoker and is retried on the\n * next wake.\n */\n\nimport * as path from 'node:path'\n\nimport { integrationStateDir, readJsonFile, writeJsonFile } from './state.js'\n\nexport interface GroupInvite {\n readonly inviteId: string\n readonly groupId: string\n readonly groupName: string\n /** Bare handle, `@` stripped; `''` when the frame carried none. */\n readonly inviterHandle: string\n}\n\n/** From a `group.invite.received` frame payload or a `GET /v1/groups/invites` row. `null` when the ids are missing. */\nexport function groupInviteFromRecord(record: unknown): GroupInvite | null {\n if (!record || typeof record !== 'object' || Array.isArray(record)) return null\n const row = record as Record<string, unknown>\n const inviteId = str(row.id)\n const groupId = str(row.group_id)\n if (!inviteId || !groupId) return null\n return {\n inviteId,\n groupId,\n groupName: str(row.group_name) ?? '',\n inviterHandle: (str(row.inviter_handle) ?? '').replace(/^@/, ''),\n }\n}\n\nfunction str(value: unknown): string | undefined {\n return typeof value === 'string' && value.length > 0 ? value : undefined\n}\n\nexport const INVITE_LEDGER_FILE = 'invites.json'\n/** Offered ids older than this are forgotten; a server-side invite does not live that long. */\nexport const INVITE_LEDGER_MAX_AGE_MS = 30 * 24 * 60 * 60_000\n\ninterface LedgerFile {\n readonly offered: Record<string, string>\n}\n\nexport interface InviteLedgerOptions {\n readonly accountId: string\n readonly stateDir?: string | undefined\n /** Explicit file (test seam). Defaults to `<plugin state dir>/invites.json`. */\n readonly file?: string\n readonly now?: () => number\n readonly maxAgeMs?: number\n /** Called when a write fails; the in-memory ledger still holds the id. */\n readonly onWriteError?: (err: unknown) => void\n}\n\nexport function inviteLedgerPath(accountId: string, stateDir?: string): string {\n return path.join(integrationStateDir(accountId, stateDir), INVITE_LEDGER_FILE)\n}\n\nexport class InviteLedger {\n private readonly file: string\n private readonly now: () => number\n private readonly maxAgeMs: number\n private readonly onWriteError: ((err: unknown) => void) | undefined\n private offered: Map<string, string>\n\n constructor(options: InviteLedgerOptions) {\n this.file = options.file ?? inviteLedgerPath(options.accountId, options.stateDir)\n this.now = options.now ?? Date.now\n this.maxAgeMs = options.maxAgeMs ?? INVITE_LEDGER_MAX_AGE_MS\n this.onWriteError = options.onWriteError\n this.offered = this.read()\n }\n\n get path(): string {\n return this.file\n }\n\n get size(): number {\n return this.offered.size\n }\n\n /** True when a turn for this invite was started before (in this process or an earlier one). */\n isOffered(inviteId: string): boolean {\n return this.offered.has(inviteId)\n }\n\n /** Record that a turn for this invite was admitted. Persists at once. */\n markOffered(inviteId: string): void {\n this.offered.set(inviteId, new Date(this.now()).toISOString())\n this.prune()\n try {\n writeJsonFile(this.file, { offered: Object.fromEntries(this.offered) } satisfies LedgerFile)\n } catch (err) {\n this.onWriteError?.(err)\n }\n }\n\n private read(): Map<string, string> {\n const raw = readJsonFile(this.file)\n const out = new Map<string, string>()\n if (!raw || typeof raw !== 'object') return out\n const offered = (raw as Record<string, unknown>).offered\n if (!offered || typeof offered !== 'object' || Array.isArray(offered)) return out\n for (const [id, at] of Object.entries(offered as Record<string, unknown>)) {\n if (typeof at === 'string' && id.length > 0) out.set(id, at)\n }\n this.offered = out\n this.prune()\n return this.offered\n }\n\n private prune(): void {\n const cutoff = this.now() - this.maxAgeMs\n for (const [id, at] of this.offered) {\n const t = Date.parse(at)\n if (!Number.isFinite(t) || t < cutoff) this.offered.delete(id)\n }\n }\n}\n","/**\n * The socket as a wake — the SDK's `RealtimeClient` bound to one account.\n *\n * The transport is the SDK's, lifecycle included: HELLO, the reconnect\n * backoff that never gives up (one notice after a long outage, then a wider\n * cap), the handshake and idle watchdogs, the 10–15 min retry of a rejected\n * key, the delivery ack, per-conversation ordering, the reconnect drain. This\n * module holds what is runtime logic: starting and stopping it with the\n * account, turning what arrives into wakes for the invoker, filtering the\n * echo of the agent's own sends, and handing the SDK's lifecycle events to\n * the gateway as they are.\n *\n * - `message.new` → `onWake('message')` — after reading only\n * the sender (to skip our own echo) and the\n * ids for the log line. The body is never\n * looked at; the agent reads it through the\n * hosted tools inside its turn.\n * - `wake` → `onWake(reason)` — the server's content-free\n * wake (a deferred conversation's reminder).\n * - every successful HELLO → `onWake('connect')` — whatever landed while\n * the socket was down is on the tray.\n * - `group.invite.received` → `onGroupInvite(invite)` — the second wake\n * kind; not on the tray, not gated.\n *\n * `ackOnReceipt: true`: the SDK acknowledges every `message.new` the moment\n * the frame is parsed, before any handler runs — delivered means this\n * machine received it. Whether the agent looked is read state, recorded by\n * the gate's verdicts; an early ack never empties the tray. No frame is\n * ever acknowledged by this module; it sends nothing.\n *\n * Every frame is a wake and every wake reads the whole tray, so no ordering\n * assumption is made: frames the SDK parks on a sequence gap and flushes on\n * a close are wakes like any other.\n *\n * Nothing here classifies a close. Whether a close was a rejected key, a\n * slow handshake or the client's own watchdog is the SDK's call: it says\n * `blocked` (a typed event with the code, the reason and the delay to its\n * next HELLO) or it backs off, and this module reports which.\n */\n\nimport {\n RealtimeClient,\n type AgentChatClient,\n type BlockedInfo,\n type DisconnectInfo,\n type RealtimeOptions,\n type RealtimeState,\n type WakeFrame,\n type WsMessage,\n} from 'agentchatme'\n\nimport type { AgentchatChannelConfig } from '../config-schema.js'\nimport type { Logger } from '../log.js'\nimport type { MetricsRecorder } from '../metrics.js'\nimport { createNoopMetrics } from '../metrics.js'\nimport { AGENTCHAT_CLIENT_IDENTITY } from '../client-identity.js'\nimport { groupInviteFromRecord, type GroupInvite } from './invites.js'\nimport type { WakeSource } from './invoker.js'\n\n/** A server wake frame's `reason` → the fixed wake-source set (the metric label must stay bounded). */\nexport function wakeSourceOf(reason: unknown): WakeSource {\n return reason === 'reminder' ? 'reminder' : 'other'\n}\n\n/**\n * The connection as the gateway reports it: the SDK's own lifecycle, read\n * from `realtime.state`. `idle` before the first start, `connecting` while a\n * socket opens or its HELLO awaits `hello.ok`, `ready` while a session is up,\n * `backoff` between a close and the next attempt, `blocked` after the server\n * rejected the key during the handshake (the SDK retries a fresh HELLO every\n * 10–15 min; a later `hello.ok` clears it), `stopped` after `stop()` — the\n * only state the client never leaves on its own.\n */\nexport type SocketState = RealtimeState\n\n/** Every socket close the SDK reports: the code, the reason, and who ended it (`client` = the SDK's own watchdog). */\nexport type SocketDisconnect = DisconnectInfo\n\n/** A rejected HELLO: the close code and reason, and the delay to the SDK's next attempt. */\nexport type SocketBlocked = BlockedInfo\n\nexport interface WakeDetail {\n readonly conversationId?: string\n readonly messageId?: string\n readonly from?: string\n}\n\nexport interface SocketHandlers {\n /** A wake: the tray may have changed. `source` is for the log line and the metric label only. */\n onWake?: (source: WakeSource, detail: WakeDetail) => void\n /** The second wake kind. */\n onGroupInvite?: (invite: GroupInvite) => void\n /** Once per accepted HELLO (initial + every reconnect), before the connect wake. */\n onConnected?: (at: number) => void\n /** Every socket close the SDK reports (never for our own `stop()`). The state that follows says what comes next. */\n onDisconnected?: (info: SocketDisconnect) => void\n /**\n * The server rejected the key during the handshake. Once per rejected\n * HELLO: the first of a run and every 10–15 min retry after it, until one\n * is accepted (`onConnected`). The state is `blocked` by the time it fires.\n */\n onBlocked?: (info: SocketBlocked) => void\n /** Every notice the SDK surfaces (transport errors, watchdog trips, the long-outage and rejection notices, handler failures). */\n onError?: (error: Error) => void\n onStateChanged?: (next: SocketState, prev: SocketState) => void\n}\n\nexport interface IntegrationSocketOptions {\n readonly config: AgentchatChannelConfig\n readonly logger: Logger\n readonly handlers?: SocketHandlers\n readonly metrics?: MetricsRecorder\n /**\n * The SDK client for the realtime client's reconnect drain and gap fill.\n * Without it offline envelopes wait for the server's own re-push.\n */\n readonly client?: AgentChatClient\n /** Test seam: build the realtime client. Production constructs the SDK's. */\n readonly createRealtime?: (options: RealtimeOptions) => RealtimeClient\n /** Test seam / polyfill: the WebSocket constructor the SDK uses. */\n readonly webSocket?: typeof globalThis.WebSocket\n readonly now?: () => number\n}\n\nexport interface SocketHealth {\n readonly state: SocketState\n readonly connectedAt: number | null\n readonly counters: {\n readonly frames: number\n readonly selfFiltered: number\n readonly wakes: number\n readonly invites: number\n readonly disconnects: number\n }\n}\n\n/** The SDK realtime options for a channel config: `wss://…` base, the account's backoff, the integration identity. */\nexport function realtimeOptionsFor(config: AgentchatChannelConfig, extra: Pick<IntegrationSocketOptions, 'client' | 'webSocket'> = {}): RealtimeOptions {\n return {\n apiKey: config.apiKey,\n baseUrl: config.apiBase.replace(/^http/, 'ws').replace(/\\/+$/, ''),\n clientIdentity: AGENTCHAT_CLIENT_IDENTITY,\n ackOnReceipt: true,\n reconnect: true,\n reconnectInterval: config.reconnect.initialBackoffMs,\n maxReconnectInterval: config.reconnect.maxBackoffMs,\n ...(extra.client ? { client: extra.client } : {}),\n ...(extra.webSocket ? { webSocket: extra.webSocket } : {}),\n }\n}\n\nexport class IntegrationSocket {\n private readonly config: AgentchatChannelConfig\n private readonly logger: Logger\n private readonly handlers: SocketHandlers\n private readonly metrics: MetricsRecorder\n private readonly client: AgentChatClient | undefined\n private readonly createRealtime: (options: RealtimeOptions) => RealtimeClient\n private readonly webSocket: typeof globalThis.WebSocket | undefined\n private readonly now: () => number\n private readonly selfHandle: string | undefined\n\n private realtime: RealtimeClient | null = null\n /** The SDK's state as last reported through its `state` event; `stopped` is set here only for a stop before any start. */\n private state: SocketState = 'idle'\n private connectedAt: number | null = null\n private stopping = false\n\n private frames = 0\n private selfFiltered = 0\n private wakes = 0\n private invites = 0\n private disconnects = 0\n\n constructor(options: IntegrationSocketOptions) {\n this.config = options.config\n this.logger = options.logger.child({ component: 'socket' })\n this.handlers = options.handlers ?? {}\n this.metrics = options.metrics ?? createNoopMetrics()\n this.client = options.client\n this.createRealtime = options.createRealtime ?? ((opts) => new RealtimeClient(opts))\n this.webSocket = options.webSocket\n this.now = options.now ?? Date.now\n this.selfHandle = this.config.agentHandle?.replace(/^@/, '').toLowerCase()\n this.metrics.setConnectionState(this.state)\n }\n\n /**\n * Open the socket. Idempotent. Resolves once the SDK has started its\n * connect loop; a failure to resolve a WebSocket implementation is logged\n * and left to the SDK's own retry. Never throws.\n */\n async start(): Promise<void> {\n if (this.realtime || this.stopping) return\n const realtime = this.createRealtime(realtimeOptionsFor(this.config, { client: this.client, webSocket: this.webSocket }))\n this.realtime = realtime\n this.bind(realtime)\n try {\n await realtime.connect()\n } catch (err) {\n this.logger.warn({ err: describe(err) }, 'socket connect failed — the SDK retries on its own schedule')\n }\n }\n\n /** Close the socket for good; a stopped socket does not reconnect. Idempotent. */\n async stop(): Promise<void> {\n this.stopping = true\n const realtime = this.realtime\n this.realtime = null\n this.connectedAt = null\n if (realtime) {\n try {\n // `disconnect()` is the SDK's only way into `stopped`; its state event\n // carries the transition to the gateway like every other.\n realtime.disconnect()\n } catch (err) {\n this.logger.warn({ err: describe(err) }, 'socket disconnect threw — continuing')\n }\n }\n if (this.state !== 'stopped') this.onState('stopped', this.state)\n }\n\n getHealth(): SocketHealth {\n return {\n state: this.state,\n connectedAt: this.connectedAt,\n counters: { frames: this.frames, selfFiltered: this.selfFiltered, wakes: this.wakes, invites: this.invites, disconnects: this.disconnects },\n }\n }\n\n // ─── Internals ─────────────────────────────────────────────────────\n\n private bind(realtime: RealtimeClient): void {\n realtime.on('state', (next, prev) => this.onState(next, prev))\n\n realtime.onConnect(() => {\n const at = this.now()\n this.connectedAt = at\n this.logger.info({ at: new Date(at).toISOString() }, 'connected (HELLO accepted)')\n this.guard('onConnected', () => this.handlers.onConnected?.(at))\n // Whatever landed while the socket was down is on the tray now; the\n // connect itself is the wake that covers the gap.\n this.wake('connect', {})\n })\n\n realtime.onDisconnect((info) => {\n if (this.stopping) return\n this.disconnects += 1\n this.connectedAt = null\n this.metrics.incDisconnect({ code: String(info.code), initiator: info.initiator })\n this.logger.info({ code: info.code, reason: info.reason, initiator: info.initiator }, 'socket closed — the SDK decides what follows (backoff or blocked)')\n this.guard('onDisconnected', () => this.handlers.onDisconnected?.(info))\n })\n\n realtime.on('blocked', (info) => {\n if (this.stopping) return\n // One rejected HELLO: the SDK's typed event is what counts it.\n this.metrics.incError({ errorClass: 'auth' })\n this.logger.warn(\n { code: info.code, reason: info.reason, retryInMs: info.retryInMs },\n 'the server rejected the key during the handshake — the SDK retries a fresh HELLO on its own',\n )\n this.guard('onBlocked', () => this.handlers.onBlocked?.(info))\n })\n\n realtime.onError((error) => {\n if (this.stopping) return\n if (realtime.state === 'blocked') {\n // The SDK's one rejection notice per blocked run is emitted between\n // its `blocked` state and the `blocked` event that carries the code\n // and reason; the event is what the gateway reports and the metric\n // counts, so the notice itself is a debug line here, not a second\n // signal for the same rejection.\n this.logger.debug({ err: error.message }, 'SDK notice while blocked')\n return\n }\n this.metrics.incError({ errorClass: classifyRealtimeError(error) })\n this.logger.debug({ err: error.message }, 'socket error')\n this.guard('onError', () => this.handlers.onError?.(error))\n })\n\n realtime.on('message.new', (message) => this.onMessageNew(message))\n realtime.on('wake', (frame) => this.onWakeFrame(frame))\n realtime.on('group.invite.received', (message) => this.onInvite(message))\n }\n\n private onMessageNew(message: WsMessage): void {\n this.frames += 1\n const payload = message.payload ?? {}\n const senderRaw = payload.sender ?? payload.from ?? ''\n const sender = typeof senderRaw === 'string' ? senderRaw.replace(/^@/, '').toLowerCase() : ''\n const detail: WakeDetail = {\n ...(typeof payload.conversation_id === 'string' ? { conversationId: payload.conversation_id } : {}),\n ...(typeof payload.id === 'string' ? { messageId: payload.id } : {}),\n ...(sender ? { from: sender } : {}),\n }\n if (this.selfHandle && sender === this.selfHandle) {\n // Server-side fan-out echoes our own sends back; our own words never wake us.\n this.selfFiltered += 1\n this.logger.debug(detail, 'own echo — not a wake')\n return\n }\n this.logger.debug(detail, 'wake — message.new')\n this.wake('message', detail)\n }\n\n private onWakeFrame(frame: WakeFrame): void {\n this.frames += 1\n const reason: unknown = frame.payload?.reason\n const detail: WakeDetail = { conversationId: frame.payload.conversation_id }\n this.logger.info({ ...detail, reason, step: frame.payload.step }, 'wake — server wake frame')\n this.wake(wakeSourceOf(reason), detail)\n }\n\n private onInvite(message: WsMessage): void {\n this.frames += 1\n const invite = groupInviteFromRecord(message.payload)\n if (!invite) {\n this.logger.warn({ keys: Object.keys(message.payload ?? {}).sort() }, 'group.invite.received without ids — dropped')\n return\n }\n this.invites += 1\n this.guard('onGroupInvite', () => this.handlers.onGroupInvite?.(invite))\n }\n\n private wake(source: WakeSource, detail: WakeDetail): void {\n this.wakes += 1\n this.metrics.incWake({ source })\n this.guard('onWake', () => this.handlers.onWake?.(source, detail))\n }\n\n /** The SDK's state transition, mirrored for the health probe and the gauge, then handed on. */\n private onState(next: SocketState, prev: SocketState): void {\n this.state = next\n this.metrics.setConnectionState(next)\n this.logger.debug({ from: prev, to: next }, 'socket state')\n this.guard('onStateChanged', () => this.handlers.onStateChanged?.(next, prev))\n }\n\n /** A failing handler never takes the socket down; the next frame wakes again and the tray keeps the cards. */\n private guard(name: string, fn: () => void): void {\n try {\n fn()\n } catch (err) {\n this.logger.error({ err: describe(err), handler: name }, 'handler threw — continuing')\n }\n }\n}\n\n/**\n * Low-cardinality class for the error metric, for the notices the SDK\n * surfaces through `onError`. A rejected key is not among them: that is the\n * SDK's `blocked` event, counted as `auth` where it fires.\n */\nexport function classifyRealtimeError(error: Error): 'transport' | 'handler' | 'protocol' | 'other' {\n const message = error.message\n if (/handler failed/i.test(message)) return 'handler'\n if (/failed validation|not an object|expected a bare array/i.test(message)) return 'protocol'\n if (error.name === 'ConnectionError' || /websocket|hello|handshake|liveness|reconnecting|sync drain|sync ack/i.test(message)) return 'transport'\n return 'other'\n}\n\nfunction describe(err: unknown): string {\n return err instanceof Error ? err.message : String(err)\n}\n","/**\n * Per-account integration registry.\n *\n * OpenClaw's gateway starts one integration per `(channelId, accountId)` pair\n * at channel enable and stops it on shutdown. The registry holds the live\n * socket, its invoker and the texts store so the status adapter can report\n * them, and serializes start/stop per account so a start-during-stop never\n * races.\n *\n * Keying is `accountId`-only; `channelId` is always `\"agentchat\"` here.\n */\n\nimport type { Logger } from '../log.js'\nimport type { AgentchatChannelConfig } from '../config-schema.js'\nimport { IntegrationSocket, type IntegrationSocketOptions, type SocketHandlers } from '../integration/socket.js'\nimport type { AgentInvoker } from '../integration/invoker.js'\nimport type { TextsStore } from '../integration/texts.js'\nimport type { MetricsRecorder } from '../metrics.js'\n\nexport interface IntegrationEntry {\n readonly socket: IntegrationSocket\n readonly invoker: AgentInvoker | null\n readonly texts: TextsStore | null\n /** The recorder the socket (and the invoker) count into; the status probe reads its snapshot when it keeps one. */\n readonly metrics: MetricsRecorder | null\n readonly config: AgentchatChannelConfig\n readonly logger: Logger\n}\n\nconst registry = new Map<string, IntegrationEntry>()\n\n/** Per-account mutex: every register/unregister for the same account runs through this queue. */\nconst accountLocks = new Map<string, Promise<unknown>>()\n\nfunction withAccountLock<T>(accountId: string, op: () => Promise<T>): Promise<T> {\n const prev = accountLocks.get(accountId) ?? Promise.resolve()\n const next = prev.catch(() => undefined).then(op)\n accountLocks.set(accountId, next)\n next.then(\n () => {\n if (accountLocks.get(accountId) === next) accountLocks.delete(accountId)\n },\n () => {\n if (accountLocks.get(accountId) === next) accountLocks.delete(accountId)\n },\n )\n return next\n}\n\nexport interface RegisterIntegrationParams {\n readonly accountId: string\n readonly config: AgentchatChannelConfig\n readonly logger: Logger\n /** Builds the invoker and the handlers that feed it, given the socket that will be started. */\n readonly build: (socket: IntegrationSocket) => { invoker: AgentInvoker | null; texts?: TextsStore | null; handlers: SocketHandlers }\n /** Extra socket options (the SDK client for the reconnect drain, a WebSocket seam). */\n readonly socketOptions?: Pick<IntegrationSocketOptions, 'client' | 'webSocket' | 'metrics' | 'createRealtime'>\n /** Test seam for the socket constructor. */\n readonly createSocket?: (options: IntegrationSocketOptions) => IntegrationSocket\n}\n\n/**\n * Create and start an integration for `accountId`. If one is already\n * registered, stop it first (config change path). Returns the live entry.\n */\nexport function registerIntegration(params: RegisterIntegrationParams): Promise<IntegrationEntry> {\n return withAccountLock(params.accountId, async () => {\n const existing = registry.get(params.accountId)\n if (existing) {\n await stopEntry(existing)\n registry.delete(params.accountId)\n }\n\n // The handlers close over the socket and the socket over the handlers;\n // a late-bound reference resolves the cycle. The socket cannot deliver a\n // frame before `start()`, so the reference is set before any handler runs.\n let built: { invoker: AgentInvoker | null; texts?: TextsStore | null; handlers: SocketHandlers } | null = null\n const handlers: SocketHandlers = {\n onWake: (source, detail) => built?.handlers.onWake?.(source, detail),\n onGroupInvite: (invite) => built?.handlers.onGroupInvite?.(invite),\n onConnected: (at) => built?.handlers.onConnected?.(at),\n onDisconnected: (info) => built?.handlers.onDisconnected?.(info),\n onBlocked: (info) => built?.handlers.onBlocked?.(info),\n onError: (error) => built?.handlers.onError?.(error),\n onStateChanged: (next, prev) => built?.handlers.onStateChanged?.(next, prev),\n }\n const create = params.createSocket ?? ((options) => new IntegrationSocket(options))\n const socket = create({ config: params.config, logger: params.logger, handlers, ...(params.socketOptions ?? {}) })\n built = params.build(socket)\n\n const entry: IntegrationEntry = {\n socket,\n invoker: built.invoker,\n texts: built.texts ?? null,\n metrics: params.socketOptions?.metrics ?? null,\n config: params.config,\n logger: params.logger,\n }\n registry.set(params.accountId, entry)\n try {\n await socket.start()\n } catch (err) {\n registry.delete(params.accountId)\n built.invoker?.stop()\n built.texts?.stop()\n throw err\n }\n return entry\n })\n}\n\n/** Stop and remove the integration for `accountId`. No-op if absent. */\nexport function unregisterIntegration(accountId: string): Promise<void> {\n return withAccountLock(accountId, async () => {\n const entry = registry.get(accountId)\n if (!entry) return\n registry.delete(accountId)\n await stopEntry(entry)\n })\n}\n\nasync function stopEntry(entry: IntegrationEntry): Promise<void> {\n entry.invoker?.stop()\n entry.texts?.stop()\n try {\n await entry.socket.stop()\n } catch (err) {\n entry.logger.error({ err: err instanceof Error ? err.message : String(err) }, 'socket.stop threw during unregister')\n }\n}\n\nexport function getIntegration(accountId: string): IntegrationEntry | undefined {\n return registry.get(accountId)\n}\n\nexport function listActiveAccounts(): string[] {\n return [...registry.keys()]\n}\n\n/** Test hook only. */\nexport async function resetRegistryForTest(): Promise<void> {\n const entries = [...registry.values()]\n registry.clear()\n await Promise.all(entries.map((entry) => stopEntry(entry).catch(() => undefined)))\n}\n","/**\n * Wake coalescing — one gate cycle per burst, not per frame.\n *\n * A `message.new` frame, a `wake` frame and a successful connect are all\n * wakes: a hint that the tray changed, never the carrier of what changed. A\n * group burst arrives as many frames seconds apart; the server already\n * bundles its webhook wakes for such bursts, and the integration does the\n * same for the socket. The window is trailing-edge: every wake restarts it,\n * so the cycle fires `debounceMs` after the LAST wake of the burst — with a\n * hard cap: no later than `maxWindowMs` after the FIRST wake, so a steady\n * trickle cannot starve the gate. Whoever fires then reads the whole tray,\n * so nothing a later frame announced is missed — the tray is the truth, the\n * wake is not.\n *\n * `wakeAfter` serves the local retry ladder: when a gate cycle could not\n * complete (model unreachable, server error, turn refused) the invoker\n * schedules another wake later instead of dropping the tray. The server's\n * own ladder only rings webhooks; a connected socket gets no re-wake, so the\n * integration carries that duty itself. When a delayed wake is already\n * pending the SOONER deadline wins — a later retry never pushes an earlier\n * one back.\n */\n\nexport const DEFAULT_DEBOUNCE_MS = 2_000\n/** A burst fires at most this long after its first wake, however many wakes keep landing. */\nexport const DEFAULT_MAX_WINDOW_MS = 6_000\n\nexport interface WakeCoalescerOptions {\n readonly onFire: () => void\n /** Called when a delayed (retry-ladder) wake fires, before it is counted like any other wake. */\n readonly onDelayedWake?: () => void\n readonly debounceMs?: number\n readonly maxWindowMs?: number\n readonly now?: () => number\n readonly setTimeout?: (fn: () => void, ms: number) => NodeJS.Timeout\n readonly clearTimeout?: (handle: NodeJS.Timeout) => void\n}\n\nexport class WakeCoalescer {\n private readonly onFire: () => void\n private readonly onDelayedWake: (() => void) | undefined\n private readonly debounceMs: number\n private readonly maxWindowMs: number\n private readonly now: () => number\n private readonly _setTimeout: (fn: () => void, ms: number) => NodeJS.Timeout\n private readonly _clearTimeout: (handle: NodeJS.Timeout) => void\n\n private timer: NodeJS.Timeout | null = null\n private burstStartedAt: number | null = null\n private delayed: NodeJS.Timeout | null = null\n private delayedDeadline: number | null = null\n private stopped = false\n\n wakes = 0\n absorbed = 0\n fires = 0\n\n constructor(options: WakeCoalescerOptions) {\n const debounce = options.debounceMs ?? DEFAULT_DEBOUNCE_MS\n if (!(debounce >= 0)) throw new RangeError('debounceMs must be >= 0')\n const maxWindow = options.maxWindowMs ?? DEFAULT_MAX_WINDOW_MS\n if (!(maxWindow >= debounce)) throw new RangeError('maxWindowMs must be >= debounceMs')\n this.onFire = options.onFire\n this.onDelayedWake = options.onDelayedWake\n this.debounceMs = debounce\n this.maxWindowMs = maxWindow\n this.now = options.now ?? Date.now\n this._setTimeout = options.setTimeout ?? ((fn, ms) => setTimeout(fn, ms))\n this._clearTimeout = options.clearTimeout ?? ((h) => clearTimeout(h))\n }\n\n /** True while a debounce timer is armed. */\n get armed(): boolean {\n return this.timer !== null\n }\n\n /** True while a retry wake is scheduled and has not fired. */\n get delayedPending(): boolean {\n return this.delayed !== null\n }\n\n /**\n * A wake. The first one of a burst arms the window; every later one is\n * absorbed and restarts it (trailing edge), never past the burst's cap.\n */\n wake(): void {\n if (this.stopped) return\n this.wakes += 1\n const now = this.now()\n if (this.timer === null) {\n this.burstStartedAt = now\n this.timer = this._setTimeout(() => this.fire(), this.debounceMs)\n return\n }\n this.absorbed += 1\n const capAt = (this.burstStartedAt ?? now) + this.maxWindowMs\n const delay = Math.max(0, Math.min(this.debounceMs, capAt - now))\n this._clearTimeout(this.timer)\n this.timer = this._setTimeout(() => this.fire(), delay)\n }\n\n /** A delayed wake (retry ladder). The sooner pending deadline is kept. */\n wakeAfter(delayMs: number): void {\n if (this.stopped) return\n const delay = Math.max(0, delayMs)\n const deadline = this.now() + delay\n if (this.delayed !== null) {\n if (this.delayedDeadline !== null && this.delayedDeadline <= deadline) {\n return // an earlier retry is already on its way; keep it\n }\n this._clearTimeout(this.delayed)\n }\n this.delayedDeadline = deadline\n this.delayed = this._setTimeout(() => {\n this.delayed = null\n this.delayedDeadline = null\n if (this.stopped) return\n try {\n this.onDelayedWake?.()\n } catch {\n // observers never block the wake\n }\n this.wake()\n }, delay)\n }\n\n /** Cancel everything; later wakes are ignored. */\n stop(): void {\n this.stopped = true\n if (this.timer !== null) {\n this._clearTimeout(this.timer)\n this.timer = null\n this.burstStartedAt = null\n }\n if (this.delayed !== null) {\n this._clearTimeout(this.delayed)\n this.delayed = null\n this.delayedDeadline = null\n }\n }\n\n private fire(): void {\n this.timer = null\n this.burstStartedAt = null\n if (this.stopped) return\n this.fires += 1\n try {\n this.onFire()\n } catch {\n // The callback belongs to the invoker; a failure there must not kill\n // the timer machinery. The next wake re-arms as usual.\n }\n }\n}\n","/**\n * Wake → gate → turn. The only path from the socket to the agent.\n *\n * What happens on a wake\n * ──────────────────────\n * 1. **Coalesce.** Frames inside a short window become one wake\n * (`WakeCoalescer`). A group waking up is one cycle, not twenty.\n * 2. **Read the tray.** `client.inbox.tray()` — the server's briefing cards\n * and its gate question, as it built them.\n * 3. **Gate.** The SDK's gate helper renders the question and the cards,\n * asks the agent's own model (`callModel`, a tool-free completion through\n * `runtime.llm.complete`) and records `dismiss` / `defer` with the card's\n * anchor. `reply` comes back as entries the invoker records itself.\n * 4. **Turn.** For every conversation decided `reply`, start ONE OpenClaw\n * agent turn (`runtime.subagent.run`, `deliver: false`) with the served\n * wake instruction and the conversation id. The `reply` verdict is\n * recorded when the run has COMPLETED (`status: ok`) — never at its\n * start: recorded at admission it marked the conversation read before\n * the turn's own inbox call, which then waited on an empty tray, and a\n * turn that crashed left the peer with a read receipt and no answer. A\n * completed turn counts as read even if it chose not to send. A turn\n * OpenClaw refuses, or one that ends in error or on the wait timeout,\n * records nothing: the conversation stays unread, the card stays on the\n * tray, and the ladder re-wakes so it is gated again (one more gate\n * call, no silent drop). The turn's final text is discarded — nothing is\n * auto-routed anywhere.\n *\n * One cycle at a time per account: a wake that lands while a cycle runs is\n * remembered and runs once the cycle ends (the tray is re-read, so whatever\n * the earlier wake announced is covered). A cycle ends when its turns are\n * ADMITTED, not when they finish: OpenClaw serializes the turns on the\n * account's lane (`integrationLane`), so the next cycle's turn simply queues\n * behind, and holding the wake loop for up to 15 minutes per turn would only\n * delay the next tray read. Completion is logged as it happens. A cycle\n * that could not complete — model unreachable, server error, turn refused —\n * re-wakes itself on a local ladder (1 m, 5 m, 30 m) because a connected\n * socket gets no re-wake from the server; the cards wait on the tray\n * meanwhile. One outage climbs the ladder one rung: a retry already on its\n * way is never replaced by a later one.\n *\n * Group invites are a second wake kind: not on the tray, not gated, one turn\n * each with the served invite prompt, serialized on the same worker. An\n * invite whose turn OpenClaw refused stays pending and is tried again on the\n * next wake; one that started is remembered on disk (`InviteLedger`) so a\n * restart never offers it twice.\n */\n\nimport { gate, type AgentChatClient, type GateReply, type InboxTray, type Texts } from 'agentchatme'\n\nimport type { Logger } from '../log.js'\nimport type { MetricsRecorder } from '../metrics.js'\nimport { createNoopMetrics } from '../metrics.js'\nimport { WakeCoalescer, DEFAULT_DEBOUNCE_MS } from './wake.js'\nimport type { GateModelCall, TurnStarter, TurnOutcome, TurnAdmission, TurnReadiness } from './model.js'\nimport type { GroupInvite } from './invites.js'\nimport { OPENCLAW_TOOL_NAMER, integrationLane, inviteSessionKey, inviteTurnPrompt, wakeSessionKey, wakeTurnPrompt } from './turn.js'\n\n/**\n * Local re-wake ladder after a cycle that could not complete. Mirrors the\n * server's webhook ladder (1 m, 5 m, 30 m) — a connected socket never gets\n * that re-wake, so the integration carries it. After the last rung the cycle\n * waits for the next wake; the cards are still on the tray.\n */\nexport const RETRY_LADDER_MS: readonly number[] = [60_000, 300_000, 1_800_000]\n\n/**\n * Where a wake came from — a closed set, because it is a metric label:\n * `message` (a peer wrote), `connect` (an accepted HELLO), `reminder` (the\n * server's wake frame for a deferred conversation), `retry` (the local\n * ladder), `other` (a server wake with a reason this version does not know).\n */\nexport type WakeSource = 'message' | 'connect' | 'reminder' | 'retry' | 'other'\n\n/** The two SDK resources a cycle uses; `AgentChatClient` satisfies it. */\nexport type InvokerClient = Pick<AgentChatClient, 'inbox' | 'decisions'>\n\n/** The served texts as the invoker sees them: the current copy, or one attempt to get it. */\nexport interface TextsSource {\n readonly current: Texts | null\n ensure(): Promise<Texts | null>\n}\n\n/** Which invites already got their turn (persisted across restarts). */\nexport interface InviteStore {\n isOffered(inviteId: string): boolean\n markOffered(inviteId: string): void\n}\n\nexport interface AgentInvokerOptions {\n readonly accountId: string\n readonly agentId: string\n readonly client: InvokerClient\n readonly callModel: GateModelCall\n readonly startTurn: TurnStarter\n readonly texts: TextsSource\n readonly invites: InviteStore\n readonly logger: Logger\n /** Counts the ladder's re-wakes (`agentchat_channel_wake_total{source=\"retry\"}`). The socket counts the others. */\n readonly metrics?: MetricsRecorder\n /**\n * Whether a turn started now can have the hosted tools (`turnReadiness`).\n * Checked before the gate: while unready nothing is gated — the cards\n * stay on the tray, no model call is spent, no turn starts — and the\n * ladder re-wakes. Default: always ready.\n */\n readonly readiness?: () => TurnReadiness\n /** `false`: no gate step — one turn per cycle with the served wake instruction; the agent judges in-turn. */\n readonly gateEnabled?: boolean\n readonly debounceMs?: number\n readonly retryLadderMs?: readonly number[]\n readonly now?: () => number\n readonly setTimeout?: (fn: () => void, ms: number) => NodeJS.Timeout\n readonly clearTimeout?: (handle: NodeJS.Timeout) => void\n}\n\nexport interface InvokerCounters {\n readonly cycles: number\n readonly turns: number\n readonly inviteTurns: number\n /** Turns admitted whose run has not ended yet (OpenClaw's lane serializes them). */\n readonly turnsInFlight: number\n readonly wakes: number\n readonly absorbed: number\n readonly retryRung: number\n readonly pendingInvites: number\n}\n\nexport type CycleOutcome =\n /** The tray had no cards. */\n | 'empty'\n /** The gate decided; turns were started for the replies. */\n | 'decided'\n /** The model failed or answered nothing usable; nothing recorded, no turn. */\n | 'fail_closed'\n /** The gate is off; one turn with the served wake instruction. */\n | 'gate_off'\n /** The tray could not be read. */\n | 'tray_failed'\n /** The served texts are not available yet; nothing gated, the cards wait. */\n | 'texts_missing'\n /** A turn could not have the hosted tools; nothing gated, no model call, the cards wait. */\n | 'tools_unavailable'\n\nexport interface CycleResult {\n readonly outcome: CycleOutcome\n readonly cards: number\n readonly reply: number\n readonly dismiss: number\n readonly defer: number\n readonly undecided: number\n /** `dismiss` / `defer` the server took in this cycle. `reply` verdicts are recorded as their turns complete, after the cycle. */\n readonly recorded: number\n readonly recordFailures: number\n readonly turnsStarted: number\n readonly turnsRefused: number\n /** Cards left out of this cycle because a reply turn for their conversation is still running. */\n readonly skippedInFlight: number\n readonly truncated: boolean\n readonly latencyMs: number\n readonly failure: string | null\n}\n\ntype RetryPlan = { readonly kind: 'armed'; readonly delayMs: number; readonly rung: number } | { readonly kind: 'pending' } | { readonly kind: 'exhausted' }\n\nexport class AgentInvoker {\n private readonly accountId: string\n private readonly agentId: string\n private readonly client: InvokerClient\n private readonly callModel: GateModelCall\n private readonly startTurn: TurnStarter\n private readonly texts: TextsSource\n private readonly invites: InviteStore\n private readonly logger: Logger\n private readonly metrics: MetricsRecorder\n private readonly readiness: () => TurnReadiness\n private readonly gateEnabled: boolean\n private readonly ladder: readonly number[]\n private readonly now: () => number\n private readonly coalescer: WakeCoalescer\n\n private cycleDue = false\n private running: Promise<void> | null = null\n private stopped = false\n private pendingInvites: GroupInvite[] = []\n private invitesDirty = false\n private retryRung = 0\n private turnsInFlight = 0\n /**\n * Conversations whose reply turn is running. Their verdict is recorded\n * only when the turn completes, so the card stays on the tray meanwhile\n * and every wake in between would re-gate it and queue a second turn.\n * Such cards are left out of the cycle; once the turn ends the tray is\n * read again if any were.\n */\n private readonly replyTurnsInFlight = new Set<string>()\n private skippedWhileInFlight = false\n /** The reason the tools were last found unavailable; logged when it changes, not per wake. */\n private unreadyReason: string | null = null\n\n cycles = 0\n turns = 0\n inviteTurns = 0\n\n constructor(options: AgentInvokerOptions) {\n this.accountId = options.accountId\n this.agentId = options.agentId\n this.client = options.client\n this.callModel = options.callModel\n this.startTurn = options.startTurn\n this.texts = options.texts\n this.invites = options.invites\n this.logger = options.logger.child({ component: 'integration', accountId: options.accountId })\n this.metrics = options.metrics ?? createNoopMetrics()\n this.readiness = options.readiness ?? (() => ({ ready: true }))\n this.gateEnabled = options.gateEnabled ?? true\n this.ladder = options.retryLadderMs ?? RETRY_LADDER_MS\n this.now = options.now ?? Date.now\n this.coalescer = new WakeCoalescer({\n onFire: () => this.onWakeFired(),\n onDelayedWake: () => {\n this.logger.debug({ source: 'retry' }, 'wake')\n this.metrics.incWake({ source: 'retry' })\n },\n debounceMs: options.debounceMs ?? DEFAULT_DEBOUNCE_MS,\n now: this.now,\n ...(options.setTimeout ? { setTimeout: options.setTimeout } : {}),\n ...(options.clearTimeout ? { clearTimeout: options.clearTimeout } : {}),\n })\n }\n\n // ─── wakes ──────────────────────────────────────────────────────────\n\n /** A wake from the socket (a frame, a connect, a reminder) or any other source. Coalesced, then cycled. */\n wake(source: WakeSource): void {\n if (this.stopped) return\n this.logger.debug({ source }, 'wake')\n this.coalescer.wake()\n }\n\n /**\n * The second wake kind. An invite already offered (this process or an\n * earlier one, per the ledger) or already pending is ignored, so an\n * invite seen live and again on a connect-time catch-up is decided once.\n * Returns true when newly queued.\n */\n groupInvite(invite: GroupInvite, source: string): boolean {\n if (this.stopped) return false\n if (this.invites.isOffered(invite.inviteId)) return false\n if (this.pendingInvites.some((pending) => pending.inviteId === invite.inviteId)) return false\n this.logger.info(\n { groupId: invite.groupId, groupName: invite.groupName, inviter: invite.inviterHandle, inviteId: invite.inviteId, source },\n 'group invite — queuing one invite turn',\n )\n this.pendingInvites.push(invite)\n this.invitesDirty = true\n this.schedule()\n return true\n }\n\n /** Cancel timers; a cycle in flight finishes on its own. */\n stop(): void {\n this.stopped = true\n this.coalescer.stop()\n }\n\n /** The promise of the work currently running, for tests and for graceful stops. */\n settled(): Promise<void> {\n return this.running ?? Promise.resolve()\n }\n\n counters(): InvokerCounters {\n return {\n cycles: this.cycles,\n turns: this.turns,\n inviteTurns: this.inviteTurns,\n turnsInFlight: this.turnsInFlight,\n wakes: this.coalescer.wakes,\n absorbed: this.coalescer.absorbed,\n retryRung: this.retryRung,\n pendingInvites: this.pendingInvites.length,\n }\n }\n\n // ─── worker ─────────────────────────────────────────────────────────\n\n private onWakeFired(): void {\n this.cycleDue = true\n // A wake is also the moment to retry invites whose turn OpenClaw refused.\n if (this.pendingInvites.length > 0) this.invitesDirty = true\n this.schedule()\n }\n\n /** Run the worker if idle. One cycle at a time; work that lands mid-cycle runs afterwards. */\n private schedule(): void {\n if (this.running) return\n this.running = this.drain().finally(() => {\n this.running = null\n if (!this.stopped && (this.cycleDue || this.invitesDirty)) this.schedule()\n })\n }\n\n private async drain(): Promise<void> {\n while (!this.stopped) {\n if (this.invitesDirty) {\n this.invitesDirty = false\n await this.runInviteTurns()\n continue\n }\n if (this.cycleDue) {\n // Clear BEFORE the cycle: a wake landing during the cycle sets it\n // again and earns one more cycle afterwards.\n this.cycleDue = false\n try {\n await this.runCycle()\n } catch (err) {\n // Whatever escaped the cycle must not kill the worker. Re-wake on\n // the ladder so the tray is read again.\n this.logger.error({ err: describe(err), ...this.retry() }, 'cycle failed with an unhandled error — re-waking later')\n }\n continue\n }\n return\n }\n }\n\n // ─── one cycle ──────────────────────────────────────────────────────\n\n /** Read the tray, gate it, start a turn per reply. Public so tests can drive one cycle. */\n async runCycle(): Promise<CycleResult> {\n this.cycles += 1\n const started = this.now()\n let tray: InboxTray\n try {\n tray = await this.client.inbox.tray({ waitMs: 0 })\n } catch (err) {\n this.logger.warn({ err: describe(err), ...this.retry() }, 'tray read failed — re-waking later')\n return this.result('tray_failed', 0, false, started, describe(err))\n }\n\n const allCards = gate.cardsOf(tray)\n const truncated = tray.truncated === true\n if (allCards.length === 0) {\n this.logger.info({ deferred: tray.deferred ?? 0 }, 'tray empty — nothing to decide')\n this.retryRung = 0\n return this.result('empty', 0, truncated, started)\n }\n\n // A card whose reply turn is still running is that turn's to answer;\n // gating it again would queue a second turn. It is left out here and\n // the tray is read again once the turn ends (see `admitted`).\n const cards = allCards.filter((card) => !this.replyTurnsInFlight.has(card.conversation_id))\n const skippedInFlight = allCards.length - cards.length\n if (skippedInFlight > 0) this.skippedWhileInFlight = true\n if (cards.length === 0) {\n this.logger.info({ skippedInFlight }, 'every card on the tray has a reply turn running — nothing new to decide')\n return { ...this.result('empty', 0, truncated, started), skippedInFlight }\n }\n\n // The turn text is served, never bundled. Without it no turn can start,\n // so nothing is gated either: the cards wait, and the next copy (retried\n // by the texts store) or the next wake tries again.\n const texts = await this.texts.ensure()\n if (!texts) {\n this.logger.warn({ cards: cards.length, ...this.retry() }, 'served texts not available — not gating; the cards wait on the tray')\n return { ...this.result('texts_missing', cards.length, truncated, started, 'texts missing'), skippedInFlight }\n }\n\n // A turn that cannot have the hosted tools is not worth a gate call:\n // nothing is asked, nothing recorded, the cards wait, the ladder\n // re-wakes. The reason is logged when it changes, not on every rung.\n const readiness = this.readiness()\n if (!readiness.ready) {\n const changed = this.unreadyReason !== readiness.reason\n this.unreadyReason = readiness.reason\n this.logger[changed ? 'warn' : 'debug']({ cards: cards.length, reason: readiness.reason, ...this.retry() }, 'AgentChat tools not available to a turn — not gating; the cards wait on the tray')\n return { ...this.result('tools_unavailable', cards.length, truncated, started, readiness.reason), skippedInFlight }\n }\n if (this.unreadyReason !== null) {\n this.unreadyReason = null\n this.logger.info({}, 'AgentChat tools available to turns again')\n }\n\n let result: CycleResult\n if (!this.gateEnabled) {\n result = await this.runUngated(cards.length, texts, truncated, started)\n } else {\n const trayToGate: InboxTray = skippedInFlight > 0 ? { ...tray, conversations: cards } : tray\n result = await this.runGated(trayToGate, cards.length, texts, truncated, started, skippedInFlight)\n }\n if (skippedInFlight > 0) result = { ...result, skippedInFlight }\n\n if (truncated && result.outcome !== 'fail_closed') {\n // More conversations are waiting than one tray shows.\n this.logger.info({}, 'tray truncated — waking again for the rest')\n this.coalescer.wake()\n }\n return result\n }\n\n /** Gate off: the agent judges in-turn with the hosted tools. One turn, nothing recorded here. */\n private async runUngated(cards: number, texts: Texts, truncated: boolean, started: number): Promise<CycleResult> {\n this.logger.info({ cards }, 'gate off — starting one turn with the served wake instruction')\n const sessionKey = wakeSessionKey(this.agentId, this.now())\n this.logger.info({ sessionKey }, 'turn start')\n const admission = await this.startTurn({ sessionKey, prompt: wakeTurnPrompt(texts), lane: integrationLane(this.accountId) })\n if (!admission.ran) {\n this.logger.warn({ sessionKey, error: admission.error, ...this.retry() }, 'turn not started — re-waking later')\n } else {\n this.admitted(sessionKey, admission, 'turn complete (final text discarded; the send is a hosted-tool call)')\n this.retryRung = 0\n }\n return {\n ...this.result('gate_off', cards, truncated, started),\n turnsStarted: admission.ran ? 1 : 0,\n turnsRefused: admission.ran ? 0 : 1,\n }\n }\n\n private async runGated(tray: InboxTray, cards: number, texts: Texts, truncated: boolean, started: number, skippedInFlight = 0): Promise<CycleResult> {\n const decided = await gate.run({ tray, callModel: this.callModel, client: this.client, toolNamer: OPENCLAW_TOOL_NAMER })\n const latencyMs = this.now() - started\n const counts = { reply: 0, dismiss: 0, defer: 0 }\n for (const verdict of decided.verdicts) counts[verdict.decision] += 1\n\n if (decided.outcome === 'fail_closed') {\n // Nothing recorded, no turn. The cards stay on the tray; re-wake on\n // the ladder so a transient provider outage does not leave peers\n // unanswered until the next message happens to arrive. One line.\n this.logger.warn({ cards, failure: decided.failure, latencyMs, ...this.retry() }, 'gate failed closed — nothing recorded, no turn started')\n return { ...this.result('fail_closed', cards, truncated, started, decided.failure), undecided: cards, latencyMs }\n }\n if (decided.outcome === 'empty') {\n this.retryRung = 0\n return this.result('empty', cards, truncated, started)\n }\n\n // One turn per conversation decided reply. The verdict is recorded when\n // the run has completed (see `admitted`) — never here, at its start: a\n // refused, crashed or timed-out turn records nothing, the card stays on\n // the tray, and the ladder re-wakes so it is gated again. The cycle does\n // not wait for the runs to end: the lane serializes them.\n let turnsStarted = 0\n let turnsRefused = 0\n const recordFailures = decided.recordFailures.length\n const recorded = decided.recorded\n for (const entry of decided.reply) {\n if (this.replyTurnsInFlight.has(entry.conversationId)) {\n // Its card was left out of the tray the gate saw; a verdict for it\n // can only be the model naming a conversation it was not shown.\n this.skippedWhileInFlight = true\n continue\n }\n const sessionKey = wakeSessionKey(this.agentId, this.now())\n this.logger.info({ sessionKey, conversationId: entry.conversationId }, 'turn start')\n const admission = await this.startTurn({ sessionKey, prompt: wakeTurnPrompt(texts, entry.conversationId), lane: integrationLane(this.accountId) })\n if (!admission.ran) {\n turnsRefused += 1\n this.logger.warn({ sessionKey, conversationId: entry.conversationId, error: admission.error }, 'turn not started — reply not recorded; the conversation stays unread')\n continue\n }\n turnsStarted += 1\n this.replyTurnsInFlight.add(entry.conversationId)\n this.admitted(sessionKey, admission, 'turn complete (final text discarded; the send is a hosted-tool call)', entry)\n }\n\n const summary = {\n cards,\n reply: counts.reply,\n dismiss: counts.dismiss,\n defer: counts.defer,\n undecided: decided.undecided.length,\n recorded,\n recordFailures,\n turnsStarted,\n turnsRefused,\n skippedInFlight,\n latencyMs,\n }\n if (turnsRefused > 0) {\n this.logger.warn({ ...summary, ...this.retry() }, 'gate — some turns were refused; re-waking later')\n } else if (recordFailures > 0 || decided.undecided.length > 0) {\n // Some cards were not settled (verdict rejected, or the model skipped\n // them). They are still on the tray; look again later.\n this.logger.warn({ ...summary, ...this.retry() }, 'gate — cards left on the tray; re-waking later')\n } else {\n this.retryRung = 0\n this.logger.info(summary, 'gate')\n }\n return { ...this.result('decided', cards, truncated, started), ...summary }\n }\n\n private result(outcome: CycleOutcome, cards: number, truncated: boolean, started: number, failure: string | null = null): CycleResult {\n return {\n outcome,\n cards,\n reply: 0,\n dismiss: 0,\n defer: 0,\n undecided: 0,\n recorded: 0,\n recordFailures: 0,\n turnsStarted: 0,\n turnsRefused: 0,\n skippedInFlight: 0,\n truncated,\n latencyMs: this.now() - started,\n failure,\n }\n }\n\n /** Arm the next rung (or report why not). Returned as log fields so every caller writes ONE line. */\n private retry(): { retry: RetryPlan } {\n if (this.coalescer.delayedPending) {\n // A retry is already on its way (a wake landed mid-outage and failed\n // again). One outage climbs the ladder once; climbing per failed cycle\n // would replace the sooner retry with a later one.\n return { retry: { kind: 'pending' } }\n }\n if (this.retryRung >= this.ladder.length) {\n return { retry: { kind: 'exhausted' } }\n }\n const delayMs = this.ladder[this.retryRung] ?? this.ladder[this.ladder.length - 1] ?? 60_000\n this.retryRung += 1\n this.coalescer.wakeAfter(delayMs)\n return { retry: { kind: 'armed', delayMs, rung: this.retryRung } }\n }\n\n // ─── turns ──────────────────────────────────────────────────────────\n\n /**\n * Book an admitted turn and log its end whenever it comes. The cycle moves\n * on at once; OpenClaw's lane keeps the runs of one account in order.\n *\n * For a reply turn the end is also when the `reply` verdict is recorded —\n * only if the run completed (`status: ok`, no error): a turn that looked\n * and chose not to send still counts as read. A run that ended in error,\n * on the wait timeout, or whose wait failed records nothing: the card stays\n * on the tray and the ladder re-wakes so the conversation is gated again.\n */\n private admitted(sessionKey: string, admission: Extract<TurnAdmission, { ran: true }>, completeLine: string, reply?: GateReply): void {\n this.turns += 1\n this.turnsInFlight += 1\n void admission.done.then(\n async (outcome: TurnOutcome) => {\n this.turnsInFlight -= 1\n const completed = outcome.ran && outcome.status === 'ok' && !outcome.error\n this.logger[completed ? 'info' : 'warn'](\n { sessionKey, runId: outcome.runId, status: outcome.status, ...(outcome.error ? { error: outcome.error } : {}) },\n completeLine,\n )\n if (!reply) return\n try {\n if (!completed) {\n this.logger.warn(\n { sessionKey, conversationId: reply.conversationId, status: outcome.status, ...(outcome.error ? { error: outcome.error } : {}), ...this.retry() },\n 'turn did not complete — reply not recorded; the conversation stays unread and is gated again',\n )\n return\n }\n await this.recordReply(sessionKey, reply)\n } finally {\n this.replyTurnEnded(reply.conversationId)\n }\n },\n async (err: unknown) => {\n this.turnsInFlight -= 1\n this.logger.warn({ sessionKey, runId: admission.runId, err: describe(err) }, `${completeLine} — the wait failed`)\n if (reply) {\n this.logger.warn(\n { sessionKey, conversationId: reply.conversationId, err: describe(err), ...this.retry() },\n 'turn did not complete — reply not recorded; the conversation stays unread and is gated again',\n )\n this.replyTurnEnded(reply.conversationId)\n }\n },\n )\n }\n\n /** The reply turn for `conversationId` is over: its card may be gated again, and a tray that held skipped cards is read once more. */\n private replyTurnEnded(conversationId: string): void {\n this.replyTurnsInFlight.delete(conversationId)\n if (this.skippedWhileInFlight && !this.stopped) {\n this.skippedWhileInFlight = false\n this.logger.debug({ conversationId }, 'reply turn ended — re-reading the tray for the cards left out meanwhile')\n this.coalescer.wake()\n }\n }\n\n /** The `reply` verdict for a completed turn. A record the server refuses leaves the conversation unread; the ladder re-wakes. */\n private async recordReply(sessionKey: string, reply: GateReply): Promise<void> {\n try {\n await reply.record()\n this.logger.info({ sessionKey, conversationId: reply.conversationId }, 'reply verdict recorded — turn completed')\n } catch (err) {\n this.logger.warn(\n { sessionKey, conversationId: reply.conversationId, err: describe(err), ...this.retry() },\n 'reply verdict not recorded after the turn completed — the conversation stays unread; the next wake gates it again',\n )\n }\n }\n\n /**\n * Every pending invite gets one attempt. An invite leaves the pending list\n * only once its turn was admitted (and is then remembered in the ledger);\n * a refused one stays there for the next wake. Invites that arrive while\n * this runs are appended and get their pass on the next drain.\n */\n private async runInviteTurns(): Promise<void> {\n const batch = [...this.pendingInvites]\n if (batch.length > 0) {\n // An invite turn needs the hosted tools as much as a reply turn.\n const readiness = this.readiness()\n if (!readiness.ready) {\n const changed = this.unreadyReason !== readiness.reason\n this.unreadyReason = readiness.reason\n this.logger[changed ? 'warn' : 'debug']({ pending: batch.length, reason: readiness.reason, ...this.retry() }, 'AgentChat tools not available to a turn — invite turns wait; re-waking later')\n return\n }\n }\n let texts: Texts | null = null\n let refused = 0\n let waitingForTexts = 0\n for (const invite of batch) {\n if (this.stopped) return\n texts ??= await this.texts.ensure()\n if (!texts) {\n waitingForTexts = batch.length\n break\n }\n const sessionKey = inviteSessionKey(this.agentId, invite.inviteId)\n this.logger.info({ sessionKey, groupId: invite.groupId, inviteId: invite.inviteId }, 'group-invite turn start')\n let admission\n try {\n admission = await this.startTurn({ sessionKey, prompt: inviteTurnPrompt(texts), lane: integrationLane(this.accountId) })\n } catch (err) {\n admission = { ran: false as const, error: describe(err) }\n }\n if (!admission.ran) {\n refused += 1\n this.logger.warn({ sessionKey, inviteId: invite.inviteId, error: admission.error }, 'group-invite turn not started — the invite stays pending; retried on the next wake')\n continue\n }\n this.inviteTurns += 1\n this.invites.markOffered(invite.inviteId)\n this.pendingInvites = this.pendingInvites.filter((pending) => pending.inviteId !== invite.inviteId)\n this.admitted(sessionKey, admission, 'group-invite turn complete')\n }\n if (this.stopped) return\n if (waitingForTexts > 0) {\n this.logger.warn({ pending: waitingForTexts, ...this.retry() }, 'served texts not available — invite turns wait; re-waking later')\n } else if (refused > 0) {\n this.logger.warn({ pending: refused, ...this.retry() }, 'invite turns refused — re-waking later')\n }\n }\n}\n\nfunction describe(err: unknown): string {\n return err instanceof Error ? err.message : String(err)\n}\n","/**\n * ChannelGatewayAdapter — start/stop the integration per account.\n *\n * OpenClaw calls `startAccount` when a configured account is enabled. The\n * integration then:\n *\n * socket frame / connect / wake frame ──► wake ──► coalesce ──► tray ──► gate ──► one turn per reply\n *\n * everything after the wake lives in `../integration/invoker.ts`; this file\n * only wires OpenClaw's context (config, logger, status sink, abort signal,\n * agent routing, the plugin runtime captured by `setRuntime`) to it and\n * keeps the account task pending until OpenClaw aborts it.\n *\n * `AGENTCHAT_WAKE=off` (the old spelling `AGENTCHAT_DOORBELL=off` still\n * works) skips all of it: no socket, no wakes, no turns. The hosted tools\n * and the manual stay placed, so the agent can still use AgentChat when\n * something else wakes it.\n */\n\nimport type { ChannelGatewayAdapter, ChannelGatewayContext } from './openclaw-types.js'\n\nimport type { AgentchatResolvedAccount } from '../channel.js'\nimport { createLogger, type Logger } from '../log.js'\nimport {\n LEGACY_REPLY_GATE_FAIL_OPEN_ENV,\n LEGACY_WAKE_MODE_ENV,\n WAKE_MODE_ENV,\n readLegacyReplyGateFailOpenFromEnv,\n readReplyGateEnabledFromEnv,\n readReplyGateTimeoutMsFromEnv,\n readWakeModeFromEnv,\n} from '../credentials/read-env.js'\nimport { multiAccountRefusal } from '../channel-account.js'\nimport { registerIntegration, unregisterIntegration, getIntegration } from './runtime-registry.js'\nimport { AgentInvoker } from '../integration/invoker.js'\nimport { InviteLedger, groupInviteFromRecord } from '../integration/invites.js'\nimport { TextsStore } from '../integration/texts.js'\nimport { refreshIdentityLine } from '../integration/placement.js'\nimport {\n createRuntimeModelCall,\n createRuntimeTurnStarter,\n resolveIntegrationAgentId,\n resolveGateAgent,\n readLlmAgentOverrideOptIn,\n readLiveConfig,\n turnReadiness,\n LLM_AGENT_OVERRIDE_PATH,\n type ChannelRuntimeLike,\n} from '../integration/model.js'\nimport type { SocketState } from '../integration/socket.js'\nimport { createInMemoryMetrics } from '../metrics.js'\nimport { resolveOpenClawDefaultAgentId } from '../openclaw-layout.js'\nimport { getClient } from './sdk-client.js'\n\nfunction adaptLog(log: ChannelGatewayContext['log']): Logger | undefined {\n if (!log) return undefined\n const adapted: Logger = {\n trace: (obj, msg) => log.debug?.(formatLogLine(obj, msg)),\n debug: (obj, msg) => log.debug?.(formatLogLine(obj, msg)),\n info: (obj, msg) => log.info(formatLogLine(obj, msg)),\n warn: (obj, msg) => log.warn(formatLogLine(obj, msg)),\n error: (obj, msg) => log.error(formatLogLine(obj, msg)),\n child: () => adapted,\n }\n return adapted\n}\n\n/**\n * OpenClaw's account lifecycle (`ChannelAccountSnapshot.lifecycle` in\n * 2026.10.x: starting | ready | recovering | blocked | stopped). The field is\n * absent from the 2026.6.10 types this package compiles against, so it is\n * added through a widened type; a gateway that does not know it ignores it.\n */\ntype Lifecycle = 'starting' | 'ready' | 'recovering' | 'blocked' | 'stopped'\n\nfunction withLifecycle<T extends object>(snapshot: T, lifecycle: Lifecycle): T {\n return Object.assign({}, snapshot, { lifecycle }) as T\n}\n\n/**\n * OpenClaw's `statusState` vocabulary for the Health table: anything else\n * is printed verbatim and read as a warning. The socket's own state name\n * stays in `lifecycle`.\n */\ntype StatusState = 'linked' | 'configured' | 'unstable' | 'not-linked' | 'disabled' | 'unconfigured'\n\nexport function statusStateFor(state: SocketState): StatusState {\n switch (state) {\n case 'ready':\n return 'linked'\n case 'blocked':\n return 'not-linked'\n case 'stopped':\n case 'idle':\n return 'configured'\n default:\n // connecting, backoff\n return 'unstable'\n }\n}\n\nfunction formatLogLine(obj: object, msg?: string): string {\n const head = msg ?? ''\n const keys = Object.keys(obj)\n if (keys.length === 0) return head\n const tail = keys\n .map((k) => {\n const val = (obj as Record<string, unknown>)[k]\n return `${k}=${typeof val === 'string' ? val : JSON.stringify(val)}`\n })\n .join(' ')\n return head ? `${head} ${tail}` : tail\n}\n\n/** Resolve when `signal` aborts; run `onAbort` first so cleanup completes before OpenClaw sees the task end. */\nexport async function waitUntilAbort(signal: AbortSignal, onAbort: () => Promise<void> | void): Promise<void> {\n if (!signal.aborted) {\n await new Promise<void>((resolve) => signal.addEventListener('abort', () => resolve(), { once: true }))\n }\n await onAbort()\n}\n\nexport const agentchatGatewayAdapter: ChannelGatewayAdapter<AgentchatResolvedAccount> = {\n async startAccount(ctx) {\n const account = ctx.account\n if (!account.enabled) {\n ctx.log?.info?.(`[agentchat:${ctx.accountId}] account disabled — skipping start`)\n return\n }\n if (!account.configured || !account.config) {\n ctx.log?.warn?.(`[agentchat:${ctx.accountId}] account not configured — skipping start`)\n return\n }\n const config = account.config\n const logger =\n adaptLog(ctx.log) ??\n createLogger({ level: config.observability.logLevel, redactKeys: config.observability.redactKeys })\n\n ctx.setStatus(withLifecycle({ ...ctx.getStatus(), running: true, connected: false }, 'starting'))\n\n const wakeMode = readWakeModeFromEnv()\n if (wakeMode.mode === 'off') {\n ctx.log?.info?.(\n `[agentchat:${ctx.accountId}] ${wakeMode.variable}=off — no socket, no wakes, no turns; the hosted tools and the manual stay placed` +\n (wakeMode.variable === LEGACY_WAKE_MODE_ENV ? ` (${LEGACY_WAKE_MODE_ENV} is the old spelling; ${WAKE_MODE_ENV} is the new one)` : ''),\n )\n ctx.setStatus(withLifecycle({ ...ctx.getStatus(), running: false, connected: false, linked: true, statusState: 'disabled' }, 'stopped'))\n await waitUntilAbort(ctx.abortSignal, () => undefined)\n return\n }\n if (readLegacyReplyGateFailOpenFromEnv()) {\n ctx.log?.warn?.(\n `[agentchat:${ctx.accountId}] ${LEGACY_REPLY_GATE_FAIL_OPEN_ENV} is set but no longer honoured — a gate that cannot run fails closed (nothing recorded, no turn) and re-wakes on the ladder`,\n )\n }\n\n // One account per gateway in this release (see `multiAccountRefusal`):\n // a second account's turn would call the hosted tools as the first.\n const refusal = multiAccountRefusal(ctx.cfg)\n if (refusal) {\n ctx.log?.error?.(`[agentchat:${ctx.accountId}] integration not started — ${refusal}`)\n ctx.setStatus(withLifecycle({ ...ctx.getStatus(), running: false, connected: false, statusState: 'not-linked', lastDisconnect: { at: Date.now(), error: refusal } }, 'blocked'))\n await waitUntilAbort(ctx.abortSignal, () => undefined)\n return\n }\n\n const channelRuntime = ctx.channelRuntime as ChannelRuntimeLike | undefined\n // Which agent wakes: OpenClaw's routing for this account. The gate call\n // names that agent only when it differs from OpenClaw's ambient default\n // — an override OpenClaw must be told to allow (D1, `model.ts`).\n const { agentId, agentIdOverride } = resolveGateAgent({\n routedAgentId: resolveIntegrationAgentId({ cfg: ctx.cfg, accountId: ctx.accountId, channelRuntime }),\n ambientAgentId: resolveOpenClawDefaultAgentId(ctx.cfg),\n })\n if (agentIdOverride && !readLlmAgentOverrideOptIn(ctx.cfg)) {\n ctx.log?.warn?.(\n `[agentchat:${ctx.accountId}] this account is routed to agent \"${agentIdOverride}\", not OpenClaw's default — the gate call will be refused (LLM_COMPLETION_NOT_AUTHORIZED) until ${LLM_AGENT_OVERRIDE_PATH} is true; \\`openclaw doctor --fix\\` writes it`,\n )\n }\n const client = getClient({ accountId: ctx.accountId, config })\n const gateTimeoutMs = readReplyGateTimeoutMsFromEnv()\n\n // The served texts: fetched now (server, then the cached copy), refreshed\n // daily. Unreachable with nothing cached → the store says so once and the\n // integration starts anyway; turns wait for the first copy.\n const texts = new TextsStore({ client, accountId: ctx.accountId, logger })\n const handle = config.agentHandle\n if (handle) {\n // A server copy that differs from the placed line refreshes it (an\n // install upgraded from a release that bundled the line gets the\n // served one on its first start); an absent line is the wizard's /\n // doctor's to place. Registered BEFORE the first load so the first\n // copy counts.\n texts.onServerCopy((copy) => {\n const refreshed = refreshIdentityLine(ctx.cfg, ctx.accountId, handle, copy.identity_line)\n if (refreshed.outcome === 'updated') ctx.log?.info?.(`[agentchat:${ctx.accountId}] identity line refreshed from the served texts in ${refreshed.path}`)\n else if (refreshed.outcome === 'failed') ctx.log?.warn?.(`[agentchat:${ctx.accountId}] identity line could not be refreshed in ${refreshed.path}: ${refreshed.detail ?? 'unknown error'}`)\n })\n }\n await texts.start()\n const invites = new InviteLedger({\n accountId: ctx.accountId,\n onWriteError: (err) => ctx.log?.warn?.(`[agentchat:${ctx.accountId}] invite ledger could not be written: ${err instanceof Error ? err.message : String(err)}`),\n })\n\n // One recorder per account for the socket's counters and the ladder's\n // retries. OpenClaw offers a plugin no Prometheus registry (see\n // `metrics.ts`), so the counters live here and the status probe reads\n // them: `openclaw channels capabilities --channel agentchat`.\n const metrics = createInMemoryMetrics()\n\n await registerIntegration({\n accountId: ctx.accountId,\n config,\n logger,\n socketOptions: { client, metrics },\n build: (socket) => {\n const invoker = new AgentInvoker({\n accountId: ctx.accountId,\n agentId,\n client,\n callModel: createRuntimeModelCall({ agentIdOverride, ...(gateTimeoutMs !== undefined ? { timeoutMs: gateTimeoutMs } : {}) }),\n startTurn: createRuntimeTurnStarter(),\n // Gating waits until a turn can have the hosted tools (the MCP\n // entry in the LIVE config — OpenClaw hot-applies `mcp.*` — and\n // its key in this process): a connect wake on a cold gateway\n // otherwise spends a gate call and runs a turn that cannot look.\n readiness: () => {\n const live = readLiveConfig(ctx.cfg)\n return turnReadiness({ cfg: live.cfg, apiBase: config.apiBase, apiKey: config.apiKey, live: live.live })\n },\n texts,\n invites,\n logger,\n metrics,\n gateEnabled: readReplyGateEnabledFromEnv(),\n })\n // True from the first rejected key until a HELLO is accepted again\n // (or the account stops). The SDK retries a rejected key with a fresh\n // HELLO every 10–15 min and reports each rejection as `blocked`; a\n // network failure in between takes it through `backoff`. For the\n // operator that is one situation, so it is one error line and one\n // steady `blocked` status at the first `blocked`, cleared at the next\n // accepted HELLO; every signal in between is a debug line, never a\n // health flap.\n let blocked = false\n return {\n invoker,\n texts,\n handlers: {\n onWake: (source) => invoker.wake(source),\n onGroupInvite: (invite) => invoker.groupInvite(invite, 'live'),\n onConnected: (at) => {\n if (blocked) {\n blocked = false\n ctx.log?.info?.(`[agentchat:${ctx.accountId}] key accepted again — blocked cleared`)\n }\n ctx.log?.info?.(`[agentchat:${ctx.accountId}] connected at ${new Date(at).toISOString()} (agent ${agentId})`)\n ctx.setStatus(withLifecycle({ ...ctx.getStatus(), running: true, connected: true, linked: true, statusState: 'linked', lastConnectedAt: at }, 'ready'))\n // Invite frames are live-only (not part of any drain), so an\n // invite that landed while the socket was down is fetched once\n // per connect and handed to the invoker, which dedups by id\n // against the ledger.\n void catchUpInvites(ctx.accountId, client, invoker, logger)\n },\n onBlocked: (info) => {\n const close = `close ${info.code}${info.reason ? ` ${info.reason}` : ''}`\n const next = info.retryInMs === null ? 'no retry scheduled' : `next HELLO in about ${Math.max(1, Math.round(info.retryInMs / 60_000))} min`\n if (blocked) {\n ctx.log?.debug?.(`[agentchat:${ctx.accountId}] still blocked (${close}; ${next})`)\n return\n }\n blocked = true\n ctx.log?.error?.(\n `[agentchat:${ctx.accountId}] key rejected (${close}) — the server refused the key; the SDK retries a fresh HELLO every 10–15 min until it is accepted (${next}); rotate the key with openclaw channels add agentchat or openclaw config set channels.agentchat.apiKey …`,\n )\n ctx.setStatus(\n withLifecycle(\n { ...ctx.getStatus(), running: false, connected: false, statusState: 'not-linked', lastDisconnect: { at: Date.now(), error: `key rejected: ${close}` } },\n 'blocked',\n ),\n )\n },\n onError: (err) => {\n // While blocked the one error line already said it.\n ctx.log?.[blocked ? 'debug' : 'warn']?.(`[agentchat:${ctx.accountId}] socket error: ${err.message}`)\n },\n onStateChanged: (next, prev) => {\n // The status follows the SDK's state. `ready` is reported by\n // onConnected (it has the time); `connecting` keeps whatever\n // came before (`starting` on the first attempt, `recovering`\n // after a backoff, `blocked` during a blocked retry).\n switch (next) {\n case 'backoff':\n if (blocked) {\n ctx.log?.debug?.(`[agentchat:${ctx.accountId}] socket in backoff while blocked (from ${prev})`)\n return\n }\n ctx.setStatus(withLifecycle({ ...ctx.getStatus(), running: true, connected: false, statusState: 'unstable' }, 'recovering'))\n return\n case 'stopped':\n ctx.setStatus(withLifecycle({ ...ctx.getStatus(), running: false, connected: false, statusState: 'configured' }, 'stopped'))\n return\n default:\n return\n }\n },\n },\n }\n },\n })\n\n // Keep the channel task pending until OpenClaw aborts it. A resolved\n // promise would read as \"channel exited\" and trigger auto-restart.\n await waitUntilAbort(ctx.abortSignal, async () => {\n try {\n await unregisterIntegration(ctx.accountId)\n } catch (err) {\n ctx.log?.error?.(`[agentchat:${ctx.accountId}] unregister failed on abort: ${err instanceof Error ? err.message : String(err)}`)\n }\n })\n },\n\n async stopAccount(ctx) {\n await unregisterIntegration(ctx.accountId)\n ctx.setStatus(withLifecycle({ ...ctx.getStatus(), running: false, connected: false }, 'stopped'))\n },\n}\n\nasync function catchUpInvites(\n accountId: string,\n client: ReturnType<typeof getClient>,\n invoker: AgentInvoker,\n logger: Logger,\n): Promise<void> {\n try {\n const invites: unknown = await client.listGroupInvites()\n if (!Array.isArray(invites)) return\n let surfaced = 0\n for (const row of invites) {\n const invite = groupInviteFromRecord(row)\n if (invite && invoker.groupInvite(invite, 'catch-up')) surfaced += 1\n }\n if (surfaced > 0) logger.info({ accountId, surfaced }, 'pending group invites surfaced on connect')\n } catch (err) {\n logger.warn(\n { accountId, err: err instanceof Error ? err.message : String(err) },\n 'pending-invite catch-up failed — live invite frames are unaffected and the agent can still list invites with the hosted tools',\n )\n }\n}\n\nexport { getIntegration }\n","/**\n * ChannelStatusAdapter — the doctor-style status for `openclaw channels status`.\n *\n * `probeAccount` reports three things an operator needs to know, with one\n * short timeout each:\n *\n * 1. the key authenticates (`GET /v1/agents/me`) and the account is active;\n * 2. the hosted MCP server is reachable with that key (one MCP\n * `initialize`), because that is where every AgentChat tool lives;\n * 3. placement: the key in the gateway environment, the identity line in\n * AGENTS.md (checked against the last served copy when one is cached),\n * the manual, the `mcp.servers.agentchat` entry.\n *\n * Plus the socket's live state when the integration is running.\n */\n\nimport type { ChannelStatusAdapter, ChannelCapabilitiesDisplayLine } from './openclaw-types.js'\n\nimport type { AgentchatResolvedAccount } from '../channel.js'\nimport { getClient } from './sdk-client.js'\nimport { probeHostedMcp } from '../integration/mcp.js'\nimport { checkPlacement, resolvePlacementAgentId, type PlacementCheck } from '../integration/placement.js'\nimport { cachedIdentityLine } from '../integration/texts.js'\nimport type { SocketState } from '../integration/socket.js'\nimport type { MetricsSnapshot } from '../metrics.js'\nimport { getIntegration } from './runtime-registry.js'\nimport { LEGACY_WAKE_MODE_ENV, WAKE_MODE_ENV, readWakeModeFromEnv } from '../credentials/read-env.js'\nimport { agentchatReenableHint, isAgentchatAccountEnabled, multiAccountRefusal } from '../channel-account.js'\n\nexport type AgentchatProbeResult = {\n readonly ok: boolean\n readonly handle?: string\n readonly status?: 'active' | 'restricted' | 'suspended' | 'deleted'\n readonly pausedByOwner?: 'none' | 'send' | 'full'\n readonly error?: string\n readonly mcp?: { readonly ok: boolean; readonly detail: string }\n readonly placement?: readonly PlacementCheck[]\n readonly integration?: {\n readonly mode: 'on' | 'off'\n readonly state?: SocketState\n readonly wakes?: number\n readonly cycles?: number\n readonly turns?: number\n /** Where the served texts came from: the server, the cached copy, or nowhere yet. */\n readonly texts?: 'server' | 'cache' | 'missing'\n /** The socket's counters since the account started: wakes by source, closes by code/initiator, SDK notices by class. */\n readonly socket?: MetricsSnapshot\n }\n /** Set when the integration refuses to start (more than one account configured). */\n readonly refusal?: string\n /** Set when the account is disabled: the re-enable route (never `channels add`, which would fetch the npm build while the plugin is not loaded). */\n readonly disabled?: string\n}\n\nconst PROBE_MIN_MS = 1_000\nconst PROBE_MAX_MS = 10_000\n\n/** `{ message: 3, connect: 1 }` → `connect 1, message 3`; empty → `none`. */\nfunction formatCounts(counts: Readonly<Record<string, number>>): string {\n const parts = Object.entries(counts).map(([label, n]) => `${label} ${n}`)\n return parts.length > 0 ? parts.join(', ') : 'none'\n}\n\nexport const agentchatStatusAdapter: ChannelStatusAdapter<AgentchatResolvedAccount, AgentchatProbeResult> = {\n async probeAccount({ account, timeoutMs, cfg }) {\n if (!account.config) {\n return { ok: false, error: 'missing channels.agentchat configuration' }\n }\n const config = account.config\n const clampedTimeout = Math.min(PROBE_MAX_MS, Math.max(PROBE_MIN_MS, timeoutMs))\n\n const client = getClient({ accountId: account.accountId, config })\n const controller = new AbortController()\n const timer = setTimeout(() => controller.abort(), clampedTimeout)\n let me: Awaited<ReturnType<typeof client.getMe>>\n try {\n me = await client.getMe({ signal: controller.signal })\n } catch (err) {\n return { ok: false, error: err instanceof Error ? err.message : String(err) }\n } finally {\n clearTimeout(timer)\n }\n\n const mcpProbe = await probeHostedMcp({ apiKey: config.apiKey, apiBase: config.apiBase, timeoutMs: clampedTimeout })\n const mcp = {\n ok: mcpProbe.ok,\n detail: mcpProbe.ok\n ? `hosted MCP server reachable with this key${mcpProbe.serverName ? ` (${mcpProbe.serverName}${mcpProbe.serverVersion ? ` ${mcpProbe.serverVersion}` : ''})` : ''}`\n : `hosted MCP server not reachable with this key: ${mcpProbe.error ?? 'unknown error'}`,\n }\n\n const placement = checkPlacement({\n cfg: cfg as object | undefined,\n handle: config.agentHandle ?? me.handle,\n apiKey: config.apiKey,\n apiBase: config.apiBase,\n identityLine: cachedIdentityLine(account.accountId),\n agentId: resolvePlacementAgentId(cfg as object | undefined, account.accountId),\n accountId: account.accountId,\n })\n const enabled = account.enabled && isAgentchatAccountEnabled(cfg as never, account.accountId)\n\n const live = getIntegration(account.accountId)\n const health = live?.socket.getHealth()\n const counters = live?.invoker?.counters()\n const textsSource: 'server' | 'cache' | 'missing' | undefined = live ? (live.texts?.source ?? 'missing') : undefined\n const socketCounters = live?.metrics?.snapshot?.()\n const integration: NonNullable<AgentchatProbeResult['integration']> = {\n mode: readWakeModeFromEnv().mode,\n ...(health ? { state: health.state } : {}),\n ...(counters ? { wakes: counters.wakes, cycles: counters.cycles, turns: counters.turns } : {}),\n ...(textsSource ? { texts: textsSource } : {}),\n ...(socketCounters ? { socket: socketCounters } : {}),\n }\n const refusal = multiAccountRefusal(cfg as never)\n\n return {\n ok: enabled && me.status === 'active' && mcp.ok && placement.every((c) => c.ok) && !refusal,\n handle: me.handle,\n status: me.status,\n pausedByOwner: me.paused_by_owner ?? 'none',\n mcp,\n placement,\n integration,\n ...(refusal ? { refusal } : {}),\n ...(enabled ? {} : { disabled: agentchatReenableHint(cfg as never, account.accountId) }),\n }\n },\n\n formatCapabilitiesProbe({ probe }) {\n const lines: ChannelCapabilitiesDisplayLine[] = []\n if (probe.error) {\n lines.push({ text: probe.error, tone: 'error' })\n return lines\n }\n lines.push({ text: `authenticated as @${probe.handle}`, tone: 'success' })\n if (probe.disabled) lines.push({ text: probe.disabled, tone: 'warn' })\n if (probe.status && probe.status !== 'active') {\n lines.push({ text: `account status: ${probe.status}`, tone: probe.status === 'restricted' ? 'warn' : 'error' })\n }\n if (probe.pausedByOwner && probe.pausedByOwner !== 'none') {\n lines.push({ text: `owner paused this account (${probe.pausedByOwner})`, tone: 'warn' })\n }\n if (probe.mcp) lines.push({ text: probe.mcp.detail, tone: probe.mcp.ok ? 'success' : 'error' })\n for (const check of probe.placement ?? []) {\n lines.push({ text: `${check.name}: ${check.detail}`, tone: check.ok ? 'muted' : 'warn' })\n }\n if (probe.refusal) lines.push({ text: `integration not started — ${probe.refusal}`, tone: 'error' })\n if (probe.integration) {\n const d = probe.integration\n if (d.mode === 'off') lines.push({ text: `integration off (${WAKE_MODE_ENV}=off or ${LEGACY_WAKE_MODE_ENV}=off): no socket, no wakes, no turns`, tone: 'warn' })\n else if (d.state) {\n lines.push({\n text: `integration ${d.state} — wakes ${d.wakes ?? 0}, cycles ${d.cycles ?? 0}, turns ${d.turns ?? 0}`,\n tone: d.state === 'ready' ? 'success' : 'warn',\n })\n if (d.socket) {\n lines.push({\n text: `socket — wakes: ${formatCounts(d.socket.wakes)} · closes: ${formatCounts(d.socket.disconnects)} · notices: ${formatCounts(d.socket.errors)}`,\n tone: 'muted',\n })\n }\n if (d.texts === 'missing') {\n lines.push({ text: 'served texts not available yet (AgentChat unreachable, nothing cached) — turns wait for the first copy', tone: 'error' })\n } else if (d.texts === 'cache') {\n lines.push({ text: 'served texts from the cached copy — AgentChat was unreachable at start; refreshed when it is back', tone: 'warn' })\n }\n } else if (!probe.refusal) lines.push({ text: 'integration not running in this process', tone: 'muted' })\n }\n return lines\n },\n\n resolveAccountState({ account, configured, enabled }) {\n if (!enabled) return 'disabled'\n if (!configured) return 'not configured'\n if (account.configured) return 'linked'\n return 'not linked'\n },\n}\n","/**\n * ChannelDoctorAdapter — `openclaw doctor` for the placement.\n *\n * `collectPreviewWarnings` (plain `openclaw doctor`) reports what the\n * integration needs and does not find in the config, the environment and\n * the workspace — without touching the network: the identity line is\n * checked against the last served copy when one is cached. `repairConfig`\n * (`openclaw doctor --fix` only — OpenClaw never calls it in preview) adds\n * the `mcp.servers.agentchat` entry (a template on `AGENTCHAT_API_KEY`,\n * never the key; hand-written entries are left alone), persists\n * `agentHandle`, writes the llm opt-in for a non-default bound agent, and\n * places a missing identity line for the configured handle — fetching the\n * served text first (server, then the cached copy). An identity line\n * already holding that text is never rewritten.\n *\n * A disabled account gets one warning naming the re-enable route and no\n * repair: its identity line and tools entry are absent by design.\n */\n\nimport type { ChannelDoctorAdapter, OpenClawConfig } from './openclaw-types.js'\n\nimport {\n AGENTCHAT_CHANNEL_ID,\n agentchatReenableHint,\n applyAgentchatAccountPatch,\n isAgentchatAccountEnabled,\n listConfiguredAccountIds,\n multiAccountRefusal,\n readAgentchatConfigField,\n} from '../channel-account.js'\nimport { validateApiKey } from '../setup-client.js'\nimport { checkPlacement, resolvePlacementAgentId, restoreIdentityLine } from '../integration/placement.js'\nimport { DEFAULT_API_BASE, withHostedMcpEntry } from '../integration/mcp.js'\nimport { LLM_AGENT_OVERRIDE_PATH, readLlmAgentOverrideOptIn, withLlmAgentOverrideOptIn } from '../integration/model.js'\nimport { cachedIdentityLine, loadIdentityLine } from '../integration/texts.js'\nimport { resolveBoundAgentId, resolveOpenClawDefaultAgentId } from '../openclaw-layout.js'\nimport { createSdkClient } from './sdk-client.js'\n\nexport const agentchatDoctorAdapter: ChannelDoctorAdapter = {\n collectPreviewWarnings({ cfg, doctorFixCommand, env }) {\n const warnings: string[] = []\n const refusal = multiAccountRefusal(cfg)\n if (refusal) warnings.push(`[${AGENTCHAT_CHANNEL_ID}] integration will not start — ${refusal}`)\n for (const accountId of listConfiguredAccountIds(cfg)) {\n if (!isAgentchatAccountEnabled(cfg, accountId)) {\n warnings.push(`[${AGENTCHAT_CHANNEL_ID}:${accountId}] ${agentchatReenableHint(cfg, accountId)}`)\n continue\n }\n const apiKey = readAgentchatConfigField(cfg, accountId, 'apiKey')\n const apiBase = readAgentchatConfigField(cfg, accountId, 'apiBase') ?? DEFAULT_API_BASE\n const handle = readAgentchatConfigField(cfg, accountId, 'agentHandle')\n const agentId = resolvePlacementAgentId(cfg, accountId)\n for (const check of checkPlacement({ cfg, handle, apiKey, apiBase, identityLine: cachedIdentityLine(accountId), agentId, accountId, env })) {\n if (check.ok) continue\n const fix = check.name === 'mcp' ? ` (${doctorFixCommand} adds it)` : ''\n warnings.push(`[${AGENTCHAT_CHANNEL_ID}:${accountId}] ${check.name}: ${check.detail}${fix}`)\n }\n const bound = resolveBoundAgentId(cfg, AGENTCHAT_CHANNEL_ID, accountId)\n const ambient = resolveOpenClawDefaultAgentId(cfg)\n if (bound && bound !== (ambient ?? bound) && !readLlmAgentOverrideOptIn(cfg)) {\n warnings.push(\n `[${AGENTCHAT_CHANNEL_ID}:${accountId}] gate: this account is bound to agent \"${bound}\", not OpenClaw's default — the gate call is refused (LLM_COMPLETION_NOT_AUTHORIZED) until ${LLM_AGENT_OVERRIDE_PATH} is true (${doctorFixCommand} writes it)`,\n )\n }\n }\n return warnings\n },\n\n async repairConfig({ cfg }) {\n const changes: string[] = []\n const warnings: string[] = []\n let next: OpenClawConfig = cfg\n const bases = new Map<string, string | undefined>()\n // One identity line per workspace: with several accounts configured the\n // integration refuses to start and the line would flip between handles.\n const placeIdentityLines = multiAccountRefusal(cfg) === null\n for (const accountId of listConfiguredAccountIds(cfg)) {\n // Disabled: the identity line and the tools entry are absent by design.\n if (!isAgentchatAccountEnabled(cfg, accountId)) continue\n const apiKey = readAgentchatConfigField(cfg, accountId, 'apiKey')\n const apiBase = readAgentchatConfigField(cfg, accountId, 'apiBase') ?? DEFAULT_API_BASE\n bases.set(apiBase, apiKey)\n // The handle the key authenticates as is the one config field only the\n // server knows. Missing (an older OpenClaw's non-interactive add could\n // not learn it before the write) → one live check per account.\n if (apiKey && !readAgentchatConfigField(cfg, accountId, 'agentHandle')) {\n try {\n const result = await validateApiKey(apiKey, { apiBase })\n if (result.ok) {\n next = applyAgentchatAccountPatch(next, accountId, { agentHandle: result.agent.handle })\n changes.push(`set channels.agentchat${accountId === 'default' ? '' : `.accounts.${accountId}`}.agentHandle = ${result.agent.handle}`)\n } else {\n warnings.push(`[${AGENTCHAT_CHANNEL_ID}:${accountId}] agentHandle not set and the key did not pass the live check (${result.reason}): ${result.message}`)\n }\n } catch (err) {\n warnings.push(`[${AGENTCHAT_CHANNEL_ID}:${accountId}] agentHandle not set and AgentChat was not reachable to learn it: ${err instanceof Error ? err.message : String(err)}`)\n }\n }\n const bound = resolveBoundAgentId(cfg, AGENTCHAT_CHANNEL_ID, accountId)\n const ambient = resolveOpenClawDefaultAgentId(cfg)\n if (bound && bound !== (ambient ?? bound)) {\n const optIn = withLlmAgentOverrideOptIn(next)\n next = optIn.cfg\n if (optIn.changed) changes.push(`set ${LLM_AGENT_OVERRIDE_PATH} = true (account ${accountId} is bound to agent \"${bound}\")`)\n }\n // The identity line for the configured handle (including one learnt\n // just above), with the served text. Present → untouched, byte for byte.\n const handle = readAgentchatConfigField(next, accountId, 'agentHandle')\n if (apiKey && handle && placeIdentityLines) {\n const identityLine = await loadIdentityLine({ client: createSdkClient({ apiKey, apiBase }), accountId })\n const restored = restoreIdentityLine(next, accountId, handle, identityLine)\n if (restored.outcome === 'placed') changes.push(`placed the identity line for @${handle.replace(/^@/, '')} in ${restored.path}`)\n else if (restored.outcome === 'failed') warnings.push(`[${AGENTCHAT_CHANNEL_ID}:${accountId}] could not place the identity line for @${handle.replace(/^@/, '')}: ${restored.detail ?? 'unknown error'}`)\n else if (restored.outcome === 'skipped') warnings.push(`[${AGENTCHAT_CHANNEL_ID}:${accountId}] identity line for @${handle.replace(/^@/, '')} not placed: ${restored.detail ?? 'the served text is not available'}`)\n }\n }\n // One hosted server entry per API base; every configured account on the\n // default base shares the single `agentchat` entry.\n for (const [apiBase, apiKey] of bases) {\n const result = withHostedMcpEntry(next, apiBase, apiKey)\n next = result.cfg\n if (result.outcome === 'added') changes.push(`added mcp.servers.agentchat → ${apiBase}/mcp (bearer template on AGENTCHAT_API_KEY)`)\n }\n return { config: next, changes, ...(warnings.length > 0 ? { warnings } : {}) }\n },\n}\n","/**\n * AgentChat channel plugin — entry point.\n *\n * The plugin is AgentChat's integration for OpenClaw (`docs/architecture.md`\n * in the core repo): it holds the socket for the account through the\n * `agentchatme` SDK, shows the server's cards and question to the agent's\n * own model through the SDK's gate helper, starts one turn per conversation\n * decided reply, and places the key, the served identity line, the hosted\n * tools and the manual where OpenClaw loads them. Nothing of the product\n * lives here — no tools, no gate wording, no message parsing, no delivery\n * semantics, no copied texts. The channel therefore carries only `gateway`,\n * `status` and `doctor` adapters: the agent's send is the hosted\n * `agentchat__agentchat_send_message` tool, not OpenClaw's `message` tool,\n * so there is no outbound adapter to route to.\n *\n * Wires the real OpenClaw SDK contracts — builds a\n * `ChannelPlugin<AgentchatResolvedAccount>` with id / meta / capabilities /\n * config-adapter / config-schema / setup + setupWizard, and wraps it via\n * `defineChannelPluginEntry(...)` for OpenClaw's extension loader. The\n * entry's `setRuntime` hands the integration OpenClaw's `PluginRuntime`\n * (`llm.complete` for the gate, `subagent.run` for the turn).\n *\n * Config adapter supports both:\n * - single-account flat form: `channels.agentchat.{ apiKey, apiBase, ... }`\n * - multi-account form: `channels.agentchat.accounts.<id>.{ apiKey, ... }`\n *\n * Loaded by OpenClaw via `package.json`'s `openclaw.extensions` entry.\n */\n\nimport {\n buildChannelConfigSchema,\n defineChannelPluginEntry,\n type ChannelConfigUiHint,\n type ChannelPlugin,\n} from 'openclaw/plugin-sdk/channel-core'\nimport { deleteAccountFromConfigSection, setAccountEnabledInConfigSection } from 'openclaw/plugin-sdk/channel-plugin-common'\nimport type { ChannelSetupInput } from 'openclaw/plugin-sdk/setup'\n\nimport {\n AGENTCHAT_CHANNEL_ID,\n AGENTCHAT_DEFAULT_ACCOUNT_ID,\n MIN_API_KEY_LENGTH,\n applyAgentchatAccountPatch,\n isAgentchatAccountEnabled,\n isApiKeyPresent,\n readAccountRaw,\n readAgentchatConfigField,\n readChannelSection,\n splitEnabledFromRaw,\n} from './channel-account.js'\nimport { agentchatSetupWizard } from './channel.wizard.js'\nimport {\n agentchatChannelConfigSchema,\n parseChannelConfig,\n type AgentchatChannelConfig,\n} from './config-schema.js'\nimport { validateApiKey } from './setup-client.js'\n\nimport {\n agentchatGatewayAdapter,\n agentchatStatusAdapter,\n agentchatDoctorAdapter,\n type AgentchatProbeResult,\n} from './binding/index.js'\nimport {\n placeIntegration,\n formatPlacement,\n applyIntegrationConfig,\n stripIntegrationConfig,\n removeIntegrationFiles,\n restoreIdentityLine,\n placeApiKeyInDotEnv,\n dotEnvPath,\n} from './integration/placement.js'\nimport { setPluginRuntime } from './integration/runtime-holder.js'\nimport { DEFAULT_API_BASE } from './integration/mcp.js'\nimport { loadIdentityLine } from './integration/texts.js'\nimport { createSdkClient } from './binding/sdk-client.js'\n\nexport {\n AGENTCHAT_CHANNEL_ID,\n AGENTCHAT_DEFAULT_ACCOUNT_ID,\n MIN_API_KEY_LENGTH,\n applyAgentchatAccountPatch,\n isApiKeyPresent,\n readAgentchatConfigField,\n} from './channel-account.js'\n\nexport interface AgentchatResolvedAccount {\n accountId: string\n enabled: boolean\n configured: boolean\n config: AgentchatChannelConfig | null\n parseError: string | null\n}\n\n/**\n * Resolve the config section for a single account. Pure function —\n * extracted from `config.resolveAccount` so `agentPrompt` (session-\n * start identity setup) can reuse it without a self-reference\n * back into the plugin object literal. Never throws: parse failures\n * are surfaced via `parseError` on the returned record.\n *\n * Takes `OpenClawConfig | undefined` to match `ChannelConfigAdapter.\n * resolveAccount`'s signature so they can share this implementation\n * directly without casting.\n */\nexport function resolveAgentchatAccount(\n cfg: import('./binding/openclaw-types.js').OpenClawConfig | undefined,\n accountId?: string | null,\n): AgentchatResolvedAccount {\n const id = accountId ?? AGENTCHAT_DEFAULT_ACCOUNT_ID\n const section = readChannelSection(cfg)\n const raw = readAccountRaw(section, id)\n const { enabled, forParse } = splitEnabledFromRaw(raw)\n let config: AgentchatChannelConfig | null = null\n let parseError: string | null = null\n if (forParse && Object.keys(forParse).length > 0) {\n try {\n config = parseChannelConfig(forParse)\n } catch (e) {\n parseError = e instanceof Error ? e.message : String(e)\n }\n }\n const configured = Boolean(config && isApiKeyPresent(config.apiKey))\n return { accountId: id, enabled, configured, config, parseError }\n}\n\nconst uiHints: Record<string, ChannelConfigUiHint> = {\n apiKey: {\n label: 'AgentChat API key',\n placeholder: 'ac_live_...',\n sensitive: true,\n help: 'The setup wizard registers you via email OTP and mints a key, recovers a lost key (handle + email OTP), or accepts an existing ac_live_… key.',\n },\n apiBase: {\n label: 'API base URL',\n placeholder: 'https://api.agentchat.me',\n help: 'Override only when targeting a self-hosted AgentChat instance.',\n advanced: true,\n },\n agentHandle: {\n label: 'Agent handle',\n placeholder: 'my-agent',\n help: '3–30 chars, lowercase letters/digits/hyphens; must start with a letter.',\n },\n reconnect: { label: 'Reconnect backoff', advanced: true },\n ping: { label: 'WebSocket ping cadence', advanced: true },\n outbound: { label: 'Outbound send tuning', advanced: true },\n observability: { label: 'Logs & metrics', advanced: true },\n}\n\n/** The CLI runtime OpenClaw hands setup hooks (`RuntimeEnv`): `log`, `error`, `exit`. Nothing else — never `.logger`. */\ntype SetupRuntimeEnv = { log?: (...args: unknown[]) => void; error?: (...args: unknown[]) => void }\n\n/**\n * The setup input with the one channel-owned field this plugin adds:\n * `agentHandle`, learnt from the key by `prepareAccountConfigInput` and\n * written by `applyAccountConfig` in the same persisted write.\n */\ntype AgentchatSetupInput = ChannelSetupInput & { agentHandle?: string }\n\nconst HANDLE_SHAPE = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/\nfunction validHandle(value: unknown): string | undefined {\n if (typeof value !== 'string') return undefined\n const bare = value.trim().replace(/^@/, '')\n return bare.length >= 3 && bare.length <= 30 && HANDLE_SHAPE.test(bare) ? bare : undefined\n}\n\nfunction say(runtime: unknown, level: 'log' | 'error', line: string): void {\n const env = runtime as SetupRuntimeEnv | undefined\n const fn = env?.[level]\n if (typeof fn === 'function') fn(line)\n}\n\ntype BaseSetupAdapter = NonNullable<ChannelPlugin<AgentchatResolvedAccount>['setup']>\n\n/**\n * `channels add agentchat --token <key>` (non-interactive) and the wizard's\n * credential step both go through this adapter. What OpenClaw persists is\n * exactly what `applyAccountConfig` returns — it is synchronous — so\n * everything that belongs in `openclaw.json` is written there: the key, the\n * API base, the handle the key authenticates as (learnt just before, in\n * `prepareAccountConfigInput`, which 2026.10.x runs first and awaits), the\n * hosted tools entry and, when the account is bound to a non-default agent,\n * the llm override opt-in. `afterAccountConfigWritten` only places files\n * (the key in the state-dir `.env`, the identity line in `AGENTS.md`) and\n * reports through the CLI runtime it is given (`RuntimeEnv.log/error`).\n * It never relies on the plugin runtime: in OpenClaw's setup-only\n * registration mode that runtime is a proxy that throws on access.\n *\n * `prepareAccountConfigInput` is absent from the 2026.6.10 types; the\n * adapter type is widened so the same object compiles against both.\n */\nexport const agentchatSetupAdapter: BaseSetupAdapter & {\n prepareAccountConfigInput?: (params: {\n cfg: import('./binding/openclaw-types.js').OpenClawConfig\n accountId: string\n input: AgentchatSetupInput\n runtime: unknown\n }) => Promise<AgentchatSetupInput>\n} = {\n /**\n * Pre-write gate: cheap, sync check that the caller supplied an API key\n * that's at least plausibly shaped. Real authentication happens in\n * `prepareAccountConfigInput` / `afterAccountConfigWritten`.\n */\n validateInput({ input }) {\n if (typeof input.token !== 'string' || input.token.trim().length === 0) {\n return 'apiKey is required — pass via --token, or run `openclaw channels add agentchat` to register a new agent or recover a lost key (handle + email OTP)'\n }\n if (input.token.length < MIN_API_KEY_LENGTH) {\n return `apiKey looks too short (got ${input.token.length} chars, expect ≥${MIN_API_KEY_LENGTH})`\n }\n if (typeof input.url === 'string' && input.url.length > 0) {\n try {\n const parsed = new URL(input.url)\n if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') {\n return 'apiBase must be http(s) — e.g. https://api.agentchat.me'\n }\n } catch {\n return 'apiBase is not a valid URL'\n }\n }\n return null\n },\n\n /**\n * Learn the handle the key authenticates as BEFORE the write, so\n * `applyAccountConfig` persists it in the same config write OpenClaw\n * already makes. A key that does not validate leaves the input untouched\n * (the write still happens; the error line says what to fix).\n */\n async prepareAccountConfigInput({ accountId, input, runtime }) {\n const apiKey = typeof input.token === 'string' ? input.token : undefined\n if (!apiKey || apiKey.length < MIN_API_KEY_LENGTH) return input\n const apiBase = typeof input.url === 'string' && input.url.length > 0 ? input.url : undefined\n try {\n const result = await validateApiKey(apiKey, { apiBase })\n if (result.ok) {\n say(runtime, 'log', `[agentchat:${accountId}] authenticated as @${result.agent.handle} (${result.agent.email})`)\n // The key goes to the state-dir .env NOW, before OpenClaw writes the\n // config and re-reads it: the hosted tools entry written in the same\n // step references ${AGENTCHAT_API_KEY}, and the post-write snapshot\n // would otherwise report the variable missing once.\n try {\n placeApiKeyInDotEnv(apiKey)\n } catch (err) {\n say(runtime, 'error', `[agentchat:${accountId}] could not write AGENTCHAT_API_KEY to ${dotEnvPath()}: ${err instanceof Error ? err.message : String(err)}`)\n }\n return { ...input, agentHandle: result.agent.handle }\n }\n say(runtime, 'error', `[agentchat:${accountId}] api key did not pass live check (${result.reason}): ${result.message}`)\n } catch (err) {\n say(runtime, 'error', `[agentchat:${accountId}] live key validation failed: ${err instanceof Error ? err.message : String(err)}`)\n }\n return input\n },\n\n /**\n * The one persisted write. Synchronous by contract, so it carries\n * everything that can be known without I/O: key, API base, the handle\n * (when `prepareAccountConfigInput` learnt it), the hosted tools entry,\n * the llm opt-in for a non-default bound agent.\n */\n applyAccountConfig({ cfg, accountId, input }) {\n const patch: Record<string, unknown> = {}\n if (typeof input.token === 'string' && input.token.length > 0) patch.apiKey = input.token\n if (typeof input.url === 'string' && input.url.length > 0) patch.apiBase = input.url\n const handle = validHandle((input as AgentchatSetupInput).agentHandle)\n if (handle) patch.agentHandle = handle\n const withAccount = applyAgentchatAccountPatch(cfg, accountId, patch)\n const apiKey = readAgentchatConfigField(withAccount, accountId, 'apiKey')\n if (!apiKey) return withAccount\n const apiBase = readAgentchatConfigField(withAccount, accountId, 'apiBase') ?? DEFAULT_API_BASE\n return applyIntegrationConfig(withAccount, { accountId, handle, apiKey, apiBase }).cfg\n },\n\n /**\n * Files only: the key into OpenClaw's state-dir `.env`, the served\n * identity line into the bound agent's `AGENTS.md`. Reports through\n * `RuntimeEnv.log`. Never throws: setup-time UX is \"warn and proceed\".\n */\n async afterAccountConfigWritten({ cfg, accountId, input, runtime }) {\n const apiKey = typeof input.token === 'string' ? input.token : readAgentchatConfigField(cfg, accountId, 'apiKey')\n if (!apiKey) return\n const apiBase = readAgentchatConfigField(cfg, accountId, 'apiBase') ?? DEFAULT_API_BASE\n let handle = validHandle((input as AgentchatSetupInput).agentHandle) ?? readAgentchatConfigField(cfg, accountId, 'agentHandle')\n if (!handle) {\n // An OpenClaw without `prepareAccountConfigInput`: learn the handle now\n // for the identity line; the config gets it from `openclaw doctor --fix`.\n try {\n const result = await validateApiKey(apiKey, { apiBase })\n if (result.ok) {\n handle = result.agent.handle\n say(runtime, 'log', `[agentchat:${accountId}] authenticated as @${handle}; run \\`openclaw doctor --fix\\` to persist channels.agentchat.agentHandle`)\n } else {\n say(runtime, 'error', `[agentchat:${accountId}] api key did not pass live check (${result.reason}): ${result.message}`)\n return\n }\n } catch (err) {\n say(runtime, 'error', `[agentchat:${accountId}] live key validation failed: ${err instanceof Error ? err.message : String(err)}`)\n return\n }\n }\n try {\n const identityLine = await loadIdentityLine({ client: createSdkClient({ apiKey, apiBase }), accountId })\n const placed = placeIntegration({ cfg, handle, apiKey, apiBase, identityLine, accountId })\n for (const line of formatPlacement(placed.steps.filter((s) => s.name !== 'mcp'))) say(runtime, 'log', `[agentchat:${accountId}] ${line}`)\n say(runtime, 'log', `[agentchat:${accountId}] ✓ config: agentHandle and mcp.servers.agentchat written with the account (restart the gateway, or reload its config, so \\${AGENTCHAT_API_KEY} resolves)`)\n } catch (err) {\n say(runtime, 'error', `[agentchat:${accountId}] placement failed: ${err instanceof Error ? err.message : String(err)}`)\n }\n },\n}\n\ntype Cfg = import('./binding/openclaw-types.js').OpenClawConfig\n\n/**\n * `channels remove agentchat` (disable): the config side only — keep the\n * key, drop the plugin's own hosted-tools entry, set `enabled: false`.\n * Pure: OpenClaw validates and persists what this returns; the files go in\n * `lifecycle.onAccountConfigChanged`, after the patch has been checked.\n */\nexport function disableAccountConfig(cfg: Cfg, accountId: string): Cfg {\n const stripped = stripIntegrationConfig(cfg, accountId).cfg\n return setAccountEnabledInConfigSection({ cfg: stripped, sectionKey: AGENTCHAT_CHANNEL_ID, accountId, enabled: false, allowTopLevel: true })\n}\n\n/** `channels remove agentchat --delete`: the config side only — the account and the plugin's own hosted-tools entry go. */\nexport function deleteAccountConfig(cfg: Cfg, accountId: string): Cfg {\n const stripped = stripIntegrationConfig(cfg, accountId).cfg\n return deleteAccountFromConfigSection({ cfg: stripped, sectionKey: AGENTCHAT_CHANNEL_ID, accountId, clearBaseFields: ['apiKey', 'apiBase', 'agentHandle'] })\n}\n\nfunction isAccountEnabled(cfg: Cfg | undefined, accountId: string): boolean {\n return isAgentchatAccountEnabled(cfg, accountId)\n}\n\n/**\n * The persisted account section must pass the plugin's own schema (the\n * same zod object OpenClaw's JSON-schema validation is emitted from).\n * OpenClaw runs the lifecycle hooks BEFORE it validates and persists a\n * removal (`applyChannelAccountRemoval` in 2026.10.9), so a hook that\n * touches files checks the patch itself first: a write OpenClaw would\n * refuse must not strand the identity line or the key.\n */\nexport function accountSectionPersistable(cfg: Cfg | undefined, accountId: string): boolean {\n const raw = readAccountRaw(readChannelSection(cfg), accountId)\n if (!raw) return true // no section: nothing for OpenClaw to refuse\n return agentchatChannelConfigSchema.safeParse(raw).success\n}\n\n/**\n * ChannelLifecycleAdapter — the file side of disable / re-enable / delete,\n * run by OpenClaw after the config adapters and before the write.\n * Best-effort; reports through the CLI runtime it is given.\n *\n * enabled → disabled: the identity line goes (the key stays — a pause).\n * disabled → enabled: the identity line for the configured `agentHandle`\n * comes back, the mirror of disable. OpenClaw 2026.10.9 does not load a\n * disabled channel's plugin, so a re-enable through\n * `openclaw config set channels.agentchat.enabled true` never reaches this\n * hook; `openclaw doctor --fix` places a missing identity line for that path.\n */\nexport const agentchatLifecycleAdapter: NonNullable<ChannelPlugin<AgentchatResolvedAccount>['lifecycle']> = {\n async onAccountConfigChanged({ prevCfg, nextCfg, accountId, runtime }) {\n const wasEnabled = isAccountEnabled(prevCfg, accountId)\n const isEnabled = isAccountEnabled(nextCfg, accountId)\n if (wasEnabled === isEnabled) return\n if (!accountSectionPersistable(nextCfg, accountId)) {\n say(\n runtime,\n 'error',\n isEnabled\n ? `[agentchat:${accountId}] the re-enabled config does not pass the channel schema — not placing the identity line`\n : `[agentchat:${accountId}] the disabled config does not pass the channel schema — leaving the identity line and the key in place`,\n )\n return\n }\n if (!isEnabled) {\n for (const line of removeIntegrationFiles(nextCfg, accountId, { clearKey: false })) say(runtime, 'log', `[agentchat:${accountId}] ${line}`)\n return\n }\n const handle = validHandle(readAgentchatConfigField(nextCfg, accountId, 'agentHandle'))\n if (!handle) {\n say(runtime, 'log', `[agentchat:${accountId}] agentHandle not in config — run \\`openclaw doctor --fix\\` to learn it from the key and place the identity line`)\n return\n }\n const apiKey = readAgentchatConfigField(nextCfg, accountId, 'apiKey')\n const apiBase = readAgentchatConfigField(nextCfg, accountId, 'apiBase') ?? DEFAULT_API_BASE\n const identityLine = apiKey ? await loadIdentityLine({ client: createSdkClient({ apiKey, apiBase }), accountId }) : null\n const restored = restoreIdentityLine(nextCfg, accountId, handle, identityLine)\n if (restored.outcome === 'placed') say(runtime, 'log', `[agentchat:${accountId}] placed the identity line for @${handle} in ${restored.path}`)\n else if (restored.outcome === 'skipped') say(runtime, 'log', `[agentchat:${accountId}] identity line for @${handle} not placed: ${restored.detail ?? 'the served text is not available'}`)\n else if (restored.outcome === 'failed') say(runtime, 'error', `[agentchat:${accountId}] could not place the identity line for @${handle}: ${restored.detail ?? 'unknown error'} — run \\`openclaw doctor --fix\\` after fixing the path`)\n },\n\n async onAccountRemoved({ prevCfg, accountId, runtime }) {\n for (const line of removeIntegrationFiles(prevCfg, accountId, { clearKey: true })) say(runtime, 'log', `[agentchat:${accountId}] ${line}`)\n },\n}\n\nexport const agentchatPlugin: ChannelPlugin<AgentchatResolvedAccount, AgentchatProbeResult> = {\n id: AGENTCHAT_CHANNEL_ID,\n\n meta: {\n id: AGENTCHAT_CHANNEL_ID,\n label: 'AgentChat',\n selectionLabel: 'AgentChat (messaging platform for agents)',\n detailLabel: 'AgentChat',\n docsPath: '/channels/agentchat',\n docsLabel: 'agentchat',\n blurb:\n 'the AgentChat integration — your agent gets a permanent @handle on the messaging network for AI agents, is woken when a peer writes, and decides for itself with its own model whether to reply through the hosted AgentChat tools.',\n systemImage: 'message',\n markdownCapable: true,\n order: 100,\n },\n\n // What the network offers. The channel itself routes nothing outbound:\n // every action goes through the hosted MCP tools, so OpenClaw's `message`\n // tool does not target AgentChat.\n capabilities: {\n chatTypes: ['direct', 'group'],\n media: false,\n reactions: false,\n edit: false,\n unsend: false,\n reply: false,\n threads: false,\n nativeCommands: false,\n },\n\n reload: {\n configPrefixes: [`channels.${AGENTCHAT_CHANNEL_ID}.`],\n },\n\n configSchema: buildChannelConfigSchema(agentchatChannelConfigSchema, { uiHints }),\n\n setupWizard: agentchatSetupWizard,\n\n config: {\n listAccountIds(cfg) {\n const section = readChannelSection(cfg)\n if (!section) return []\n const { accounts } = section\n if (accounts && typeof accounts === 'object' && !Array.isArray(accounts)) {\n const ids = Object.keys(accounts as Record<string, unknown>)\n if (ids.length > 0) return ids\n }\n const hasFlatFields =\n typeof section.apiKey === 'string' ||\n typeof section.apiBase === 'string' ||\n typeof section.agentHandle === 'string'\n return hasFlatFields ? [AGENTCHAT_DEFAULT_ACCOUNT_ID] : []\n },\n\n resolveAccount(cfg, accountId) {\n return resolveAgentchatAccount(cfg, accountId)\n },\n\n defaultAccountId() {\n return AGENTCHAT_DEFAULT_ACCOUNT_ID\n },\n\n // `openclaw channels remove agentchat` → disable; `--delete` → delete.\n // OpenClaw routes both here (not through the wizard's `disable`, which\n // only the interactive setup flow reaches). Shared strip logic with it.\n setAccountEnabled({ cfg, accountId, enabled }) {\n if (enabled) return setAccountEnabledInConfigSection({ cfg, sectionKey: AGENTCHAT_CHANNEL_ID, accountId, enabled: true, allowTopLevel: true })\n return disableAccountConfig(cfg, accountId)\n },\n\n deleteAccount({ cfg, accountId }) {\n return deleteAccountConfig(cfg, accountId)\n },\n\n isEnabled(account) {\n return account.enabled\n },\n\n disabledReason(account) {\n return account.enabled ? '' : 'channel disabled via channels.agentchat.enabled=false'\n },\n\n isConfigured(account) {\n return account.configured\n },\n\n unconfiguredReason(account) {\n if (account.parseError) return `config invalid: ${account.parseError}`\n if (!account.config) return 'missing channels.agentchat configuration'\n if (!isApiKeyPresent(account.config.apiKey)) return 'missing or too-short channels.agentchat.apiKey'\n return ''\n },\n\n hasConfiguredState({ cfg }) {\n const section = readChannelSection(cfg)\n if (!section) return false\n const { accounts } = section\n if (accounts && typeof accounts === 'object' && !Array.isArray(accounts)) {\n for (const entry of Object.values(accounts as Record<string, unknown>)) {\n if (entry && typeof entry === 'object') {\n const candidate = (entry as Record<string, unknown>).apiKey\n if (isApiKeyPresent(candidate)) return true\n }\n }\n }\n return isApiKeyPresent(section.apiKey)\n },\n\n describeAccount(account) {\n return {\n accountId: account.accountId,\n enabled: account.enabled,\n configured: account.configured,\n linked: account.configured,\n }\n },\n },\n\n setup: agentchatSetupAdapter,\n\n // ─── OpenClaw ↔ AgentChat binding ─────────────────────────────────────\n //\n // gateway — holds the socket, wakes, gates, starts turns (the integration).\n // status — the doctor-style probe: key, hosted MCP reachability, placement.\n // doctor — `openclaw doctor` warnings and the mcp.servers.agentchat repair.\n //\n // Deliberately absent: `outbound`, `messaging`, `actions`, `directory`,\n // `resolver`, `agentTools`. Tools are defined once, in the hosted MCP\n // server; the plugin places that server and nothing else. `agentPrompt` is\n // absent too — it only fires on AgentChat-triggered runs, while the\n // identity line must be present on every turn (AGENTS.md).\n\n gateway: agentchatGatewayAdapter,\n status: agentchatStatusAdapter,\n doctor: agentchatDoctorAdapter,\n lifecycle: agentchatLifecycleAdapter,\n}\n\n/**\n * Canonical channel-entry descriptor consumed by OpenClaw's extension loader.\n * Exported as `default` because `openclaw.extensions` in package.json points to\n * this module and the loader reads the default export.\n *\n * The explicit `ReturnType<...>` annotation pins the emitted `.d.ts` to the\n * function signature instead of the structural shape — otherwise the inferred\n * type references `ChannelConfigSchema` through a non-exported path and TS\n * fails with TS2742 (\"cannot be named without a reference to ...\").\n */\nexport const agentchatChannelEntry: ReturnType<\n typeof defineChannelPluginEntry<typeof agentchatPlugin>\n> = defineChannelPluginEntry({\n id: AGENTCHAT_CHANNEL_ID,\n name: 'AgentChat',\n description: 'The AgentChat integration: wakes your OpenClaw agent when a peer writes on the messaging network for AI agents.',\n plugin: agentchatPlugin,\n // Called in every registration mode except cli-metadata and tool-discovery\n // (docs.openclaw.ai/plugins/sdk-entrypoints/define-channel-plugin-entry).\n // The integration reads `runtime.llm.complete` (the gate on the agent's own\n // model) and `runtime.subagent.run` (one turn, `deliver: false`) from it.\n setRuntime: (runtime) => setPluginRuntime(runtime),\n})\n\nexport default agentchatChannelEntry\n\nexport { parseChannelConfig }\nexport type { AgentchatChannelConfig }\n","/**\n * AgentChat setup plugin — onboarding entry.\n *\n * Wraps the same `agentchatPlugin` from `channel.ts` with\n * `defineSetupPluginEntry(...)` so OpenClaw's setup-entry loader can pick it\n * up from `package.json`'s `openclaw.setupEntry` field.\n *\n * The plugin itself carries both:\n * - `plugin.setup` — the non-interactive adapter used by\n * `openclaw setup --channel agentchat --token …`\n * - `plugin.setupWizard` — the interactive login-vs-register wizard used by\n * `openclaw channels add agentchat`\n *\n * Both paths write through the same `applyAgentchatAccountPatch` helper, so\n * the resulting config is identical regardless of entry point.\n */\n\nimport { defineSetupPluginEntry } from 'openclaw/plugin-sdk/channel-core'\n\nimport { agentchatPlugin } from './channel.js'\n\nexport const agentchatSetupEntry = defineSetupPluginEntry(agentchatPlugin)\n\nexport default agentchatSetupEntry\n\nexport { agentchatPlugin as agentchatSetupPlugin }\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/channel-account.ts","../src/version.ts","../src/client-identity.ts","../src/setup-client.ts","../src/integration/turn.ts","../src/integration/mcp.ts","../src/integration/runtime-holder.ts","../src/integration/model.ts","../src/integration/placement.ts","../src/integration/state.ts","../src/integration/texts.ts","../src/binding/sdk-client.ts","../src/channel.wizard.ts","../src/config-schema.ts","../src/log.ts","../src/metrics.ts","../src/integration/invites.ts","../src/integration/socket.ts","../src/binding/runtime-registry.ts","../src/integration/wake.ts","../src/integration/invoker.ts","../src/binding/gateway.ts","../src/binding/status.ts","../src/binding/doctor.ts","../src/channel.ts","../src/channel.setup.ts"],"names":["path","API_KEY_ENV","DEFAULT_API_BASE","resolveOpenClawStateDir","fs","resolveBoundAgentId","resolveOpenClawDefaultAgentId","removeAgentsAnchor","agentsAnchorPath","hasAgentsAnchorFor","writeAgentsAnchor","readAgentsAnchor","path2","fs2","path3","describe","AgentChatClient","HANDLE_PATTERN","isValidHandleShape","current","patched","WizardCancelledError","readApiKeyFromEnv","setSetupChannelEnabled","z","pino","path4","RealtimeClient","gate","readWakeModeFromEnv","LEGACY_WAKE_MODE_ENV","WAKE_MODE_ENV","readLegacyReplyGateFailOpenFromEnv","LEGACY_REPLY_GATE_FAIL_OPEN_ENV","readReplyGateTimeoutMsFromEnv","readReplyGateEnabledFromEnv","setAccountEnabledInConfigSection","deleteAccountFromConfigSection","buildChannelConfigSchema","defineChannelPluginEntry","defineSetupPluginEntry"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqBO,IAAM,oBAAA,GAAuB,WAAA;AAC7B,IAAM,4BAAA,GAA+B,SAAA;AAErC,IAAM,kBAAA,GAAqB,EAAA;AAU3B,SAAS,mBAAmB,GAAA,EAAgE;AACjG,EAAA,MAAM,WAAY,GAAA,EAA4D,QAAA;AAC9E,EAAA,MAAM,OAAA,GAAU,WAAW,oBAAoB,CAAA;AAC/C,EAAA,OAAO,OAAA,IAAW,OAAO,OAAA,KAAY,QAAA,IAAY,CAAC,KAAA,CAAM,OAAA,CAAQ,OAAO,CAAA,GAClE,OAAA,GACD,MAAA;AACN;AAEO,SAAS,cAAA,CACd,SACA,SAAA,EACqC;AACrC,EAAA,IAAI,CAAC,SAAS,OAAO,MAAA;AACrB,EAAA,MAAM,EAAE,UAAS,GAAI,OAAA;AACrB,EAAA,IAAI,QAAA,IAAY,OAAO,QAAA,KAAa,QAAA,IAAY,CAAC,KAAA,CAAM,OAAA,CAAQ,QAAQ,CAAA,EAAG;AACxE,IAAA,MAAM,KAAA,GAAS,SAAqC,SAAS,CAAA;AAC7D,IAAA,IAAI,KAAA,IAAS,OAAO,KAAA,KAAU,QAAA,EAAU,OAAO,KAAA;AAAA,EACjD;AAIA,EAAA,IAAI,cAAc,4BAAA,EAA8B;AAC9C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KAAA,IAAS,MAAA,CAAO,MAAA,CAAO,QAAmC,CAAA,EAAG;AACtE,UAAA,IAAI,KAAA,IAAS,OAAO,KAAA,KAAU,QAAA,EAAU;AACtC,YAAA,MAAM,YAAa,KAAA,CAAkC,MAAA;AACrD,YAAA,IAAI,eAAA,CAAgB,SAAS,CAAA,EAAG,OAAO,IAAA;AAAA,UACzC;AAAA,QACF;AAAA,MACF;AACA,MAAA,OAAO,eAAA,CAAgB,QAAQ,MAAM,CAAA;AAAA,IACvC,CAAA;AAAA,IAEA,gBAAgB,OAAA,EAAS;AACvB,MAAA,OAAO;AAAA,QACL,WAAW,OAAA,CAAQ,SAAA;AAAA,QACnB,SAAS,OAAA,CAAQ,OAAA;AAAA,QACjB,YAAY,OAAA,CAAQ,UAAA;AAAA,QACpB,QAAQ,OAAA,CAAQ;AAAA,OAClB;AAAA,IACF;AAAA,GACF;AAAA,EAEA,KAAA,EAAO,qBAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAcP,OAAA,EAAS,uBAAA;AAAA,EACT,MAAA,EAAQ,sBAAA;AAAA,EACR,MAAA,EAAQ,sBAAA;AAAA,EACR,SAAA,EAAW;AACb;AAcIG,oCAAA,CAAyB;AAAA,EAC3B,EAAA,EAAI,oBAAA;AAAA,EACJ,IAAA,EAAM,WAAA;AAAA,EACN,WAAA,EAAa,iHAAA;AAAA,EACb,MAAA,EAAQ,eAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAKR,UAAA,EAAY,CAAC,OAAA,KAAY,gBAAA,CAAiB,OAAO;AACnD,CAAC;;;AC/hBM,IAAM,mBAAA,GAAsBC,mCAAuB,eAAe","file":"setup-entry.cjs","sourcesContent":["/**\n * Account-config primitives for the AgentChat channel plugin.\n *\n * This module owns the smallest set of shared pieces that both the plugin\n * definition (`channel.ts`) and the interactive setup wizard\n * (`channel.wizard.ts`) need to read or mutate the `channels.agentchat.*`\n * section of the OpenClaw config. Keeping them in a leaf file (no imports\n * from other channel-* modules) breaks the channel.ts ↔ channel.wizard.ts\n * import cycle — without it, the wizard literal's `channel:` field resolves\n * to the temporal-dead-zone value of `AGENTCHAT_CHANNEL_ID` at module-init\n * time, which bundlers emit as `undefined`.\n *\n * Invariants:\n * - Flat form (`channels.agentchat.{apiKey,...}`) is the default-account\n * layout when no `accounts` key is present. Once a named account is\n * written, flat form is never used again for the default account.\n * - The `enabled` flag is section-level (not per-account) and is kept out\n * of the Zod-parsed account shape because the schema is `.strict()`.\n */\nimport type { OpenClawConfig } from 'openclaw/plugin-sdk/channel-core'\n\nexport const AGENTCHAT_CHANNEL_ID = 'agentchat' as const\nexport const AGENTCHAT_DEFAULT_ACCOUNT_ID = 'default'\n\nexport const MIN_API_KEY_LENGTH = 20\n\nexport type ChannelSectionRaw = Record<string, unknown> & {\n accounts?: Record<string, unknown>\n enabled?: unknown\n apiKey?: unknown\n apiBase?: unknown\n agentHandle?: unknown\n}\n\nexport function readChannelSection(cfg: OpenClawConfig | undefined): ChannelSectionRaw | undefined {\n const channels = (cfg as { channels?: Record<string, unknown> } | undefined)?.channels\n const section = channels?.[AGENTCHAT_CHANNEL_ID]\n return section && typeof section === 'object' && !Array.isArray(section)\n ? (section as ChannelSectionRaw)\n : undefined\n}\n\nexport function readAccountRaw(\n section: ChannelSectionRaw | undefined,\n accountId: string,\n): Record<string, unknown> | undefined {\n if (!section) return undefined\n const { accounts } = section\n if (accounts && typeof accounts === 'object' && !Array.isArray(accounts)) {\n const entry = (accounts as Record<string, unknown>)[accountId]\n if (entry && typeof entry === 'object') return entry as Record<string, unknown>\n }\n // Single-account fallback: treat section-level fields as the 'default' account,\n // stripping the `accounts` subsection (but preserving `enabled`, which the\n // caller extracts before Zod parsing).\n if (accountId === AGENTCHAT_DEFAULT_ACCOUNT_ID) {\n const { accounts: _accounts, ...rest } = section\n void _accounts\n return rest as Record<string, unknown>\n }\n return undefined\n}\n\n/**\n * Pulls the `enabled` flag out of a raw account record and returns a copy\n * safe to feed into `parseChannelConfig` (which enforces `.strict()` — an\n * unknown `enabled` key would otherwise reject).\n */\nexport function splitEnabledFromRaw(\n raw: Record<string, unknown> | undefined,\n): { enabled: boolean; forParse: Record<string, unknown> | undefined } {\n if (!raw) return { enabled: true, forParse: undefined }\n const { enabled, ...rest } = raw\n return { enabled: enabled !== false, forParse: rest }\n}\n\n/**\n * Whether OpenClaw treats this account as enabled: neither the section-level\n * `channels.agentchat.enabled` nor the account's own `enabled` is `false`.\n * (For the flat default account the two are the same field.)\n */\nexport function isAgentchatAccountEnabled(cfg: OpenClawConfig | undefined, accountId: string): boolean {\n const section = readChannelSection(cfg)\n if (!section) return true\n if (section.enabled === false) return false\n const raw = readAccountRaw(section, accountId)\n return raw?.enabled !== false\n}\n\n/**\n * The config path whose `false` keeps this account disabled — the one\n * `openclaw config set <path> true` must flip. The section-level flag\n * first: while it is `false` OpenClaw does not load the plugin at all.\n */\nexport function agentchatEnabledConfigPath(cfg: OpenClawConfig | undefined, accountId: string): string {\n const section = readChannelSection(cfg)\n const sectionPath = `channels.${AGENTCHAT_CHANNEL_ID}.enabled`\n if (!section || section.enabled === false) return sectionPath\n const { accounts } = section\n const entry = accounts && typeof accounts === 'object' && !Array.isArray(accounts) ? (accounts as Record<string, unknown>)[accountId] : undefined\n if (entry && typeof entry === 'object') return `channels.${AGENTCHAT_CHANNEL_ID}.accounts.${accountId}.enabled`\n return sectionPath\n}\n\n/**\n * The remedy for anything missing on a DISABLED account. Never\n * `channels add`: OpenClaw (2026.10.9) does not load a disabled channel's\n * plugin, so `channels add` treats AgentChat as a missing plugin, downloads\n * `@agentchatme/openclaw` from npm and asks to install it over this one.\n * `config set … true` re-enables in place (\"applies without restarting the\n * gateway\"); `doctor --fix` then restores the hosted tools entry and the\n * identity line.\n */\nexport function agentchatReenableHint(cfg: OpenClawConfig | undefined, accountId: string): string {\n return (\n `the account is disabled — re-enable it with \\`openclaw config set ${agentchatEnabledConfigPath(cfg, accountId)} true\\`, then run \\`openclaw doctor --fix\\` ` +\n '(not `openclaw channels add`: OpenClaw does not load a disabled channel\\'s plugin and would install @agentchatme/openclaw from npm over this one)'\n )\n}\n\n/**\n * Every account id the config declares: the keys of `accounts.*` when\n * present, else `default` when the flat section carries an `apiKey`. Shared\n * by the config adapter, the gateway's single-account check and the doctor.\n */\nexport function listConfiguredAccountIds(cfg: OpenClawConfig | undefined): string[] {\n const section = readChannelSection(cfg)\n if (!section) return []\n const { accounts } = section\n if (accounts && typeof accounts === 'object' && !Array.isArray(accounts)) {\n const ids = Object.keys(accounts as Record<string, unknown>)\n if (ids.length > 0) return ids\n }\n return typeof section.apiKey === 'string' ? [AGENTCHAT_DEFAULT_ACCOUNT_ID] : []\n}\n\n/**\n * This release runs ONE AgentChat account per gateway. The hosted tools are\n * one `mcp.servers.agentchat` entry whose bearer header is a template on one\n * environment variable (`AGENTCHAT_API_KEY`), so a second account's turn\n * would call the tools as the first account. The integration refuses to start\n * when more than one account is configured, and `channels status` says so.\n *\n * TODO (per-account integrations): one MCP entry per account\n * (`mcp.servers.agentchat-<accountId>`, bearer template on\n * `AGENTCHAT_API_KEY_<ACCOUNT>`), the turn prompt naming that account's tool\n * prefix (`agentchat-<accountId>__…`), the identity line per agent workspace,\n * and the key placed under its own variable name in `.env`.\n */\nexport function multiAccountRefusal(cfg: OpenClawConfig | undefined): string | null {\n const ids = listConfiguredAccountIds(cfg)\n if (ids.length <= 1) return null\n return (\n `${ids.length} AgentChat accounts are configured (${ids.join(', ')}); this release runs one account per gateway ` +\n '— the hosted tools are one mcp.servers.agentchat entry on one AGENTCHAT_API_KEY, so a second account would act as the first. ' +\n 'Keep one account under channels.agentchat (or run a second gateway) until per-account integrations ship.'\n )\n}\n\nexport function isApiKeyPresent(value: unknown): value is string {\n return typeof value === 'string' && value.length >= MIN_API_KEY_LENGTH\n}\n\n/**\n * Read a string-valued field from the resolved account record. Mirrors the\n * fallback logic of `resolveAccount` — accounts.<id>.<field> when present,\n * falling back to the flat section for the default account.\n *\n * Used by the setup wizard so it can render live config state without\n * re-running the Zod parser (which would reject partial work-in-progress\n * inputs during the interactive flow).\n */\nexport function readAgentchatConfigField(\n cfg: OpenClawConfig | undefined,\n accountId: string,\n field: 'apiKey' | 'apiBase' | 'agentHandle',\n): string | undefined {\n const section = readChannelSection(cfg)\n const raw = readAccountRaw(section, accountId)\n if (!raw) return undefined\n const value = raw[field]\n return typeof value === 'string' && value.length > 0 ? value : undefined\n}\n\n/**\n * Shared writer for both the non-interactive `setup.applyAccountConfig`\n * adapter and the interactive wizard. Maintains the same flat-vs-accounts\n * invariant: default account uses flat form iff no `accounts` key is present;\n * named accounts always nest under `accounts.<id>`.\n */\nexport function applyAgentchatAccountPatch(\n cfg: OpenClawConfig | undefined,\n accountId: string,\n patch: Record<string, unknown>,\n): OpenClawConfig {\n const channels: Record<string, unknown> = {\n ...((cfg as { channels?: Record<string, unknown> } | undefined)?.channels ?? {}),\n }\n const currentSection = channels[AGENTCHAT_CHANNEL_ID]\n const section: ChannelSectionRaw =\n currentSection && typeof currentSection === 'object' && !Array.isArray(currentSection)\n ? { ...(currentSection as ChannelSectionRaw) }\n : {}\n\n if (accountId === AGENTCHAT_DEFAULT_ACCOUNT_ID && !section.accounts) {\n Object.assign(section, patch)\n } else {\n const accounts: Record<string, unknown> = {\n ...((section.accounts as Record<string, unknown> | undefined) ?? {}),\n }\n const prevAccount =\n typeof accounts[accountId] === 'object' && accounts[accountId] !== null\n ? (accounts[accountId] as Record<string, unknown>)\n : {}\n accounts[accountId] = { ...prevAccount, ...patch }\n section.accounts = accounts\n }\n\n channels[AGENTCHAT_CHANNEL_ID] = section\n return { ...(cfg ?? {}), channels } as OpenClawConfig\n}\n","/**\n * Single source of truth for the package version string.\n *\n * Kept as a hand-edited constant (not an `import ... from '../package.json'`)\n * so that tsup can bundle ESM/CJS without requiring `resolveJsonModule` +\n * runtime filesystem access from inside the published dist. A unit test\n * (`tests/version.test.ts`) pins this against `package.json` so bumping one\n * without the other fails CI.\n */\nexport const PACKAGE_VERSION = '0.9.2'\n","import type { AgentChatClientIdentity } from 'agentchatme'\n\nimport { PACKAGE_VERSION } from './version.js'\n\n/** The server's low-cardinality client taxonomy names this plugin `openclaw`. */\nexport const AGENTCHAT_CLIENT_NAME = 'openclaw'\n\n/** What the SDK client and the realtime client announce on every request and HELLO. */\nexport const AGENTCHAT_CLIENT_IDENTITY: Readonly<AgentChatClientIdentity> = {\n name: AGENTCHAT_CLIENT_NAME,\n version: PACKAGE_VERSION,\n}\n\n/** The same identity as headers, for the plugin's own `fetch` calls (setup, the hosted-MCP probe). */\nexport const AGENTCHAT_CLIENT_HEADERS: Readonly<Record<string, string>> = {\n 'X-AgentChat-Client': AGENTCHAT_CLIENT_NAME,\n 'X-AgentChat-Client-Version': PACKAGE_VERSION,\n}\n","/**\n * Minimal HTTP client used by the setup plugin (P7) to:\n * - verify an API key is live before finalizing setup (`validateApiKey`)\n * - drive the email-OTP self-registration flow for agents without a key yet\n * (`registerAgentStart` → `registerAgentVerify`)\n * - drive the email-OTP recovery flow that re-issues a lost API key\n * (`recoverAgentStart` → `recoverAgentVerify`)\n *\n * Why this lives separately from `outbound.ts`:\n * - `outbound.ts` is the hot-path message sender. It wants retries, a circuit\n * breaker, metrics, and a long-lived `fetch`. Setup is one-shot, low-rate,\n * user-interactive — a 200ms validation call doesn't need any of that.\n * - Setup runs before the runtime exists; coupling it to `OutboundAdapter`\n * (which expects a parsed `AgentchatChannelConfig`) would force an odd\n * partial-config path during registration.\n *\n * The server endpoints this module targets are stable AgentChat REST calls:\n * - `GET /v1/agents/me` → 200 OK when the key authenticates\n * - `POST /v1/register` → 200 with `{ pending_id }`\n * - `POST /v1/register/verify` → 201 with `{ agent, api_key }` on success\n * - `POST /v1/agents/recover` → 200 with `{ pending_id, message }` — always,\n * whether or not the email + handle match\n * a live agent (no existence leak)\n * - `POST /v1/agents/recover/verify` → 200 with `{ handle, api_key }` on success\n *\n * Registration and recovery deliberately bypass the `agentchatme` SDK: the\n * SDK's `recover(email)` predates the handle + email recovery contract and\n * has no way to send `handle`, and the pinned SDK floor cannot move until a\n * compatible SDK is published. Owning these four calls here keeps the plugin\n * on the current server contract regardless of which SDK version resolves.\n *\n * Per-email policy (server-enforced, the numbers live in the server's\n * `agent_email_policy` row and are NOT hard-coded here): an email can back\n * up to `max_active` live agents and `max_lifetime` registrations overall.\n * The server quotes the number that applies in `details.limit`; every\n * user-facing string built from these results must quote that value rather\n * than assume one.\n *\n * All methods return strongly-typed result unions — setup UIs can `switch` on\n * the discriminant without guessing at HTTP status codes.\n */\n\nimport { AgentChatChannelError } from './errors.js'\nimport { AGENTCHAT_CLIENT_HEADERS } from './client-identity.js'\n\nconst DEFAULT_API_BASE = 'https://api.agentchat.me'\nconst DEFAULT_TIMEOUT_MS = 10_000\n\n/** Subset of the AgentChat agent row the setup surface needs to show the user. */\nexport interface AgentchatAgentIdentity {\n readonly handle: string\n readonly displayName: string | null\n readonly email: string\n readonly createdAt: string\n}\n\nexport type ValidateApiKeyResult =\n | { readonly ok: true; readonly agent: AgentchatAgentIdentity }\n | {\n readonly ok: false\n /** High-level reason code the UI can map to a localized message. */\n readonly reason:\n | 'unauthorized'\n | 'forbidden'\n | 'deleted'\n | 'network-error'\n | 'unreachable'\n | 'server-error'\n | 'unexpected-shape'\n readonly message: string\n readonly status?: number\n }\n\nexport interface ValidateApiKeyOptions {\n readonly apiBase?: string\n readonly fetch?: typeof fetch\n readonly timeoutMs?: number\n}\n\n/**\n * Probe the API key against `GET /v1/agents/me`. Returns a discriminated\n * result — never throws on HTTP or network errors. The caller decides how\n * to surface each failure mode to the user.\n */\nexport async function validateApiKey(\n apiKey: string,\n opts: ValidateApiKeyOptions = {},\n): Promise<ValidateApiKeyResult> {\n if (!apiKey || typeof apiKey !== 'string') {\n return { ok: false, reason: 'unauthorized', message: 'API key is empty' }\n }\n const base = (opts.apiBase ?? DEFAULT_API_BASE).replace(/\\/+$/, '')\n const url = `${base}/v1/agents/me`\n const controller = new AbortController()\n const fetchImpl = opts.fetch ?? fetch\n const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS\n const timer = setTimeout(() => controller.abort(), timeoutMs)\n\n let res: Response\n try {\n res = await fetchImpl(url, {\n method: 'GET',\n headers: {\n Authorization: `Bearer ${apiKey}`,\n Accept: 'application/json',\n ...AGENTCHAT_CLIENT_HEADERS,\n },\n signal: controller.signal,\n })\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err)\n const unreachable =\n err instanceof Error &&\n (err.name === 'AbortError' || /ECONN|ETIMEDOUT|ENOTFOUND|EAI_AGAIN/i.test(message))\n return {\n ok: false,\n reason: unreachable ? 'unreachable' : 'network-error',\n message: `agentchat: GET /v1/agents/me failed: ${message}`,\n }\n } finally {\n clearTimeout(timer)\n }\n\n if (res.status === 401) {\n return { ok: false, reason: 'unauthorized', status: 401, message: 'API key is invalid or revoked' }\n }\n if (res.status === 403) {\n return { ok: false, reason: 'forbidden', status: 403, message: 'API key lacks permission to read /agents/me' }\n }\n if (res.status === 410) {\n return { ok: false, reason: 'deleted', status: 410, message: 'Agent account has been deleted' }\n }\n if (res.status >= 500) {\n return { ok: false, reason: 'server-error', status: res.status, message: `AgentChat API returned ${res.status}` }\n }\n if (!res.ok) {\n return {\n ok: false,\n reason: 'server-error',\n status: res.status,\n message: `AgentChat API returned ${res.status}`,\n }\n }\n\n const body = (await res.json().catch(() => null)) as {\n handle?: unknown\n display_name?: unknown\n email?: unknown\n email_masked?: unknown\n created_at?: unknown\n } | null\n // The live `GET /v1/agents/me` endpoint masks PII: it returns\n // `email_masked` (e.g. `a****@agentchat.local`), never the real `email`.\n // Accept either so tests that stub an unmasked body still pass, but the\n // caller should expect a masked value in production.\n const email =\n typeof body?.email === 'string'\n ? body.email\n : typeof body?.email_masked === 'string'\n ? body.email_masked\n : null\n if (!body || typeof body.handle !== 'string' || email === null || typeof body.created_at !== 'string') {\n return {\n ok: false,\n reason: 'unexpected-shape',\n status: res.status,\n message: 'AgentChat /agents/me returned an unrecognized shape',\n }\n }\n return {\n ok: true,\n agent: {\n handle: body.handle,\n displayName: typeof body.display_name === 'string' ? body.display_name : null,\n email,\n createdAt: body.created_at,\n },\n }\n}\n\n// ─── Self-registration (email + OTP) ───────────────────────────────────\n\nexport interface RegisterAgentStartInput {\n readonly email: string\n readonly handle: string\n readonly displayName?: string\n readonly description?: string\n}\n\n/**\n * Per-email policy rejections, shared by `/register` and `/register/verify`\n * (the pre-check fires at start; the DB trigger is the race-proof net at\n * verify time, and the server maps both to the same 409 shapes).\n *\n * - `email-limit-reached` — the email already backs the maximum number of\n * live agents. Also what the retired `EMAIL_TAKEN` code from a server\n * that predates the multi-agent policy collapses into: that server\n * allowed exactly one live agent per email, so \"taken\" means \"at its\n * limit\" — just without a `limit` to quote.\n * - `email-exhausted` — the email has used up its lifetime registration\n * budget (deleted agents count). Only a different email helps.\n */\nexport type EmailPolicyReason = 'email-limit-reached' | 'email-exhausted'\n\nexport type RegisterStartResult =\n | { readonly ok: true; readonly pendingId: string }\n | {\n readonly ok: false\n readonly reason:\n | 'invalid-handle'\n | 'handle-taken'\n | EmailPolicyReason\n | 'rate-limited'\n | 'otp-failed'\n | 'network-error'\n | 'server-error'\n | 'validation'\n readonly message: string\n readonly status?: number\n readonly retryAfterSeconds?: number\n /**\n * The policy number the server quoted in `details.limit` for an\n * `email-limit-reached` / `email-exhausted` rejection. Absent when the\n * server did not send one (legacy `EMAIL_TAKEN`); callers must then\n * fall back to `message` instead of guessing a number.\n */\n readonly limit?: number\n }\n\nexport interface RegisterAgentVerifyInput {\n readonly pendingId: string\n readonly code: string\n}\n\nexport type RegisterVerifyResult =\n | {\n readonly ok: true\n readonly apiKey: string\n readonly agent: AgentchatAgentIdentity\n }\n | {\n readonly ok: false\n readonly reason:\n | 'expired'\n | 'invalid-code'\n | 'rate-limited'\n | 'handle-taken'\n | EmailPolicyReason\n | 'network-error'\n | 'server-error'\n | 'unexpected-shape'\n | 'validation'\n readonly message: string\n readonly status?: number\n readonly retryAfterSeconds?: number\n /** See `RegisterStartResult.limit`. */\n readonly limit?: number\n }\n\nexport interface RegisterOptions {\n readonly apiBase?: string\n readonly fetch?: typeof fetch\n readonly timeoutMs?: number\n}\n\n/**\n * Kick off an email-OTP registration. Server caches the intent under a\n * `pending_id` for 10 minutes and emails a 6-digit code to `email`.\n */\nexport async function registerAgentStart(\n input: RegisterAgentStartInput,\n opts: RegisterOptions = {},\n): Promise<RegisterStartResult> {\n const res = await post('/v1/register', input, opts)\n if (res.kind === 'network') {\n return { ok: false, reason: 'network-error', message: res.message }\n }\n if (res.kind === 'timeout') {\n return { ok: false, reason: 'network-error', message: 'request timed out' }\n }\n\n const body = (res.body as { pending_id?: unknown; code?: unknown; message?: unknown; details?: unknown }) ?? {}\n\n if (res.status === 200) {\n if (typeof body.pending_id !== 'string') {\n return {\n ok: false,\n reason: 'server-error',\n status: 200,\n message: 'AgentChat /register returned no pending_id',\n }\n }\n return { ok: true, pendingId: body.pending_id }\n }\n\n const code = typeof body.code === 'string' ? body.code : ''\n const message = typeof body.message === 'string' ? body.message : `status ${res.status}`\n\n if (res.status === 400 && code === 'INVALID_HANDLE') return { ok: false, reason: 'invalid-handle', message, status: 400 }\n if (res.status === 400 && code === 'VALIDATION_ERROR') return { ok: false, reason: 'validation', message, status: 400 }\n if (res.status === 409 && code === 'HANDLE_TAKEN') return { ok: false, reason: 'handle-taken', message, status: 409 }\n const emailPolicy = res.status === 409 ? classifyEmailPolicyRejection(code) : undefined\n if (emailPolicy) {\n return { ok: false, reason: emailPolicy, message, status: 409, limit: readPolicyLimit(body.details) }\n }\n if (res.status === 429) {\n return {\n ok: false,\n reason: 'rate-limited',\n message,\n status: 429,\n retryAfterSeconds: res.retryAfterSeconds,\n }\n }\n if (res.status >= 500 || code === 'OTP_FAILED') return { ok: false, reason: 'otp-failed', message, status: res.status }\n return { ok: false, reason: 'server-error', status: res.status, message }\n}\n\n/** Verify the OTP the user received by email and mint the API key. */\nexport async function registerAgentVerify(\n input: RegisterAgentVerifyInput,\n opts: RegisterOptions = {},\n): Promise<RegisterVerifyResult> {\n const res = await post('/v1/register/verify', { pending_id: input.pendingId, code: input.code }, opts)\n if (res.kind === 'network') return { ok: false, reason: 'network-error', message: res.message }\n if (res.kind === 'timeout') return { ok: false, reason: 'network-error', message: 'request timed out' }\n\n const body = (res.body ?? {}) as {\n code?: unknown\n message?: unknown\n details?: unknown\n agent?: { handle?: unknown; display_name?: unknown; email?: unknown; created_at?: unknown }\n api_key?: unknown\n }\n\n if (res.status === 201) {\n const agent = body.agent\n if (\n typeof body.api_key !== 'string' ||\n !agent ||\n typeof agent.handle !== 'string' ||\n typeof agent.email !== 'string' ||\n typeof agent.created_at !== 'string'\n ) {\n return {\n ok: false,\n reason: 'unexpected-shape',\n status: 201,\n message: 'AgentChat /register/verify returned an unrecognized shape',\n }\n }\n return {\n ok: true,\n apiKey: body.api_key,\n agent: {\n handle: agent.handle,\n displayName: typeof agent.display_name === 'string' ? agent.display_name : null,\n email: agent.email,\n createdAt: agent.created_at,\n },\n }\n }\n\n const code = typeof body.code === 'string' ? body.code : ''\n const message = typeof body.message === 'string' ? body.message : `status ${res.status}`\n\n if (res.status === 400 && code === 'EXPIRED') return { ok: false, reason: 'expired', message, status: 400 }\n if (res.status === 400 && code === 'INVALID_CODE') return { ok: false, reason: 'invalid-code', message, status: 400 }\n if (res.status === 400 && code === 'VALIDATION_ERROR') return { ok: false, reason: 'validation', message, status: 400 }\n if (res.status === 409 && code === 'HANDLE_TAKEN') return { ok: false, reason: 'handle-taken', message, status: 409 }\n // The verify-time insert runs under the same per-email policy as the\n // start pre-check (a DB trigger is the race-proof net), so the same\n // 409 shapes can surface here when sibling registrations raced us.\n const emailPolicy = res.status === 409 ? classifyEmailPolicyRejection(code) : undefined\n if (emailPolicy) {\n return { ok: false, reason: emailPolicy, message, status: 409, limit: readPolicyLimit(body.details) }\n }\n if (res.status === 429) {\n return { ok: false, reason: 'rate-limited', message, status: 429, retryAfterSeconds: res.retryAfterSeconds }\n }\n return { ok: false, reason: 'server-error', status: res.status, message }\n}\n\n// ─── API-key recovery (handle + email + OTP) ────────────────────────────\n\nexport interface RecoverAgentStartInput {\n /** Email the agent registered with. Normalized server-side (lowercase/trim). */\n readonly email: string\n /**\n * Handle of the agent whose key is being re-issued. Required — not\n * optional — because one email can back several agents and the server\n * can only pick the right one when told. A client that omits it gets a\n * `HANDLE_REQUIRED` at verify time on a multi-agent email; this type\n * makes that path unreachable from the plugin.\n */\n readonly handle: string\n}\n\nexport type RecoverStartResult =\n | {\n readonly ok: true\n readonly pendingId: string\n /**\n * The server's generic acknowledgement. It is deliberately the same\n * whether or not the email + handle matched a live agent, so surface\n * it verbatim — do not paraphrase it into \"code sent\".\n */\n readonly message: string\n }\n | {\n readonly ok: false\n readonly reason: 'validation' | 'rate-limited' | 'network-error' | 'server-error' | 'unexpected-shape'\n readonly message: string\n readonly status?: number\n readonly retryAfterSeconds?: number\n }\n\nexport interface RecoverAgentVerifyInput {\n readonly pendingId: string\n readonly code: string\n}\n\nexport type RecoverVerifyResult =\n | {\n readonly ok: true\n /** Freshly minted key. The previous key is revoked the moment this is issued. */\n readonly apiKey: string\n /** Handle the new key authenticates as — the source of truth for `agentHandle`. */\n readonly handle: string\n }\n | {\n readonly ok: false\n readonly reason:\n | 'expired'\n | 'invalid-code'\n | 'rate-limited'\n | 'handle-required'\n | 'network-error'\n | 'server-error'\n | 'unexpected-shape'\n | 'validation'\n readonly message: string\n readonly status?: number\n readonly retryAfterSeconds?: number\n /**\n * `handle-required` only: the live handles on that email, in\n * registration order. The server lists them here and nowhere else —\n * the caller has just proven inbox control. Show them and ask the\n * user to run recovery again naming one.\n */\n readonly handles?: readonly string[]\n }\n\n/**\n * Kick off a recovery. The server always answers `200 { pending_id, message }`\n * — for a matching agent it emails a 6-digit code; for a non-matching\n * email + handle it mints a decoy `pending_id` so step 2 behaves identically\n * (the code simply never validates). Nothing in this response reveals\n * whether the agent exists.\n */\nexport async function recoverAgentStart(\n input: RecoverAgentStartInput,\n opts: RegisterOptions = {},\n): Promise<RecoverStartResult> {\n const res = await post('/v1/agents/recover', { email: input.email, handle: input.handle }, opts)\n if (res.kind === 'network') return { ok: false, reason: 'network-error', message: res.message }\n if (res.kind === 'timeout') return { ok: false, reason: 'network-error', message: 'request timed out' }\n\n const body = (res.body ?? {}) as { pending_id?: unknown; code?: unknown; message?: unknown }\n const message = typeof body.message === 'string' ? body.message : `status ${res.status}`\n\n if (res.status === 200) {\n if (typeof body.pending_id !== 'string') {\n // A server that predates the handle + email contract omits\n // `pending_id` when nothing matched the email — and sends no code.\n // Stop here rather than let the user wait on an email that is not\n // coming.\n return {\n ok: false,\n reason: 'unexpected-shape',\n status: 200,\n message:\n 'AgentChat did not start a recovery (no pending_id in the response). Check that the email is the one this agent registered with.',\n }\n }\n return { ok: true, pendingId: body.pending_id, message }\n }\n\n const code = typeof body.code === 'string' ? body.code : ''\n if (res.status === 400 && code === 'VALIDATION_ERROR') return { ok: false, reason: 'validation', message, status: 400 }\n if (res.status === 429) {\n return { ok: false, reason: 'rate-limited', message, status: 429, retryAfterSeconds: res.retryAfterSeconds }\n }\n return { ok: false, reason: 'server-error', status: res.status, message }\n}\n\n/** Verify the recovery code and receive the re-issued API key. */\nexport async function recoverAgentVerify(\n input: RecoverAgentVerifyInput,\n opts: RegisterOptions = {},\n): Promise<RecoverVerifyResult> {\n const res = await post('/v1/agents/recover/verify', { pending_id: input.pendingId, code: input.code }, opts)\n if (res.kind === 'network') return { ok: false, reason: 'network-error', message: res.message }\n if (res.kind === 'timeout') return { ok: false, reason: 'network-error', message: 'request timed out' }\n\n const body = (res.body ?? {}) as {\n code?: unknown\n message?: unknown\n details?: unknown\n handle?: unknown\n api_key?: unknown\n }\n\n if (res.status === 200) {\n if (typeof body.api_key !== 'string' || typeof body.handle !== 'string') {\n return {\n ok: false,\n reason: 'unexpected-shape',\n status: 200,\n message: 'AgentChat /agents/recover/verify returned an unrecognized shape',\n }\n }\n return { ok: true, apiKey: body.api_key, handle: body.handle }\n }\n\n const code = typeof body.code === 'string' ? body.code : ''\n const message = typeof body.message === 'string' ? body.message : `status ${res.status}`\n\n if (res.status === 400 && code === 'EXPIRED') return { ok: false, reason: 'expired', message, status: 400 }\n if (res.status === 400 && code === 'INVALID_CODE') return { ok: false, reason: 'invalid-code', message, status: 400 }\n if (res.status === 400 && code === 'VALIDATION_ERROR') return { ok: false, reason: 'validation', message, status: 400 }\n if (res.status === 409 && code === 'HANDLE_REQUIRED') {\n return { ok: false, reason: 'handle-required', message, status: 409, handles: readHandleList(body.details) }\n }\n if (res.status === 429) {\n return { ok: false, reason: 'rate-limited', message, status: 429, retryAfterSeconds: res.retryAfterSeconds }\n }\n return { ok: false, reason: 'server-error', status: res.status, message }\n}\n\n// ─── Internals ─────────────────────────────────────────────────────────\n\n/**\n * Map a 409 error code from `/register` or `/register/verify` onto the\n * per-email policy reasons. `EMAIL_TAKEN` is the retired single-agent code;\n * see `EmailPolicyReason` for why it folds into `email-limit-reached`.\n */\nfunction classifyEmailPolicyRejection(code: string): EmailPolicyReason | undefined {\n if (code === 'EMAIL_LIMIT_REACHED' || code === 'EMAIL_TAKEN') return 'email-limit-reached'\n if (code === 'EMAIL_EXHAUSTED') return 'email-exhausted'\n return undefined\n}\n\n/**\n * `details.limit` from a policy rejection, or undefined when the server\n * sent none or sent garbage. Guarded to a positive integer so a malformed\n * body can never produce \"already backs NaN agents\" in the UI.\n */\nfunction readPolicyLimit(details: unknown): number | undefined {\n if (!details || typeof details !== 'object') return undefined\n const limit = (details as { limit?: unknown }).limit\n return typeof limit === 'number' && Number.isInteger(limit) && limit > 0 ? limit : undefined\n}\n\n/**\n * `details.handles` from a `HANDLE_REQUIRED` rejection. Non-string entries\n * are dropped rather than rendered as `[object Object]`; a missing or\n * malformed list yields `[]` so the caller's copy degrades to the plain\n * instruction without crashing.\n */\nfunction readHandleList(details: unknown): readonly string[] {\n if (!details || typeof details !== 'object') return []\n const handles = (details as { handles?: unknown }).handles\n if (!Array.isArray(handles)) return []\n return handles.filter((h): h is string => typeof h === 'string' && h.length > 0)\n}\n\ntype PostOutcome =\n | { kind: 'http'; status: number; body: unknown; retryAfterSeconds?: number }\n | { kind: 'network'; message: string }\n | { kind: 'timeout' }\n\nasync function post(path: string, body: unknown, opts: RegisterOptions): Promise<PostOutcome> {\n const base = (opts.apiBase ?? DEFAULT_API_BASE).replace(/\\/+$/, '')\n const url = `${base}${path}`\n const controller = new AbortController()\n const fetchImpl = opts.fetch ?? fetch\n const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS\n const timer = setTimeout(() => controller.abort(), timeoutMs)\n try {\n const res = await fetchImpl(url, {\n method: 'POST',\n headers: {\n 'content-type': 'application/json',\n accept: 'application/json',\n ...AGENTCHAT_CLIENT_HEADERS,\n },\n body: JSON.stringify(body),\n signal: controller.signal,\n })\n const parsed = await res.json().catch(() => null)\n const retryAfterHeader = res.headers.get('retry-after')\n const retryAfterSeconds = retryAfterHeader ? Number(retryAfterHeader) : undefined\n return {\n kind: 'http',\n status: res.status,\n body: parsed,\n retryAfterSeconds: Number.isFinite(retryAfterSeconds) ? retryAfterSeconds : undefined,\n }\n } catch (err) {\n if (err instanceof Error && err.name === 'AbortError') return { kind: 'timeout' }\n return { kind: 'network', message: err instanceof Error ? err.message : String(err) }\n } finally {\n clearTimeout(timer)\n }\n}\n\n/**\n * Throw-flavored wrapper used by callers that prefer exception control flow\n * (the setup plugin's `afterAccountConfigWritten` hook). Converts a failure\n * result into an `AgentChatChannelError` with an appropriate class.\n */\nexport async function assertApiKeyValid(\n apiKey: string,\n opts: ValidateApiKeyOptions = {},\n): Promise<AgentchatAgentIdentity> {\n const result = await validateApiKey(apiKey, opts)\n if (result.ok) return result.agent\n const class_ =\n result.reason === 'unauthorized' || result.reason === 'forbidden' || result.reason === 'deleted'\n ? 'terminal-auth'\n : result.reason === 'server-error'\n ? 'retry-transient'\n : 'retry-transient'\n throw new AgentChatChannelError(class_, `${result.message} [reason=${result.reason}]`, {\n statusCode: result.status,\n })\n}\n","/**\n * Turns: the names OpenClaw gives the hosted tools, the prompts a turn starts\n * with, and the session keys and lane the turns run on.\n *\n * No product text lives here. The wake instruction and the invite prompt are\n * served by AgentChat (`GET /v1/texts`, fetched by `./texts.ts`) and placed\n * by this module; the one line of our own states a fact (which conversation\n * the gate decided to answer), never judgement.\n *\n * OpenClaw exposes an MCP server's tools to the model as `<server>__<tool>`:\n * the tool-policy pipeline builds the namespace prefix as\n * `normalizeToolName(sanitizeServerName(serverName) + \"__\")`\n * (`openclaw/dist/tool-policy-*.js`, 2026.6.10) and the docs describe the\n * same shape (docs.openclaw.ai/tools/mcp). The server spells the hosted\n * tools by their bare names (`agentchat_inbox`); `spellToolsForOpenClaw`\n * re-spells exactly those tokens so the agent is told the names it can call.\n */\n\nimport type { Texts, ToolNamer } from 'agentchatme'\n\n/** Name of the MCP server entry this plugin places. Changing it changes every tool name the model sees — keep in lockstep with `./mcp.ts`. */\nexport const MCP_SERVER_NAME = 'agentchat'\n\n/** OpenClaw's MCP namespace delimiter. */\nexport const MCP_TOOL_DELIMITER = '__'\n\n/** The bundled manual, as OpenClaw loads it: the `agentchat` skill. */\nexport const SKILL_NAME = 'agentchat'\n\nconst MCP_TOOL_PREFIX = `${MCP_SERVER_NAME}${MCP_TOOL_DELIMITER}`\n\n/** `agentchat_inbox` → `agentchat__agentchat_inbox`. */\nexport function mcpToolName(tool: string): string {\n return `${MCP_TOOL_PREFIX}${tool}`\n}\n\nexport const INBOX_TOOL = mcpToolName('agentchat_inbox')\nexport const DECIDE_TOOL = mcpToolName('agentchat_decide')\nexport const GET_CONVERSATION_TOOL = mcpToolName('agentchat_get_conversation')\nexport const SEND_MESSAGE_TOOL = mcpToolName('agentchat_send_message')\n\n/**\n * How OpenClaw spells a hosted tool. Idempotent: a name that already carries\n * the server prefix is returned as is, so a server that one day serves the\n * OpenClaw spelling itself is not prefixed twice.\n */\nexport const OPENCLAW_TOOL_NAMER: ToolNamer = (tool) => (tool.startsWith(MCP_TOOL_PREFIX) ? tool : mcpToolName(tool))\n\n// A bare hosted tool name: `agentchat_` followed by the tool, never a second\n// underscore (which is the already-prefixed form) and never inside a longer\n// word. `api.agentchat.me` carries no underscore and is untouched.\nconst HOSTED_TOOL_TOKEN = /\\bagentchat_(?!_)[a-z0-9_]+\\b/g\n\n/** Re-spell every bare hosted tool name in a served text the way OpenClaw exposes it. Pure, idempotent. */\nexport function spellToolsForOpenClaw(text: string): string {\n return text.replace(HOSTED_TOOL_TOKEN, (token) => OPENCLAW_TOOL_NAMER(token))\n}\n\n/**\n * The prompt a wake turn starts with: the served wake instruction and, when\n * the gate decided a specific conversation, one factual line naming it. The\n * `reply` verdict is recorded when the turn has completed — never at its\n * start — so while the turn runs the conversation is still unread and its\n * card still on the tray; the line says so and names the conversation to\n * open. The model may record its own verdict in the turn (the served texts\n * tell it to record `reply` after its send, or `dismiss` when it read and\n * chose not to answer); the invoker then records nothing more for it. Only\n * a turn that recorded none gets `reply` from the host when it completes.\n */\nexport function wakeTurnPrompt(texts: Pick<Texts, 'wake_instruction'>, conversationId?: string): string {\n const instruction = texts.wake_instruction.trim()\n if (!conversationId) return instruction\n return `${instruction}\\n\\n${conversationLine(conversationId)}`\n}\n\n/** The one line of ours in a wake turn: facts about this turn, with OpenClaw's tool name. */\nexport function conversationLine(conversationId: string): string {\n return (\n `Conversation to answer in this turn: ${conversationId}. The gate decided reply; its card is still on the tray while you work, ` +\n `and the reply verdict for it is recorded for you when this turn completes unless you record one yourself with ${DECIDE_TOOL} ` +\n `(reply after your answer is sent, or dismiss if you read and choose not to answer) — ` +\n `open it with ${GET_CONVERSATION_TOOL} and reply.`\n )\n}\n\n/** The prompt a group-invite turn starts with: the served invite prompt. */\nexport function inviteTurnPrompt(texts: Pick<Texts, 'invite_prompt'>): string {\n return texts.invite_prompt.trim()\n}\n\n/**\n * A fresh OpenClaw session per wake turn, in the shape OpenClaw's own\n * documentation uses for plugin-owned runs\n * (`agent:<agentId>:subagent:<name>`, docs.openclaw.ai/plugins/sdk-runtime/background-work).\n * The conversation state lives on the server and is read through the\n * hosted tools inside the turn; a per-wake session keeps OpenClaw's own\n * history from growing without bound and stays greppable in its session\n * store.\n */\nexport function wakeSessionKey(agentId: string, now: number = Date.now(), nonce: string = randomNonce()): string {\n return `agent:${agentId}:subagent:agentchat-wake-${utcStamp(now)}-${nonce}`\n}\n\nexport function inviteSessionKey(agentId: string, inviteId: string): string {\n return `agent:${agentId}:subagent:agentchat-invite-${sanitizeKeyPart(inviteId)}`\n}\n\n/** One serialization lane per account so AgentChat turns never block the agent's main lane and never overlap each other. */\nexport function integrationLane(accountId: string): string {\n return `agentchat-integration:${sanitizeKeyPart(accountId)}`\n}\n\nfunction utcStamp(ms: number): string {\n return new Date(ms).toISOString().replace(/[-:]/g, '').replace(/\\.\\d{3}Z$/, 'Z')\n}\n\nfunction randomNonce(): string {\n return Math.random().toString(16).slice(2, 8).padEnd(6, '0')\n}\n\nfunction sanitizeKeyPart(value: string): string {\n const clean = value.replace(/[^A-Za-z0-9_-]/g, '-')\n return clean.length > 0 ? clean : 'x'\n}\n","/**\n * The hosted AgentChat MCP server as OpenClaw sees it.\n *\n * The tools an agent uses on AgentChat are defined once, in the hosted tool\n * layer at `https://api.agentchat.me/mcp` (Streamable HTTP, bearer key). The\n * integration does not define tools; it tells OpenClaw where they are.\n *\n * What OpenClaw offers, verified against the installed 2026.6.10 package and\n * the current docs (docs.openclaw.ai/tools/mcp, /plugins/manifest,\n * /gateway/configuration/environment-variables):\n *\n * - `mcp.servers.<name>` in `openclaw.json` declares a remote MCP server:\n * `url`, `transport: \"streamable-http\"` (a `url` without `transport`\n * defaults to SSE, so it is always set), `headers`, `enabled`, timeouts,\n * `toolFilter` (`McpServerConfig`, `plugin-sdk/config-types`).\n * - Any config string value may reference an environment variable as\n * `${VAR_NAME}`; OpenClaw reads the process environment plus `.env` in the\n * working directory and `~/.openclaw/.env` at start. The key therefore\n * lives in the gateway's environment, and the header in config is a\n * template — never the key itself.\n * - A plugin manifest may also carry `mcpServers` (same shape, active while\n * the plugin is enabled, overridden by an operator `mcp.servers` entry of\n * the same name). Whether manifest header values pass through the config\n * loader's `${VAR}` substitution is not documented and could not be\n * confirmed in the installed build, and an unresolved template would send\n * a literal bearer string before the wizard has placed anything. This\n * plugin therefore places the operator entry below from the wizard and\n * the doctor (where substitution is documented) and does not declare the\n * server in the manifest.\n * - Tools reach the model as `<server>__<tool>` (see `./turn.ts`), and a\n * server's `instructions` are injected into the system prompt, capped at\n * 2,000 characters per server.\n */\n\nimport { AGENTCHAT_CLIENT_HEADERS } from '../client-identity.js'\nimport { API_KEY_ENV } from '../credentials/read-env.js'\nimport { MCP_SERVER_NAME } from './turn.js'\n\nexport const MCP_PATH = '/mcp'\nexport const AUTH_HEADER_TEMPLATE = `Bearer \\${${API_KEY_ENV}}`\nexport const DEFAULT_API_BASE = 'https://api.agentchat.me'\n\n/** The MCP protocol revision this probe speaks; the server answers with the one it serves. */\nconst MCP_PROTOCOL_VERSION = '2025-06-18'\n\nexport function hostedMcpUrl(apiBase: string = DEFAULT_API_BASE): string {\n return `${apiBase.replace(/\\/+$/, '')}${MCP_PATH}`\n}\n\nexport interface McpServerEntry {\n readonly url: string\n readonly transport: 'streamable-http'\n readonly headers: { readonly Authorization: string }\n}\n\n/** The `mcp.servers.agentchat` value this plugin places. */\nexport function hostedMcpServerEntry(apiBase: string = DEFAULT_API_BASE): McpServerEntry {\n return {\n url: hostedMcpUrl(apiBase),\n transport: 'streamable-http',\n headers: { Authorization: AUTH_HEADER_TEMPLATE },\n }\n}\n\n/** The same entry as JSON5, for the README and for operators placing it by hand. */\nexport function hostedMcpSnippet(apiBase: string = DEFAULT_API_BASE): string {\n return [\n '{',\n ' mcp: {',\n ' servers: {',\n ` ${MCP_SERVER_NAME}: {`,\n ` url: \"${hostedMcpUrl(apiBase)}\",`,\n ' transport: \"streamable-http\",',\n ` headers: { Authorization: \"${AUTH_HEADER_TEMPLATE}\" },`,\n ' },',\n ' },',\n ' },',\n '}',\n ].join('\\n')\n}\n\nexport type McpEntryState = 'missing' | 'ours' | 'user_managed' | 'disabled'\n\n/**\n * Classify the `mcp.servers.agentchat` entry in an OpenClaw config object.\n * OpenClaw hands plugins the env-substituted config, so an entry we wrote\n * with the `${AGENTCHAT_API_KEY}` template comes back carrying the key\n * itself; `apiKey` lets the classifier recognise it as ours.\n */\nexport function describeMcpEntry(cfg: unknown, apiBase: string = DEFAULT_API_BASE, apiKey?: string): McpEntryState {\n const servers = (cfg as { mcp?: { servers?: unknown } } | undefined)?.mcp?.servers\n if (!servers || typeof servers !== 'object' || Array.isArray(servers)) return 'missing'\n const entry = (servers as Record<string, unknown>)[MCP_SERVER_NAME]\n if (entry === undefined || entry === null) return 'missing'\n if (typeof entry !== 'object' || Array.isArray(entry)) return 'user_managed'\n const record = entry as Record<string, unknown>\n if (record.enabled === false) return 'disabled'\n return pointsAtUs(record, apiBase, apiKey) ? 'ours' : 'user_managed'\n}\n\n/**\n * URL is the hosted endpoint and the transport is Streamable HTTP; the\n * Authorization header, when present, is either the `${AGENTCHAT_API_KEY}`\n * template or — after OpenClaw's env substitution — a bearer equal to the\n * configured key. Extra keys the user added (timeouts, `toolFilter`) keep\n * the entry \"ours\"; a different URL, transport or credential do not — those\n * are the user's decisions and are never modified.\n */\nfunction pointsAtUs(entry: Record<string, unknown>, apiBase: string, apiKey: string | undefined): boolean {\n if (entry.url !== hostedMcpUrl(apiBase)) return false\n if (entry.transport !== 'streamable-http') return false\n const headers = entry.headers\n if (headers === undefined) return true\n if (!headers || typeof headers !== 'object' || Array.isArray(headers)) return false\n const auth = (headers as Record<string, unknown>).Authorization ?? (headers as Record<string, unknown>).authorization\n if (auth === undefined) return true\n if (typeof auth !== 'string') return false\n if (auth === AUTH_HEADER_TEMPLATE || auth.includes(`\\${${API_KEY_ENV}}`)) return true\n return apiKey !== undefined && apiKey.length > 0 && auth.trim() === `Bearer ${apiKey}`\n}\n\nexport type McpEntryOutcome = 'added' | 'present' | 'user_managed' | 'disabled'\n\n/**\n * Return a config with `mcp.servers.agentchat` present. Pure: the caller\n * persists the result through OpenClaw (the wizard returns it; the doctor\n * returns it as a repair). A same-name entry the user wrote themselves\n * always wins and is never modified.\n */\nexport function withHostedMcpEntry<T extends object>(\n cfg: T | undefined,\n apiBase: string = DEFAULT_API_BASE,\n apiKey?: string,\n): { cfg: T; outcome: McpEntryOutcome } {\n const state = describeMcpEntry(cfg, apiBase, apiKey)\n const base = (cfg ?? {}) as T\n if (state === 'ours') return { cfg: base, outcome: 'present' }\n if (state === 'user_managed') return { cfg: base, outcome: 'user_managed' }\n if (state === 'disabled') return { cfg: base, outcome: 'disabled' }\n const mcp = { ...((base as { mcp?: Record<string, unknown> }).mcp ?? {}) }\n const servers = { ...((mcp.servers as Record<string, unknown> | undefined) ?? {}) }\n servers[MCP_SERVER_NAME] = hostedMcpServerEntry(apiBase)\n mcp.servers = servers\n return { cfg: { ...base, mcp } as T, outcome: 'added' }\n}\n\n/** Return a config without the entry when it is ours; a hand-written entry is left alone. */\nexport function withoutHostedMcpEntry<T extends object>(cfg: T, apiBase: string = DEFAULT_API_BASE, apiKey?: string): { cfg: T; removed: boolean } {\n if (describeMcpEntry(cfg, apiBase, apiKey) !== 'ours') return { cfg, removed: false }\n const mcp = { ...((cfg as { mcp?: Record<string, unknown> }).mcp ?? {}) }\n const servers = { ...((mcp.servers as Record<string, unknown> | undefined) ?? {}) }\n delete servers[MCP_SERVER_NAME]\n mcp.servers = servers\n return { cfg: { ...cfg, mcp } as T, removed: true }\n}\n\nexport interface McpProbeResult {\n readonly ok: boolean\n readonly status?: number\n readonly serverName?: string\n readonly serverVersion?: string\n readonly protocolVersion?: string\n /** Whether the server published `instructions` (OpenClaw injects them into the system prompt). */\n readonly hasInstructions?: boolean\n readonly error?: string\n}\n\n/**\n * Doctor check: is the hosted MCP server reachable with this key? Sends one\n * MCP `initialize` over Streamable HTTP with the bearer key — the same\n * request OpenClaw makes on connect — and reads the server's answer. A\n * `401` means the key does not authenticate; a transport error means the\n * endpoint is not reachable from here.\n */\nexport async function probeHostedMcp(params: {\n apiKey: string\n apiBase?: string\n timeoutMs?: number\n fetch?: typeof fetch\n}): Promise<McpProbeResult> {\n const fetchImpl = params.fetch ?? fetch\n const controller = new AbortController()\n const timer = setTimeout(() => controller.abort(), params.timeoutMs ?? 10_000)\n try {\n const res = await fetchImpl(hostedMcpUrl(params.apiBase ?? DEFAULT_API_BASE), {\n method: 'POST',\n headers: {\n authorization: `Bearer ${params.apiKey}`,\n 'content-type': 'application/json',\n accept: 'application/json, text/event-stream',\n ...AGENTCHAT_CLIENT_HEADERS,\n },\n body: JSON.stringify({\n jsonrpc: '2.0',\n id: 1,\n method: 'initialize',\n params: {\n protocolVersion: MCP_PROTOCOL_VERSION,\n capabilities: {},\n clientInfo: { name: '@agentchatme/openclaw doctor', version: '0' },\n },\n }),\n signal: controller.signal,\n })\n if (!res.ok) {\n return { ok: false, status: res.status, error: res.status === 401 ? 'the key does not authenticate against the hosted MCP server' : `HTTP ${res.status}` }\n }\n const text = await res.text()\n const result = readInitializeResult(text)\n if (!result) return { ok: false, status: res.status, error: 'no initialize result in the answer' }\n const serverInfo = (result.serverInfo ?? {}) as Record<string, unknown>\n return {\n ok: true,\n status: res.status,\n serverName: typeof serverInfo.name === 'string' ? serverInfo.name : undefined,\n serverVersion: typeof serverInfo.version === 'string' ? serverInfo.version : undefined,\n protocolVersion: typeof result.protocolVersion === 'string' ? result.protocolVersion : undefined,\n hasInstructions: typeof result.instructions === 'string' && result.instructions.trim().length > 0,\n }\n } catch (err) {\n return { ok: false, error: err instanceof Error ? err.message : String(err) }\n } finally {\n clearTimeout(timer)\n }\n}\n\n/** The initialize result from a JSON body or an SSE body (`data: {...}` lines). */\nfunction readInitializeResult(text: string): Record<string, unknown> | null {\n const candidates: string[] = []\n const trimmed = text.trim()\n if (trimmed.startsWith('{')) candidates.push(trimmed)\n for (const line of text.split(/\\r?\\n/)) {\n if (line.startsWith('data:')) candidates.push(line.slice(5).trim())\n }\n for (const candidate of candidates) {\n try {\n const parsed = JSON.parse(candidate) as Record<string, unknown>\n const result = parsed.result\n if (result && typeof result === 'object' && !Array.isArray(result)) return result as Record<string, unknown>\n } catch {\n // not JSON — try the next candidate\n }\n }\n return null\n}\n","/**\n * The OpenClaw `PluginRuntime` handed to this plugin at registration.\n *\n * `defineChannelPluginEntry({ setRuntime })` (openclaw/plugin-sdk/channel-core)\n * calls `setRuntime(runtime)` in every registration mode except\n * `cli-metadata` and `tool-discovery` (docs.openclaw.ai/plugins/sdk-entrypoints/define-channel-plugin-entry).\n * The integration needs two of its helpers:\n *\n * - `runtime.llm.complete(...)` — the gate call on the agent's own model (tool-free).\n * - `runtime.subagent.run({ deliver: false, ... })` — one agent turn whose\n * final text is not routed anywhere; the agent's send is its own hosted\n * tool call.\n *\n * Stored here, read by `./model.ts`. Tests inject a fake through\n * `setPluginRuntime` and clear it with `resetPluginRuntimeForTest`.\n */\n\nimport type { PluginRuntime } from 'openclaw/plugin-sdk/channel-core'\n\nlet current: PluginRuntime | null = null\n\n/**\n * OpenClaw 2026.10.9 loads a channel plugin for `channels add` in a\n * \"setup-only\" registration mode whose `api.runtime` is a Proxy that throws\n * on ANY property access — and still calls `setRuntime(api.runtime)`. A\n * guarded probe tells the real runtime from that proxy; the proxy is not\n * stored, so `getPluginRuntime()` is `null` in setup and nothing downstream\n * believes it has a runtime it cannot use.\n */\nexport function isUsablePluginRuntime(runtime: unknown): runtime is PluginRuntime {\n if (!runtime || (typeof runtime !== 'object' && typeof runtime !== 'function')) return false\n try {\n const probe = (runtime as { config?: unknown }).config\n return probe !== undefined || 'llm' in (runtime as object)\n } catch {\n return false\n }\n}\n\nexport function setPluginRuntime(runtime: PluginRuntime): void {\n current = isUsablePluginRuntime(runtime) ? runtime : null\n}\n\nexport function getPluginRuntime(): PluginRuntime | null {\n return current\n}\n\nexport function resetPluginRuntimeForTest(): void {\n current = null\n}\n","/**\n * Where the integration meets OpenClaw's agent runtime.\n *\n * Two things only, both on the `PluginRuntime` OpenClaw hands a channel entry\n * through `defineChannelPluginEntry({ setRuntime })`:\n *\n * 1. **The gate call** — `runtime.llm.complete({ messages, maxTokens,\n * temperature, purpose })` runs one tool-free completion on the agent's\n * own configured model and credentials (`LlmCompleteParams`,\n * `plugin-sdk/types`; docs.openclaw.ai/plugins/sdk-runtime/models). The\n * prompt is the SDK's rendering of the server's question and cards\n * (`gate.buildPrompt`); nothing of ours is added. No tools are passed:\n * the gate is a triage, and the integration records the verdicts. Without\n * an `agentId` OpenClaw uses the ambient default agent; passing one is an\n * OVERRIDE that OpenClaw 2026.10.9 rejects with\n * `LLM_COMPLETION_NOT_AUTHORIZED` unless the operator set\n * `plugins.entries.agentchat.llm.allowAgentIdOverride: true`. The\n * integration therefore passes `agentId` only when the account is\n * genuinely routed to a non-default agent (`agentIdOverride`), and the\n * wizard / doctor write the opt-in in that case.\n *\n * 2. **The turn** — `runtime.subagent.run({ sessionKey, message, lane,\n * deliver: false })` admits one agent run with the prompt as its message\n * and no delivery of its final text (`SubagentRunParams`;\n * docs.openclaw.ai/plugins/sdk-runtime/background-work — the same shape\n * OpenClaw's own background features use with `deliver: false`). The\n * turn's output is never routed anywhere: the agent's only way to say\n * something on AgentChat is the hosted `agentchat__agentchat_send_message`\n * tool during the turn. Admission and completion are reported separately\n * (`TurnAdmission`): the invoker records the `reply` verdict the moment\n * the run is admitted, and `runtime.subagent.waitForRun` bounds how long\n * it waits before the next cycle may start; it never cancels the run.\n *\n * The agent id is resolved the way OpenClaw routes inbound for this channel\n * (`channelRuntime.routing.resolveAgentRoute`), so the integration wakes the\n * agent the operator bound to the account; `main` when nothing is bound.\n */\n\nimport type { PluginRuntime } from 'openclaw/plugin-sdk/channel-core'\nimport type { GateModelCall } from 'agentchatme'\n\nimport { getPluginRuntime } from './runtime-holder.js'\nimport { describeMcpEntry } from './mcp.js'\nimport { MCP_SERVER_NAME } from './turn.js'\nimport { AGENTCHAT_CHANNEL_ID } from '../channel-account.js'\nimport { API_KEY_ENV } from '../credentials/read-env.js'\n\nexport type { GateModelCall }\n\n/** OpenClaw's default agent id when an account has no explicit binding. */\nexport const DEFAULT_AGENT_ID = 'main'\n\n/** The gate is a short JSON verdict; `temperature: 0` keeps it as deterministic as the provider allows. */\nconst GATE_TEMPERATURE = 0\n\n/** Output ceiling for the verdict JSON: a few dozen tokens per card. The tray is capped at 50 cards server-side. */\nexport const DEFAULT_GATE_MAX_TOKENS = 2048\n\n/** Decision-call timeout. The gate must never block the integration forever. */\nexport const DEFAULT_GATE_TIMEOUT_MS = 20_000\n\n/** How long one turn may run before the invoker moves on. Bounds the wait, not the run. */\nexport const DEFAULT_TURN_WAIT_MS = 15 * 60_000\n\nexport class RuntimeUnavailableError extends Error {\n constructor(what: string) {\n super(`OpenClaw plugin runtime unavailable — ${what} needs setRuntime(...) from defineChannelPluginEntry`)\n this.name = 'RuntimeUnavailableError'\n }\n}\n\n/** The slice of OpenClaw's channel runtime surface the integration reads. */\nexport type ChannelRuntimeLike = {\n readonly routing?: {\n readonly resolveAgentRoute?: (params: {\n cfg: unknown\n channel: string\n accountId: string\n peer: { kind: 'direct' | 'group' | 'channel'; id: string | number }\n }) => { agentId?: unknown; sessionKey?: unknown } | undefined\n }\n readonly [key: string]: unknown\n}\n\n/**\n * The agent OpenClaw would route this account's inbound to. A synthetic\n * direct peer (`wake`) is enough for the agent binding — bindings match on\n * channel and account, and we need no per-peer session here.\n */\nexport function resolveIntegrationAgentId(params: {\n cfg: unknown\n accountId: string\n channelRuntime: ChannelRuntimeLike | undefined\n}): string {\n try {\n const route = params.channelRuntime?.routing?.resolveAgentRoute?.({\n cfg: params.cfg,\n channel: AGENTCHAT_CHANNEL_ID,\n accountId: params.accountId,\n peer: { kind: 'direct', id: 'wake' },\n })\n const agentId = route?.agentId\n if (typeof agentId === 'string' && agentId.trim().length > 0) return agentId.trim()\n } catch {\n // Routing is OpenClaw's; a failure there falls back to the default agent.\n }\n return DEFAULT_AGENT_ID\n}\n\n/**\n * The gate's model call for production: one tool-free completion on the\n * agent's own model through `runtime.llm.complete`. The SDK's rendered\n * prompt is the single user message; no system prompt, no tools.\n * `agentIdOverride` is set only when the account is routed to an agent\n * other than OpenClaw's ambient default (see the module header); the\n * default path sends no `agentId` at all.\n */\nexport function createRuntimeModelCall(params: {\n agentIdOverride?: string | undefined\n runtime?: () => PluginRuntime | null\n maxTokens?: number\n timeoutMs?: number\n}): GateModelCall {\n const getRuntime = params.runtime ?? getPluginRuntime\n const maxTokens = params.maxTokens ?? DEFAULT_GATE_MAX_TOKENS\n const timeoutMs = params.timeoutMs ?? DEFAULT_GATE_TIMEOUT_MS\n return async (prompt) => {\n const runtime = getRuntime()\n if (!runtime) throw new RuntimeUnavailableError('the gate call')\n const result = await runtime.llm.complete({\n messages: [{ role: 'user', content: prompt }],\n maxTokens,\n temperature: GATE_TEMPERATURE,\n ...(params.agentIdOverride ? { agentId: params.agentIdOverride } : {}),\n purpose: 'AgentChat reply gate: the server\\'s question about the server\\'s cards (tool-free triage)',\n ...(Number.isFinite(timeoutMs) && timeoutMs > 0 ? { signal: AbortSignal.timeout(timeoutMs) } : {}),\n })\n return typeof result?.text === 'string' ? result.text : ''\n }\n}\n\n/** The config key OpenClaw reads before honouring an `agentId` override on `llm.complete`. */\nexport const LLM_AGENT_OVERRIDE_PATH = 'plugins.entries.agentchat.llm.allowAgentIdOverride'\n\nexport function readLlmAgentOverrideOptIn(cfg: unknown): boolean {\n const entries = (cfg as { plugins?: { entries?: Record<string, unknown> } } | undefined)?.plugins?.entries\n const entry = entries && typeof entries === 'object' ? (entries as Record<string, unknown>).agentchat : undefined\n const llm = entry && typeof entry === 'object' ? (entry as { llm?: unknown }).llm : undefined\n return Boolean(llm && typeof llm === 'object' && (llm as { allowAgentIdOverride?: unknown }).allowAgentIdOverride === true)\n}\n\n/** Return a config with the override opt-in set (pure; the caller persists it). */\nexport function withLlmAgentOverrideOptIn<T extends object>(cfg: T): { cfg: T; changed: boolean } {\n if (readLlmAgentOverrideOptIn(cfg)) return { cfg, changed: false }\n const plugins = { ...((cfg as { plugins?: Record<string, unknown> }).plugins ?? {}) }\n const entries = { ...((plugins.entries as Record<string, unknown> | undefined) ?? {}) }\n const entry = { ...((entries.agentchat as Record<string, unknown> | undefined) ?? {}) }\n const llm = { ...((entry.llm as Record<string, unknown> | undefined) ?? {}) }\n llm.allowAgentIdOverride = true\n entry.llm = llm\n entries.agentchat = entry\n plugins.entries = entries\n return { cfg: { ...cfg, plugins } as T, changed: true }\n}\n\n/**\n * Which agent the integration wakes, and whether that is an override\n * OpenClaw must be told about. `routed` is what OpenClaw's routing returns\n * for this account (an explicit binding, or the default); `ambient` is\n * OpenClaw's default agent. They differ only when the operator bound the\n * AgentChat account to another agent.\n */\nexport function resolveGateAgent(params: { routedAgentId: string; ambientAgentId: string | undefined }): {\n agentId: string\n agentIdOverride: string | undefined\n} {\n const routed = params.routedAgentId.trim().toLowerCase()\n const ambient = params.ambientAgentId?.trim().toLowerCase()\n return { agentId: routed, agentIdOverride: routed === (ambient ?? routed) ? undefined : routed }\n}\n\nexport interface TurnRequest {\n readonly sessionKey: string\n readonly prompt: string\n readonly lane: string\n}\n\nexport interface TurnOutcome {\n readonly ran: boolean\n readonly runId?: string\n readonly status?: string\n readonly error?: string\n}\n\n/**\n * What starting a turn tells the invoker: refused (OpenClaw did not admit\n * the run — no runtime, a thrown `subagent.run`), or admitted with a bounded\n * promise of the outcome.\n */\nexport type TurnAdmission =\n | { readonly ran: false; readonly error: string }\n | { readonly ran: true; readonly runId: string; readonly done: Promise<TurnOutcome> }\n\n/** Starts one agent turn. Injectable so the invoker is testable without OpenClaw. */\nexport type TurnStarter = (request: TurnRequest) => Promise<TurnAdmission>\n\n/** Whether a turn started now can look at AgentChat at all; `reason` is the operator line when it cannot. */\nexport type TurnReadiness = { readonly ready: true } | { readonly ready: false; readonly reason: string }\n\n/**\n * The gateway config as it is NOW. OpenClaw hot-applies `mcp.*` changes (a\n * running gateway's turns have the tools right after `openclaw doctor --fix`\n * wrote the entry), so a readiness check must not read the snapshot the\n * account started with. `runtime.config.loadConfig()` is that live read;\n * without a usable runtime, or if it throws, the snapshot is what there is\n * (`live: false`) — and then a config fix needs a restart to be seen.\n */\nexport function readLiveConfig(fallback: unknown, runtime: () => PluginRuntime | null = getPluginRuntime): { cfg: unknown; live: boolean } {\n try {\n const loaded: unknown = runtime()?.config?.loadConfig?.()\n if (loaded && typeof loaded === 'object') return { cfg: loaded, live: true }\n } catch {\n // fall through to the snapshot\n }\n return { cfg: fallback, live: false }\n}\n\n/**\n * What can be known from inside the gateway about the hosted tools a turn\n * will have. OpenClaw discovers MCP servers per turn and the plugin runtime\n * exposes no tool catalog, so the plugin cannot ask which tools a run gets;\n * it can check the two things that decide it: the `mcp.servers.agentchat`\n * entry is in the gateway config (enabled), and the credential its bearer\n * template names is in this process's environment (OpenClaw resolves\n * `${AGENTCHAT_API_KEY}` from the gateway env; a gateway started before the\n * wizard wrote `.env` holds the unresolved template until it restarts or\n * reloads). A hand-written entry is the operator's and counts as ready.\n *\n * The invoker checks this before the gate: while unready nothing is asked,\n * nothing recorded, the cards wait on the tray and the ladder re-wakes —\n * instead of a turn running blind and then marking the conversation read.\n * `live: false` means `cfg` is the start-time snapshot (see `readLiveConfig`),\n * so a config fix is only seen after a restart; the reason says so then.\n */\nexport function turnReadiness(params: { cfg: unknown; apiBase: string; apiKey: string; env?: NodeJS.ProcessEnv; live?: boolean }): TurnReadiness {\n const env = params.env ?? process.env\n const restart = params.live === false ? ', then restart the gateway (this gateway cannot re-read its config while running)' : ''\n switch (describeMcpEntry(params.cfg, params.apiBase, params.apiKey)) {\n case 'missing':\n return { ready: false, reason: `mcp.servers.${MCP_SERVER_NAME} is not in the gateway config — run \\`openclaw doctor --fix\\`${restart}` }\n case 'disabled':\n return { ready: false, reason: `mcp.servers.${MCP_SERVER_NAME} is disabled in the gateway config — enable it${restart}` }\n case 'user_managed':\n return { ready: true }\n case 'ours': {\n const value = env[API_KEY_ENV]\n if (typeof value !== 'string' || value.trim().length === 0) {\n return {\n ready: false,\n reason: `${API_KEY_ENV} is not set in the gateway process, so the hosted tools' bearer template cannot resolve — restart the gateway (or reload its config) once ~/.openclaw/.env carries it`,\n }\n }\n return { ready: true }\n }\n }\n}\n\n/**\n * The turn starter for production. `deliver: false` — the final text is\n * recorded by OpenClaw and announced nowhere. The run's result is never read\n * by the integration: the agent's send is a hosted-tool call inside the\n * turn. `done` resolves when the run ends or `waitMs` passes, whichever\n * comes first; it never rejects.\n */\nexport function createRuntimeTurnStarter(params: {\n runtime?: () => PluginRuntime | null\n waitMs?: number\n} = {}): TurnStarter {\n const getRuntime = params.runtime ?? getPluginRuntime\n const waitMs = params.waitMs ?? DEFAULT_TURN_WAIT_MS\n return async (request) => {\n const runtime = getRuntime()\n if (!runtime) return { ran: false, error: new RuntimeUnavailableError('the agent turn').message }\n let runId: string\n try {\n const admitted = await runtime.subagent.run({\n sessionKey: request.sessionKey,\n message: request.prompt,\n lane: request.lane,\n deliver: false,\n })\n runId = admitted.runId\n } catch (err) {\n return { ran: false, error: err instanceof Error ? err.message : String(err) }\n }\n const done = runtime.subagent\n .waitForRun({ runId, timeoutMs: waitMs })\n .then(\n (waited): TurnOutcome => ({ ran: true, runId, status: waited.status, ...(waited.error ? { error: waited.error } : {}) }),\n // The run was admitted; only the wait failed. The turn is OpenClaw's now.\n (err): TurnOutcome => ({ ran: true, runId, status: 'unknown', error: err instanceof Error ? err.message : String(err) }),\n )\n return { ran: true, runId, done }\n }\n}\n","/**\n * Placing the four things AgentChat authored where OpenClaw loads them.\n *\n * 1. **The key** — `AGENTCHAT_API_KEY=…` in OpenClaw's state-dir `.env`\n * (`~/.openclaw/.env`, or `$OPENCLAW_STATE_DIR/.env`), which OpenClaw\n * reads at start as its global environment fallback. The hosted MCP\n * server's bearer header is a template on that variable, so the key is\n * never written into `openclaw.json` as part of the tool declaration.\n * (The channel's own `channels.agentchat.apiKey` keeps holding the key\n * for the socket, as before.)\n * 2. **The identity line** — the served `identity_line` (`GET /v1/texts`,\n * `../integration/texts.ts`) in the workspace `AGENTS.md`, loaded into\n * every turn (`../binding/agents-anchor.ts`). The callers fetch the text\n * (server, then the cached copy) and hand it in; with neither available\n * the step is skipped and reported, never invented.\n * 3. **The manual** — `https://agentchat.me/skill.md` verbatim, bundled as\n * the `agentchat` skill. Nothing to write; verified present.\n * 4. **The tools** — `mcp.servers.agentchat` in `openclaw.json` (`./mcp.ts`),\n * returned as a config patch for OpenClaw to persist.\n *\n * Every placer is idempotent and reports what it did; the wizard prints the\n * report, the status probe and the doctor run the checks again.\n */\n\nimport * as fs from 'node:fs'\nimport * as path from 'node:path'\n\nimport { API_KEY_ENV } from '../credentials/read-env.js'\nimport { resolveBoundAgentId, resolveOpenClawDefaultAgentId, resolveOpenClawStateDir } from '../openclaw-layout.js'\nimport { describeMcpEntry, hostedMcpUrl, withHostedMcpEntry, withoutHostedMcpEntry, type McpEntryOutcome } from './mcp.js'\nimport { LLM_AGENT_OVERRIDE_PATH, withLlmAgentOverrideOptIn } from './model.js'\nimport { writeAgentsAnchor, agentsAnchorPath, hasAgentsAnchorFor, readAgentsAnchor, removeAgentsAnchor } from '../binding/agents-anchor.js'\nimport {\n AGENTCHAT_CHANNEL_ID,\n AGENTCHAT_DEFAULT_ACCOUNT_ID,\n agentchatReenableHint,\n applyAgentchatAccountPatch,\n isAgentchatAccountEnabled,\n readAgentchatConfigField,\n} from '../channel-account.js'\n\nconst HANDLE_PATTERN = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/\nfunction isValidHandleShape(value: string): boolean {\n return value.length >= 3 && value.length <= 30 && HANDLE_PATTERN.test(value)\n}\n\nexport type PlacementStatus = 'ok' | 'changed' | 'skipped' | 'failed'\n\nexport interface PlacementStep {\n readonly name: 'key' | 'anchor' | 'manual' | 'mcp'\n readonly status: PlacementStatus\n readonly detail: string\n}\n\nconst DOTENV_NAME = '.env'\n\nexport { resolveOpenClawStateDir }\n\nexport function dotEnvPath(stateDir: string = resolveOpenClawStateDir()): string {\n return path.join(stateDir, DOTENV_NAME)\n}\n\n/**\n * Upsert `AGENTCHAT_API_KEY=<key>` in the state-dir `.env`. Other lines are\n * kept byte for byte; the file is created `0600` when absent. Returns the\n * path and whether the content changed.\n */\nexport function placeApiKeyInDotEnv(apiKey: string, stateDir: string = resolveOpenClawStateDir()): { path: string; changed: boolean } {\n const trimmed = apiKey.trim()\n if (!trimmed) throw new Error('placeApiKeyInDotEnv: key is empty')\n if (/[\\r\\n]/.test(trimmed)) throw new Error('placeApiKeyInDotEnv: key contains a line break')\n const file = dotEnvPath(stateDir)\n fs.mkdirSync(stateDir, { recursive: true })\n const existing = fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : ''\n const next = upsertDotEnvLine(existing, API_KEY_ENV, trimmed)\n if (next === existing) return { path: file, changed: false }\n fs.writeFileSync(file, next, { encoding: 'utf8', mode: 0o600 })\n try {\n fs.chmodSync(file, 0o600)\n } catch {\n // Best effort: a filesystem without POSIX modes keeps its own defaults.\n }\n return { path: file, changed: true }\n}\n\n/** Blank the key line (keeps the variable name so a later placement finds its slot). */\nexport function clearApiKeyInDotEnv(stateDir: string = resolveOpenClawStateDir()): { path: string; changed: boolean } {\n const file = dotEnvPath(stateDir)\n if (!fs.existsSync(file)) return { path: file, changed: false }\n const existing = fs.readFileSync(file, 'utf8')\n const next = existing\n .split(/\\r?\\n/)\n .filter((line) => !lineSetsVariable(line, API_KEY_ENV))\n .join('\\n')\n if (next === existing) return { path: file, changed: false }\n fs.writeFileSync(file, next, { encoding: 'utf8', mode: 0o600 })\n return { path: file, changed: true }\n}\n\n/** The value the state-dir `.env` holds for the key, if any. */\nexport function readApiKeyFromDotEnv(stateDir: string = resolveOpenClawStateDir()): string | undefined {\n const file = dotEnvPath(stateDir)\n if (!fs.existsSync(file)) return undefined\n for (const line of fs.readFileSync(file, 'utf8').split(/\\r?\\n/)) {\n if (!lineSetsVariable(line, API_KEY_ENV)) continue\n const value = line.slice(line.indexOf('=') + 1).trim()\n return stripQuotes(value) || undefined\n }\n return undefined\n}\n\nexport function upsertDotEnvLine(content: string, name: string, value: string): string {\n const line = `${name}=${value}`\n const lines = content.length > 0 ? content.split(/\\r?\\n/) : []\n let replaced = false\n const out = lines.map((existing) => {\n if (!replaced && lineSetsVariable(existing, name)) {\n replaced = true\n return line\n }\n return existing\n })\n if (!replaced) {\n if (out.length > 0 && out[out.length - 1] !== '') out.push(line)\n else if (out.length > 0) out.splice(out.length - 1, 0, line)\n else out.push(line)\n }\n let next = out.join('\\n')\n if (!next.endsWith('\\n')) next += '\\n'\n return next\n}\n\nfunction lineSetsVariable(line: string, name: string): boolean {\n const trimmed = line.trim()\n if (trimmed.startsWith('#')) return false\n const body = trimmed.startsWith('export ') ? trimmed.slice('export '.length).trim() : trimmed\n return body.startsWith(`${name}=`)\n}\n\nfunction stripQuotes(value: string): string {\n if (value.length >= 2 && ((value.startsWith('\"') && value.endsWith('\"')) || (value.startsWith(\"'\") && value.endsWith(\"'\")))) {\n return value.slice(1, -1)\n }\n return value\n}\n\n// ─── the config side of placement (pure) ───────────────────────────────\n\nexport interface IntegrationConfigParams {\n readonly accountId: string\n /** The handle the key authenticates as; omitted when not yet known (an older OpenClaw without `prepareAccountConfigInput`). */\n readonly handle?: string | undefined\n readonly apiKey: string\n readonly apiBase: string\n}\n\n/**\n * Everything placement writes INTO `openclaw.json`, as one pure patch:\n * `channels.agentchat.agentHandle` (the handle the key authenticates as),\n * `mcp.servers.agentchat` (the hosted tools), and — only when the account\n * is bound to an agent other than OpenClaw's default —\n * `plugins.entries.agentchat.llm.allowAgentIdOverride`. Returns the config\n * and one line per change, for the wizard, the non-interactive hook (through\n * `runtime.config.mutateConfigFile`) and `doctor --fix` alike.\n */\nexport function applyIntegrationConfig<TCfg extends object>(cfg: TCfg, params: IntegrationConfigParams): { cfg: TCfg; changes: string[] } {\n const changes: string[] = []\n let next: TCfg = cfg\n const bareHandle = (params.handle ?? '').trim().replace(/^@/, '')\n if (bareHandle && readAgentchatConfigField(next as never, params.accountId, 'agentHandle') !== bareHandle && isValidHandleShape(bareHandle)) {\n next = applyAgentchatAccountPatch(next as never, params.accountId, { agentHandle: bareHandle }) as unknown as TCfg\n changes.push(`channels.agentchat${params.accountId === AGENTCHAT_DEFAULT_ACCOUNT_ID ? '' : `.accounts.${params.accountId}`}.agentHandle = ${bareHandle}`)\n }\n const mcp = withHostedMcpEntry(next, params.apiBase, params.apiKey)\n next = mcp.cfg\n if (mcp.outcome === 'added') changes.push(`mcp.servers.agentchat → ${hostedMcpUrl(params.apiBase)} (bearer template on ${API_KEY_ENV})`)\n const bound = resolveBoundAgentId(next, AGENTCHAT_CHANNEL_ID, params.accountId)\n const ambient = resolveOpenClawDefaultAgentId(next)\n if (bound && bound !== (ambient ?? bound)) {\n const optIn = withLlmAgentOverrideOptIn(next)\n next = optIn.cfg\n if (optIn.changed) changes.push(`${LLM_AGENT_OVERRIDE_PATH} = true (account bound to agent \"${bound}\", not the default)`)\n }\n return { cfg: next, changes }\n}\n\n/** The agent this account's identity line belongs to: the bound agent, else OpenClaw's default. */\nexport function resolvePlacementAgentId(cfg: object | undefined, accountId: string): string | undefined {\n return resolveBoundAgentId(cfg, AGENTCHAT_CHANNEL_ID, accountId) ?? resolveOpenClawDefaultAgentId(cfg)\n}\n\n/**\n * Undo the config side of placement for an account that is being disabled\n * or deleted: the plugin's own `mcp.servers.agentchat` entry goes (a\n * hand-written one stays). Pure; shared by `config.setAccountEnabled`,\n * `config.deleteAccount` and the wizard's `disable`.\n */\nexport function stripIntegrationConfig<TCfg extends object>(cfg: TCfg, accountId: string): { cfg: TCfg; changes: string[] } {\n const apiBase = readAgentchatConfigField(cfg as never, accountId, 'apiBase') ?? 'https://api.agentchat.me'\n const apiKey = readAgentchatConfigField(cfg as never, accountId, 'apiKey')\n const { cfg: next, removed } = withoutHostedMcpEntry(cfg, apiBase, apiKey)\n return { cfg: next, changes: removed ? ['removed mcp.servers.agentchat'] : [] }\n}\n\n/**\n * Undo the file side of placement: the identity line in the bound agent's\n * `AGENTS.md`, and — on delete — the key line in the state-dir `.env`.\n * Best-effort: a filesystem error never blocks a remove.\n */\nexport function removeIntegrationFiles(cfg: object | undefined, accountId: string, options: { clearKey: boolean; stateDir?: string }): string[] {\n const changes: string[] = []\n try {\n const removed = removeAgentsAnchor({ cfg: cfg as never, agentId: resolvePlacementAgentId(cfg, accountId) })\n if (removed.removed) changes.push(`removed the identity line from ${removed.path}`)\n } catch {\n // best effort\n }\n if (options.clearKey) {\n try {\n const cleared = clearApiKeyInDotEnv(options.stateDir)\n if (cleared.changed) changes.push(`removed ${API_KEY_ENV} from ${cleared.path}`)\n } catch {\n // best effort\n }\n }\n return changes\n}\n\nexport interface IdentityLineRestore {\n readonly outcome: 'placed' | 'present' | 'failed' | 'skipped'\n readonly path: string\n readonly detail?: string\n}\n\n/**\n * Redo the file side of placement for an enabled account: the served\n * identity line for `handle` in the bound agent's `AGENTS.md` (the\n * workspace resolved the way OpenClaw resolves it). The mirror of\n * `removeIntegrationFiles` on re-enable, and `doctor --fix`'s repair. A\n * line already holding exactly that text is not rewritten — the file stays\n * byte-identical. `identityLine` null (texts unreachable, nothing cached)\n * → `skipped`, nothing written. Never throws.\n */\nexport function restoreIdentityLine(cfg: object | undefined, accountId: string, handle: string, identityLine: string | null): IdentityLineRestore {\n const agentId = resolvePlacementAgentId(cfg, accountId)\n const bare = handle.trim().replace(/^@/, '')\n let filePath = ''\n try {\n filePath = agentsAnchorPath(cfg as never, agentId)\n if (!isValidHandleShape(bare)) return { outcome: 'failed', path: filePath, detail: `agentHandle \"${bare}\" is not a valid AgentChat handle` }\n if (identityLine === null) {\n return { outcome: 'skipped', path: filePath, detail: 'the served identity line is not available (AgentChat unreachable and nothing cached) — run openclaw doctor --fix once it is' }\n }\n const present = hasAgentsAnchorFor({ cfg: cfg as never, handle: bare, text: identityLine, agentId })\n filePath = present.path\n if (present.present) return { outcome: 'present', path: present.path }\n const written = writeAgentsAnchor({ cfg: cfg as never, handle: bare, text: identityLine, agentId })\n return { outcome: 'placed', path: written.path }\n } catch (err) {\n return { outcome: 'failed', path: filePath, detail: describe(err) }\n }\n}\n\n/**\n * The running gateway's duty when a fresh server copy of the text arrives:\n * a block that is PRESENT but holds older text is rewritten; an absent\n * block is left to the wizard / doctor (placement is a setup decision, not a\n * runtime one). Never throws.\n */\nexport function refreshIdentityLine(\n cfg: object | undefined,\n accountId: string,\n handle: string,\n identityLine: string,\n): { outcome: 'updated' | 'unchanged' | 'absent' | 'failed'; path: string; detail?: string } {\n const agentId = resolvePlacementAgentId(cfg, accountId)\n try {\n const found = readAgentsAnchor({ cfg: cfg as never, agentId })\n if (!found.present) return { outcome: 'absent', path: found.path }\n if (found.text === identityLine.trim()) return { outcome: 'unchanged', path: found.path }\n const written = writeAgentsAnchor({ cfg: cfg as never, handle, text: identityLine, agentId })\n return { outcome: 'updated', path: written.path }\n } catch (err) {\n return { outcome: 'failed', path: agentsAnchorPath(cfg as never, agentId), detail: describe(err) }\n }\n}\n\n// ─── placement, as one report ──────────────────────────────────────────\n\nexport interface PlaceParams<TCfg extends object> {\n readonly cfg: TCfg | undefined\n readonly handle: string\n readonly apiKey: string\n readonly apiBase: string\n /** The served identity line (spelled for OpenClaw); `null` when AgentChat was unreachable and nothing is cached. */\n readonly identityLine: string | null\n /** The channel account; selects the bound agent whose workspace holds the identity line. */\n readonly accountId?: string\n /** Explicit agent whose workspace holds the identity line; defaults to the bound agent, else OpenClaw's default. */\n readonly agentId?: string | undefined\n /** Test seam: where the state-dir `.env` lives. */\n readonly stateDir?: string\n /** Test seam: skip the `.env` write (e.g. a read-only CI). */\n readonly placeKey?: boolean\n}\n\nexport interface PlaceResult<TCfg extends object> {\n readonly cfg: TCfg\n readonly steps: readonly PlacementStep[]\n readonly mcp: McpEntryOutcome\n}\n\n/**\n * Key, identity line, manual, tools — in that order. Never throws: each\n * step reports `failed` with the reason instead. Returns the config with\n * the tools entry applied for the caller to persist.\n */\nexport function placeIntegration<TCfg extends object>(params: PlaceParams<TCfg>): PlaceResult<TCfg> {\n const steps: PlacementStep[] = []\n\n if (params.placeKey !== false) {\n try {\n const key = placeApiKeyInDotEnv(params.apiKey, params.stateDir)\n steps.push({\n name: 'key',\n status: key.changed ? 'changed' : 'ok',\n detail: `${API_KEY_ENV} in ${key.path}${key.changed ? ` (a gateway started before this needs a restart, or a config reload, to resolve \\${${API_KEY_ENV}})` : ''}`,\n })\n } catch (err) {\n steps.push({ name: 'key', status: 'failed', detail: `could not write ${API_KEY_ENV} to the OpenClaw .env: ${describe(err)}` })\n }\n }\n\n const agentId = params.agentId ?? resolvePlacementAgentId(params.cfg, params.accountId ?? AGENTCHAT_DEFAULT_ACCOUNT_ID)\n const handle = params.handle.replace(/^@/, '')\n if (params.identityLine === null) {\n steps.push({\n name: 'anchor',\n status: 'skipped',\n detail: `identity line for @${handle} not placed — AgentChat's texts were unreachable and nothing is cached; run openclaw doctor --fix once it is reachable`,\n })\n } else {\n try {\n const anchor = writeAgentsAnchor({ cfg: params.cfg as never, handle: params.handle, text: params.identityLine, agentId })\n steps.push({ name: 'anchor', status: 'ok', detail: `identity line for @${handle} in ${anchor.path}` })\n } catch (err) {\n steps.push({ name: 'anchor', status: 'failed', detail: `could not write the identity line to AGENTS.md: ${describe(err)}` })\n }\n }\n\n steps.push({ name: 'manual', status: 'ok', detail: 'manual bundled as the agentchat skill (skills/agentchat/SKILL.md, https://agentchat.me/skill.md verbatim)' })\n\n const mcp = withHostedMcpEntry(params.cfg, params.apiBase, params.apiKey)\n steps.push(describeMcpOutcome(mcp.outcome, params.apiBase))\n\n return { cfg: mcp.cfg, steps, mcp: mcp.outcome }\n}\n\nexport function describeMcpOutcome(outcome: McpEntryOutcome, apiBase: string): PlacementStep {\n switch (outcome) {\n case 'added':\n return { name: 'mcp', status: 'changed', detail: `hosted tools registered as mcp.servers.agentchat → ${hostedMcpUrl(apiBase)} (bearer template on ${API_KEY_ENV})` }\n case 'present':\n return { name: 'mcp', status: 'ok', detail: 'hosted tools already registered as mcp.servers.agentchat' }\n case 'disabled':\n return { name: 'mcp', status: 'skipped', detail: 'mcp.servers.agentchat exists but is disabled in openclaw.json — left alone' }\n case 'user_managed':\n return { name: 'mcp', status: 'skipped', detail: 'mcp.servers.agentchat is managed by hand in openclaw.json — left alone' }\n }\n}\n\n/** One line per step, for the wizard's note and the status pane. */\nexport function formatPlacement(steps: readonly PlacementStep[]): string[] {\n return steps.map((step) => `${step.status === 'failed' ? '✗' : step.status === 'skipped' ? '–' : '✓'} ${step.name}: ${step.detail}`)\n}\n\n// ─── checks (doctor / status) ──────────────────────────────────────────\n\nexport interface PlacementCheck {\n readonly name: 'key' | 'anchor' | 'manual' | 'mcp'\n readonly ok: boolean\n readonly detail: string\n}\n\nexport function checkPlacement<TCfg extends object>(params: {\n cfg: TCfg | undefined\n handle: string | undefined\n apiKey: string | undefined\n apiBase: string\n /** The served identity line as last seen (cached); without it any of our blocks naming the handle passes. */\n identityLine?: string | null | undefined\n agentId?: string | undefined\n /** The channel account; a disabled one gets the re-enable remedy, never `channels add`. Defaults to `default`. */\n accountId?: string\n stateDir?: string\n /** The gateway's own environment (defaults to `process.env`). */\n env?: NodeJS.ProcessEnv\n}): PlacementCheck[] {\n const checks: PlacementCheck[] = []\n const env = params.env ?? process.env\n const accountId = params.accountId ?? AGENTCHAT_DEFAULT_ACCOUNT_ID\n // While the account is disabled OpenClaw does not load this plugin, and\n // `channels add` would fetch the npm build over it: every remedy for a\n // disabled account is the re-enable route instead.\n const reenable = isAgentchatAccountEnabled(params.cfg as never, accountId) ? undefined : agentchatReenableHint(params.cfg as never, accountId)\n const remedy = (forEnabled: string): string => reenable ?? forEnabled\n\n // What this process can see: its own environment and the state-dir .env.\n // It cannot see the running gateway's environment (OpenClaw loads the\n // state-dir .env into every process, the CLI included), so the wording\n // never claims to.\n const inProcess = (env[API_KEY_ENV] ?? '').trim()\n const inDotEnv = readApiKeyFromDotEnv(params.stateDir)\n if (params.apiKey && (inProcess === params.apiKey || inDotEnv === params.apiKey)) {\n checks.push({\n name: 'key',\n ok: true,\n detail:\n `${API_KEY_ENV} ${inProcess === params.apiKey ? 'present in this process' : `in ${dotEnvPath(params.stateDir)}`}; ` +\n `a gateway started before the wizard placed it needs a restart (or a config reload) to resolve \\${${API_KEY_ENV}}`,\n })\n } else if (inProcess || inDotEnv) {\n checks.push({ name: 'key', ok: false, detail: `${API_KEY_ENV} differs from the configured channel key — ${remedy('re-run the wizard (openclaw channels add agentchat) to place the current key')}` })\n } else {\n checks.push({ name: 'key', ok: false, detail: `${API_KEY_ENV} is not placed — the hosted tools cannot authenticate; ${remedy('run openclaw channels add agentchat')}` })\n }\n\n if (params.handle) {\n const anchor = hasAgentsAnchorFor({ cfg: params.cfg as never, handle: params.handle, text: params.identityLine, agentId: params.agentId })\n checks.push({\n name: 'anchor',\n ok: anchor.present,\n detail: anchor.present\n ? `identity line for @${params.handle} in ${anchor.path}`\n : `identity line for @${params.handle} missing from ${anchor.path} — ${remedy('run openclaw doctor --fix (or openclaw channels add agentchat)')}`,\n })\n } else {\n checks.push({ name: 'anchor', ok: false, detail: `agentHandle not in config — the identity line cannot be checked; ${remedy('run openclaw doctor --fix (it learns the handle from the key)')}` })\n }\n\n checks.push({ name: 'manual', ok: true, detail: 'manual bundled as the agentchat skill' })\n\n const mcpState = describeMcpEntry(params.cfg, params.apiBase, params.apiKey)\n checks.push({\n name: 'mcp',\n ok: mcpState === 'ours' || mcpState === 'user_managed',\n detail:\n mcpState === 'ours'\n ? 'hosted tools registered as mcp.servers.agentchat'\n : mcpState === 'user_managed'\n ? 'mcp.servers.agentchat is managed by hand'\n : mcpState === 'disabled'\n ? 'mcp.servers.agentchat is disabled — the agent has no AgentChat tools'\n : `mcp.servers.agentchat missing — ${remedy('run openclaw doctor --fix (or openclaw channels add agentchat)')}`,\n })\n return checks\n}\n\nexport { agentsAnchorPath }\n\nfunction describe(err: unknown): string {\n return err instanceof Error ? err.message : String(err)\n}\n","/**\n * The plugin's own state on disk: `<OpenClaw state dir>/agentchat/<accountId>/`.\n *\n * Two small JSON files live there, both caches of facts that exist elsewhere:\n * the served texts (`texts.json`, so a gateway can start while the server is\n * unreachable) and the group invites already offered to the agent\n * (`invites.json`, so a restart never starts a second turn for an invite the\n * agent chose to leave pending). Nothing secret, nothing authoritative —\n * deleting the directory costs one texts fetch and, at worst, one repeated\n * invite turn.\n *\n * Writes are atomic (temp file + rename) so a crash mid-write leaves the\n * previous copy, never a truncated one.\n */\n\nimport * as fs from 'node:fs'\nimport * as path from 'node:path'\n\nimport { resolveOpenClawStateDir } from '../openclaw-layout.js'\n\nexport const PLUGIN_STATE_DIRNAME = 'agentchat'\n\nfunction safeSegment(value: string): string {\n const clean = value.replace(/[^A-Za-z0-9_.-]/g, '-').replace(/^\\.+/, '')\n return clean.length > 0 ? clean : 'default'\n}\n\n/** `<state dir>/agentchat/<accountId>` — created on first write. */\nexport function integrationStateDir(accountId: string, stateDir: string = resolveOpenClawStateDir()): string {\n return path.join(stateDir, PLUGIN_STATE_DIRNAME, safeSegment(accountId))\n}\n\n/** Parse a JSON file; `null` when it is absent, unreadable or not valid JSON. */\nexport function readJsonFile(file: string): unknown {\n let raw: string\n try {\n raw = fs.readFileSync(file, 'utf8')\n } catch {\n return null\n }\n try {\n return JSON.parse(raw) as unknown\n } catch {\n return null\n }\n}\n\n/** Write JSON atomically (temp file in the same directory, then rename). Throws on I/O errors. */\nexport function writeJsonFile(file: string, value: unknown): void {\n fs.mkdirSync(path.dirname(file), { recursive: true })\n const tmp = `${file}.${process.pid}.${Date.now().toString(36)}.tmp`\n fs.writeFileSync(tmp, `${JSON.stringify(value, null, 2)}\\n`, 'utf8')\n try {\n fs.renameSync(tmp, file)\n } catch (err) {\n try {\n fs.unlinkSync(tmp)\n } catch {\n // the rename failed; the temp file is the only thing left to clean\n }\n throw err\n }\n}\n","/**\n * The served texts: fetched from AgentChat, never bundled.\n *\n * Every text an agent sees is written once, in AgentChat's experience layer,\n * and served as data (`GET /v1/texts?runtime=openclaw`): the wake\n * instruction a turn starts with, the invite prompt, the identity line that\n * goes into the workspace `AGENTS.md`, and where the manual is. This module\n * fetches them at channel start and every 24 hours, keeps the last copy in\n * the plugin's state dir, and hands them out spelled for OpenClaw (the hosted\n * tools as `agentchat__<tool>`, see `./turn.ts`).\n *\n * When the server is unreachable at start the last cached copy is used; with\n * nothing cached the channel still starts (the socket connects, the gate can\n * run) and logs once — turns wait for the first successful fetch, which is\n * retried every few minutes until it lands.\n */\n\nimport * as path from 'node:path'\n\nimport type { AgentChatClient, Texts } from 'agentchatme'\n\nimport type { Logger } from '../log.js'\nimport { integrationStateDir, readJsonFile, writeJsonFile } from './state.js'\nimport { spellToolsForOpenClaw } from './turn.js'\n\nexport const TEXTS_RUNTIME = 'openclaw' as const\n/** The server suggests a daily refresh. */\nexport const TEXTS_REFRESH_MS = 24 * 60 * 60_000\n/** Until the first copy exists, try again this often. */\nexport const TEXTS_RETRY_MS = 5 * 60_000\n/** One fetch must never hold the channel start for long. */\nexport const TEXTS_FETCH_TIMEOUT_MS = 10_000\nexport const TEXTS_CACHE_FILE = 'texts.json'\n\nexport type TextsClient = Pick<AgentChatClient, 'texts'>\n\nexport interface CachedTexts {\n readonly fetched_at: string\n /** Server-verbatim; spelled for OpenClaw on the way out. */\n readonly texts: Texts\n}\n\nexport type TextsSourceKind = 'server' | 'cache'\n\nexport interface LoadedTexts {\n /** Spelled for OpenClaw. */\n readonly texts: Texts\n readonly source: TextsSourceKind\n readonly fetchedAt: string\n}\n\n/** The shape every consumer relies on. Extra fields a newer server adds pass through. */\nexport function isTexts(value: unknown): value is Texts {\n if (!value || typeof value !== 'object' || Array.isArray(value)) return false\n const t = value as Record<string, unknown>\n const manual = t.manual as Record<string, unknown> | undefined\n return (\n typeof t.version === 'string' &&\n typeof t.wake_instruction === 'string' &&\n t.wake_instruction.length > 0 &&\n typeof t.invite_prompt === 'string' &&\n t.invite_prompt.length > 0 &&\n typeof t.identity_line === 'string' &&\n t.identity_line.length > 0 &&\n typeof t.identity_line_template === 'string' &&\n !!manual &&\n typeof manual === 'object' &&\n typeof manual.url === 'string' &&\n typeof manual.version === 'string'\n )\n}\n\nexport function textsCachePath(accountId: string, stateDir?: string): string {\n return path.join(integrationStateDir(accountId, stateDir), TEXTS_CACHE_FILE)\n}\n\nexport function readCachedTexts(accountId: string, stateDir?: string): CachedTexts | null {\n const raw = readJsonFile(textsCachePath(accountId, stateDir))\n if (!raw || typeof raw !== 'object') return null\n const entry = raw as Record<string, unknown>\n if (typeof entry.fetched_at !== 'string' || !isTexts(entry.texts)) return null\n return { fetched_at: entry.fetched_at, texts: entry.texts }\n}\n\n/** Persist a server copy. Returns the file written. Throws on I/O errors. */\nexport function writeCachedTexts(accountId: string, texts: Texts, fetchedAt: Date, stateDir?: string): string {\n const file = textsCachePath(accountId, stateDir)\n const entry: CachedTexts = { fetched_at: fetchedAt.toISOString(), texts }\n writeJsonFile(file, entry)\n return file\n}\n\n/** The served texts with every hosted tool name spelled the way OpenClaw exposes it. */\nexport function spellTextsForOpenClaw(texts: Texts): Texts {\n return {\n ...texts,\n wake_instruction: spellToolsForOpenClaw(texts.wake_instruction),\n invite_prompt: spellToolsForOpenClaw(texts.invite_prompt),\n identity_line: spellToolsForOpenClaw(texts.identity_line),\n identity_line_template: spellToolsForOpenClaw(texts.identity_line_template),\n }\n}\n\n/** One fetch, server-verbatim. Throws on transport errors, non-2xx answers and an unusable shape. */\nexport async function fetchTexts(client: TextsClient, timeoutMs: number = TEXTS_FETCH_TIMEOUT_MS): Promise<Texts> {\n const texts: unknown = await client.texts.get({ runtime: TEXTS_RUNTIME, timeoutMs })\n if (!isTexts(texts)) throw new Error('GET /v1/texts: answer is not a texts set (missing wake_instruction, invite_prompt or identity_line)')\n return texts\n}\n\nexport interface LoadTextsParams {\n readonly client: TextsClient\n readonly accountId: string\n readonly stateDir?: string | undefined\n readonly now?: () => number\n readonly log?: Logger | undefined\n readonly timeoutMs?: number\n}\n\n/**\n * Server first; the cache when the server cannot be reached. A server\n * success refreshes the cache (a cache write failure is logged, never\n * fatal). `null` when neither is available. Never throws.\n */\nexport async function loadTexts(params: LoadTextsParams): Promise<LoadedTexts | null> {\n const now = params.now ?? Date.now\n try {\n const texts = await fetchTexts(params.client, params.timeoutMs)\n const fetchedAt = new Date(now())\n try {\n writeCachedTexts(params.accountId, texts, fetchedAt, params.stateDir)\n } catch (err) {\n params.log?.warn({ err: describe(err) }, 'texts fetched but the cache could not be written')\n }\n return { texts: spellTextsForOpenClaw(texts), source: 'server', fetchedAt: fetchedAt.toISOString() }\n } catch (err) {\n const cached = readCachedTexts(params.accountId, params.stateDir)\n if (cached) {\n params.log?.info({ err: describe(err), fetchedAt: cached.fetched_at }, 'texts: server unreachable — using the cached copy')\n return { texts: spellTextsForOpenClaw(cached.texts), source: 'cache', fetchedAt: cached.fetched_at }\n }\n params.log?.debug({ err: describe(err) }, 'texts: server unreachable and nothing cached')\n return null\n }\n}\n\n/**\n * The identity line for the key's own agent, spelled for OpenClaw — for the\n * placement paths that run outside the gateway (wizard, `channels add`,\n * `doctor --fix`, re-enable). Server, then cache; `null` when neither.\n */\nexport async function loadIdentityLine(params: LoadTextsParams): Promise<string | null> {\n const loaded = await loadTexts(params)\n return loaded ? loaded.texts.identity_line : null\n}\n\n/** The cached identity line, spelled for OpenClaw, without touching the network (status, doctor preview). */\nexport function cachedIdentityLine(accountId: string, stateDir?: string): string | null {\n const cached = readCachedTexts(accountId, stateDir)\n return cached ? spellToolsForOpenClaw(cached.texts.identity_line) : null\n}\n\nexport interface TextsStoreOptions {\n readonly client: TextsClient\n readonly accountId: string\n readonly logger: Logger\n readonly stateDir?: string | undefined\n readonly refreshMs?: number\n readonly retryMs?: number\n readonly fetchTimeoutMs?: number\n readonly now?: () => number\n readonly setTimeout?: (fn: () => void, ms: number) => NodeJS.Timeout\n readonly clearTimeout?: (handle: NodeJS.Timeout) => void\n}\n\n/**\n * The texts for one running account: loaded at start, refreshed on a timer,\n * available synchronously to the invoker. `ensure()` is what a cycle calls\n * when it needs them: the current copy, or one load attempt right now.\n */\nexport class TextsStore {\n private readonly client: TextsClient\n private readonly accountId: string\n private readonly logger: Logger\n private readonly stateDir: string | undefined\n private readonly refreshMs: number\n private readonly retryMs: number\n private readonly fetchTimeoutMs: number\n private readonly now: () => number\n private readonly _setTimeout: (fn: () => void, ms: number) => NodeJS.Timeout\n private readonly _clearTimeout: (handle: NodeJS.Timeout) => void\n\n private loaded: LoadedTexts | null = null\n private timer: NodeJS.Timeout | null = null\n private inFlight: Promise<Texts | null> | null = null\n private stopped = false\n private missingAnnounced = false\n private readonly listeners = new Set<(texts: Texts, source: TextsSourceKind) => void>()\n\n loads = 0\n serverLoads = 0\n\n constructor(options: TextsStoreOptions) {\n this.client = options.client\n this.accountId = options.accountId\n this.logger = options.logger.child({ component: 'texts', accountId: options.accountId })\n this.stateDir = options.stateDir\n this.refreshMs = options.refreshMs ?? TEXTS_REFRESH_MS\n this.retryMs = options.retryMs ?? TEXTS_RETRY_MS\n this.fetchTimeoutMs = options.fetchTimeoutMs ?? TEXTS_FETCH_TIMEOUT_MS\n this.now = options.now ?? Date.now\n this._setTimeout = options.setTimeout ?? ((fn, ms) => setTimeout(fn, ms))\n this._clearTimeout = options.clearTimeout ?? ((h) => clearTimeout(h))\n }\n\n /** The texts spelled for OpenClaw, or null until the first copy exists. */\n get current(): Texts | null {\n return this.loaded?.texts ?? null\n }\n\n get source(): TextsSourceKind | null {\n return this.loaded?.source ?? null\n }\n\n get fetchedAt(): string | null {\n return this.loaded?.fetchedAt ?? null\n }\n\n /** Called with every copy that arrives from the server (not with a cached one). */\n onServerCopy(listener: (texts: Texts, source: TextsSourceKind) => void): () => void {\n this.listeners.add(listener)\n return () => {\n this.listeners.delete(listener)\n }\n }\n\n /** First load (server, then cache), then the timer. Resolves after the first attempt; never throws. */\n async start(): Promise<Texts | null> {\n const texts = await this.load()\n if (!texts && !this.missingAnnounced) {\n this.missingAnnounced = true\n this.logger.warn(\n { retryMs: this.retryMs },\n 'AgentChat texts unreachable and nothing cached — starting anyway; turns wait for the first copy, retried until it arrives',\n )\n }\n this.arm()\n return texts\n }\n\n /** The current copy, or one load attempt now (coalesced with any in flight). */\n async ensure(): Promise<Texts | null> {\n if (this.loaded) return this.loaded.texts\n if (this.stopped) return null\n return this.load()\n }\n\n /** Force a refresh (tests, operators). Coalesced. */\n refresh(): Promise<Texts | null> {\n return this.load()\n }\n\n stop(): void {\n this.stopped = true\n if (this.timer !== null) {\n this._clearTimeout(this.timer)\n this.timer = null\n }\n this.listeners.clear()\n }\n\n private load(): Promise<Texts | null> {\n if (this.inFlight) return this.inFlight\n this.inFlight = (async () => {\n this.loads += 1\n const next = await loadTexts({\n client: this.client,\n accountId: this.accountId,\n stateDir: this.stateDir,\n now: this.now,\n log: this.logger,\n timeoutMs: this.fetchTimeoutMs,\n })\n if (this.stopped) return next?.texts ?? null\n if (next) {\n const changed = this.loaded?.texts.version !== next.texts.version || this.loaded?.texts.wake_instruction !== next.texts.wake_instruction\n this.loaded = next\n if (next.source === 'server') {\n this.serverLoads += 1\n this.logger[changed ? 'info' : 'debug'](\n { version: next.texts.version, manual: next.texts.manual.version },\n 'texts fetched from the server',\n )\n for (const listener of this.listeners) {\n try {\n listener(next.texts, next.source)\n } catch (err) {\n this.logger.warn({ err: describe(err) }, 'texts listener threw — continuing')\n }\n }\n }\n }\n return next?.texts ?? null\n })().finally(() => {\n this.inFlight = null\n })\n return this.inFlight\n }\n\n private arm(): void {\n if (this.stopped) return\n if (this.timer !== null) this._clearTimeout(this.timer)\n // Nothing yet → retry soon. A cached copy → ask the server again soon\n // too, so a long-offline gateway does not run a day on stale text. A\n // server copy → the daily refresh.\n const delay = this.loaded === null ? this.retryMs : this.loaded.source === 'cache' ? this.retryMs : this.refreshMs\n this.timer = this._setTimeout(() => {\n this.timer = null\n void this.load().finally(() => this.arm())\n }, delay)\n ;(this.timer as { unref?: () => void }).unref?.()\n }\n}\n\nfunction describe(err: unknown): string {\n return err instanceof Error ? err.message : String(err)\n}\n","/**\n * The `agentchatme` SDK client for this plugin.\n *\n * `getClient` caches one `AgentChatClient` per account for everything the\n * binding and the integration call over REST (status, the tray, verdicts,\n * texts, the realtime client's reconnect drain) so no call spins up a new\n * HTTP client and a key rotation swaps the cached one uniformly: the cache\n * is keyed by `accountId` and invalidated when the apiKey or apiBase\n * changes. `createSdkClient` is the uncached form for the setup-time paths\n * (wizard, `channels add`, `doctor --fix`) that have a key but no parsed\n * channel config.\n *\n * Every client carries the plugin's identity (`openclaw/<version>`) on\n * every request, through the SDK's own `clientIdentity` option.\n */\n\nimport { AgentChatClient, type AgentChatClientOptions } from 'agentchatme'\n\nimport type { AgentchatChannelConfig } from '../config-schema.js'\nimport { AGENTCHAT_CLIENT_IDENTITY } from '../client-identity.js'\n\ninterface CacheEntry {\n readonly client: AgentChatClient\n readonly apiKey: string\n readonly apiBase: string\n}\n\nconst cache = new Map<string, CacheEntry>()\n\nexport interface GetClientParams {\n readonly accountId: string\n readonly config: Pick<AgentchatChannelConfig, 'apiKey' | 'apiBase'>\n readonly options?: Partial<AgentChatClientOptions>\n}\n\n/** One client, uncached. */\nexport function createSdkClient(params: { apiKey: string; apiBase?: string | undefined; options?: Partial<AgentChatClientOptions> }): AgentChatClient {\n return new AgentChatClient({\n apiKey: params.apiKey,\n ...(params.apiBase ? { baseUrl: params.apiBase } : {}),\n clientIdentity: AGENTCHAT_CLIENT_IDENTITY,\n ...params.options,\n })\n}\n\n/**\n * Return a shared `AgentChatClient` for `accountId`, reusing the cached\n * instance unless the apiKey or apiBase changed (implicit invalidation on\n * silent config drift — better than a stale key surviving a rotation).\n */\nexport function getClient({ accountId, config, options }: GetClientParams): AgentChatClient {\n const existing = cache.get(accountId)\n if (existing && existing.apiKey === config.apiKey && existing.apiBase === config.apiBase) {\n return existing.client\n }\n\n const client = createSdkClient({ apiKey: config.apiKey, apiBase: config.apiBase, options })\n\n cache.set(accountId, {\n client,\n apiKey: config.apiKey,\n apiBase: config.apiBase,\n })\n return client\n}\n\n/** Drop the cached client for `accountId` — e.g. after a key rotation. */\nexport function disposeClient(accountId: string): void {\n cache.delete(accountId)\n}\n\n/** Clear the entire cache. Test hook only. */\nexport function resetClientCacheForTest(): void {\n cache.clear()\n}\n","/**\n * AgentChat channel setup wizard.\n *\n * Implements the interactive onboarding flow that OpenClaw's `setup` driver\n * invokes for users who just ran `openclaw plugins install @agentchatme/openclaw`\n * and `openclaw channels add agentchat`.\n *\n * The core UX decision this wizard encodes: AgentChat is the first channel in\n * the OpenClaw ecosystem where the identity the channel authenticates against\n * lives inside the plugin's own issuer (not an external provider like Slack or\n * Telegram). That means we can — and should — let brand-new users provision\n * credentials without ever leaving the CLI. Hence the three-way branch at the\n * top: paste an existing key, register via email OTP in-wizard, or recover a\n * lost key via email OTP in-wizard.\n *\n * Flow:\n * 1. `status.resolveConfigured` — reports \"configured / not configured\" for\n * `openclaw setup`'s pre-selection summary.\n * 2. `prepare` — runs BEFORE the credential step. Branches on user intent:\n * - \"I have a key\" → returns void; framework prompts for the key next.\n * - \"Register me\" → drives email-OTP registration via the REST client,\n * writes the minted key directly to cfg, and marks\n * a sentinel in credentialValues so the credential\n * step skips its redundant keep/replace prompt.\n * - \"Recover my key\"→ drives handle + email OTP recovery via the REST\n * client (same persistence + sentinel as register).\n * The handle defaults to the one already in config\n * for this account, because the overwhelmingly\n * common case is \"my configured key stopped\n * working\" — not \"recover some other agent\".\n * 3. `credentials[0]` — the API-key credential. `shouldPrompt` honors the\n * post-register/recover sentinel; otherwise the framework's default\n * prompt runs.\n * 4. `finalize` — calls GET /v1/agents/me once more to confirm the key works,\n * surfaces the authenticated handle, and places the integration: the key in\n * OpenClaw's `.env`, the served identity line in AGENTS.md, the hosted MCP\n * server in `mcp.servers.agentchat` (returned as a config patch for\n * OpenClaw to persist). Never throws on transport errors (a fresh clone\n * with a proxy should still save config and retry later).\n *\n * Writes go through `applyAgentchatAccountPatch` — the same helper backing\n * `setup.applyAccountConfig`, so the non-interactive `openclaw setup --token\n * ac_live_…` path and the interactive wizard path converge on the same config\n * shape and stay round-trippable.\n *\n * `disable` wires `setSetupChannelEnabled` so `openclaw channels remove\n * agentchat` produces `channels.agentchat.enabled: false` and keeps the\n * apiKey on disk (in case the operator just wants to pause, not rotate).\n */\n\nimport {\n WizardCancelledError,\n setSetupChannelEnabled,\n type ChannelSetupWizard,\n type OpenClawConfig,\n type WizardPrompter,\n} from 'openclaw/plugin-sdk/setup'\n\n/**\n * Inline of `ChannelSetupWizardCredentialValues` — the plugin-sdk's public\n * barrel does not re-export it, so we match its shape locally. Extra keys\n * beyond `keyof ChannelSetupInput` (e.g. our `_agentchatJustRegistered`\n * sentinel) are allowed because the framework treats this as a bag of strings\n * keyed by whatever the wizard steps use.\n */\ntype ChannelSetupWizardCredentialValues = Partial<Record<string, string>>\n\nimport {\n AGENTCHAT_CHANNEL_ID,\n MIN_API_KEY_LENGTH,\n agentchatReenableHint,\n applyAgentchatAccountPatch,\n isAgentchatAccountEnabled,\n isApiKeyPresent,\n readAgentchatConfigField,\n} from './channel-account.js'\nimport {\n recoverAgentStart,\n recoverAgentVerify,\n registerAgentStart,\n registerAgentVerify,\n validateApiKey,\n type EmailPolicyReason,\n type RecoverStartResult,\n type RecoverVerifyResult,\n type RegisterStartResult,\n type RegisterVerifyResult,\n} from './setup-client.js'\n// Credential lookup helper — see SECURITY.md for why this lives in a\n// separate module and must not be inlined into the wizard.\nimport { readApiKeyFromEnv } from './credentials/read-env.js'\nimport { placeIntegration, formatPlacement, applyIntegrationConfig, stripIntegrationConfig } from './integration/placement.js'\nimport { DEFAULT_API_BASE } from './integration/mcp.js'\nimport { loadIdentityLine } from './integration/texts.js'\nimport { createSdkClient } from './binding/sdk-client.js'\n\n/**\n * Sentinel credential-values key used to signal \"the register or recover\n * path in prepare already minted + persisted the API key, don't re-prompt\".\n * Framework-level prompt skipping is per-credential; we read this in\n * `shouldPrompt` below. The leading underscore keeps it out of any\n * `keyof ChannelSetupInput` path.\n */\nconst JUST_REGISTERED_SENTINEL = '_agentchatJustRegistered' as const\n\n// Canonical handle shape — the AgentChat handle rule (`^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$`)\n// HANDLE_REGEX plus the 3–30 length check. Server is authoritative; this is\n// a client-side fast-fail so users don't round-trip an obviously-bad handle.\nconst HANDLE_PATTERN = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/\nconst HANDLE_MIN_LENGTH = 3\nconst HANDLE_MAX_LENGTH = 30\nconst EMAIL_PATTERN = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/\n\nfunction isValidHandleShape(value: string): boolean {\n return (\n value.length >= HANDLE_MIN_LENGTH &&\n value.length <= HANDLE_MAX_LENGTH &&\n HANDLE_PATTERN.test(value)\n )\n}\n\n/** 6-digit numeric OTP; the server rejects any other shape with INVALID_CODE. */\nconst OTP_PATTERN = /^\\d{6}$/\n\nfunction hasConfiguredKey(cfg: OpenClawConfig | undefined, accountId: string): boolean {\n return isApiKeyPresent(readAgentchatConfigField(cfg, accountId, 'apiKey'))\n}\n\n/**\n * How many times we'll re-prompt around a retryable start-of-registration\n * error (handle-taken, invalid-handle, email-exhausted, …) before giving up\n * and steering the user to paste an existing key or cancel. A hard cap stops\n * a confused user looping forever; 5 is enough to pick a fresh handle or email\n * without being punishing.\n */\nconst MAX_START_RETRIES = 5\n\nasync function promptEmail(\n prompter: WizardPrompter,\n opts: {\n /** Headline. Defaults to the register-flow wording. */\n readonly message?: string\n } = {},\n): Promise<string> {\n return (\n await prompter.text({\n message: opts.message ?? 'Email — receives a 6-digit verification code',\n placeholder: 'you@example.com',\n validate: (value) => {\n const trimmed = value.trim()\n if (!trimmed) return 'Email is required'\n if (!EMAIL_PATTERN.test(trimmed)) return 'Not a valid email format'\n return undefined\n },\n })\n ).trim()\n}\n\nasync function promptHandle(\n prompter: WizardPrompter,\n opts: {\n /** Headline. Defaults to the register-flow wording. */\n readonly message?: string\n /** Pre-filled value the user can accept with Enter (recovery: the configured handle). */\n readonly initialValue?: string\n } = {},\n): Promise<string> {\n // The rules live in `placeholder` (the gray hint text inside the\n // input box, which clears on first keystroke) so the headline stays\n // a clean call to action. Per-rule validation errors below tell the\n // user exactly which rule failed instead of dumping the full rule\n // list every time.\n return (\n await prompter.text({\n message: opts.message ?? 'Choose a handle (your @name on AgentChat)',\n placeholder: '3–30 chars, lowercase a-z, 0-9, hyphens, starts with a letter',\n ...(opts.initialValue ? { initialValue: opts.initialValue } : {}),\n validate: (value) => {\n const trimmed = value.trim()\n if (!trimmed) return 'Handle is required'\n if (trimmed.length < HANDLE_MIN_LENGTH || trimmed.length > HANDLE_MAX_LENGTH) {\n return `Length must be ${HANDLE_MIN_LENGTH}–${HANDLE_MAX_LENGTH} chars (you entered ${trimmed.length})`\n }\n if (!/^[a-z]/.test(trimmed)) return 'Must start with a lowercase letter'\n if (/[^a-z0-9-]/.test(trimmed)) {\n return 'Only lowercase letters, digits, and hyphens — no underscores, dots, or symbols'\n }\n if (trimmed.includes('--')) return 'No consecutive hyphens'\n if (trimmed.endsWith('-')) return 'Cannot end with a hyphen'\n return undefined\n },\n })\n ).trim()\n}\n\nasync function promptDisplayName(prompter: WizardPrompter): Promise<string> {\n // The visible prompt deliberately does NOT say \"optional\" anymore —\n // empty input still passes validation (no server-side blocker; an\n // agent without display_name is a valid account), but framing it as\n // \"optional\" turned ~half of recent registrations into NULL rows\n // that render as @handle-only in the dashboard. Dropping the word\n // soft-pressures users to fill it without breaking anyone who really\n // doesn't want one. The placeholder example carries the load that\n // \"optional\" used to carry — it tells the user what shape this field\n // is for, without telling them they can skip it.\n return (\n await prompter.text({\n message: 'Display name (shown next to your @handle)',\n placeholder: 'e.g. Anton, Builder Bot, Sasha',\n validate: () => undefined,\n })\n ).trim()\n}\n\n/**\n * Change-API-base flow: only relevant for self-hosted AgentChat deployments.\n * The production client hits `https://api.agentchat.me` by default and the\n * config-schema pins that as the default value, so blank means \"reset to\n * default\" (remove the apiBase override entirely). Non-empty values must\n * parse as a valid http:// or https:// URL — we fail fast here so the user\n * does not save a typo that later surfaces as a misleading DNS-resolution\n * error at connect time.\n */\nasync function runChangeApiBaseFlow(params: {\n cfg: OpenClawConfig\n accountId: string\n prompter: WizardPrompter\n}): Promise<{ cfg: OpenClawConfig } | undefined> {\n const { cfg, accountId, prompter } = params\n const current = readAgentchatConfigField(cfg, accountId, 'apiBase')\n\n const input = (\n await prompter.text({\n message: 'New API base URL (blank to reset to default)',\n placeholder: current ?? 'https://api.agentchat.me',\n validate: (value) => {\n const trimmed = value.trim()\n if (!trimmed) return undefined // blank = reset to default\n try {\n const url = new URL(trimmed)\n if (url.protocol !== 'https:' && url.protocol !== 'http:') {\n return 'API base must use http:// or https://'\n }\n return undefined\n } catch {\n return 'Not a valid URL'\n }\n },\n })\n ).trim()\n\n if (!input) {\n const patched = applyAgentchatAccountPatch(cfg, accountId, {\n apiBase: undefined,\n })\n await prompter.note(\n 'API base reset to default (https://api.agentchat.me).',\n 'Updated',\n )\n return { cfg: patched }\n }\n\n const patched = applyAgentchatAccountPatch(cfg, accountId, {\n apiBase: input,\n })\n await prompter.note(`API base set to ${input}`, 'Updated')\n return { cfg: patched }\n}\n\n/**\n * Return values from `runRegisterFlow`:\n * - success object → registration minted a key; credential step\n * should use it and skip its own prompt.\n * - `'abort'` → registration failed; caller shows the fallback\n * note and the framework prompts for a pasted key.\n * - `'user-chose-paste'` → user explicitly elected to paste an existing key\n * (from an in-flow branch point like \"this email\n * is at its agent limit\"). Caller skips the\n * fallback note because the user has already\n * acknowledged what's next.\n * - `'user-chose-recover'`→ same branch point, but the user wants to\n * recover a lost key for one of the agents that\n * email already backs. Caller hands off to\n * `runRecoverFlow`.\n */\ntype RegisterFlowOutcome =\n | { cfg: OpenClawConfig; credentialValues: ChannelSetupWizardCredentialValues }\n | 'abort'\n | 'user-chose-paste'\n | 'user-chose-recover'\n\n/**\n * Operator copy for a per-email policy rejection. Quotes the limit the\n * server returned — the numbers are server-tunable and must never be\n * assumed here. When the server sent no limit (a server that predates the\n * multi-agent policy emits the retired `EMAIL_TAKEN` without one), its own\n * message is the most honest thing we have.\n */\nfunction describeEmailPolicyRejection(\n email: string,\n result: { readonly reason: EmailPolicyReason; readonly limit?: number; readonly message: string },\n): string {\n if (result.limit === undefined) return result.message\n return result.reason === 'email-limit-reached'\n ? `${email} already backs ${result.limit} active agents — the per-email limit.`\n : `${email} has used all ${result.limit} of its lifetime account registrations.`\n}\n\n/**\n * What the user can do once an email is at a policy limit. Recovery is\n * offered because the most likely reason someone re-registers on a full\n * email is that one of the existing agents lost its key; a `+` alias is\n * called out because it is the sanctioned way to get a fresh budget.\n */\ntype EmailPolicyChoice = 'retry' | 'recover' | 'paste' | 'cancel'\n\nasync function promptEmailPolicyChoice(\n prompter: WizardPrompter,\n email: string,\n result: { readonly reason: EmailPolicyReason; readonly limit?: number; readonly message: string },\n): Promise<EmailPolicyChoice> {\n return prompter.select<EmailPolicyChoice>({\n message: `${describeEmailPolicyRejection(email, result)} What next?`,\n options: [\n {\n value: 'retry',\n label: 'Use a different email address',\n hint: 'a +alias like you+agent2@example.com counts as a separate email',\n },\n {\n value: 'recover',\n label: 'Recover the API key of an agent this email already backs',\n hint: 'needs that agent’s handle — a code goes to this email',\n },\n { value: 'paste', label: 'Paste a key from an existing agent' },\n { value: 'cancel', label: 'Cancel registration' },\n ],\n initialValue: 'retry',\n })\n}\n\nasync function runRegisterFlow(params: {\n cfg: OpenClawConfig\n accountId: string\n prompter: WizardPrompter\n apiBase: string | undefined\n}): Promise<RegisterFlowOutcome> {\n const { cfg, accountId, prompter, apiBase } = params\n\n await prompter.note(\n [\n 'Registration mints a new AgentChat agent identity tied to your email.',\n 'One email can back several agents (the server enforces the limit);',\n 'each one registers and verifies separately.',\n 'You will receive a 6-digit code to verify — check your inbox (and spam).',\n ].join('\\n'),\n 'AgentChat: register a new agent',\n )\n\n // Collect all three fields up front. If the server rejects on one specific\n // field (handle / email), we loop back and re-prompt ONLY that field below\n // — keeping the already-correct state so the user isn't punished for a\n // partial collision.\n let email = await promptEmail(prompter)\n let handle = await promptHandle(prompter)\n const displayName = await promptDisplayName(prompter)\n\n // ─── Start: request OTP, with field-specific retry ──────────────────\n // Retry semantics:\n // invalid-handle / handle-taken → re-prompt handle, keep email+displayName\n // email-limit-reached /\n // email-exhausted → branch: pick new email, recover a key\n // for an agent on this email, paste an\n // existing key, or cancel\n // rate-limited / otp-failed /\n // network / server / validation → abort with a clear message\n let startResult: RegisterStartResult | undefined\n let startedOk = false\n for (let attempt = 1; attempt <= MAX_START_RETRIES; attempt += 1) {\n const startSpinner = prompter.progress(\n attempt === 1 ? 'Sending verification code…' : 'Retrying…',\n )\n try {\n startResult = await registerAgentStart(\n {\n email,\n handle,\n ...(displayName ? { displayName } : {}),\n },\n { apiBase },\n )\n } catch (err) {\n startSpinner.stop('Could not reach AgentChat')\n await prompter.note(\n `${err instanceof Error ? err.message : String(err)}. Try again when the network is available, or paste an existing key instead.`,\n 'Registration failed',\n )\n return 'abort'\n }\n\n if (startResult.ok) {\n startSpinner.stop(`Verification code sent to ${email}`)\n startedOk = true\n break\n }\n\n startSpinner.stop('Registration rejected')\n\n switch (startResult.reason) {\n case 'invalid-handle':\n case 'handle-taken': {\n const detail =\n startResult.reason === 'handle-taken'\n ? `Handle @${handle} is already taken.`\n : 'That handle is not acceptable (3–30 chars — lowercase letters/digits/hyphens; must start with a letter).'\n await prompter.note(`${detail} Pick a different handle and we'll try again.`, 'Pick a different handle')\n handle = await promptHandle(prompter)\n continue\n }\n case 'email-limit-reached':\n case 'email-exhausted': {\n const choice = await promptEmailPolicyChoice(prompter, email, {\n reason: startResult.reason,\n limit: startResult.limit,\n message: startResult.message,\n })\n if (choice === 'paste') return 'user-chose-paste'\n if (choice === 'recover') return 'user-chose-recover'\n if (choice === 'cancel') return 'abort'\n email = await promptEmail(prompter)\n continue\n }\n case 'rate-limited': {\n const wait = startResult.retryAfterSeconds\n ? ` Try again in ${startResult.retryAfterSeconds}s.`\n : ''\n await prompter.note(`Too many registration attempts.${wait}`, 'Rate limited')\n return 'abort'\n }\n case 'otp-failed': {\n await prompter.note(\n 'The verification-code email could not be sent. Try again in a minute, or paste an existing key instead.',\n 'OTP delivery failed',\n )\n return 'abort'\n }\n case 'network-error':\n case 'server-error':\n case 'validation':\n default: {\n await prompter.note(describeRegisterStartError(startResult), 'Could not start registration')\n return 'abort'\n }\n }\n }\n\n if (!startedOk || !startResult || !startResult.ok) {\n await prompter.note(\n 'Too many attempts. Restart the wizard to try again, or paste an existing key at the next prompt.',\n 'Registration failed',\n )\n return 'abort'\n }\n\n // ─── Verify: collect OTP, retry on mistyped codes ───────────────────\n const maxCodeAttempts = 3\n let verifyResult: RegisterVerifyResult | null = null\n for (let attempt = 1; attempt <= maxCodeAttempts; attempt += 1) {\n const code = (\n await prompter.text({\n message:\n attempt === 1\n ? 'Enter the 6-digit verification code from your email'\n : `Verification code (attempt ${attempt}/${maxCodeAttempts})`,\n placeholder: '123456',\n validate: (value) => {\n const trimmed = value.trim()\n if (!trimmed) return 'Code is required'\n if (!OTP_PATTERN.test(trimmed)) return 'Code is 6 digits'\n return undefined\n },\n })\n ).trim()\n\n const verifySpinner = prompter.progress('Verifying code…')\n try {\n verifyResult = await registerAgentVerify({ pendingId: startResult.pendingId, code }, { apiBase })\n } catch (err) {\n verifySpinner.stop('Could not reach AgentChat')\n await prompter.note(\n `${err instanceof Error ? err.message : String(err)}. Try again, or paste an existing key instead.`,\n 'Verification failed',\n )\n return 'abort'\n }\n\n if (verifyResult.ok) {\n verifySpinner.stop(`Registered as @${verifyResult.agent.handle}`)\n break\n }\n\n verifySpinner.stop('Verification failed')\n\n // Retryable: bad code. Other failure modes are terminal for this flow.\n if (verifyResult.reason === 'invalid-code' && attempt < maxCodeAttempts) {\n await prompter.note(\n 'That code did not match. Check your email and try again.',\n 'Invalid verification code',\n )\n continue\n }\n\n await prompter.note(describeRegisterVerifyError(verifyResult), 'Registration failed')\n return 'abort'\n }\n\n if (!verifyResult || !verifyResult.ok) {\n await prompter.note(\n 'Too many incorrect codes. Restart the wizard to receive a new code.',\n 'Registration failed',\n )\n return 'abort'\n }\n\n // ─── Persist: write minted key to cfg, advertise handle in config ───\n const patch: Record<string, unknown> = { apiKey: verifyResult.apiKey }\n if (isValidHandleShape(verifyResult.agent.handle)) {\n patch.agentHandle = verifyResult.agent.handle\n }\n const nextCfg = applyAgentchatAccountPatch(cfg, accountId, patch)\n\n await prompter.note(\n [\n `Handle: @${verifyResult.agent.handle}`,\n `Email: ${verifyResult.agent.email}`,\n `API key: ${redactKey(verifyResult.apiKey)} (saved to your OpenClaw config)`,\n ].join('\\n'),\n 'AgentChat account created',\n )\n\n return {\n cfg: nextCfg,\n credentialValues: {\n token: verifyResult.apiKey,\n [JUST_REGISTERED_SENTINEL]: '1',\n },\n }\n}\n\nfunction describeRegisterStartError(result: Extract<RegisterStartResult, { ok: false }>): string {\n switch (result.reason) {\n case 'invalid-handle':\n return 'That handle is not acceptable. Try a different one (3–30 chars — lowercase letters/digits/hyphens; must start with a letter).'\n case 'handle-taken':\n return 'That handle is already taken. Try a different one.'\n case 'email-limit-reached':\n return `${result.limit === undefined ? result.message : `This email already backs ${result.limit} active agents — the per-email limit.`} Use a different email (a +alias works), recover a key for one of its agents, or paste an existing key.`\n case 'email-exhausted':\n return `${result.limit === undefined ? result.message : `This email has used all ${result.limit} of its lifetime account registrations.`} Use a different email (a +alias works), or paste a key from an existing agent.`\n case 'rate-limited': {\n const wait = result.retryAfterSeconds ? ` Try again in ${result.retryAfterSeconds}s.` : ''\n return `Rate limited.${wait}`\n }\n case 'otp-failed':\n return 'The verification-code email could not be sent. Try again in a minute.'\n case 'network-error':\n case 'server-error':\n case 'validation':\n default:\n return result.message\n }\n}\n\nfunction describeRegisterVerifyError(result: Extract<RegisterVerifyResult, { ok: false }>): string {\n switch (result.reason) {\n case 'expired':\n return 'This code expired. Restart the wizard to receive a new one.'\n case 'invalid-code':\n return 'Too many incorrect codes. Restart the wizard to receive a new one.'\n case 'handle-taken':\n return 'Your chosen handle was claimed by another registration in the meantime. Restart with a different handle.'\n case 'email-limit-reached':\n // Another registration on this email landed between our start and\n // verify and took the last live slot.\n return `${result.limit === undefined ? result.message : `This email reached its limit of ${result.limit} active agents while you were verifying.`} Restart with a different email (a +alias works), or paste an existing key.`\n case 'email-exhausted':\n return `${result.limit === undefined ? result.message : `This email used all ${result.limit} of its lifetime account registrations while you were verifying.`} Restart with a different email (a +alias works), or paste an existing key.`\n case 'rate-limited': {\n const wait = result.retryAfterSeconds ? ` Try again in ${result.retryAfterSeconds}s.` : ''\n return `Rate limited.${wait}`\n }\n case 'network-error':\n case 'server-error':\n case 'unexpected-shape':\n case 'validation':\n default:\n return result.message\n }\n}\n\n// ─── Recovery (handle + email + OTP) ───────────────────────────────────\n\n/**\n * Return values from `runRecoverFlow`:\n * - success object → recovery minted a key; credential step should use it\n * and skip its own prompt.\n * - `'abort'` → recovery did not complete; the user was told why and\n * what to do next. Caller falls through to the\n * framework's paste-a-key prompt.\n */\ntype RecoverFlowOutcome =\n | { cfg: OpenClawConfig; credentialValues: ChannelSetupWizardCredentialValues }\n | 'abort'\n\n/**\n * Re-issue a lost API key. Always sends handle + email: one email can back\n * several agents, and the server can only pick the right one when told.\n *\n * Handle default: the `agentHandle` already in config for this account,\n * pre-filled so Enter accepts it. That is the case this flow exists for —\n * \"the key I have configured stopped working\" — while still letting the\n * user type a different handle (an agent set up elsewhere, or a sibling on\n * the same email). The email is always asked: the plugin never stores it\n * and `/agents/me` only ever returns it masked.\n *\n * Attempt budget is deliberately tight. `POST /agents/recover` is\n * rate-limited per IP far more strictly than registration (it sends OTPs\n * to arbitrary addresses), so there is no start-retry loop here — a\n * rejected start ends the flow with a clear note.\n */\nasync function runRecoverFlow(params: {\n cfg: OpenClawConfig\n accountId: string\n prompter: WizardPrompter\n apiBase: string | undefined\n}): Promise<RecoverFlowOutcome> {\n const { cfg, accountId, prompter, apiBase } = params\n\n const storedHandle = readAgentchatConfigField(cfg, accountId, 'agentHandle')\n const defaultHandle = storedHandle && isValidHandleShape(storedHandle) ? storedHandle : undefined\n\n await prompter.note(\n [\n 'Recovery re-issues the API key for ONE agent — the handle you name below.',\n 'You need that handle and the email it registered with; a 6-digit code',\n 'goes to that email. The old key stops working the moment the new one',\n 'is minted.',\n ...(defaultHandle\n ? ['', `@${defaultHandle} is configured here — press Enter at the handle prompt to recover it.`]\n : []),\n ].join('\\n'),\n 'AgentChat: recover a lost API key',\n )\n\n const handle = await promptHandle(prompter, {\n message: 'Handle of the agent to recover (its @name on AgentChat)',\n ...(defaultHandle ? { initialValue: defaultHandle } : {}),\n })\n const email = await promptEmail(prompter, {\n message: `Email @${handle} registered with — receives a 6-digit recovery code`,\n })\n\n // ─── Start: request OTP ────────────────────────────────────────────\n const startSpinner = prompter.progress('Requesting recovery code…')\n let startResult: RecoverStartResult\n try {\n startResult = await recoverAgentStart({ email, handle }, { apiBase })\n } catch (err) {\n startSpinner.stop('Could not reach AgentChat')\n await prompter.note(\n `${err instanceof Error ? err.message : String(err)}. Try again when the network is available, or paste an existing key instead.`,\n 'Recovery failed',\n )\n return 'abort'\n }\n\n if (!startResult.ok) {\n startSpinner.stop('Recovery rejected')\n await prompter.note(describeRecoverStartError(startResult), 'Could not start recovery')\n return 'abort'\n }\n // The server's acknowledgement is intentionally the same whether or not\n // the email + handle matched an agent — echo it rather than promising a\n // code that may not be coming.\n startSpinner.stop(startResult.message)\n\n // ─── Verify: collect OTP, retry on mistyped codes ───────────────────\n const maxCodeAttempts = 3\n let verifyResult: RecoverVerifyResult | null = null\n for (let attempt = 1; attempt <= maxCodeAttempts; attempt += 1) {\n const code = (\n await prompter.text({\n message:\n attempt === 1\n ? `Enter the 6-digit recovery code (check ${email}, including spam)`\n : `Recovery code (attempt ${attempt}/${maxCodeAttempts})`,\n placeholder: '123456',\n validate: (value) => {\n const trimmed = value.trim()\n if (!trimmed) return 'Code is required'\n if (!OTP_PATTERN.test(trimmed)) return 'Code is 6 digits'\n return undefined\n },\n })\n ).trim()\n\n const verifySpinner = prompter.progress('Verifying code…')\n try {\n verifyResult = await recoverAgentVerify({ pendingId: startResult.pendingId, code }, { apiBase })\n } catch (err) {\n verifySpinner.stop('Could not reach AgentChat')\n await prompter.note(\n `${err instanceof Error ? err.message : String(err)}. Try again, or paste an existing key instead.`,\n 'Recovery failed',\n )\n return 'abort'\n }\n\n if (verifyResult.ok) {\n verifySpinner.stop(`Recovered @${verifyResult.handle}`)\n break\n }\n\n verifySpinner.stop('Verification failed')\n\n // Retryable: bad code. Other failure modes are terminal for this flow.\n // Note a decoy pending (email + handle matched nothing) also lands\n // here as invalid-code — by design the server does not distinguish.\n if (verifyResult.reason === 'invalid-code' && attempt < maxCodeAttempts) {\n await prompter.note(\n 'That code did not match. Check your email and try again — if no code arrived, the handle and email may not belong to the same agent.',\n 'Invalid recovery code',\n )\n continue\n }\n\n await prompter.note(describeRecoverVerifyError(verifyResult), 'Recovery failed')\n return 'abort'\n }\n\n if (!verifyResult || !verifyResult.ok) {\n await prompter.note(\n 'Too many incorrect codes. Restart the wizard to request a new one — and double-check the handle and email belong to the same agent.',\n 'Recovery failed',\n )\n return 'abort'\n }\n\n // ─── Persist: the new key now authenticates as the recovered handle ──\n // `agentHandle` is overwritten with the server's answer, not what the\n // user typed: the key is the identity, and the config must describe the\n // key it holds.\n const patch: Record<string, unknown> = { apiKey: verifyResult.apiKey }\n if (isValidHandleShape(verifyResult.handle)) {\n patch.agentHandle = verifyResult.handle\n }\n const nextCfg = applyAgentchatAccountPatch(cfg, accountId, patch)\n\n await prompter.note(\n [\n `Handle: @${verifyResult.handle}`,\n `API key: ${redactKey(verifyResult.apiKey)} (saved to your OpenClaw config)`,\n '',\n 'The previous key for this agent has been revoked.',\n ].join('\\n'),\n 'AgentChat API key recovered',\n )\n\n return {\n cfg: nextCfg,\n credentialValues: {\n token: verifyResult.apiKey,\n [JUST_REGISTERED_SENTINEL]: '1',\n },\n }\n}\n\nfunction describeRecoverStartError(result: Extract<RecoverStartResult, { ok: false }>): string {\n switch (result.reason) {\n case 'rate-limited': {\n const wait = result.retryAfterSeconds ? ` Try again in ${result.retryAfterSeconds}s.` : ''\n return `Too many recovery attempts from this network.${wait}`\n }\n case 'validation':\n return `AgentChat rejected the request: ${result.message}`\n case 'network-error':\n case 'server-error':\n case 'unexpected-shape':\n default:\n return result.message\n }\n}\n\nfunction describeRecoverVerifyError(result: Extract<RecoverVerifyResult, { ok: false }>): string {\n switch (result.reason) {\n case 'expired':\n return 'This recovery code expired. Restart the wizard to request a new one.'\n case 'invalid-code':\n return 'Too many incorrect codes. Restart the wizard to request a new one.'\n case 'handle-required': {\n // Defensive: this plugin always sends a handle, so a compliant server\n // never answers HANDLE_REQUIRED to it. If one does, the server has\n // just confirmed inbox control and listed the live handles — show\n // them so the re-run is a straight pick instead of a guess.\n const handles = result.handles ?? []\n const list = handles.length > 0 ? `\\n\\nAgents on this email:\\n${handles.map((h) => ` @${h}`).join('\\n')}` : ''\n return `This email backs more than one agent. Run recovery again and enter the handle you want to recover.${list}`\n }\n case 'rate-limited': {\n const wait = result.retryAfterSeconds ? ` Try again in ${result.retryAfterSeconds}s.` : ''\n return `Rate limited.${wait}`\n }\n case 'network-error':\n case 'server-error':\n case 'unexpected-shape':\n case 'validation':\n default:\n return result.message\n }\n}\n\nfunction redactKey(apiKey: string): string {\n if (apiKey.length < 12) return '••••'\n return `${apiKey.slice(0, 8)}…${apiKey.slice(-4)}`\n}\n\nexport const agentchatSetupWizard: ChannelSetupWizard = {\n channel: AGENTCHAT_CHANNEL_ID,\n\n // AgentChat is one-agent-per-account by product design — the agent IS the\n // account, identity is its handle. The default OpenClaw `promptAccountId`\n // helper is built for channels like Telegram/Slack where one workspace\n // can host multiple bot accounts; it forces every user through an\n // \"Add a new account\" → \"Set account id\" prompt that doesn't map to\n // anything meaningful here.\n //\n // Override the resolver to silently use the default account id, so the\n // wizard goes straight from channel selection into the register-or-paste\n // step. An explicit `--account` override still wins so power users who\n // genuinely want a second agent on the same machine can scope their\n // config that way (rare, by intent).\n resolveAccountIdForConfigure: async ({ accountOverride }) => {\n const trimmed = accountOverride?.trim()\n return trimmed ? trimmed : 'default'\n },\n\n status: {\n configuredLabel: 'configured',\n unconfiguredLabel: 'not configured',\n configuredHint: 'AgentChat agent is ready to receive messages',\n unconfiguredHint: 'connect your agent to the AgentChat messaging platform',\n configuredScore: 90,\n unconfiguredScore: 30,\n resolveConfigured: ({ cfg, accountId }) => {\n return hasConfiguredKey(cfg, accountId ?? 'default')\n },\n resolveStatusLines: ({ cfg, accountId, configured }) => {\n const id = accountId ?? 'default'\n if (!configured) {\n return ['AgentChat: not configured — the wizard will register you, accept an existing key, or recover a lost one.']\n }\n const handle = readAgentchatConfigField(cfg, id, 'agentHandle')\n if (!isAgentchatAccountEnabled(cfg, id)) return [`AgentChat: configured${handle ? ` (@${handle})` : ''}; ${agentchatReenableHint(cfg, id)}`]\n return [`AgentChat: configured${handle ? ` (@${handle})` : ''}`]\n },\n },\n\n introNote: {\n title: 'AgentChat',\n lines: [\n 'AgentChat is a messaging platform for AI agents — direct messages,',\n 'groups, presence, attachments. Registration is free.',\n '',\n 'This wizard will mint a new account via email OTP, accept an existing',\n 'API key, or recover a lost key (handle + email OTP) — your choice in',\n 'the next prompt.',\n ],\n },\n\n prepare: async ({ cfg, accountId, credentialValues, prompter }) => {\n // Re-run against an already-configured account: offer the edit menu\n // (keep / change-base / replace-key). `change-base` is the only action\n // that cannot be driven through the framework's credential UX — it has\n // to mutate `apiBase`, which is not a credential field. `keep` and\n // `replace-key` both fall through to the framework's keep/replace prompt\n // on the credential step; the only difference is that `replace-key`\n // surfaces the register-or-paste menu below so the user gets the\n // in-wizard register path instead of just a paste box.\n if (hasConfiguredKey(cfg, accountId) && typeof credentialValues.token === 'string') {\n const editChoice = await prompter.select<'keep' | 'change-base' | 'replace-key'>({\n message: 'AgentChat is already configured. What would you like to do?',\n options: [\n {\n value: 'keep',\n label: 'Keep current config',\n hint: 'the credential step will still re-validate on the next run',\n },\n {\n value: 'change-base',\n label: 'Change API base URL',\n hint: 'only for self-hosted AgentChat deployments',\n },\n {\n value: 'replace-key',\n label: 'Replace the API key',\n hint: 'paste a new key, register a new agent, or recover a lost key',\n },\n ],\n initialValue: 'keep',\n })\n\n if (editChoice === 'keep') return\n if (editChoice === 'change-base') {\n return await runChangeApiBaseFlow({ cfg, accountId, prompter })\n }\n // 'replace-key' falls through to the register / paste / recover menu below.\n }\n\n const choice = await prompter.select<'register' | 'paste' | 'recover'>({\n message: 'How would you like to configure AgentChat?',\n options: [\n {\n value: 'register',\n label: 'Register a new agent (email OTP)',\n hint: 'no account yet — the wizard creates one',\n },\n {\n value: 'paste',\n label: 'I already have an API key',\n hint: 'paste ac_live_… on the next prompt',\n },\n {\n value: 'recover',\n label: 'Recover a lost API key (handle + email OTP)',\n hint: 'an agent exists but its key is gone — re-issue it',\n },\n ],\n initialValue: 'register',\n })\n\n if (choice === 'paste') {\n return\n }\n\n const apiBase = readAgentchatConfigField(cfg, accountId, 'apiBase')\n\n // Recovery tail, shared by the menu entry and the hand-off from the\n // register flow: a minted key is returned as-is; an abort tells the\n // user they can still paste a key at the next prompt. Unexpected\n // throws are reported under their own title so a failure inside\n // recovery is never misattributed to registration.\n const recover = async () => {\n try {\n const result = await runRecoverFlow({ cfg, accountId, prompter, apiBase })\n if (result === 'abort') {\n await prompter.note(\n 'Recovery was not completed. You can still paste an existing API key at the next prompt, or cancel the wizard.',\n 'Falling back to credential entry',\n )\n return\n }\n return result\n } catch (err) {\n if (err instanceof WizardCancelledError) throw err\n await prompter.note(\n `${err instanceof Error ? err.message : String(err)}`,\n 'Recovery flow failed',\n )\n return\n }\n }\n\n if (choice === 'recover') {\n return await recover()\n }\n\n let registerOutcome: RegisterFlowOutcome\n try {\n registerOutcome = await runRegisterFlow({ cfg, accountId, prompter, apiBase })\n } catch (err) {\n if (err instanceof WizardCancelledError) throw err\n await prompter.note(\n `${err instanceof Error ? err.message : String(err)}`,\n 'Registration flow failed',\n )\n return\n }\n\n if (registerOutcome === 'abort') {\n // User can still paste an existing key at the credential step.\n await prompter.note(\n 'Registration was not completed. You can still paste an existing API key at the next prompt, or cancel the wizard.',\n 'Falling back to credential entry',\n )\n return\n }\n if (registerOutcome === 'user-chose-paste') {\n // User picked the \"paste my existing key\" branch from inside the\n // register flow — they already acknowledged what's next, so don't\n // re-surface the generic fallback note. Fall through to the\n // credential step which will prompt for the key.\n return\n }\n if (registerOutcome === 'user-chose-recover') {\n // The email is at its agent limit and the user wants the key of one\n // of the agents it already backs. Hand off to recovery; it asks for\n // the handle and the email again — the register flow's email is a\n // reasonable guess but not necessarily the one that agent registered\n // with, so it is not pre-filled.\n return await recover()\n }\n return registerOutcome\n },\n\n credentials: [\n {\n inputKey: 'token',\n providerHint: 'agentchat',\n credentialLabel: 'API key',\n preferredEnvVar: 'AGENTCHAT_API_KEY',\n envPrompt: 'AGENTCHAT_API_KEY detected in env. Use it?',\n keepPrompt: 'AgentChat API key already configured. Keep it?',\n inputPrompt: 'Paste your AgentChat API key (ac_live_…)',\n helpTitle: 'AgentChat API key',\n helpLines: [\n 'Format: ac_live_<base64>, ≥20 chars. Validated against',\n 'GET /v1/agents/me during this wizard — bad keys fail fast instead',\n 'of flapping reconnects at runtime.',\n ],\n allowEnv: () => true,\n shouldPrompt: ({ credentialValues, currentValue }) => {\n // Post-register: we already minted + persisted the key in prepare.\n if (credentialValues[JUST_REGISTERED_SENTINEL] === '1') return false\n // No key yet: always prompt.\n if (!currentValue) return true\n // Existing key + user didn't choose register: show keep/replace.\n return true\n },\n inspect: ({ cfg, accountId }) => {\n const apiKey = readAgentchatConfigField(cfg, accountId, 'apiKey')\n const configured = isApiKeyPresent(apiKey)\n // Delegated to the credential helper — see SECURITY.md.\n const envValue = readApiKeyFromEnv(MIN_API_KEY_LENGTH)\n return {\n accountConfigured: configured,\n hasConfiguredValue: configured,\n resolvedValue: configured ? apiKey : undefined,\n envValue,\n }\n },\n },\n ],\n\n finalize: async ({ cfg, accountId, credentialValues, prompter }) => {\n const apiKey =\n typeof credentialValues.token === 'string' && credentialValues.token.length >= MIN_API_KEY_LENGTH\n ? credentialValues.token\n : readAgentchatConfigField(cfg, accountId, 'apiKey')\n\n if (!apiKey || !isApiKeyPresent(apiKey)) {\n // Nothing to validate — prepare aborted and credential step got skipped\n // or the user bailed mid-flow. The `configure` call above will still\n // write whatever cfg we return; nothing more to do here.\n return\n }\n\n const apiBase = readAgentchatConfigField(cfg, accountId, 'apiBase')\n const spinner = prompter.progress('Validating API key against AgentChat…')\n try {\n const result = await validateApiKey(apiKey, { apiBase })\n if (result.ok) {\n spinner.stop(`Authenticated as @${result.agent.handle}`)\n\n // Place the integration: the key in OpenClaw's state-dir `.env` (the\n // hosted tools' bearer header is a template on it), the served\n // identity line in AGENTS.md (loaded every turn), the manual\n // (bundled), and the hosted MCP server in `mcp.servers.agentchat`.\n // Best-effort by intent: a read-only workspace must NOT bounce the\n // wizard — the key and config are saved; the report says what to\n // repair.\n const handle = result.agent.handle\n const resolvedBase = apiBase ?? DEFAULT_API_BASE\n const identityLine = await loadIdentityLine({ client: createSdkClient({ apiKey, apiBase: resolvedBase }), accountId })\n const placed = placeIntegration({ cfg, handle, apiKey, apiBase: resolvedBase, identityLine, accountId })\n const failed = placed.steps.filter((s) => s.status === 'failed')\n const skipped = placed.steps.filter((s) => s.status === 'skipped' && s.name === 'anchor')\n await prompter.note(\n [\n ...formatPlacement(placed.steps),\n '',\n placed.mcp === 'added' || placed.steps.some((s) => s.name === 'key' && s.status === 'changed')\n ? 'Restart the gateway once so its environment carries the key and it connects the hosted tools. Then `openclaw channels status` shows the integration and the tools.'\n : 'The agent is reachable: a peer\\'s message wakes it; the agent decides with its own model; it answers through the hosted AgentChat tools.',\n ...(failed.length > 0\n ? ['', 'Some placement failed (above). Your account is configured; re-run `openclaw channels add agentchat` after fixing the path, or `openclaw doctor --fix` for the config entry.']\n : []),\n ...(skipped.length > 0 ? ['', 'The identity line waits for AgentChat to be reachable: run `openclaw doctor --fix` then.'] : []),\n ].join('\\n'),\n 'AgentChat integration placed',\n )\n\n // The config side of placement: the handle the key authenticates as\n // (configured-state, doctor and the own-echo filter need it), the\n // hosted tools entry, and the llm override opt-in when this account\n // is bound to an agent other than OpenClaw's default.\n const applied = applyIntegrationConfig(placed.cfg, { accountId, handle, apiKey, apiBase: resolvedBase })\n return { cfg: applied.cfg }\n }\n\n spinner.stop(`API key did not pass the live check (${result.reason})`)\n await prompter.note(\n [\n result.message,\n '',\n 'The config was saved — you can re-run `openclaw channels add agentchat`',\n 'to replace the key, or edit ~/.openclaw/config.yaml directly.',\n ].join('\\n'),\n 'AgentChat validation warning',\n )\n } catch (err) {\n spinner.stop('Could not reach AgentChat for validation')\n await prompter.note(\n [\n err instanceof Error ? err.message : String(err),\n '',\n 'The config was saved — the runtime will retry on startup.',\n ].join('\\n'),\n 'AgentChat API unreachable',\n )\n }\n return\n },\n\n completionNote: {\n title: 'AgentChat is ready',\n // After our wizard returns, OpenClaw's setupChannels keeps running\n // its own outer flow (a Select-a-channel loop, then optional\n // follow-up prompts for display names and channel→agent binding).\n // None of that is suppressible from a channel plugin — there's no\n // field on ChannelSetupWizard that hides those prompts. So this\n // note keeps to the only thing the user actually needs to know:\n // pick Finished. The earlier \"or pick another channel\" copy read\n // as a vague alt-branch and produced the \"did this break?\"\n // reaction; one direct sentence is the cure.\n lines: ['On the next prompt, choose \"Finished\" to exit.'],\n },\n\n // `disable` fires on `openclaw channels remove agentchat`. We strip the\n // AGENTS.md identity line and our own `mcp.servers.agentchat` entry so the\n // agent stops being told it is @handle on AgentChat and stops seeing the\n // hosted tools the moment the channel is removed. The key stays in the\n // channel config and in `.env` (a remove is a pause, not a rotation).\n // Best-effort: FS errors never block the channel-remove. Plugin uninstall\n // (`openclaw plugins uninstall`) fires no plugin hook, so this only runs\n // when the user explicitly removes the channel; orphans are documented in\n // RUNBOOK.md.\n disable: (cfg) => {\n // The config side only, same as `config.setAccountEnabled(false)`: the\n // plugin's own mcp.servers.agentchat entry goes (matched by URL +\n // transport on the env-substituted config), the key stays — a remove is\n // a pause, not a rotation. Files (the identity line) are removed by the\n // lifecycle hook after the patch is checked, never from a pure adapter.\n return setSetupChannelEnabled(stripIntegrationConfig(cfg, 'default').cfg, AGENTCHAT_CHANNEL_ID, false)\n },\n}\n","/**\n * Zod schema for AgentChat channel config.\n *\n * Source of truth: this file. The JSON Schema inlined in `openclaw.plugin.json`\n * MUST stay in sync (P1 adds a build step that emits it via zod-to-json-schema).\n *\n * `.strict()` rejects unknown keys — a common source of \"the config silently\n * ignored my setting\" bugs.\n */\n\nimport { z } from 'zod'\n\n/**\n * Socket reconnect backoff, handed to the SDK's `RealtimeClient`:\n * `initialBackoffMs` → `reconnectInterval`, `maxBackoffMs` →\n * `maxReconnectInterval`. `jitterRatio` is accepted for configuration\n * compatibility and unused: the SDK applies its own ±25 % jitter.\n */\nexport const reconnectConfigSchema = z\n .object({\n initialBackoffMs: z.number().int().min(100).max(10_000).default(1_000),\n maxBackoffMs: z.number().int().min(1_000).max(300_000).default(30_000),\n jitterRatio: z.number().min(0).max(1).default(0.2),\n })\n .strict()\n\n/**\n * Accepted for configuration compatibility with releases that ran their own\n * socket and unused: the SDK's realtime client has no client-side ping; the\n * server's heartbeat keeps the session alive. Kept so an existing\n * `channels.agentchat.ping` block still parses under the strict schema.\n */\nexport const pingConfigSchema = z\n .object({\n intervalMs: z.number().int().min(5_000).max(120_000).default(45_000),\n timeoutMs: z.number().int().min(1_000).max(60_000).default(30_000),\n })\n .strict()\n\n/**\n * Accepted for configuration compatibility with releases before the\n * integration and otherwise unused: the integration sends nothing itself\n * (the agent's send is a hosted-tool call), so there is no outbound to tune.\n * Kept so an existing `channels.agentchat.outbound` block still parses\n * under the strict schema.\n */\nexport const outboundConfigSchema = z\n .object({\n maxInFlight: z.number().int().min(1).max(10_000).default(256),\n sendTimeoutMs: z.number().int().min(1_000).max(60_000).default(15_000),\n })\n .strict()\n\nexport const observabilityConfigSchema = z\n .object({\n logLevel: z.enum(['trace', 'debug', 'info', 'warn', 'error']).default('info'),\n redactKeys: z\n .array(z.string())\n .default(['apiKey', 'authorization', 'cookie', 'set-cookie']),\n })\n .strict()\n\nexport const agentHandleSchema = z\n .string()\n .regex(\n /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,\n 'handle must be lowercase letters/digits/hyphens; start with a letter; no trailing or doubled hyphens',\n )\n .min(3, 'handle must be at least 3 characters')\n .max(30, 'handle must be at most 30 characters')\n\nexport const agentchatChannelConfigSchema = z\n .object({\n /**\n * Written by OpenClaw on `channels remove` (disable) / re-enable through\n * `config.setAccountEnabled`, and validated by OpenClaw against the JSON\n * schema emitted from this object before the write is persisted — so the\n * strict schema must know it. At runtime `splitEnabledFromRaw` lifts it\n * out before the account is parsed; it is never read from the parsed\n * config.\n */\n enabled: z.boolean().optional(),\n apiBase: z.string().url().default('https://api.agentchat.me'),\n apiKey: z.string().min(20, 'apiKey looks too short for an AgentChat API key'),\n agentHandle: agentHandleSchema.optional(),\n // `.prefault({})` — Zod 4 idiom: when the key is missing from input, parse\n // `{}` through the inner schema so its own per-field defaults kick in.\n // Using `.default({})` here fails in Zod 4 because the output type's fields\n // are non-optional once the inner schema has defaults.\n reconnect: reconnectConfigSchema.prefault({}),\n ping: pingConfigSchema.prefault({}),\n outbound: outboundConfigSchema.prefault({}),\n observability: observabilityConfigSchema.prefault({}),\n })\n .strict()\n\nexport type AgentchatChannelConfig = z.infer<typeof agentchatChannelConfigSchema>\nexport type AgentchatChannelConfigInput = z.input<typeof agentchatChannelConfigSchema>\n\n/**\n * Parse + validate config at plugin startup.\n *\n * Strict on `apiKey` and the four nested groups — `parseChannelConfig` is\n * called only AFTER `resolveAgentchatAccount` has confirmed that the\n * persisted config block is non-empty (see `channel.ts`), so an empty\n * install-time config never reaches Zod. The runtime-time strictness here\n * surfaces typos and out-of-range values fast. The OpenClaw install-time\n * JSON Schema (emitted by `scripts/emit-manifest-schema.mjs`) is more\n * permissive — see that script's post-process step for the rationale —\n * so a freshly-installed plugin can pass install validation against an\n * empty config block before the setup wizard fills in credentials.\n *\n * `AgentChatChannelError` wraps validation failures so the gateway can\n * classify them (`terminal-user` — operator fix required).\n */\nexport function parseChannelConfig(input: unknown): AgentchatChannelConfig {\n return agentchatChannelConfigSchema.parse(input)\n}\n","/**\n * Structured logger for the channel plugin.\n *\n * Wraps pino with:\n * - Secret redaction (`apiKey`, `authorization`, `cookie`, `set-cookie` by default)\n * - A `child({ correlationId })` helper for per-operation logs\n * - Graceful integration: when OpenClaw's channel runtime context provides\n * a logger, we delegate to it so logs stream through the gateway's sink.\n *\n * Never logs the API key. Never logs message bodies above `debug` level.\n */\n\nimport pino from 'pino'\n\nexport type LogLevel = 'trace' | 'debug' | 'info' | 'warn' | 'error'\n\nexport interface Logger {\n trace(obj: object, msg?: string): void\n debug(obj: object, msg?: string): void\n info(obj: object, msg?: string): void\n warn(obj: object, msg?: string): void\n error(obj: object, msg?: string): void\n child(bindings: Record<string, unknown>): Logger\n}\n\nexport interface CreateLoggerOptions {\n level: LogLevel\n redactKeys: readonly string[]\n /** If provided, delegates to the gateway's logger instead of creating our own. */\n delegate?: Logger | undefined\n}\n\nexport function createLogger(options: CreateLoggerOptions): Logger {\n if (options.delegate) {\n return options.delegate\n }\n\n const pinoLogger = pino({\n level: options.level,\n base: { plugin: '@agentchatme/openclaw' },\n redact: {\n paths: buildRedactPaths(options.redactKeys),\n censor: '[REDACTED]',\n },\n timestamp: pino.stdTimeFunctions.isoTime,\n })\n\n return wrapPino(pinoLogger)\n}\n\nfunction buildRedactPaths(keys: readonly string[]): string[] {\n // Cover common shapes: top-level, nested under `config.*`, nested under\n // `headers.*`, nested under `context.*`. Pino redact paths are JSON-path-ish.\n const prefixes = ['', 'config.', 'headers.', 'context.', 'req.headers.', 'res.headers.']\n const paths: string[] = []\n for (const key of keys) {\n for (const prefix of prefixes) {\n paths.push(`${prefix}${key}`)\n }\n }\n // Also redact under `*` wildcard at top level for deeply nested cases.\n paths.push(...keys.map((k) => `*.${k}`))\n return paths\n}\n\nfunction wrapPino(p: pino.Logger): Logger {\n return {\n trace: (obj, msg) => p.trace(obj, msg),\n debug: (obj, msg) => p.debug(obj, msg),\n info: (obj, msg) => p.info(obj, msg),\n warn: (obj, msg) => p.warn(obj, msg),\n error: (obj, msg) => p.error(obj, msg),\n child: (bindings) => wrapPino(p.child(bindings)),\n }\n}\n\n/**\n * Redact a string for display in logs — shows first 8 and last 4 chars,\n * masks the middle. Useful for surfacing \"which key\" without leaking it.\n */\nexport function maskSecret(value: string): string {\n if (value.length <= 12) return '[REDACTED]'\n return `${value.slice(0, 8)}••••${value.slice(-4)}`\n}\n","/**\n * Counters for the integration: the socket's state, its closes and the\n * notices the SDK surfaces, and the wakes handed to the invoker. The\n * integration sends nothing, so there are no outbound metrics.\n *\n * Where they can be read. OpenClaw gives a plugin no Prometheus registry:\n * its `/api/diagnostics/prometheus` (the `diagnostics-prometheus` plugin)\n * renders a fixed catalog of `openclaw_*` families from trusted or\n * dispatcher-owned diagnostic events, and a third-party plugin's\n * `emitDiagnosticEvent` is untrusted by definition and dropped by that\n * exporter. So inside the gateway these counters are kept in memory\n * (`createInMemoryMetrics`) and shown by the status probe\n * (`openclaw channels capabilities --channel agentchat`, the `socket —`\n * line). `createMetrics` registers the same counters into a `prom-client`\n * registry for a host that runs the plugin's classes in its own process and\n * owns a scrape endpoint; `createNoopMetrics` is the zero-cost default.\n *\n * Names are prefixed with `agentchat_channel_` (dashboards: see CHANGELOG):\n * agentchat_channel_wake_total{source} — message | connect | reminder | retry | other\n * agentchat_channel_disconnect_total{code,initiator} — initiator = server (the wire) | client (the SDK's own watchdog)\n * agentchat_channel_connection_state{kind} — the SDK's state: idle | connecting | ready | backoff | blocked | stopped\n * agentchat_channel_error_total{errorClass} — auth (one per rejected HELLO) | transport | handler | protocol | other\n */\n\n/** The counters so far, as the in-memory recorder keeps them. */\nexport interface MetricsSnapshot {\n /** The connection state last set (the gauge's active kind). */\n readonly state: string\n /** Wakes by source. */\n readonly wakes: Readonly<Record<string, number>>\n /** Socket closes by `<code>/<initiator>`, e.g. `1006/server`, `4000/client`. */\n readonly disconnects: Readonly<Record<string, number>>\n /** Rejected HELLOs (`auth`) and the SDK's other notices, by class. */\n readonly errors: Readonly<Record<string, number>>\n}\n\nexport interface MetricsRecorder {\n /** Incremented on every socket close the SDK reports; `initiator` is `server` (the wire) or `client` (the SDK's own watchdog). */\n incDisconnect(labels: { code: string; initiator: string }): void\n /** Incremented on every rejected HELLO (`auth`) and every other notice the SDK surfaces, labeled by class. */\n incError(labels: { errorClass: string }): void\n /** Set the current connection state (cardinality bounded by state kinds). */\n setConnectionState(kind: string): void\n /** Incremented on every wake handed to the invoker (message frames, connects, server wake frames, the ladder's retries). */\n incWake(labels: { source: string }): void\n /** The counters so far, when the recorder keeps them (the in-memory one does; a prom-client registry is read by scraping). */\n snapshot?(): MetricsSnapshot\n}\n\n/** Minimal contract for a prom-client-compatible registry. */\nexport interface PromRegistryLike {\n registerMetric(metric: unknown): void\n}\n\n/** Minimal contract for a prom-client factory; avoids a hard dep on `prom-client`. */\nexport interface PromFactory {\n Counter: new (cfg: MetricConfig) => {\n inc(labels?: Record<string, string>, value?: number): void\n }\n Gauge: new (cfg: MetricConfig) => {\n set(labelsOrValue: Record<string, string> | number, value?: number): void\n }\n}\n\ninterface MetricConfig {\n name: string\n help: string\n labelNames?: readonly string[]\n registers?: readonly unknown[]\n}\n\nexport interface CreateMetricsOptions {\n registry: PromRegistryLike\n factory: PromFactory\n}\n\n/** The recorder for a host with a `prom-client` registry and a scrape endpoint of its own. */\nexport function createMetrics(options: CreateMetricsOptions): MetricsRecorder {\n const { registry, factory } = options\n\n const disconnects = new factory.Counter({\n name: 'agentchat_channel_disconnect_total',\n help: 'WebSocket closes reported by the SDK, by close code and initiator (server | client).',\n labelNames: ['code', 'initiator'],\n registers: [registry],\n })\n\n const errors = new factory.Counter({\n name: 'agentchat_channel_error_total',\n help: 'Rejected HELLOs (auth) and the other notices the SDK surfaced, labeled by error class.',\n labelNames: ['errorClass'],\n registers: [registry],\n })\n\n const connectionState = new factory.Gauge({\n name: 'agentchat_channel_connection_state',\n help: 'Current connection state (1 = active kind, 0 = otherwise).',\n labelNames: ['kind'],\n registers: [registry],\n })\n\n const wakes = new factory.Counter({\n name: 'agentchat_channel_wake_total',\n help: 'Wakes handed to the integration (message frames, connects, server wake frames).',\n labelNames: ['source'],\n registers: [registry],\n })\n\n return {\n incDisconnect: ({ code, initiator }) => disconnects.inc({ code, initiator }),\n incError: ({ errorClass }) => errors.inc({ errorClass }),\n setConnectionState: (kind) => connectionState.set({ kind }, 1),\n incWake: ({ source }) => wakes.inc({ source }),\n }\n}\n\n/**\n * The recorder the gateway binding uses: the same counters, kept in memory\n * and read by the status probe. Label sets are bounded by construction\n * (fixed source / class / state vocabularies, close codes from the wire).\n */\nexport function createInMemoryMetrics(): MetricsRecorder & { snapshot(): MetricsSnapshot } {\n let state = 'idle'\n const wakes = new Map<string, number>()\n const disconnects = new Map<string, number>()\n const errors = new Map<string, number>()\n const bump = (map: Map<string, number>, key: string): void => {\n map.set(key, (map.get(key) ?? 0) + 1)\n }\n const plain = (map: Map<string, number>): Record<string, number> => Object.fromEntries([...map.entries()].sort(([a], [b]) => a.localeCompare(b)))\n return {\n incDisconnect: ({ code, initiator }) => bump(disconnects, `${code}/${initiator}`),\n incError: ({ errorClass }) => bump(errors, errorClass),\n setConnectionState: (kind) => {\n state = kind\n },\n incWake: ({ source }) => bump(wakes, source),\n snapshot: () => ({ state, wakes: plain(wakes), disconnects: plain(disconnects), errors: plain(errors) }),\n }\n}\n\n/** No-op recorder — zero overhead when nothing reads the counters. */\nexport function createNoopMetrics(): MetricsRecorder {\n return {\n incDisconnect: () => undefined,\n incError: () => undefined,\n setConnectionState: () => undefined,\n incWake: () => undefined,\n }\n}\n","/**\n * Group invites: the second wake kind, and the ledger of invites already\n * offered to the agent.\n *\n * An invite is not on the tray and is not gated: the agent gets one turn\n * with the served invite prompt and decides for itself through the hosted\n * tools (accept, decline, or leave it pending). Invites arrive live\n * (`group.invite.received` frame) and are listed again on every connect\n * (`GET /v1/groups/invites`), so the same invite is seen many times over\n * the life of an account. The ledger remembers which invites were offered —\n * on disk, so a gateway restart never starts one more turn for an invite\n * the agent chose to leave pending. An invite whose turn could not start is\n * NOT marked offered: it stays pending in the invoker and is retried on the\n * next wake.\n */\n\nimport * as path from 'node:path'\n\nimport { integrationStateDir, readJsonFile, writeJsonFile } from './state.js'\n\nexport interface GroupInvite {\n readonly inviteId: string\n readonly groupId: string\n readonly groupName: string\n /** Bare handle, `@` stripped; `''` when the frame carried none. */\n readonly inviterHandle: string\n}\n\n/** From a `group.invite.received` frame payload or a `GET /v1/groups/invites` row. `null` when the ids are missing. */\nexport function groupInviteFromRecord(record: unknown): GroupInvite | null {\n if (!record || typeof record !== 'object' || Array.isArray(record)) return null\n const row = record as Record<string, unknown>\n const inviteId = str(row.id)\n const groupId = str(row.group_id)\n if (!inviteId || !groupId) return null\n return {\n inviteId,\n groupId,\n groupName: str(row.group_name) ?? '',\n inviterHandle: (str(row.inviter_handle) ?? '').replace(/^@/, ''),\n }\n}\n\nfunction str(value: unknown): string | undefined {\n return typeof value === 'string' && value.length > 0 ? value : undefined\n}\n\nexport const INVITE_LEDGER_FILE = 'invites.json'\n/** Offered ids older than this are forgotten; a server-side invite does not live that long. */\nexport const INVITE_LEDGER_MAX_AGE_MS = 30 * 24 * 60 * 60_000\n\ninterface LedgerFile {\n readonly offered: Record<string, string>\n}\n\nexport interface InviteLedgerOptions {\n readonly accountId: string\n readonly stateDir?: string | undefined\n /** Explicit file (test seam). Defaults to `<plugin state dir>/invites.json`. */\n readonly file?: string\n readonly now?: () => number\n readonly maxAgeMs?: number\n /** Called when a write fails; the in-memory ledger still holds the id. */\n readonly onWriteError?: (err: unknown) => void\n}\n\nexport function inviteLedgerPath(accountId: string, stateDir?: string): string {\n return path.join(integrationStateDir(accountId, stateDir), INVITE_LEDGER_FILE)\n}\n\nexport class InviteLedger {\n private readonly file: string\n private readonly now: () => number\n private readonly maxAgeMs: number\n private readonly onWriteError: ((err: unknown) => void) | undefined\n private offered: Map<string, string>\n\n constructor(options: InviteLedgerOptions) {\n this.file = options.file ?? inviteLedgerPath(options.accountId, options.stateDir)\n this.now = options.now ?? Date.now\n this.maxAgeMs = options.maxAgeMs ?? INVITE_LEDGER_MAX_AGE_MS\n this.onWriteError = options.onWriteError\n this.offered = this.read()\n }\n\n get path(): string {\n return this.file\n }\n\n get size(): number {\n return this.offered.size\n }\n\n /** True when a turn for this invite was started before (in this process or an earlier one). */\n isOffered(inviteId: string): boolean {\n return this.offered.has(inviteId)\n }\n\n /** Record that a turn for this invite was admitted. Persists at once. */\n markOffered(inviteId: string): void {\n this.offered.set(inviteId, new Date(this.now()).toISOString())\n this.prune()\n try {\n writeJsonFile(this.file, { offered: Object.fromEntries(this.offered) } satisfies LedgerFile)\n } catch (err) {\n this.onWriteError?.(err)\n }\n }\n\n private read(): Map<string, string> {\n const raw = readJsonFile(this.file)\n const out = new Map<string, string>()\n if (!raw || typeof raw !== 'object') return out\n const offered = (raw as Record<string, unknown>).offered\n if (!offered || typeof offered !== 'object' || Array.isArray(offered)) return out\n for (const [id, at] of Object.entries(offered as Record<string, unknown>)) {\n if (typeof at === 'string' && id.length > 0) out.set(id, at)\n }\n this.offered = out\n this.prune()\n return this.offered\n }\n\n private prune(): void {\n const cutoff = this.now() - this.maxAgeMs\n for (const [id, at] of this.offered) {\n const t = Date.parse(at)\n if (!Number.isFinite(t) || t < cutoff) this.offered.delete(id)\n }\n }\n}\n","/**\n * The socket as a wake — the SDK's `RealtimeClient` bound to one account.\n *\n * The transport is the SDK's, lifecycle included: HELLO, the reconnect\n * backoff that never gives up (one notice after a long outage, then a wider\n * cap), the handshake and idle watchdogs, the 10–15 min retry of a rejected\n * key, the delivery ack, per-conversation ordering, the reconnect drain. This\n * module holds what is runtime logic: starting and stopping it with the\n * account, turning what arrives into wakes for the invoker, filtering the\n * echo of the agent's own sends, and handing the SDK's lifecycle events to\n * the gateway as they are.\n *\n * - `message.new` → `onWake('message')` — after reading only\n * the sender (to skip our own echo) and the\n * ids for the log line. The body is never\n * looked at; the agent reads it through the\n * hosted tools inside its turn.\n * - `wake` → `onWake(reason)` — the server's content-free\n * wake (a deferred conversation's reminder).\n * - every successful HELLO → `onWake('connect')` — whatever landed while\n * the socket was down is on the tray.\n * - `group.invite.received` → `onGroupInvite(invite)` — the second wake\n * kind; not on the tray, not gated.\n *\n * `ackOnReceipt: true`: the SDK acknowledges every `message.new` the moment\n * the frame is parsed, before any handler runs — delivered means this\n * machine received it. Whether the agent looked is read state, recorded by\n * the gate's verdicts; an early ack never empties the tray. No frame is\n * ever acknowledged by this module; it sends nothing.\n *\n * Every frame is a wake and every wake reads the whole tray, so no ordering\n * assumption is made: frames the SDK parks on a sequence gap and flushes on\n * a close are wakes like any other.\n *\n * Nothing here classifies a close. Whether a close was a rejected key, a\n * slow handshake or the client's own watchdog is the SDK's call: it says\n * `blocked` (a typed event with the code, the reason and the delay to its\n * next HELLO) or it backs off, and this module reports which.\n */\n\nimport {\n RealtimeClient,\n type AgentChatClient,\n type BlockedInfo,\n type DisconnectInfo,\n type RealtimeOptions,\n type RealtimeState,\n type WakeFrame,\n type WsMessage,\n} from 'agentchatme'\n\nimport type { AgentchatChannelConfig } from '../config-schema.js'\nimport type { Logger } from '../log.js'\nimport type { MetricsRecorder } from '../metrics.js'\nimport { createNoopMetrics } from '../metrics.js'\nimport { AGENTCHAT_CLIENT_IDENTITY } from '../client-identity.js'\nimport { groupInviteFromRecord, type GroupInvite } from './invites.js'\nimport type { WakeSource } from './invoker.js'\n\n/** A server wake frame's `reason` → the fixed wake-source set (the metric label must stay bounded). */\nexport function wakeSourceOf(reason: unknown): WakeSource {\n return reason === 'reminder' ? 'reminder' : 'other'\n}\n\n/**\n * The connection as the gateway reports it: the SDK's own lifecycle, read\n * from `realtime.state`. `idle` before the first start, `connecting` while a\n * socket opens or its HELLO awaits `hello.ok`, `ready` while a session is up,\n * `backoff` between a close and the next attempt, `blocked` after the server\n * rejected the key during the handshake (the SDK retries a fresh HELLO every\n * 10–15 min; a later `hello.ok` clears it), `stopped` after `stop()` — the\n * only state the client never leaves on its own.\n */\nexport type SocketState = RealtimeState\n\n/** Every socket close the SDK reports: the code, the reason, and who ended it (`client` = the SDK's own watchdog). */\nexport type SocketDisconnect = DisconnectInfo\n\n/** A rejected HELLO: the close code and reason, and the delay to the SDK's next attempt. */\nexport type SocketBlocked = BlockedInfo\n\nexport interface WakeDetail {\n readonly conversationId?: string\n readonly messageId?: string\n readonly from?: string\n}\n\nexport interface SocketHandlers {\n /** A wake: the tray may have changed. `source` is for the log line and the metric label only. */\n onWake?: (source: WakeSource, detail: WakeDetail) => void\n /** The second wake kind. */\n onGroupInvite?: (invite: GroupInvite) => void\n /** Once per accepted HELLO (initial + every reconnect), before the connect wake. */\n onConnected?: (at: number) => void\n /** Every socket close the SDK reports (never for our own `stop()`). The state that follows says what comes next. */\n onDisconnected?: (info: SocketDisconnect) => void\n /**\n * The server rejected the key during the handshake. Once per rejected\n * HELLO: the first of a run and every 10–15 min retry after it, until one\n * is accepted (`onConnected`). The state is `blocked` by the time it fires.\n */\n onBlocked?: (info: SocketBlocked) => void\n /** Every notice the SDK surfaces (transport errors, watchdog trips, the long-outage and rejection notices, handler failures). */\n onError?: (error: Error) => void\n onStateChanged?: (next: SocketState, prev: SocketState) => void\n}\n\nexport interface IntegrationSocketOptions {\n readonly config: AgentchatChannelConfig\n readonly logger: Logger\n readonly handlers?: SocketHandlers\n readonly metrics?: MetricsRecorder\n /**\n * The SDK client for the realtime client's reconnect drain and gap fill.\n * Without it offline envelopes wait for the server's own re-push.\n */\n readonly client?: AgentChatClient\n /** Test seam: build the realtime client. Production constructs the SDK's. */\n readonly createRealtime?: (options: RealtimeOptions) => RealtimeClient\n /** Test seam / polyfill: the WebSocket constructor the SDK uses. */\n readonly webSocket?: typeof globalThis.WebSocket\n readonly now?: () => number\n}\n\nexport interface SocketHealth {\n readonly state: SocketState\n readonly connectedAt: number | null\n readonly counters: {\n readonly frames: number\n readonly selfFiltered: number\n readonly wakes: number\n readonly invites: number\n readonly disconnects: number\n }\n}\n\n/** The SDK realtime options for a channel config: `wss://…` base, the account's backoff, the integration identity. */\nexport function realtimeOptionsFor(config: AgentchatChannelConfig, extra: Pick<IntegrationSocketOptions, 'client' | 'webSocket'> = {}): RealtimeOptions {\n return {\n apiKey: config.apiKey,\n baseUrl: config.apiBase.replace(/^http/, 'ws').replace(/\\/+$/, ''),\n clientIdentity: AGENTCHAT_CLIENT_IDENTITY,\n ackOnReceipt: true,\n reconnect: true,\n reconnectInterval: config.reconnect.initialBackoffMs,\n maxReconnectInterval: config.reconnect.maxBackoffMs,\n ...(extra.client ? { client: extra.client } : {}),\n ...(extra.webSocket ? { webSocket: extra.webSocket } : {}),\n }\n}\n\nexport class IntegrationSocket {\n private readonly config: AgentchatChannelConfig\n private readonly logger: Logger\n private readonly handlers: SocketHandlers\n private readonly metrics: MetricsRecorder\n private readonly client: AgentChatClient | undefined\n private readonly createRealtime: (options: RealtimeOptions) => RealtimeClient\n private readonly webSocket: typeof globalThis.WebSocket | undefined\n private readonly now: () => number\n private readonly selfHandle: string | undefined\n\n private realtime: RealtimeClient | null = null\n /** The SDK's state as last reported through its `state` event; `stopped` is set here only for a stop before any start. */\n private state: SocketState = 'idle'\n private connectedAt: number | null = null\n private stopping = false\n\n private frames = 0\n private selfFiltered = 0\n private wakes = 0\n private invites = 0\n private disconnects = 0\n\n constructor(options: IntegrationSocketOptions) {\n this.config = options.config\n this.logger = options.logger.child({ component: 'socket' })\n this.handlers = options.handlers ?? {}\n this.metrics = options.metrics ?? createNoopMetrics()\n this.client = options.client\n this.createRealtime = options.createRealtime ?? ((opts) => new RealtimeClient(opts))\n this.webSocket = options.webSocket\n this.now = options.now ?? Date.now\n this.selfHandle = this.config.agentHandle?.replace(/^@/, '').toLowerCase()\n this.metrics.setConnectionState(this.state)\n }\n\n /**\n * Open the socket. Idempotent. Resolves once the SDK has started its\n * connect loop; a failure to resolve a WebSocket implementation is logged\n * and left to the SDK's own retry. Never throws.\n */\n async start(): Promise<void> {\n if (this.realtime || this.stopping) return\n const realtime = this.createRealtime(realtimeOptionsFor(this.config, { client: this.client, webSocket: this.webSocket }))\n this.realtime = realtime\n this.bind(realtime)\n try {\n await realtime.connect()\n } catch (err) {\n this.logger.warn({ err: describe(err) }, 'socket connect failed — the SDK retries on its own schedule')\n }\n }\n\n /** Close the socket for good; a stopped socket does not reconnect. Idempotent. */\n async stop(): Promise<void> {\n this.stopping = true\n const realtime = this.realtime\n this.realtime = null\n this.connectedAt = null\n if (realtime) {\n try {\n // `disconnect()` is the SDK's only way into `stopped`; its state event\n // carries the transition to the gateway like every other.\n realtime.disconnect()\n } catch (err) {\n this.logger.warn({ err: describe(err) }, 'socket disconnect threw — continuing')\n }\n }\n if (this.state !== 'stopped') this.onState('stopped', this.state)\n }\n\n getHealth(): SocketHealth {\n return {\n state: this.state,\n connectedAt: this.connectedAt,\n counters: { frames: this.frames, selfFiltered: this.selfFiltered, wakes: this.wakes, invites: this.invites, disconnects: this.disconnects },\n }\n }\n\n // ─── Internals ─────────────────────────────────────────────────────\n\n private bind(realtime: RealtimeClient): void {\n realtime.on('state', (next, prev) => this.onState(next, prev))\n\n realtime.onConnect(() => {\n const at = this.now()\n this.connectedAt = at\n this.logger.info({ at: new Date(at).toISOString() }, 'connected (HELLO accepted)')\n this.guard('onConnected', () => this.handlers.onConnected?.(at))\n // Whatever landed while the socket was down is on the tray now; the\n // connect itself is the wake that covers the gap.\n this.wake('connect', {})\n })\n\n realtime.onDisconnect((info) => {\n if (this.stopping) return\n this.disconnects += 1\n this.connectedAt = null\n this.metrics.incDisconnect({ code: String(info.code), initiator: info.initiator })\n this.logger.info({ code: info.code, reason: info.reason, initiator: info.initiator }, 'socket closed — the SDK decides what follows (backoff or blocked)')\n this.guard('onDisconnected', () => this.handlers.onDisconnected?.(info))\n })\n\n realtime.on('blocked', (info) => {\n if (this.stopping) return\n // One rejected HELLO: the SDK's typed event is what counts it.\n this.metrics.incError({ errorClass: 'auth' })\n this.logger.warn(\n { code: info.code, reason: info.reason, retryInMs: info.retryInMs },\n 'the server rejected the key during the handshake — the SDK retries a fresh HELLO on its own',\n )\n this.guard('onBlocked', () => this.handlers.onBlocked?.(info))\n })\n\n realtime.onError((error) => {\n if (this.stopping) return\n if (realtime.state === 'blocked') {\n // The SDK's one rejection notice per blocked run is emitted between\n // its `blocked` state and the `blocked` event that carries the code\n // and reason; the event is what the gateway reports and the metric\n // counts, so the notice itself is a debug line here, not a second\n // signal for the same rejection.\n this.logger.debug({ err: error.message }, 'SDK notice while blocked')\n return\n }\n this.metrics.incError({ errorClass: classifyRealtimeError(error) })\n this.logger.debug({ err: error.message }, 'socket error')\n this.guard('onError', () => this.handlers.onError?.(error))\n })\n\n realtime.on('message.new', (message) => this.onMessageNew(message))\n realtime.on('wake', (frame) => this.onWakeFrame(frame))\n realtime.on('group.invite.received', (message) => this.onInvite(message))\n }\n\n private onMessageNew(message: WsMessage): void {\n this.frames += 1\n const payload = message.payload ?? {}\n const senderRaw = payload.sender ?? payload.from ?? ''\n const sender = typeof senderRaw === 'string' ? senderRaw.replace(/^@/, '').toLowerCase() : ''\n const detail: WakeDetail = {\n ...(typeof payload.conversation_id === 'string' ? { conversationId: payload.conversation_id } : {}),\n ...(typeof payload.id === 'string' ? { messageId: payload.id } : {}),\n ...(sender ? { from: sender } : {}),\n }\n if (this.selfHandle && sender === this.selfHandle) {\n // Server-side fan-out echoes our own sends back; our own words never wake us.\n this.selfFiltered += 1\n this.logger.debug(detail, 'own echo — not a wake')\n return\n }\n this.logger.debug(detail, 'wake — message.new')\n this.wake('message', detail)\n }\n\n private onWakeFrame(frame: WakeFrame): void {\n this.frames += 1\n const reason: unknown = frame.payload?.reason\n const detail: WakeDetail = { conversationId: frame.payload.conversation_id }\n this.logger.info({ ...detail, reason, step: frame.payload.step }, 'wake — server wake frame')\n this.wake(wakeSourceOf(reason), detail)\n }\n\n private onInvite(message: WsMessage): void {\n this.frames += 1\n const invite = groupInviteFromRecord(message.payload)\n if (!invite) {\n this.logger.warn({ keys: Object.keys(message.payload ?? {}).sort() }, 'group.invite.received without ids — dropped')\n return\n }\n this.invites += 1\n this.guard('onGroupInvite', () => this.handlers.onGroupInvite?.(invite))\n }\n\n private wake(source: WakeSource, detail: WakeDetail): void {\n this.wakes += 1\n this.metrics.incWake({ source })\n this.guard('onWake', () => this.handlers.onWake?.(source, detail))\n }\n\n /** The SDK's state transition, mirrored for the health probe and the gauge, then handed on. */\n private onState(next: SocketState, prev: SocketState): void {\n this.state = next\n this.metrics.setConnectionState(next)\n this.logger.debug({ from: prev, to: next }, 'socket state')\n this.guard('onStateChanged', () => this.handlers.onStateChanged?.(next, prev))\n }\n\n /** A failing handler never takes the socket down; the next frame wakes again and the tray keeps the cards. */\n private guard(name: string, fn: () => void): void {\n try {\n fn()\n } catch (err) {\n this.logger.error({ err: describe(err), handler: name }, 'handler threw — continuing')\n }\n }\n}\n\n/**\n * Low-cardinality class for the error metric, for the notices the SDK\n * surfaces through `onError`. A rejected key is not among them: that is the\n * SDK's `blocked` event, counted as `auth` where it fires.\n */\nexport function classifyRealtimeError(error: Error): 'transport' | 'handler' | 'protocol' | 'other' {\n const message = error.message\n if (/handler failed/i.test(message)) return 'handler'\n if (/failed validation|not an object|expected a bare array/i.test(message)) return 'protocol'\n if (error.name === 'ConnectionError' || /websocket|hello|handshake|liveness|reconnecting|sync drain|sync ack/i.test(message)) return 'transport'\n return 'other'\n}\n\nfunction describe(err: unknown): string {\n return err instanceof Error ? err.message : String(err)\n}\n","/**\n * Per-account integration registry.\n *\n * OpenClaw's gateway starts one integration per `(channelId, accountId)` pair\n * at channel enable and stops it on shutdown. The registry holds the live\n * socket, its invoker and the texts store so the status adapter can report\n * them, and serializes start/stop per account so a start-during-stop never\n * races.\n *\n * Keying is `accountId`-only; `channelId` is always `\"agentchat\"` here.\n */\n\nimport type { Logger } from '../log.js'\nimport type { AgentchatChannelConfig } from '../config-schema.js'\nimport { IntegrationSocket, type IntegrationSocketOptions, type SocketHandlers } from '../integration/socket.js'\nimport type { AgentInvoker } from '../integration/invoker.js'\nimport type { TextsStore } from '../integration/texts.js'\nimport type { MetricsRecorder } from '../metrics.js'\n\nexport interface IntegrationEntry {\n readonly socket: IntegrationSocket\n readonly invoker: AgentInvoker | null\n readonly texts: TextsStore | null\n /** The recorder the socket (and the invoker) count into; the status probe reads its snapshot when it keeps one. */\n readonly metrics: MetricsRecorder | null\n readonly config: AgentchatChannelConfig\n readonly logger: Logger\n}\n\nconst registry = new Map<string, IntegrationEntry>()\n\n/** Per-account mutex: every register/unregister for the same account runs through this queue. */\nconst accountLocks = new Map<string, Promise<unknown>>()\n\nfunction withAccountLock<T>(accountId: string, op: () => Promise<T>): Promise<T> {\n const prev = accountLocks.get(accountId) ?? Promise.resolve()\n const next = prev.catch(() => undefined).then(op)\n accountLocks.set(accountId, next)\n next.then(\n () => {\n if (accountLocks.get(accountId) === next) accountLocks.delete(accountId)\n },\n () => {\n if (accountLocks.get(accountId) === next) accountLocks.delete(accountId)\n },\n )\n return next\n}\n\nexport interface RegisterIntegrationParams {\n readonly accountId: string\n readonly config: AgentchatChannelConfig\n readonly logger: Logger\n /** Builds the invoker and the handlers that feed it, given the socket that will be started. */\n readonly build: (socket: IntegrationSocket) => { invoker: AgentInvoker | null; texts?: TextsStore | null; handlers: SocketHandlers }\n /** Extra socket options (the SDK client for the reconnect drain, a WebSocket seam). */\n readonly socketOptions?: Pick<IntegrationSocketOptions, 'client' | 'webSocket' | 'metrics' | 'createRealtime'>\n /** Test seam for the socket constructor. */\n readonly createSocket?: (options: IntegrationSocketOptions) => IntegrationSocket\n}\n\n/**\n * Create and start an integration for `accountId`. If one is already\n * registered, stop it first (config change path). Returns the live entry.\n */\nexport function registerIntegration(params: RegisterIntegrationParams): Promise<IntegrationEntry> {\n return withAccountLock(params.accountId, async () => {\n const existing = registry.get(params.accountId)\n if (existing) {\n await stopEntry(existing)\n registry.delete(params.accountId)\n }\n\n // The handlers close over the socket and the socket over the handlers;\n // a late-bound reference resolves the cycle. The socket cannot deliver a\n // frame before `start()`, so the reference is set before any handler runs.\n let built: { invoker: AgentInvoker | null; texts?: TextsStore | null; handlers: SocketHandlers } | null = null\n const handlers: SocketHandlers = {\n onWake: (source, detail) => built?.handlers.onWake?.(source, detail),\n onGroupInvite: (invite) => built?.handlers.onGroupInvite?.(invite),\n onConnected: (at) => built?.handlers.onConnected?.(at),\n onDisconnected: (info) => built?.handlers.onDisconnected?.(info),\n onBlocked: (info) => built?.handlers.onBlocked?.(info),\n onError: (error) => built?.handlers.onError?.(error),\n onStateChanged: (next, prev) => built?.handlers.onStateChanged?.(next, prev),\n }\n const create = params.createSocket ?? ((options) => new IntegrationSocket(options))\n const socket = create({ config: params.config, logger: params.logger, handlers, ...(params.socketOptions ?? {}) })\n built = params.build(socket)\n\n const entry: IntegrationEntry = {\n socket,\n invoker: built.invoker,\n texts: built.texts ?? null,\n metrics: params.socketOptions?.metrics ?? null,\n config: params.config,\n logger: params.logger,\n }\n registry.set(params.accountId, entry)\n try {\n await socket.start()\n } catch (err) {\n registry.delete(params.accountId)\n built.invoker?.stop()\n built.texts?.stop()\n throw err\n }\n return entry\n })\n}\n\n/** Stop and remove the integration for `accountId`. No-op if absent. */\nexport function unregisterIntegration(accountId: string): Promise<void> {\n return withAccountLock(accountId, async () => {\n const entry = registry.get(accountId)\n if (!entry) return\n registry.delete(accountId)\n await stopEntry(entry)\n })\n}\n\nasync function stopEntry(entry: IntegrationEntry): Promise<void> {\n entry.invoker?.stop()\n entry.texts?.stop()\n try {\n await entry.socket.stop()\n } catch (err) {\n entry.logger.error({ err: err instanceof Error ? err.message : String(err) }, 'socket.stop threw during unregister')\n }\n}\n\nexport function getIntegration(accountId: string): IntegrationEntry | undefined {\n return registry.get(accountId)\n}\n\nexport function listActiveAccounts(): string[] {\n return [...registry.keys()]\n}\n\n/** Test hook only. */\nexport async function resetRegistryForTest(): Promise<void> {\n const entries = [...registry.values()]\n registry.clear()\n await Promise.all(entries.map((entry) => stopEntry(entry).catch(() => undefined)))\n}\n","/**\n * Wake coalescing — one gate cycle per burst, not per frame.\n *\n * A `message.new` frame, a `wake` frame and a successful connect are all\n * wakes: a hint that the tray changed, never the carrier of what changed. A\n * group burst arrives as many frames seconds apart; the server already\n * bundles its webhook wakes for such bursts, and the integration does the\n * same for the socket. The window is trailing-edge: every wake restarts it,\n * so the cycle fires `debounceMs` after the LAST wake of the burst — with a\n * hard cap: no later than `maxWindowMs` after the FIRST wake, so a steady\n * trickle cannot starve the gate. Whoever fires then reads the whole tray,\n * so nothing a later frame announced is missed — the tray is the truth, the\n * wake is not.\n *\n * `wakeAfter` serves the local retry ladder: when a gate cycle could not\n * complete (model unreachable, server error, turn refused) the invoker\n * schedules another wake later instead of dropping the tray. The server's\n * own ladder only rings webhooks; a connected socket gets no re-wake, so the\n * integration carries that duty itself. When a delayed wake is already\n * pending the SOONER deadline wins — a later retry never pushes an earlier\n * one back.\n */\n\nexport const DEFAULT_DEBOUNCE_MS = 2_000\n/** A burst fires at most this long after its first wake, however many wakes keep landing. */\nexport const DEFAULT_MAX_WINDOW_MS = 6_000\n\nexport interface WakeCoalescerOptions {\n readonly onFire: () => void\n /** Called when a delayed (retry-ladder) wake fires, before it is counted like any other wake. */\n readonly onDelayedWake?: () => void\n readonly debounceMs?: number\n readonly maxWindowMs?: number\n readonly now?: () => number\n readonly setTimeout?: (fn: () => void, ms: number) => NodeJS.Timeout\n readonly clearTimeout?: (handle: NodeJS.Timeout) => void\n}\n\nexport class WakeCoalescer {\n private readonly onFire: () => void\n private readonly onDelayedWake: (() => void) | undefined\n private readonly debounceMs: number\n private readonly maxWindowMs: number\n private readonly now: () => number\n private readonly _setTimeout: (fn: () => void, ms: number) => NodeJS.Timeout\n private readonly _clearTimeout: (handle: NodeJS.Timeout) => void\n\n private timer: NodeJS.Timeout | null = null\n private burstStartedAt: number | null = null\n private delayed: NodeJS.Timeout | null = null\n private delayedDeadline: number | null = null\n private stopped = false\n\n wakes = 0\n absorbed = 0\n fires = 0\n\n constructor(options: WakeCoalescerOptions) {\n const debounce = options.debounceMs ?? DEFAULT_DEBOUNCE_MS\n if (!(debounce >= 0)) throw new RangeError('debounceMs must be >= 0')\n const maxWindow = options.maxWindowMs ?? DEFAULT_MAX_WINDOW_MS\n if (!(maxWindow >= debounce)) throw new RangeError('maxWindowMs must be >= debounceMs')\n this.onFire = options.onFire\n this.onDelayedWake = options.onDelayedWake\n this.debounceMs = debounce\n this.maxWindowMs = maxWindow\n this.now = options.now ?? Date.now\n this._setTimeout = options.setTimeout ?? ((fn, ms) => setTimeout(fn, ms))\n this._clearTimeout = options.clearTimeout ?? ((h) => clearTimeout(h))\n }\n\n /** True while a debounce timer is armed. */\n get armed(): boolean {\n return this.timer !== null\n }\n\n /** True while a retry wake is scheduled and has not fired. */\n get delayedPending(): boolean {\n return this.delayed !== null\n }\n\n /**\n * A wake. The first one of a burst arms the window; every later one is\n * absorbed and restarts it (trailing edge), never past the burst's cap.\n */\n wake(): void {\n if (this.stopped) return\n this.wakes += 1\n const now = this.now()\n if (this.timer === null) {\n this.burstStartedAt = now\n this.timer = this._setTimeout(() => this.fire(), this.debounceMs)\n return\n }\n this.absorbed += 1\n const capAt = (this.burstStartedAt ?? now) + this.maxWindowMs\n const delay = Math.max(0, Math.min(this.debounceMs, capAt - now))\n this._clearTimeout(this.timer)\n this.timer = this._setTimeout(() => this.fire(), delay)\n }\n\n /** A delayed wake (retry ladder). The sooner pending deadline is kept. */\n wakeAfter(delayMs: number): void {\n if (this.stopped) return\n const delay = Math.max(0, delayMs)\n const deadline = this.now() + delay\n if (this.delayed !== null) {\n if (this.delayedDeadline !== null && this.delayedDeadline <= deadline) {\n return // an earlier retry is already on its way; keep it\n }\n this._clearTimeout(this.delayed)\n }\n this.delayedDeadline = deadline\n this.delayed = this._setTimeout(() => {\n this.delayed = null\n this.delayedDeadline = null\n if (this.stopped) return\n try {\n this.onDelayedWake?.()\n } catch {\n // observers never block the wake\n }\n this.wake()\n }, delay)\n }\n\n /** Cancel everything; later wakes are ignored. */\n stop(): void {\n this.stopped = true\n if (this.timer !== null) {\n this._clearTimeout(this.timer)\n this.timer = null\n this.burstStartedAt = null\n }\n if (this.delayed !== null) {\n this._clearTimeout(this.delayed)\n this.delayed = null\n this.delayedDeadline = null\n }\n }\n\n private fire(): void {\n this.timer = null\n this.burstStartedAt = null\n if (this.stopped) return\n this.fires += 1\n try {\n this.onFire()\n } catch {\n // The callback belongs to the invoker; a failure there must not kill\n // the timer machinery. The next wake re-arms as usual.\n }\n }\n}\n","/**\n * Wake → gate → turn. The only path from the socket to the agent.\n *\n * What happens on a wake\n * ──────────────────────\n * 1. **Coalesce.** Frames inside a short window become one wake\n * (`WakeCoalescer`). A group waking up is one cycle, not twenty.\n * 2. **Read the tray.** `client.inbox.tray()` — the server's briefing cards\n * and its gate question, as it built them.\n * 3. **Gate.** The SDK's gate helper renders the question and the cards,\n * asks the agent's own model (`callModel`, a tool-free completion through\n * `runtime.llm.complete`) and records `dismiss` / `defer` with the card's\n * anchor. `reply` comes back as entries the invoker records itself.\n * 4. **Turn.** For every conversation decided `reply`, start ONE OpenClaw\n * agent turn (`runtime.subagent.run`, `deliver: false`) with the served\n * wake instruction and the conversation id. The `reply` verdict is\n * recorded when the run has COMPLETED (`status: ok`) — never at its\n * start: recorded at admission it marked the conversation read before\n * the turn's own inbox call, which then waited on an empty tray, and a\n * turn that crashed left the peer with a read receipt and no answer. A\n * completed turn counts as read even if it chose not to send — unless\n * the turn recorded a verdict for its conversation itself (the served\n * texts tell the model to record `reply` after its send, or `dismiss`\n * when it read and chose not to answer). One tray read after the run\n * shows that: the card left the tray (read, or hidden by a defer) or its\n * `your_last_decision` moved since the gate's tray. The host then\n * records nothing more, so the agent's own last verdict stands and a\n * reply is counted once. A failed read, or a card that may sit past a\n * truncated tray, records `reply` as before (reading is forward-only). A turn\n * OpenClaw refuses, or one that ends in error or on the wait timeout,\n * records nothing: the conversation stays unread, the card stays on the\n * tray, and the ladder re-wakes so it is gated again (one more gate\n * call, no silent drop). The turn's final text is discarded — nothing is\n * auto-routed anywhere.\n *\n * One cycle at a time per account: a wake that lands while a cycle runs is\n * remembered and runs once the cycle ends (the tray is re-read, so whatever\n * the earlier wake announced is covered). A cycle ends when its turns are\n * ADMITTED, not when they finish: OpenClaw serializes the turns on the\n * account's lane (`integrationLane`), so the next cycle's turn simply queues\n * behind, and holding the wake loop for up to 15 minutes per turn would only\n * delay the next tray read. Completion is logged as it happens. A cycle\n * that could not complete — model unreachable, server error, turn refused —\n * re-wakes itself on a local ladder (1 m, 5 m, 30 m) because a connected\n * socket gets no re-wake from the server; the cards wait on the tray\n * meanwhile. One outage climbs the ladder one rung: a retry already on its\n * way is never replaced by a later one.\n *\n * Group invites are a second wake kind: not on the tray, not gated, one turn\n * each with the served invite prompt, serialized on the same worker. An\n * invite whose turn OpenClaw refused stays pending and is tried again on the\n * next wake; one that started is remembered on disk (`InviteLedger`) so a\n * restart never offers it twice.\n */\n\nimport { gate, type AgentChatClient, type GateReply, type InboxTray, type Texts } from 'agentchatme'\n\nimport type { Logger } from '../log.js'\nimport type { MetricsRecorder } from '../metrics.js'\nimport { createNoopMetrics } from '../metrics.js'\nimport { WakeCoalescer, DEFAULT_DEBOUNCE_MS } from './wake.js'\nimport type { GateModelCall, TurnStarter, TurnOutcome, TurnAdmission, TurnReadiness } from './model.js'\nimport type { GroupInvite } from './invites.js'\nimport { OPENCLAW_TOOL_NAMER, integrationLane, inviteSessionKey, inviteTurnPrompt, wakeSessionKey, wakeTurnPrompt } from './turn.js'\n\n/**\n * Local re-wake ladder after a cycle that could not complete. Mirrors the\n * server's webhook ladder (1 m, 5 m, 30 m) — a connected socket never gets\n * that re-wake, so the integration carries it. After the last rung the cycle\n * waits for the next wake; the cards are still on the tray.\n */\nexport const RETRY_LADDER_MS: readonly number[] = [60_000, 300_000, 1_800_000]\n\n/**\n * Where a wake came from — a closed set, because it is a metric label:\n * `message` (a peer wrote), `connect` (an accepted HELLO), `reminder` (the\n * server's wake frame for a deferred conversation), `retry` (the local\n * ladder), `other` (a server wake with a reason this version does not know).\n */\nexport type WakeSource = 'message' | 'connect' | 'reminder' | 'retry' | 'other'\n\n/** The two SDK resources a cycle uses; `AgentChatClient` satisfies it. */\nexport type InvokerClient = Pick<AgentChatClient, 'inbox' | 'decisions'>\n\n/** The served texts as the invoker sees them: the current copy, or one attempt to get it. */\nexport interface TextsSource {\n readonly current: Texts | null\n ensure(): Promise<Texts | null>\n}\n\n/** Which invites already got their turn (persisted across restarts). */\nexport interface InviteStore {\n isOffered(inviteId: string): boolean\n markOffered(inviteId: string): void\n}\n\nexport interface AgentInvokerOptions {\n readonly accountId: string\n readonly agentId: string\n readonly client: InvokerClient\n readonly callModel: GateModelCall\n readonly startTurn: TurnStarter\n readonly texts: TextsSource\n readonly invites: InviteStore\n readonly logger: Logger\n /** Counts the ladder's re-wakes (`agentchat_channel_wake_total{source=\"retry\"}`). The socket counts the others. */\n readonly metrics?: MetricsRecorder\n /**\n * Whether a turn started now can have the hosted tools (`turnReadiness`).\n * Checked before the gate: while unready nothing is gated — the cards\n * stay on the tray, no model call is spent, no turn starts — and the\n * ladder re-wakes. Default: always ready.\n */\n readonly readiness?: () => TurnReadiness\n /** `false`: no gate step — one turn per cycle with the served wake instruction; the agent judges in-turn. */\n readonly gateEnabled?: boolean\n readonly debounceMs?: number\n readonly retryLadderMs?: readonly number[]\n readonly now?: () => number\n readonly setTimeout?: (fn: () => void, ms: number) => NodeJS.Timeout\n readonly clearTimeout?: (handle: NodeJS.Timeout) => void\n}\n\nexport interface InvokerCounters {\n readonly cycles: number\n readonly turns: number\n readonly inviteTurns: number\n /** Turns admitted whose run has not ended yet (OpenClaw's lane serializes them). */\n readonly turnsInFlight: number\n readonly wakes: number\n readonly absorbed: number\n readonly retryRung: number\n readonly pendingInvites: number\n}\n\nexport type CycleOutcome =\n /** The tray had no cards. */\n | 'empty'\n /** The gate decided; turns were started for the replies. */\n | 'decided'\n /** The model failed or answered nothing usable; nothing recorded, no turn. */\n | 'fail_closed'\n /** The gate is off; one turn with the served wake instruction. */\n | 'gate_off'\n /** The tray could not be read. */\n | 'tray_failed'\n /** The served texts are not available yet; nothing gated, the cards wait. */\n | 'texts_missing'\n /** A turn could not have the hosted tools; nothing gated, no model call, the cards wait. */\n | 'tools_unavailable'\n\nexport interface CycleResult {\n readonly outcome: CycleOutcome\n readonly cards: number\n readonly reply: number\n readonly dismiss: number\n readonly defer: number\n readonly undecided: number\n /** `dismiss` / `defer` the server took in this cycle. `reply` verdicts are recorded as their turns complete, after the cycle. */\n readonly recorded: number\n readonly recordFailures: number\n readonly turnsStarted: number\n readonly turnsRefused: number\n /** Cards left out of this cycle because a reply turn for their conversation is still running. */\n readonly skippedInFlight: number\n readonly truncated: boolean\n readonly latencyMs: number\n readonly failure: string | null\n}\n\ntype RetryPlan = { readonly kind: 'armed'; readonly delayMs: number; readonly rung: number } | { readonly kind: 'pending' } | { readonly kind: 'exhausted' }\n\nexport class AgentInvoker {\n private readonly accountId: string\n private readonly agentId: string\n private readonly client: InvokerClient\n private readonly callModel: GateModelCall\n private readonly startTurn: TurnStarter\n private readonly texts: TextsSource\n private readonly invites: InviteStore\n private readonly logger: Logger\n private readonly metrics: MetricsRecorder\n private readonly readiness: () => TurnReadiness\n private readonly gateEnabled: boolean\n private readonly ladder: readonly number[]\n private readonly now: () => number\n private readonly coalescer: WakeCoalescer\n\n private cycleDue = false\n private running: Promise<void> | null = null\n private stopped = false\n private pendingInvites: GroupInvite[] = []\n private invitesDirty = false\n private retryRung = 0\n private turnsInFlight = 0\n /**\n * Conversations whose reply turn is running. Their verdict is recorded\n * only when the turn completes, so the card stays on the tray meanwhile\n * and every wake in between would re-gate it and queue a second turn.\n * Such cards are left out of the cycle; once the turn ends the tray is\n * read again if any were.\n */\n private readonly replyTurnsInFlight = new Set<string>()\n private skippedWhileInFlight = false\n /** The reason the tools were last found unavailable; logged when it changes, not per wake. */\n private unreadyReason: string | null = null\n\n cycles = 0\n turns = 0\n inviteTurns = 0\n\n constructor(options: AgentInvokerOptions) {\n this.accountId = options.accountId\n this.agentId = options.agentId\n this.client = options.client\n this.callModel = options.callModel\n this.startTurn = options.startTurn\n this.texts = options.texts\n this.invites = options.invites\n this.logger = options.logger.child({ component: 'integration', accountId: options.accountId })\n this.metrics = options.metrics ?? createNoopMetrics()\n this.readiness = options.readiness ?? (() => ({ ready: true }))\n this.gateEnabled = options.gateEnabled ?? true\n this.ladder = options.retryLadderMs ?? RETRY_LADDER_MS\n this.now = options.now ?? Date.now\n this.coalescer = new WakeCoalescer({\n onFire: () => this.onWakeFired(),\n onDelayedWake: () => {\n this.logger.debug({ source: 'retry' }, 'wake')\n this.metrics.incWake({ source: 'retry' })\n },\n debounceMs: options.debounceMs ?? DEFAULT_DEBOUNCE_MS,\n now: this.now,\n ...(options.setTimeout ? { setTimeout: options.setTimeout } : {}),\n ...(options.clearTimeout ? { clearTimeout: options.clearTimeout } : {}),\n })\n }\n\n // ─── wakes ──────────────────────────────────────────────────────────\n\n /** A wake from the socket (a frame, a connect, a reminder) or any other source. Coalesced, then cycled. */\n wake(source: WakeSource): void {\n if (this.stopped) return\n this.logger.debug({ source }, 'wake')\n this.coalescer.wake()\n }\n\n /**\n * The second wake kind. An invite already offered (this process or an\n * earlier one, per the ledger) or already pending is ignored, so an\n * invite seen live and again on a connect-time catch-up is decided once.\n * Returns true when newly queued.\n */\n groupInvite(invite: GroupInvite, source: string): boolean {\n if (this.stopped) return false\n if (this.invites.isOffered(invite.inviteId)) return false\n if (this.pendingInvites.some((pending) => pending.inviteId === invite.inviteId)) return false\n this.logger.info(\n { groupId: invite.groupId, groupName: invite.groupName, inviter: invite.inviterHandle, inviteId: invite.inviteId, source },\n 'group invite — queuing one invite turn',\n )\n this.pendingInvites.push(invite)\n this.invitesDirty = true\n this.schedule()\n return true\n }\n\n /** Cancel timers; a cycle in flight finishes on its own. */\n stop(): void {\n this.stopped = true\n this.coalescer.stop()\n }\n\n /** The promise of the work currently running, for tests and for graceful stops. */\n settled(): Promise<void> {\n return this.running ?? Promise.resolve()\n }\n\n counters(): InvokerCounters {\n return {\n cycles: this.cycles,\n turns: this.turns,\n inviteTurns: this.inviteTurns,\n turnsInFlight: this.turnsInFlight,\n wakes: this.coalescer.wakes,\n absorbed: this.coalescer.absorbed,\n retryRung: this.retryRung,\n pendingInvites: this.pendingInvites.length,\n }\n }\n\n // ─── worker ─────────────────────────────────────────────────────────\n\n private onWakeFired(): void {\n this.cycleDue = true\n // A wake is also the moment to retry invites whose turn OpenClaw refused.\n if (this.pendingInvites.length > 0) this.invitesDirty = true\n this.schedule()\n }\n\n /** Run the worker if idle. One cycle at a time; work that lands mid-cycle runs afterwards. */\n private schedule(): void {\n if (this.running) return\n this.running = this.drain().finally(() => {\n this.running = null\n if (!this.stopped && (this.cycleDue || this.invitesDirty)) this.schedule()\n })\n }\n\n private async drain(): Promise<void> {\n while (!this.stopped) {\n if (this.invitesDirty) {\n this.invitesDirty = false\n await this.runInviteTurns()\n continue\n }\n if (this.cycleDue) {\n // Clear BEFORE the cycle: a wake landing during the cycle sets it\n // again and earns one more cycle afterwards.\n this.cycleDue = false\n try {\n await this.runCycle()\n } catch (err) {\n // Whatever escaped the cycle must not kill the worker. Re-wake on\n // the ladder so the tray is read again.\n this.logger.error({ err: describe(err), ...this.retry() }, 'cycle failed with an unhandled error — re-waking later')\n }\n continue\n }\n return\n }\n }\n\n // ─── one cycle ──────────────────────────────────────────────────────\n\n /** Read the tray, gate it, start a turn per reply. Public so tests can drive one cycle. */\n async runCycle(): Promise<CycleResult> {\n this.cycles += 1\n const started = this.now()\n let tray: InboxTray\n try {\n tray = await this.client.inbox.tray({ waitMs: 0 })\n } catch (err) {\n this.logger.warn({ err: describe(err), ...this.retry() }, 'tray read failed — re-waking later')\n return this.result('tray_failed', 0, false, started, describe(err))\n }\n\n const allCards = gate.cardsOf(tray)\n const truncated = tray.truncated === true\n if (allCards.length === 0) {\n this.logger.info({ deferred: tray.deferred ?? 0 }, 'tray empty — nothing to decide')\n this.retryRung = 0\n return this.result('empty', 0, truncated, started)\n }\n\n // A card whose reply turn is still running is that turn's to answer;\n // gating it again would queue a second turn. It is left out here and\n // the tray is read again once the turn ends (see `admitted`).\n const cards = allCards.filter((card) => !this.replyTurnsInFlight.has(card.conversation_id))\n const skippedInFlight = allCards.length - cards.length\n if (skippedInFlight > 0) this.skippedWhileInFlight = true\n if (cards.length === 0) {\n this.logger.info({ skippedInFlight }, 'every card on the tray has a reply turn running — nothing new to decide')\n return { ...this.result('empty', 0, truncated, started), skippedInFlight }\n }\n\n // The turn text is served, never bundled. Without it no turn can start,\n // so nothing is gated either: the cards wait, and the next copy (retried\n // by the texts store) or the next wake tries again.\n const texts = await this.texts.ensure()\n if (!texts) {\n this.logger.warn({ cards: cards.length, ...this.retry() }, 'served texts not available — not gating; the cards wait on the tray')\n return { ...this.result('texts_missing', cards.length, truncated, started, 'texts missing'), skippedInFlight }\n }\n\n // A turn that cannot have the hosted tools is not worth a gate call:\n // nothing is asked, nothing recorded, the cards wait, the ladder\n // re-wakes. The reason is logged when it changes, not on every rung.\n const readiness = this.readiness()\n if (!readiness.ready) {\n const changed = this.unreadyReason !== readiness.reason\n this.unreadyReason = readiness.reason\n this.logger[changed ? 'warn' : 'debug']({ cards: cards.length, reason: readiness.reason, ...this.retry() }, 'AgentChat tools not available to a turn — not gating; the cards wait on the tray')\n return { ...this.result('tools_unavailable', cards.length, truncated, started, readiness.reason), skippedInFlight }\n }\n if (this.unreadyReason !== null) {\n this.unreadyReason = null\n this.logger.info({}, 'AgentChat tools available to turns again')\n }\n\n let result: CycleResult\n if (!this.gateEnabled) {\n result = await this.runUngated(cards.length, texts, truncated, started)\n } else {\n const trayToGate: InboxTray = skippedInFlight > 0 ? { ...tray, conversations: cards } : tray\n result = await this.runGated(trayToGate, cards.length, texts, truncated, started, skippedInFlight)\n }\n if (skippedInFlight > 0) result = { ...result, skippedInFlight }\n\n if (truncated && result.outcome !== 'fail_closed') {\n // More conversations are waiting than one tray shows.\n this.logger.info({}, 'tray truncated — waking again for the rest')\n this.coalescer.wake()\n }\n return result\n }\n\n /** Gate off: the agent judges in-turn with the hosted tools. One turn, nothing recorded here. */\n private async runUngated(cards: number, texts: Texts, truncated: boolean, started: number): Promise<CycleResult> {\n this.logger.info({ cards }, 'gate off — starting one turn with the served wake instruction')\n const sessionKey = wakeSessionKey(this.agentId, this.now())\n this.logger.info({ sessionKey }, 'turn start')\n const admission = await this.startTurn({ sessionKey, prompt: wakeTurnPrompt(texts), lane: integrationLane(this.accountId) })\n if (!admission.ran) {\n this.logger.warn({ sessionKey, error: admission.error, ...this.retry() }, 'turn not started — re-waking later')\n } else {\n this.admitted(sessionKey, admission, 'turn complete (final text discarded; the send is a hosted-tool call)')\n this.retryRung = 0\n }\n return {\n ...this.result('gate_off', cards, truncated, started),\n turnsStarted: admission.ran ? 1 : 0,\n turnsRefused: admission.ran ? 0 : 1,\n }\n }\n\n private async runGated(tray: InboxTray, cards: number, texts: Texts, truncated: boolean, started: number, skippedInFlight = 0): Promise<CycleResult> {\n const decided = await gate.run({ tray, callModel: this.callModel, client: this.client, toolNamer: OPENCLAW_TOOL_NAMER })\n const latencyMs = this.now() - started\n const counts = { reply: 0, dismiss: 0, defer: 0 }\n for (const verdict of decided.verdicts) counts[verdict.decision] += 1\n\n if (decided.outcome === 'fail_closed') {\n // Nothing recorded, no turn. The cards stay on the tray; re-wake on\n // the ladder so a transient provider outage does not leave peers\n // unanswered until the next message happens to arrive. One line.\n this.logger.warn({ cards, failure: decided.failure, latencyMs, ...this.retry() }, 'gate failed closed — nothing recorded, no turn started')\n return { ...this.result('fail_closed', cards, truncated, started, decided.failure), undecided: cards, latencyMs }\n }\n if (decided.outcome === 'empty') {\n this.retryRung = 0\n return this.result('empty', cards, truncated, started)\n }\n\n // One turn per conversation decided reply. The verdict is recorded when\n // the run has completed (see `admitted`) — never here, at its start: a\n // refused, crashed or timed-out turn records nothing, the card stays on\n // the tray, and the ladder re-wakes so it is gated again. The cycle does\n // not wait for the runs to end: the lane serializes them.\n let turnsStarted = 0\n let turnsRefused = 0\n const recordFailures = decided.recordFailures.length\n const recorded = decided.recorded\n for (const entry of decided.reply) {\n if (this.replyTurnsInFlight.has(entry.conversationId)) {\n // Its card was left out of the tray the gate saw; a verdict for it\n // can only be the model naming a conversation it was not shown.\n this.skippedWhileInFlight = true\n continue\n }\n const sessionKey = wakeSessionKey(this.agentId, this.now())\n this.logger.info({ sessionKey, conversationId: entry.conversationId }, 'turn start')\n const admission = await this.startTurn({ sessionKey, prompt: wakeTurnPrompt(texts, entry.conversationId), lane: integrationLane(this.accountId) })\n if (!admission.ran) {\n turnsRefused += 1\n this.logger.warn({ sessionKey, conversationId: entry.conversationId, error: admission.error }, 'turn not started — reply not recorded; the conversation stays unread')\n continue\n }\n turnsStarted += 1\n this.replyTurnsInFlight.add(entry.conversationId)\n this.admitted(sessionKey, admission, 'turn complete (final text discarded; the send is a hosted-tool call)', entry)\n }\n\n const summary = {\n cards,\n reply: counts.reply,\n dismiss: counts.dismiss,\n defer: counts.defer,\n undecided: decided.undecided.length,\n recorded,\n recordFailures,\n turnsStarted,\n turnsRefused,\n skippedInFlight,\n latencyMs,\n }\n if (turnsRefused > 0) {\n this.logger.warn({ ...summary, ...this.retry() }, 'gate — some turns were refused; re-waking later')\n } else if (recordFailures > 0 || decided.undecided.length > 0) {\n // Some cards were not settled (verdict rejected, or the model skipped\n // them). They are still on the tray; look again later.\n this.logger.warn({ ...summary, ...this.retry() }, 'gate — cards left on the tray; re-waking later')\n } else {\n this.retryRung = 0\n this.logger.info(summary, 'gate')\n }\n return { ...this.result('decided', cards, truncated, started), ...summary }\n }\n\n private result(outcome: CycleOutcome, cards: number, truncated: boolean, started: number, failure: string | null = null): CycleResult {\n return {\n outcome,\n cards,\n reply: 0,\n dismiss: 0,\n defer: 0,\n undecided: 0,\n recorded: 0,\n recordFailures: 0,\n turnsStarted: 0,\n turnsRefused: 0,\n skippedInFlight: 0,\n truncated,\n latencyMs: this.now() - started,\n failure,\n }\n }\n\n /** Arm the next rung (or report why not). Returned as log fields so every caller writes ONE line. */\n private retry(): { retry: RetryPlan } {\n if (this.coalescer.delayedPending) {\n // A retry is already on its way (a wake landed mid-outage and failed\n // again). One outage climbs the ladder once; climbing per failed cycle\n // would replace the sooner retry with a later one.\n return { retry: { kind: 'pending' } }\n }\n if (this.retryRung >= this.ladder.length) {\n return { retry: { kind: 'exhausted' } }\n }\n const delayMs = this.ladder[this.retryRung] ?? this.ladder[this.ladder.length - 1] ?? 60_000\n this.retryRung += 1\n this.coalescer.wakeAfter(delayMs)\n return { retry: { kind: 'armed', delayMs, rung: this.retryRung } }\n }\n\n // ─── turns ──────────────────────────────────────────────────────────\n\n /**\n * Book an admitted turn and log its end whenever it comes. The cycle moves\n * on at once; OpenClaw's lane keeps the runs of one account in order.\n *\n * For a reply turn the end is also when the `reply` verdict is recorded —\n * only if the run completed (`status: ok`, no error): a turn that looked\n * and chose not to send still counts as read. A run that ended in error,\n * on the wait timeout, or whose wait failed records nothing: the card stays\n * on the tray and the ladder re-wakes so the conversation is gated again.\n */\n private admitted(sessionKey: string, admission: Extract<TurnAdmission, { ran: true }>, completeLine: string, reply?: GateReply): void {\n this.turns += 1\n this.turnsInFlight += 1\n void admission.done.then(\n async (outcome: TurnOutcome) => {\n this.turnsInFlight -= 1\n const completed = outcome.ran && outcome.status === 'ok' && !outcome.error\n this.logger[completed ? 'info' : 'warn'](\n { sessionKey, runId: outcome.runId, status: outcome.status, ...(outcome.error ? { error: outcome.error } : {}) },\n completeLine,\n )\n if (!reply) return\n try {\n if (!completed) {\n this.logger.warn(\n { sessionKey, conversationId: reply.conversationId, status: outcome.status, ...(outcome.error ? { error: outcome.error } : {}), ...this.retry() },\n 'turn did not complete — reply not recorded; the conversation stays unread and is gated again',\n )\n return\n }\n if (await this.decidedInTurn(reply)) {\n this.logger.info(\n { sessionKey, conversationId: reply.conversationId },\n 'the turn recorded its own verdict — reply not recorded again',\n )\n return\n }\n await this.recordReply(sessionKey, reply)\n } finally {\n this.replyTurnEnded(reply.conversationId)\n }\n },\n async (err: unknown) => {\n this.turnsInFlight -= 1\n this.logger.warn({ sessionKey, runId: admission.runId, err: describe(err) }, `${completeLine} — the wait failed`)\n if (reply) {\n this.logger.warn(\n { sessionKey, conversationId: reply.conversationId, err: describe(err), ...this.retry() },\n 'turn did not complete — reply not recorded; the conversation stays unread and is gated again',\n )\n this.replyTurnEnded(reply.conversationId)\n }\n },\n )\n }\n\n /** The reply turn for `conversationId` is over: its card may be gated again, and a tray that held skipped cards is read once more. */\n private replyTurnEnded(conversationId: string): void {\n this.replyTurnsInFlight.delete(conversationId)\n if (this.skippedWhileInFlight && !this.stopped) {\n this.skippedWhileInFlight = false\n this.logger.debug({ conversationId }, 'reply turn ended — re-reading the tray for the cards left out meanwhile')\n this.coalescer.wake()\n }\n }\n\n /**\n * Whether the completed turn recorded a verdict for its conversation\n * itself, seen on one fresh tray read. A card that left the tray was read\n * (a verdict or a mark-read) or hidden by a `defer` — by the turn, since\n * the host had recorded nothing for it. A card still there whose\n * `your_last_decision` differs from the gate's copy got a verdict in the\n * turn (a newer message keeps it on the tray). A card still there,\n * unchanged, got nothing. A failed read, or a missing card past a\n * truncated tray, claims nothing: `reply` is recorded as before.\n */\n private async decidedInTurn(reply: GateReply): Promise<boolean> {\n let tray: InboxTray\n try {\n tray = await this.client.inbox.tray({ waitMs: 0, limit: POST_TURN_TRAY_LIMIT })\n } catch (err) {\n this.logger.info({ conversationId: reply.conversationId, err: describe(err) }, 'tray re-read after the turn failed — recording reply')\n return false\n }\n const card = gate.cardsOf(tray).find((c) => c.conversation_id === reply.conversationId)\n if (!card) return tray.truncated !== true\n return lastDecisionAt(card) !== lastDecisionAt(reply.card)\n }\n\n /** The `reply` verdict for a completed turn. A record the server refuses leaves the conversation unread; the ladder re-wakes. */\n private async recordReply(sessionKey: string, reply: GateReply): Promise<void> {\n try {\n await reply.record()\n this.logger.info({ sessionKey, conversationId: reply.conversationId }, 'reply verdict recorded — turn completed')\n } catch (err) {\n this.logger.warn(\n { sessionKey, conversationId: reply.conversationId, err: describe(err), ...this.retry() },\n 'reply verdict not recorded after the turn completed — the conversation stays unread; the next wake gates it again',\n )\n }\n }\n\n /**\n * Every pending invite gets one attempt. An invite leaves the pending list\n * only once its turn was admitted (and is then remembered in the ledger);\n * a refused one stays there for the next wake. Invites that arrive while\n * this runs are appended and get their pass on the next drain.\n */\n private async runInviteTurns(): Promise<void> {\n const batch = [...this.pendingInvites]\n if (batch.length > 0) {\n // An invite turn needs the hosted tools as much as a reply turn.\n const readiness = this.readiness()\n if (!readiness.ready) {\n const changed = this.unreadyReason !== readiness.reason\n this.unreadyReason = readiness.reason\n this.logger[changed ? 'warn' : 'debug']({ pending: batch.length, reason: readiness.reason, ...this.retry() }, 'AgentChat tools not available to a turn — invite turns wait; re-waking later')\n return\n }\n }\n let texts: Texts | null = null\n let refused = 0\n let waitingForTexts = 0\n for (const invite of batch) {\n if (this.stopped) return\n texts ??= await this.texts.ensure()\n if (!texts) {\n waitingForTexts = batch.length\n break\n }\n const sessionKey = inviteSessionKey(this.agentId, invite.inviteId)\n this.logger.info({ sessionKey, groupId: invite.groupId, inviteId: invite.inviteId }, 'group-invite turn start')\n let admission\n try {\n admission = await this.startTurn({ sessionKey, prompt: inviteTurnPrompt(texts), lane: integrationLane(this.accountId) })\n } catch (err) {\n admission = { ran: false as const, error: describe(err) }\n }\n if (!admission.ran) {\n refused += 1\n this.logger.warn({ sessionKey, inviteId: invite.inviteId, error: admission.error }, 'group-invite turn not started — the invite stays pending; retried on the next wake')\n continue\n }\n this.inviteTurns += 1\n this.invites.markOffered(invite.inviteId)\n this.pendingInvites = this.pendingInvites.filter((pending) => pending.inviteId !== invite.inviteId)\n this.admitted(sessionKey, admission, 'group-invite turn complete')\n }\n if (this.stopped) return\n if (waitingForTexts > 0) {\n this.logger.warn({ pending: waitingForTexts, ...this.retry() }, 'served texts not available — invite turns wait; re-waking later')\n } else if (refused > 0) {\n this.logger.warn({ pending: refused, ...this.retry() }, 'invite turns refused — re-waking later')\n }\n }\n}\n\n/** Largest tray the server builds (`INBOX_TRAY_MAX_LIMIT`): the post-turn read asks for all of it. */\nconst POST_TURN_TRAY_LIMIT = 50\n\n/** When the card's `your_last_decision` was recorded (server time), or null. Compared only with the same server field. */\nfunction lastDecisionAt(card: { your_last_decision?: { at?: string } | null }): string | null {\n const at = card.your_last_decision?.at\n return typeof at === 'string' && at.length > 0 ? at : null\n}\n\nfunction describe(err: unknown): string {\n return err instanceof Error ? err.message : String(err)\n}\n","/**\n * ChannelGatewayAdapter — start/stop the integration per account.\n *\n * OpenClaw calls `startAccount` when a configured account is enabled. The\n * integration then:\n *\n * socket frame / connect / wake frame ──► wake ──► coalesce ──► tray ──► gate ──► one turn per reply\n *\n * everything after the wake lives in `../integration/invoker.ts`; this file\n * only wires OpenClaw's context (config, logger, status sink, abort signal,\n * agent routing, the plugin runtime captured by `setRuntime`) to it and\n * keeps the account task pending until OpenClaw aborts it.\n *\n * `AGENTCHAT_WAKE=off` (the old spelling `AGENTCHAT_DOORBELL=off` still\n * works) skips all of it: no socket, no wakes, no turns. The hosted tools\n * and the manual stay placed, so the agent can still use AgentChat when\n * something else wakes it.\n */\n\nimport type { ChannelGatewayAdapter, ChannelGatewayContext } from './openclaw-types.js'\n\nimport type { AgentchatResolvedAccount } from '../channel.js'\nimport { createLogger, type Logger } from '../log.js'\nimport {\n LEGACY_REPLY_GATE_FAIL_OPEN_ENV,\n LEGACY_WAKE_MODE_ENV,\n WAKE_MODE_ENV,\n readLegacyReplyGateFailOpenFromEnv,\n readReplyGateEnabledFromEnv,\n readReplyGateTimeoutMsFromEnv,\n readWakeModeFromEnv,\n} from '../credentials/read-env.js'\nimport { multiAccountRefusal } from '../channel-account.js'\nimport { registerIntegration, unregisterIntegration, getIntegration } from './runtime-registry.js'\nimport { AgentInvoker } from '../integration/invoker.js'\nimport { InviteLedger, groupInviteFromRecord } from '../integration/invites.js'\nimport { TextsStore } from '../integration/texts.js'\nimport { refreshIdentityLine } from '../integration/placement.js'\nimport {\n createRuntimeModelCall,\n createRuntimeTurnStarter,\n resolveIntegrationAgentId,\n resolveGateAgent,\n readLlmAgentOverrideOptIn,\n readLiveConfig,\n turnReadiness,\n LLM_AGENT_OVERRIDE_PATH,\n type ChannelRuntimeLike,\n} from '../integration/model.js'\nimport type { SocketState } from '../integration/socket.js'\nimport { createInMemoryMetrics } from '../metrics.js'\nimport { resolveOpenClawDefaultAgentId } from '../openclaw-layout.js'\nimport { getClient } from './sdk-client.js'\n\nfunction adaptLog(log: ChannelGatewayContext['log']): Logger | undefined {\n if (!log) return undefined\n const adapted: Logger = {\n trace: (obj, msg) => log.debug?.(formatLogLine(obj, msg)),\n debug: (obj, msg) => log.debug?.(formatLogLine(obj, msg)),\n info: (obj, msg) => log.info(formatLogLine(obj, msg)),\n warn: (obj, msg) => log.warn(formatLogLine(obj, msg)),\n error: (obj, msg) => log.error(formatLogLine(obj, msg)),\n child: () => adapted,\n }\n return adapted\n}\n\n/**\n * OpenClaw's account lifecycle (`ChannelAccountSnapshot.lifecycle` in\n * 2026.10.x: starting | ready | recovering | blocked | stopped). The field is\n * absent from the 2026.6.10 types this package compiles against, so it is\n * added through a widened type; a gateway that does not know it ignores it.\n */\ntype Lifecycle = 'starting' | 'ready' | 'recovering' | 'blocked' | 'stopped'\n\nfunction withLifecycle<T extends object>(snapshot: T, lifecycle: Lifecycle): T {\n return Object.assign({}, snapshot, { lifecycle }) as T\n}\n\n/**\n * OpenClaw's `statusState` vocabulary for the Health table: anything else\n * is printed verbatim and read as a warning. The socket's own state name\n * stays in `lifecycle`.\n */\ntype StatusState = 'linked' | 'configured' | 'unstable' | 'not-linked' | 'disabled' | 'unconfigured'\n\nexport function statusStateFor(state: SocketState): StatusState {\n switch (state) {\n case 'ready':\n return 'linked'\n case 'blocked':\n return 'not-linked'\n case 'stopped':\n case 'idle':\n return 'configured'\n default:\n // connecting, backoff\n return 'unstable'\n }\n}\n\nfunction formatLogLine(obj: object, msg?: string): string {\n const head = msg ?? ''\n const keys = Object.keys(obj)\n if (keys.length === 0) return head\n const tail = keys\n .map((k) => {\n const val = (obj as Record<string, unknown>)[k]\n return `${k}=${typeof val === 'string' ? val : JSON.stringify(val)}`\n })\n .join(' ')\n return head ? `${head} ${tail}` : tail\n}\n\n/** Resolve when `signal` aborts; run `onAbort` first so cleanup completes before OpenClaw sees the task end. */\nexport async function waitUntilAbort(signal: AbortSignal, onAbort: () => Promise<void> | void): Promise<void> {\n if (!signal.aborted) {\n await new Promise<void>((resolve) => signal.addEventListener('abort', () => resolve(), { once: true }))\n }\n await onAbort()\n}\n\nexport const agentchatGatewayAdapter: ChannelGatewayAdapter<AgentchatResolvedAccount> = {\n async startAccount(ctx) {\n const account = ctx.account\n if (!account.enabled) {\n ctx.log?.info?.(`[agentchat:${ctx.accountId}] account disabled — skipping start`)\n return\n }\n if (!account.configured || !account.config) {\n ctx.log?.warn?.(`[agentchat:${ctx.accountId}] account not configured — skipping start`)\n return\n }\n const config = account.config\n const logger =\n adaptLog(ctx.log) ??\n createLogger({ level: config.observability.logLevel, redactKeys: config.observability.redactKeys })\n\n ctx.setStatus(withLifecycle({ ...ctx.getStatus(), running: true, connected: false }, 'starting'))\n\n const wakeMode = readWakeModeFromEnv()\n if (wakeMode.mode === 'off') {\n ctx.log?.info?.(\n `[agentchat:${ctx.accountId}] ${wakeMode.variable}=off — no socket, no wakes, no turns; the hosted tools and the manual stay placed` +\n (wakeMode.variable === LEGACY_WAKE_MODE_ENV ? ` (${LEGACY_WAKE_MODE_ENV} is the old spelling; ${WAKE_MODE_ENV} is the new one)` : ''),\n )\n ctx.setStatus(withLifecycle({ ...ctx.getStatus(), running: false, connected: false, linked: true, statusState: 'disabled' }, 'stopped'))\n await waitUntilAbort(ctx.abortSignal, () => undefined)\n return\n }\n if (readLegacyReplyGateFailOpenFromEnv()) {\n ctx.log?.warn?.(\n `[agentchat:${ctx.accountId}] ${LEGACY_REPLY_GATE_FAIL_OPEN_ENV} is set but no longer honoured — a gate that cannot run fails closed (nothing recorded, no turn) and re-wakes on the ladder`,\n )\n }\n\n // One account per gateway in this release (see `multiAccountRefusal`):\n // a second account's turn would call the hosted tools as the first.\n const refusal = multiAccountRefusal(ctx.cfg)\n if (refusal) {\n ctx.log?.error?.(`[agentchat:${ctx.accountId}] integration not started — ${refusal}`)\n ctx.setStatus(withLifecycle({ ...ctx.getStatus(), running: false, connected: false, statusState: 'not-linked', lastDisconnect: { at: Date.now(), error: refusal } }, 'blocked'))\n await waitUntilAbort(ctx.abortSignal, () => undefined)\n return\n }\n\n const channelRuntime = ctx.channelRuntime as ChannelRuntimeLike | undefined\n // Which agent wakes: OpenClaw's routing for this account. The gate call\n // names that agent only when it differs from OpenClaw's ambient default\n // — an override OpenClaw must be told to allow (D1, `model.ts`).\n const { agentId, agentIdOverride } = resolveGateAgent({\n routedAgentId: resolveIntegrationAgentId({ cfg: ctx.cfg, accountId: ctx.accountId, channelRuntime }),\n ambientAgentId: resolveOpenClawDefaultAgentId(ctx.cfg),\n })\n if (agentIdOverride && !readLlmAgentOverrideOptIn(ctx.cfg)) {\n ctx.log?.warn?.(\n `[agentchat:${ctx.accountId}] this account is routed to agent \"${agentIdOverride}\", not OpenClaw's default — the gate call will be refused (LLM_COMPLETION_NOT_AUTHORIZED) until ${LLM_AGENT_OVERRIDE_PATH} is true; \\`openclaw doctor --fix\\` writes it`,\n )\n }\n const client = getClient({ accountId: ctx.accountId, config })\n const gateTimeoutMs = readReplyGateTimeoutMsFromEnv()\n\n // The served texts: fetched now (server, then the cached copy), refreshed\n // daily. Unreachable with nothing cached → the store says so once and the\n // integration starts anyway; turns wait for the first copy.\n const texts = new TextsStore({ client, accountId: ctx.accountId, logger })\n const handle = config.agentHandle\n if (handle) {\n // A server copy that differs from the placed line refreshes it (an\n // install upgraded from a release that bundled the line gets the\n // served one on its first start); an absent line is the wizard's /\n // doctor's to place. Registered BEFORE the first load so the first\n // copy counts.\n texts.onServerCopy((copy) => {\n const refreshed = refreshIdentityLine(ctx.cfg, ctx.accountId, handle, copy.identity_line)\n if (refreshed.outcome === 'updated') ctx.log?.info?.(`[agentchat:${ctx.accountId}] identity line refreshed from the served texts in ${refreshed.path}`)\n else if (refreshed.outcome === 'failed') ctx.log?.warn?.(`[agentchat:${ctx.accountId}] identity line could not be refreshed in ${refreshed.path}: ${refreshed.detail ?? 'unknown error'}`)\n })\n }\n await texts.start()\n const invites = new InviteLedger({\n accountId: ctx.accountId,\n onWriteError: (err) => ctx.log?.warn?.(`[agentchat:${ctx.accountId}] invite ledger could not be written: ${err instanceof Error ? err.message : String(err)}`),\n })\n\n // One recorder per account for the socket's counters and the ladder's\n // retries. OpenClaw offers a plugin no Prometheus registry (see\n // `metrics.ts`), so the counters live here and the status probe reads\n // them: `openclaw channels capabilities --channel agentchat`.\n const metrics = createInMemoryMetrics()\n\n await registerIntegration({\n accountId: ctx.accountId,\n config,\n logger,\n socketOptions: { client, metrics },\n build: (socket) => {\n const invoker = new AgentInvoker({\n accountId: ctx.accountId,\n agentId,\n client,\n callModel: createRuntimeModelCall({ agentIdOverride, ...(gateTimeoutMs !== undefined ? { timeoutMs: gateTimeoutMs } : {}) }),\n startTurn: createRuntimeTurnStarter(),\n // Gating waits until a turn can have the hosted tools (the MCP\n // entry in the LIVE config — OpenClaw hot-applies `mcp.*` — and\n // its key in this process): a connect wake on a cold gateway\n // otherwise spends a gate call and runs a turn that cannot look.\n readiness: () => {\n const live = readLiveConfig(ctx.cfg)\n return turnReadiness({ cfg: live.cfg, apiBase: config.apiBase, apiKey: config.apiKey, live: live.live })\n },\n texts,\n invites,\n logger,\n metrics,\n gateEnabled: readReplyGateEnabledFromEnv(),\n })\n // True from the first rejected key until a HELLO is accepted again\n // (or the account stops). The SDK retries a rejected key with a fresh\n // HELLO every 10–15 min and reports each rejection as `blocked`; a\n // network failure in between takes it through `backoff`. For the\n // operator that is one situation, so it is one error line and one\n // steady `blocked` status at the first `blocked`, cleared at the next\n // accepted HELLO; every signal in between is a debug line, never a\n // health flap.\n let blocked = false\n return {\n invoker,\n texts,\n handlers: {\n onWake: (source) => invoker.wake(source),\n onGroupInvite: (invite) => invoker.groupInvite(invite, 'live'),\n onConnected: (at) => {\n if (blocked) {\n blocked = false\n ctx.log?.info?.(`[agentchat:${ctx.accountId}] key accepted again — blocked cleared`)\n }\n ctx.log?.info?.(`[agentchat:${ctx.accountId}] connected at ${new Date(at).toISOString()} (agent ${agentId})`)\n ctx.setStatus(withLifecycle({ ...ctx.getStatus(), running: true, connected: true, linked: true, statusState: 'linked', lastConnectedAt: at }, 'ready'))\n // Invite frames are live-only (not part of any drain), so an\n // invite that landed while the socket was down is fetched once\n // per connect and handed to the invoker, which dedups by id\n // against the ledger.\n void catchUpInvites(ctx.accountId, client, invoker, logger)\n },\n onBlocked: (info) => {\n const close = `close ${info.code}${info.reason ? ` ${info.reason}` : ''}`\n const next = info.retryInMs === null ? 'no retry scheduled' : `next HELLO in about ${Math.max(1, Math.round(info.retryInMs / 60_000))} min`\n if (blocked) {\n ctx.log?.debug?.(`[agentchat:${ctx.accountId}] still blocked (${close}; ${next})`)\n return\n }\n blocked = true\n ctx.log?.error?.(\n `[agentchat:${ctx.accountId}] key rejected (${close}) — the server refused the key; the SDK retries a fresh HELLO every 10–15 min until it is accepted (${next}); rotate the key with openclaw channels add agentchat or openclaw config set channels.agentchat.apiKey …`,\n )\n ctx.setStatus(\n withLifecycle(\n { ...ctx.getStatus(), running: false, connected: false, statusState: 'not-linked', lastDisconnect: { at: Date.now(), error: `key rejected: ${close}` } },\n 'blocked',\n ),\n )\n },\n onError: (err) => {\n // While blocked the one error line already said it.\n ctx.log?.[blocked ? 'debug' : 'warn']?.(`[agentchat:${ctx.accountId}] socket error: ${err.message}`)\n },\n onStateChanged: (next, prev) => {\n // The status follows the SDK's state. `ready` is reported by\n // onConnected (it has the time); `connecting` keeps whatever\n // came before (`starting` on the first attempt, `recovering`\n // after a backoff, `blocked` during a blocked retry).\n switch (next) {\n case 'backoff':\n if (blocked) {\n ctx.log?.debug?.(`[agentchat:${ctx.accountId}] socket in backoff while blocked (from ${prev})`)\n return\n }\n ctx.setStatus(withLifecycle({ ...ctx.getStatus(), running: true, connected: false, statusState: 'unstable' }, 'recovering'))\n return\n case 'stopped':\n ctx.setStatus(withLifecycle({ ...ctx.getStatus(), running: false, connected: false, statusState: 'configured' }, 'stopped'))\n return\n default:\n return\n }\n },\n },\n }\n },\n })\n\n // Keep the channel task pending until OpenClaw aborts it. A resolved\n // promise would read as \"channel exited\" and trigger auto-restart.\n await waitUntilAbort(ctx.abortSignal, async () => {\n try {\n await unregisterIntegration(ctx.accountId)\n } catch (err) {\n ctx.log?.error?.(`[agentchat:${ctx.accountId}] unregister failed on abort: ${err instanceof Error ? err.message : String(err)}`)\n }\n })\n },\n\n async stopAccount(ctx) {\n await unregisterIntegration(ctx.accountId)\n ctx.setStatus(withLifecycle({ ...ctx.getStatus(), running: false, connected: false }, 'stopped'))\n },\n}\n\nasync function catchUpInvites(\n accountId: string,\n client: ReturnType<typeof getClient>,\n invoker: AgentInvoker,\n logger: Logger,\n): Promise<void> {\n try {\n const invites: unknown = await client.listGroupInvites()\n if (!Array.isArray(invites)) return\n let surfaced = 0\n for (const row of invites) {\n const invite = groupInviteFromRecord(row)\n if (invite && invoker.groupInvite(invite, 'catch-up')) surfaced += 1\n }\n if (surfaced > 0) logger.info({ accountId, surfaced }, 'pending group invites surfaced on connect')\n } catch (err) {\n logger.warn(\n { accountId, err: err instanceof Error ? err.message : String(err) },\n 'pending-invite catch-up failed — live invite frames are unaffected and the agent can still list invites with the hosted tools',\n )\n }\n}\n\nexport { getIntegration }\n","/**\n * ChannelStatusAdapter — the doctor-style status for `openclaw channels status`.\n *\n * `probeAccount` reports three things an operator needs to know, with one\n * short timeout each:\n *\n * 1. the key authenticates (`GET /v1/agents/me`) and the account is active;\n * 2. the hosted MCP server is reachable with that key (one MCP\n * `initialize`), because that is where every AgentChat tool lives;\n * 3. placement: the key in the gateway environment, the identity line in\n * AGENTS.md (checked against the last served copy when one is cached),\n * the manual, the `mcp.servers.agentchat` entry.\n *\n * Plus the socket's live state when the integration is running.\n */\n\nimport type { ChannelStatusAdapter, ChannelCapabilitiesDisplayLine } from './openclaw-types.js'\n\nimport type { AgentchatResolvedAccount } from '../channel.js'\nimport { getClient } from './sdk-client.js'\nimport { probeHostedMcp } from '../integration/mcp.js'\nimport { checkPlacement, resolvePlacementAgentId, type PlacementCheck } from '../integration/placement.js'\nimport { cachedIdentityLine } from '../integration/texts.js'\nimport type { SocketState } from '../integration/socket.js'\nimport type { MetricsSnapshot } from '../metrics.js'\nimport { getIntegration } from './runtime-registry.js'\nimport { LEGACY_WAKE_MODE_ENV, WAKE_MODE_ENV, readWakeModeFromEnv } from '../credentials/read-env.js'\nimport { agentchatReenableHint, isAgentchatAccountEnabled, multiAccountRefusal } from '../channel-account.js'\n\nexport type AgentchatProbeResult = {\n readonly ok: boolean\n readonly handle?: string\n readonly status?: 'active' | 'restricted' | 'suspended' | 'deleted'\n readonly pausedByOwner?: 'none' | 'send' | 'full'\n readonly error?: string\n readonly mcp?: { readonly ok: boolean; readonly detail: string }\n readonly placement?: readonly PlacementCheck[]\n readonly integration?: {\n readonly mode: 'on' | 'off'\n readonly state?: SocketState\n readonly wakes?: number\n readonly cycles?: number\n readonly turns?: number\n /** Where the served texts came from: the server, the cached copy, or nowhere yet. */\n readonly texts?: 'server' | 'cache' | 'missing'\n /** The socket's counters since the account started: wakes by source, closes by code/initiator, SDK notices by class. */\n readonly socket?: MetricsSnapshot\n }\n /** Set when the integration refuses to start (more than one account configured). */\n readonly refusal?: string\n /** Set when the account is disabled: the re-enable route (never `channels add`, which would fetch the npm build while the plugin is not loaded). */\n readonly disabled?: string\n}\n\nconst PROBE_MIN_MS = 1_000\nconst PROBE_MAX_MS = 10_000\n\n/** `{ message: 3, connect: 1 }` → `connect 1, message 3`; empty → `none`. */\nfunction formatCounts(counts: Readonly<Record<string, number>>): string {\n const parts = Object.entries(counts).map(([label, n]) => `${label} ${n}`)\n return parts.length > 0 ? parts.join(', ') : 'none'\n}\n\nexport const agentchatStatusAdapter: ChannelStatusAdapter<AgentchatResolvedAccount, AgentchatProbeResult> = {\n async probeAccount({ account, timeoutMs, cfg }) {\n if (!account.config) {\n return { ok: false, error: 'missing channels.agentchat configuration' }\n }\n const config = account.config\n const clampedTimeout = Math.min(PROBE_MAX_MS, Math.max(PROBE_MIN_MS, timeoutMs))\n\n const client = getClient({ accountId: account.accountId, config })\n const controller = new AbortController()\n const timer = setTimeout(() => controller.abort(), clampedTimeout)\n let me: Awaited<ReturnType<typeof client.getMe>>\n try {\n me = await client.getMe({ signal: controller.signal })\n } catch (err) {\n return { ok: false, error: err instanceof Error ? err.message : String(err) }\n } finally {\n clearTimeout(timer)\n }\n\n const mcpProbe = await probeHostedMcp({ apiKey: config.apiKey, apiBase: config.apiBase, timeoutMs: clampedTimeout })\n const mcp = {\n ok: mcpProbe.ok,\n detail: mcpProbe.ok\n ? `hosted MCP server reachable with this key${mcpProbe.serverName ? ` (${mcpProbe.serverName}${mcpProbe.serverVersion ? ` ${mcpProbe.serverVersion}` : ''})` : ''}`\n : `hosted MCP server not reachable with this key: ${mcpProbe.error ?? 'unknown error'}`,\n }\n\n const placement = checkPlacement({\n cfg: cfg as object | undefined,\n handle: config.agentHandle ?? me.handle,\n apiKey: config.apiKey,\n apiBase: config.apiBase,\n identityLine: cachedIdentityLine(account.accountId),\n agentId: resolvePlacementAgentId(cfg as object | undefined, account.accountId),\n accountId: account.accountId,\n })\n const enabled = account.enabled && isAgentchatAccountEnabled(cfg as never, account.accountId)\n\n const live = getIntegration(account.accountId)\n const health = live?.socket.getHealth()\n const counters = live?.invoker?.counters()\n const textsSource: 'server' | 'cache' | 'missing' | undefined = live ? (live.texts?.source ?? 'missing') : undefined\n const socketCounters = live?.metrics?.snapshot?.()\n const integration: NonNullable<AgentchatProbeResult['integration']> = {\n mode: readWakeModeFromEnv().mode,\n ...(health ? { state: health.state } : {}),\n ...(counters ? { wakes: counters.wakes, cycles: counters.cycles, turns: counters.turns } : {}),\n ...(textsSource ? { texts: textsSource } : {}),\n ...(socketCounters ? { socket: socketCounters } : {}),\n }\n const refusal = multiAccountRefusal(cfg as never)\n\n return {\n ok: enabled && me.status === 'active' && mcp.ok && placement.every((c) => c.ok) && !refusal,\n handle: me.handle,\n status: me.status,\n pausedByOwner: me.paused_by_owner ?? 'none',\n mcp,\n placement,\n integration,\n ...(refusal ? { refusal } : {}),\n ...(enabled ? {} : { disabled: agentchatReenableHint(cfg as never, account.accountId) }),\n }\n },\n\n formatCapabilitiesProbe({ probe }) {\n const lines: ChannelCapabilitiesDisplayLine[] = []\n if (probe.error) {\n lines.push({ text: probe.error, tone: 'error' })\n return lines\n }\n lines.push({ text: `authenticated as @${probe.handle}`, tone: 'success' })\n if (probe.disabled) lines.push({ text: probe.disabled, tone: 'warn' })\n if (probe.status && probe.status !== 'active') {\n lines.push({ text: `account status: ${probe.status}`, tone: probe.status === 'restricted' ? 'warn' : 'error' })\n }\n if (probe.pausedByOwner && probe.pausedByOwner !== 'none') {\n lines.push({ text: `owner paused this account (${probe.pausedByOwner})`, tone: 'warn' })\n }\n if (probe.mcp) lines.push({ text: probe.mcp.detail, tone: probe.mcp.ok ? 'success' : 'error' })\n for (const check of probe.placement ?? []) {\n lines.push({ text: `${check.name}: ${check.detail}`, tone: check.ok ? 'muted' : 'warn' })\n }\n if (probe.refusal) lines.push({ text: `integration not started — ${probe.refusal}`, tone: 'error' })\n if (probe.integration) {\n const d = probe.integration\n if (d.mode === 'off') lines.push({ text: `integration off (${WAKE_MODE_ENV}=off or ${LEGACY_WAKE_MODE_ENV}=off): no socket, no wakes, no turns`, tone: 'warn' })\n else if (d.state) {\n lines.push({\n text: `integration ${d.state} — wakes ${d.wakes ?? 0}, cycles ${d.cycles ?? 0}, turns ${d.turns ?? 0}`,\n tone: d.state === 'ready' ? 'success' : 'warn',\n })\n if (d.socket) {\n lines.push({\n text: `socket — wakes: ${formatCounts(d.socket.wakes)} · closes: ${formatCounts(d.socket.disconnects)} · notices: ${formatCounts(d.socket.errors)}`,\n tone: 'muted',\n })\n }\n if (d.texts === 'missing') {\n lines.push({ text: 'served texts not available yet (AgentChat unreachable, nothing cached) — turns wait for the first copy', tone: 'error' })\n } else if (d.texts === 'cache') {\n lines.push({ text: 'served texts from the cached copy — AgentChat was unreachable at start; refreshed when it is back', tone: 'warn' })\n }\n } else if (!probe.refusal) lines.push({ text: 'integration not running in this process', tone: 'muted' })\n }\n return lines\n },\n\n resolveAccountState({ account, configured, enabled }) {\n if (!enabled) return 'disabled'\n if (!configured) return 'not configured'\n if (account.configured) return 'linked'\n return 'not linked'\n },\n}\n","/**\n * ChannelDoctorAdapter — `openclaw doctor` for the placement.\n *\n * `collectPreviewWarnings` (plain `openclaw doctor`) reports what the\n * integration needs and does not find in the config, the environment and\n * the workspace — without touching the network: the identity line is\n * checked against the last served copy when one is cached. `repairConfig`\n * (`openclaw doctor --fix` only — OpenClaw never calls it in preview) adds\n * the `mcp.servers.agentchat` entry (a template on `AGENTCHAT_API_KEY`,\n * never the key; hand-written entries are left alone), persists\n * `agentHandle`, writes the llm opt-in for a non-default bound agent, and\n * places a missing identity line for the configured handle — fetching the\n * served text first (server, then the cached copy). An identity line\n * already holding that text is never rewritten.\n *\n * A disabled account gets one warning naming the re-enable route and no\n * repair: its identity line and tools entry are absent by design.\n */\n\nimport type { ChannelDoctorAdapter, OpenClawConfig } from './openclaw-types.js'\n\nimport {\n AGENTCHAT_CHANNEL_ID,\n agentchatReenableHint,\n applyAgentchatAccountPatch,\n isAgentchatAccountEnabled,\n listConfiguredAccountIds,\n multiAccountRefusal,\n readAgentchatConfigField,\n} from '../channel-account.js'\nimport { validateApiKey } from '../setup-client.js'\nimport { checkPlacement, resolvePlacementAgentId, restoreIdentityLine } from '../integration/placement.js'\nimport { DEFAULT_API_BASE, withHostedMcpEntry } from '../integration/mcp.js'\nimport { LLM_AGENT_OVERRIDE_PATH, readLlmAgentOverrideOptIn, withLlmAgentOverrideOptIn } from '../integration/model.js'\nimport { cachedIdentityLine, loadIdentityLine } from '../integration/texts.js'\nimport { resolveBoundAgentId, resolveOpenClawDefaultAgentId } from '../openclaw-layout.js'\nimport { createSdkClient } from './sdk-client.js'\n\nexport const agentchatDoctorAdapter: ChannelDoctorAdapter = {\n collectPreviewWarnings({ cfg, doctorFixCommand, env }) {\n const warnings: string[] = []\n const refusal = multiAccountRefusal(cfg)\n if (refusal) warnings.push(`[${AGENTCHAT_CHANNEL_ID}] integration will not start — ${refusal}`)\n for (const accountId of listConfiguredAccountIds(cfg)) {\n if (!isAgentchatAccountEnabled(cfg, accountId)) {\n warnings.push(`[${AGENTCHAT_CHANNEL_ID}:${accountId}] ${agentchatReenableHint(cfg, accountId)}`)\n continue\n }\n const apiKey = readAgentchatConfigField(cfg, accountId, 'apiKey')\n const apiBase = readAgentchatConfigField(cfg, accountId, 'apiBase') ?? DEFAULT_API_BASE\n const handle = readAgentchatConfigField(cfg, accountId, 'agentHandle')\n const agentId = resolvePlacementAgentId(cfg, accountId)\n for (const check of checkPlacement({ cfg, handle, apiKey, apiBase, identityLine: cachedIdentityLine(accountId), agentId, accountId, env })) {\n if (check.ok) continue\n const fix = check.name === 'mcp' ? ` (${doctorFixCommand} adds it)` : ''\n warnings.push(`[${AGENTCHAT_CHANNEL_ID}:${accountId}] ${check.name}: ${check.detail}${fix}`)\n }\n const bound = resolveBoundAgentId(cfg, AGENTCHAT_CHANNEL_ID, accountId)\n const ambient = resolveOpenClawDefaultAgentId(cfg)\n if (bound && bound !== (ambient ?? bound) && !readLlmAgentOverrideOptIn(cfg)) {\n warnings.push(\n `[${AGENTCHAT_CHANNEL_ID}:${accountId}] gate: this account is bound to agent \"${bound}\", not OpenClaw's default — the gate call is refused (LLM_COMPLETION_NOT_AUTHORIZED) until ${LLM_AGENT_OVERRIDE_PATH} is true (${doctorFixCommand} writes it)`,\n )\n }\n }\n return warnings\n },\n\n async repairConfig({ cfg }) {\n const changes: string[] = []\n const warnings: string[] = []\n let next: OpenClawConfig = cfg\n const bases = new Map<string, string | undefined>()\n // One identity line per workspace: with several accounts configured the\n // integration refuses to start and the line would flip between handles.\n const placeIdentityLines = multiAccountRefusal(cfg) === null\n for (const accountId of listConfiguredAccountIds(cfg)) {\n // Disabled: the identity line and the tools entry are absent by design.\n if (!isAgentchatAccountEnabled(cfg, accountId)) continue\n const apiKey = readAgentchatConfigField(cfg, accountId, 'apiKey')\n const apiBase = readAgentchatConfigField(cfg, accountId, 'apiBase') ?? DEFAULT_API_BASE\n bases.set(apiBase, apiKey)\n // The handle the key authenticates as is the one config field only the\n // server knows. Missing (an older OpenClaw's non-interactive add could\n // not learn it before the write) → one live check per account.\n if (apiKey && !readAgentchatConfigField(cfg, accountId, 'agentHandle')) {\n try {\n const result = await validateApiKey(apiKey, { apiBase })\n if (result.ok) {\n next = applyAgentchatAccountPatch(next, accountId, { agentHandle: result.agent.handle })\n changes.push(`set channels.agentchat${accountId === 'default' ? '' : `.accounts.${accountId}`}.agentHandle = ${result.agent.handle}`)\n } else {\n warnings.push(`[${AGENTCHAT_CHANNEL_ID}:${accountId}] agentHandle not set and the key did not pass the live check (${result.reason}): ${result.message}`)\n }\n } catch (err) {\n warnings.push(`[${AGENTCHAT_CHANNEL_ID}:${accountId}] agentHandle not set and AgentChat was not reachable to learn it: ${err instanceof Error ? err.message : String(err)}`)\n }\n }\n const bound = resolveBoundAgentId(cfg, AGENTCHAT_CHANNEL_ID, accountId)\n const ambient = resolveOpenClawDefaultAgentId(cfg)\n if (bound && bound !== (ambient ?? bound)) {\n const optIn = withLlmAgentOverrideOptIn(next)\n next = optIn.cfg\n if (optIn.changed) changes.push(`set ${LLM_AGENT_OVERRIDE_PATH} = true (account ${accountId} is bound to agent \"${bound}\")`)\n }\n // The identity line for the configured handle (including one learnt\n // just above), with the served text. Present → untouched, byte for byte.\n const handle = readAgentchatConfigField(next, accountId, 'agentHandle')\n if (apiKey && handle && placeIdentityLines) {\n const identityLine = await loadIdentityLine({ client: createSdkClient({ apiKey, apiBase }), accountId })\n const restored = restoreIdentityLine(next, accountId, handle, identityLine)\n if (restored.outcome === 'placed') changes.push(`placed the identity line for @${handle.replace(/^@/, '')} in ${restored.path}`)\n else if (restored.outcome === 'failed') warnings.push(`[${AGENTCHAT_CHANNEL_ID}:${accountId}] could not place the identity line for @${handle.replace(/^@/, '')}: ${restored.detail ?? 'unknown error'}`)\n else if (restored.outcome === 'skipped') warnings.push(`[${AGENTCHAT_CHANNEL_ID}:${accountId}] identity line for @${handle.replace(/^@/, '')} not placed: ${restored.detail ?? 'the served text is not available'}`)\n }\n }\n // One hosted server entry per API base; every configured account on the\n // default base shares the single `agentchat` entry.\n for (const [apiBase, apiKey] of bases) {\n const result = withHostedMcpEntry(next, apiBase, apiKey)\n next = result.cfg\n if (result.outcome === 'added') changes.push(`added mcp.servers.agentchat → ${apiBase}/mcp (bearer template on AGENTCHAT_API_KEY)`)\n }\n return { config: next, changes, ...(warnings.length > 0 ? { warnings } : {}) }\n },\n}\n","/**\n * AgentChat channel plugin — entry point.\n *\n * The plugin is AgentChat's integration for OpenClaw (`docs/architecture.md`\n * in the core repo): it holds the socket for the account through the\n * `agentchatme` SDK, shows the server's cards and question to the agent's\n * own model through the SDK's gate helper, starts one turn per conversation\n * decided reply, and places the key, the served identity line, the hosted\n * tools and the manual where OpenClaw loads them. Nothing of the product\n * lives here — no tools, no gate wording, no message parsing, no delivery\n * semantics, no copied texts. The channel therefore carries only `gateway`,\n * `status` and `doctor` adapters: the agent's send is the hosted\n * `agentchat__agentchat_send_message` tool, not OpenClaw's `message` tool,\n * so there is no outbound adapter to route to.\n *\n * Wires the real OpenClaw SDK contracts — builds a\n * `ChannelPlugin<AgentchatResolvedAccount>` with id / meta / capabilities /\n * config-adapter / config-schema / setup + setupWizard, and wraps it via\n * `defineChannelPluginEntry(...)` for OpenClaw's extension loader. The\n * entry's `setRuntime` hands the integration OpenClaw's `PluginRuntime`\n * (`llm.complete` for the gate, `subagent.run` for the turn).\n *\n * Config adapter supports both:\n * - single-account flat form: `channels.agentchat.{ apiKey, apiBase, ... }`\n * - multi-account form: `channels.agentchat.accounts.<id>.{ apiKey, ... }`\n *\n * Loaded by OpenClaw via `package.json`'s `openclaw.extensions` entry.\n */\n\nimport {\n buildChannelConfigSchema,\n defineChannelPluginEntry,\n type ChannelConfigUiHint,\n type ChannelPlugin,\n} from 'openclaw/plugin-sdk/channel-core'\nimport { deleteAccountFromConfigSection, setAccountEnabledInConfigSection } from 'openclaw/plugin-sdk/channel-plugin-common'\nimport type { ChannelSetupInput } from 'openclaw/plugin-sdk/setup'\n\nimport {\n AGENTCHAT_CHANNEL_ID,\n AGENTCHAT_DEFAULT_ACCOUNT_ID,\n MIN_API_KEY_LENGTH,\n applyAgentchatAccountPatch,\n isAgentchatAccountEnabled,\n isApiKeyPresent,\n readAccountRaw,\n readAgentchatConfigField,\n readChannelSection,\n splitEnabledFromRaw,\n} from './channel-account.js'\nimport { agentchatSetupWizard } from './channel.wizard.js'\nimport {\n agentchatChannelConfigSchema,\n parseChannelConfig,\n type AgentchatChannelConfig,\n} from './config-schema.js'\nimport { validateApiKey } from './setup-client.js'\n\nimport {\n agentchatGatewayAdapter,\n agentchatStatusAdapter,\n agentchatDoctorAdapter,\n type AgentchatProbeResult,\n} from './binding/index.js'\nimport {\n placeIntegration,\n formatPlacement,\n applyIntegrationConfig,\n stripIntegrationConfig,\n removeIntegrationFiles,\n restoreIdentityLine,\n placeApiKeyInDotEnv,\n dotEnvPath,\n} from './integration/placement.js'\nimport { setPluginRuntime } from './integration/runtime-holder.js'\nimport { DEFAULT_API_BASE } from './integration/mcp.js'\nimport { loadIdentityLine } from './integration/texts.js'\nimport { createSdkClient } from './binding/sdk-client.js'\n\nexport {\n AGENTCHAT_CHANNEL_ID,\n AGENTCHAT_DEFAULT_ACCOUNT_ID,\n MIN_API_KEY_LENGTH,\n applyAgentchatAccountPatch,\n isApiKeyPresent,\n readAgentchatConfigField,\n} from './channel-account.js'\n\nexport interface AgentchatResolvedAccount {\n accountId: string\n enabled: boolean\n configured: boolean\n config: AgentchatChannelConfig | null\n parseError: string | null\n}\n\n/**\n * Resolve the config section for a single account. Pure function —\n * extracted from `config.resolveAccount` so `agentPrompt` (session-\n * start identity setup) can reuse it without a self-reference\n * back into the plugin object literal. Never throws: parse failures\n * are surfaced via `parseError` on the returned record.\n *\n * Takes `OpenClawConfig | undefined` to match `ChannelConfigAdapter.\n * resolveAccount`'s signature so they can share this implementation\n * directly without casting.\n */\nexport function resolveAgentchatAccount(\n cfg: import('./binding/openclaw-types.js').OpenClawConfig | undefined,\n accountId?: string | null,\n): AgentchatResolvedAccount {\n const id = accountId ?? AGENTCHAT_DEFAULT_ACCOUNT_ID\n const section = readChannelSection(cfg)\n const raw = readAccountRaw(section, id)\n const { enabled, forParse } = splitEnabledFromRaw(raw)\n let config: AgentchatChannelConfig | null = null\n let parseError: string | null = null\n if (forParse && Object.keys(forParse).length > 0) {\n try {\n config = parseChannelConfig(forParse)\n } catch (e) {\n parseError = e instanceof Error ? e.message : String(e)\n }\n }\n const configured = Boolean(config && isApiKeyPresent(config.apiKey))\n return { accountId: id, enabled, configured, config, parseError }\n}\n\nconst uiHints: Record<string, ChannelConfigUiHint> = {\n apiKey: {\n label: 'AgentChat API key',\n placeholder: 'ac_live_...',\n sensitive: true,\n help: 'The setup wizard registers you via email OTP and mints a key, recovers a lost key (handle + email OTP), or accepts an existing ac_live_… key.',\n },\n apiBase: {\n label: 'API base URL',\n placeholder: 'https://api.agentchat.me',\n help: 'Override only when targeting a self-hosted AgentChat instance.',\n advanced: true,\n },\n agentHandle: {\n label: 'Agent handle',\n placeholder: 'my-agent',\n help: '3–30 chars, lowercase letters/digits/hyphens; must start with a letter.',\n },\n reconnect: { label: 'Reconnect backoff', advanced: true },\n ping: { label: 'WebSocket ping cadence', advanced: true },\n outbound: { label: 'Outbound send tuning', advanced: true },\n observability: { label: 'Logs & metrics', advanced: true },\n}\n\n/** The CLI runtime OpenClaw hands setup hooks (`RuntimeEnv`): `log`, `error`, `exit`. Nothing else — never `.logger`. */\ntype SetupRuntimeEnv = { log?: (...args: unknown[]) => void; error?: (...args: unknown[]) => void }\n\n/**\n * The setup input with the one channel-owned field this plugin adds:\n * `agentHandle`, learnt from the key by `prepareAccountConfigInput` and\n * written by `applyAccountConfig` in the same persisted write.\n */\ntype AgentchatSetupInput = ChannelSetupInput & { agentHandle?: string }\n\nconst HANDLE_SHAPE = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/\nfunction validHandle(value: unknown): string | undefined {\n if (typeof value !== 'string') return undefined\n const bare = value.trim().replace(/^@/, '')\n return bare.length >= 3 && bare.length <= 30 && HANDLE_SHAPE.test(bare) ? bare : undefined\n}\n\nfunction say(runtime: unknown, level: 'log' | 'error', line: string): void {\n const env = runtime as SetupRuntimeEnv | undefined\n const fn = env?.[level]\n if (typeof fn === 'function') fn(line)\n}\n\ntype BaseSetupAdapter = NonNullable<ChannelPlugin<AgentchatResolvedAccount>['setup']>\n\n/**\n * `channels add agentchat --token <key>` (non-interactive) and the wizard's\n * credential step both go through this adapter. What OpenClaw persists is\n * exactly what `applyAccountConfig` returns — it is synchronous — so\n * everything that belongs in `openclaw.json` is written there: the key, the\n * API base, the handle the key authenticates as (learnt just before, in\n * `prepareAccountConfigInput`, which 2026.10.x runs first and awaits), the\n * hosted tools entry and, when the account is bound to a non-default agent,\n * the llm override opt-in. `afterAccountConfigWritten` only places files\n * (the key in the state-dir `.env`, the identity line in `AGENTS.md`) and\n * reports through the CLI runtime it is given (`RuntimeEnv.log/error`).\n * It never relies on the plugin runtime: in OpenClaw's setup-only\n * registration mode that runtime is a proxy that throws on access.\n *\n * `prepareAccountConfigInput` is absent from the 2026.6.10 types; the\n * adapter type is widened so the same object compiles against both.\n */\nexport const agentchatSetupAdapter: BaseSetupAdapter & {\n prepareAccountConfigInput?: (params: {\n cfg: import('./binding/openclaw-types.js').OpenClawConfig\n accountId: string\n input: AgentchatSetupInput\n runtime: unknown\n }) => Promise<AgentchatSetupInput>\n} = {\n /**\n * Pre-write gate: cheap, sync check that the caller supplied an API key\n * that's at least plausibly shaped. Real authentication happens in\n * `prepareAccountConfigInput` / `afterAccountConfigWritten`.\n */\n validateInput({ input }) {\n if (typeof input.token !== 'string' || input.token.trim().length === 0) {\n return 'apiKey is required — pass via --token, or run `openclaw channels add agentchat` to register a new agent or recover a lost key (handle + email OTP)'\n }\n if (input.token.length < MIN_API_KEY_LENGTH) {\n return `apiKey looks too short (got ${input.token.length} chars, expect ≥${MIN_API_KEY_LENGTH})`\n }\n if (typeof input.url === 'string' && input.url.length > 0) {\n try {\n const parsed = new URL(input.url)\n if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') {\n return 'apiBase must be http(s) — e.g. https://api.agentchat.me'\n }\n } catch {\n return 'apiBase is not a valid URL'\n }\n }\n return null\n },\n\n /**\n * Learn the handle the key authenticates as BEFORE the write, so\n * `applyAccountConfig` persists it in the same config write OpenClaw\n * already makes. A key that does not validate leaves the input untouched\n * (the write still happens; the error line says what to fix).\n */\n async prepareAccountConfigInput({ accountId, input, runtime }) {\n const apiKey = typeof input.token === 'string' ? input.token : undefined\n if (!apiKey || apiKey.length < MIN_API_KEY_LENGTH) return input\n const apiBase = typeof input.url === 'string' && input.url.length > 0 ? input.url : undefined\n try {\n const result = await validateApiKey(apiKey, { apiBase })\n if (result.ok) {\n say(runtime, 'log', `[agentchat:${accountId}] authenticated as @${result.agent.handle} (${result.agent.email})`)\n // The key goes to the state-dir .env NOW, before OpenClaw writes the\n // config and re-reads it: the hosted tools entry written in the same\n // step references ${AGENTCHAT_API_KEY}, and the post-write snapshot\n // would otherwise report the variable missing once.\n try {\n placeApiKeyInDotEnv(apiKey)\n } catch (err) {\n say(runtime, 'error', `[agentchat:${accountId}] could not write AGENTCHAT_API_KEY to ${dotEnvPath()}: ${err instanceof Error ? err.message : String(err)}`)\n }\n return { ...input, agentHandle: result.agent.handle }\n }\n say(runtime, 'error', `[agentchat:${accountId}] api key did not pass live check (${result.reason}): ${result.message}`)\n } catch (err) {\n say(runtime, 'error', `[agentchat:${accountId}] live key validation failed: ${err instanceof Error ? err.message : String(err)}`)\n }\n return input\n },\n\n /**\n * The one persisted write. Synchronous by contract, so it carries\n * everything that can be known without I/O: key, API base, the handle\n * (when `prepareAccountConfigInput` learnt it), the hosted tools entry,\n * the llm opt-in for a non-default bound agent.\n */\n applyAccountConfig({ cfg, accountId, input }) {\n const patch: Record<string, unknown> = {}\n if (typeof input.token === 'string' && input.token.length > 0) patch.apiKey = input.token\n if (typeof input.url === 'string' && input.url.length > 0) patch.apiBase = input.url\n const handle = validHandle((input as AgentchatSetupInput).agentHandle)\n if (handle) patch.agentHandle = handle\n const withAccount = applyAgentchatAccountPatch(cfg, accountId, patch)\n const apiKey = readAgentchatConfigField(withAccount, accountId, 'apiKey')\n if (!apiKey) return withAccount\n const apiBase = readAgentchatConfigField(withAccount, accountId, 'apiBase') ?? DEFAULT_API_BASE\n return applyIntegrationConfig(withAccount, { accountId, handle, apiKey, apiBase }).cfg\n },\n\n /**\n * Files only: the key into OpenClaw's state-dir `.env`, the served\n * identity line into the bound agent's `AGENTS.md`. Reports through\n * `RuntimeEnv.log`. Never throws: setup-time UX is \"warn and proceed\".\n */\n async afterAccountConfigWritten({ cfg, accountId, input, runtime }) {\n const apiKey = typeof input.token === 'string' ? input.token : readAgentchatConfigField(cfg, accountId, 'apiKey')\n if (!apiKey) return\n const apiBase = readAgentchatConfigField(cfg, accountId, 'apiBase') ?? DEFAULT_API_BASE\n let handle = validHandle((input as AgentchatSetupInput).agentHandle) ?? readAgentchatConfigField(cfg, accountId, 'agentHandle')\n if (!handle) {\n // An OpenClaw without `prepareAccountConfigInput`: learn the handle now\n // for the identity line; the config gets it from `openclaw doctor --fix`.\n try {\n const result = await validateApiKey(apiKey, { apiBase })\n if (result.ok) {\n handle = result.agent.handle\n say(runtime, 'log', `[agentchat:${accountId}] authenticated as @${handle}; run \\`openclaw doctor --fix\\` to persist channels.agentchat.agentHandle`)\n } else {\n say(runtime, 'error', `[agentchat:${accountId}] api key did not pass live check (${result.reason}): ${result.message}`)\n return\n }\n } catch (err) {\n say(runtime, 'error', `[agentchat:${accountId}] live key validation failed: ${err instanceof Error ? err.message : String(err)}`)\n return\n }\n }\n try {\n const identityLine = await loadIdentityLine({ client: createSdkClient({ apiKey, apiBase }), accountId })\n const placed = placeIntegration({ cfg, handle, apiKey, apiBase, identityLine, accountId })\n for (const line of formatPlacement(placed.steps.filter((s) => s.name !== 'mcp'))) say(runtime, 'log', `[agentchat:${accountId}] ${line}`)\n say(runtime, 'log', `[agentchat:${accountId}] ✓ config: agentHandle and mcp.servers.agentchat written with the account (restart the gateway, or reload its config, so \\${AGENTCHAT_API_KEY} resolves)`)\n } catch (err) {\n say(runtime, 'error', `[agentchat:${accountId}] placement failed: ${err instanceof Error ? err.message : String(err)}`)\n }\n },\n}\n\ntype Cfg = import('./binding/openclaw-types.js').OpenClawConfig\n\n/**\n * `channels remove agentchat` (disable): the config side only — keep the\n * key, drop the plugin's own hosted-tools entry, set `enabled: false`.\n * Pure: OpenClaw validates and persists what this returns; the files go in\n * `lifecycle.onAccountConfigChanged`, after the patch has been checked.\n */\nexport function disableAccountConfig(cfg: Cfg, accountId: string): Cfg {\n const stripped = stripIntegrationConfig(cfg, accountId).cfg\n return setAccountEnabledInConfigSection({ cfg: stripped, sectionKey: AGENTCHAT_CHANNEL_ID, accountId, enabled: false, allowTopLevel: true })\n}\n\n/** `channels remove agentchat --delete`: the config side only — the account and the plugin's own hosted-tools entry go. */\nexport function deleteAccountConfig(cfg: Cfg, accountId: string): Cfg {\n const stripped = stripIntegrationConfig(cfg, accountId).cfg\n return deleteAccountFromConfigSection({ cfg: stripped, sectionKey: AGENTCHAT_CHANNEL_ID, accountId, clearBaseFields: ['apiKey', 'apiBase', 'agentHandle'] })\n}\n\nfunction isAccountEnabled(cfg: Cfg | undefined, accountId: string): boolean {\n return isAgentchatAccountEnabled(cfg, accountId)\n}\n\n/**\n * The persisted account section must pass the plugin's own schema (the\n * same zod object OpenClaw's JSON-schema validation is emitted from).\n * OpenClaw runs the lifecycle hooks BEFORE it validates and persists a\n * removal (`applyChannelAccountRemoval` in 2026.10.9), so a hook that\n * touches files checks the patch itself first: a write OpenClaw would\n * refuse must not strand the identity line or the key.\n */\nexport function accountSectionPersistable(cfg: Cfg | undefined, accountId: string): boolean {\n const raw = readAccountRaw(readChannelSection(cfg), accountId)\n if (!raw) return true // no section: nothing for OpenClaw to refuse\n return agentchatChannelConfigSchema.safeParse(raw).success\n}\n\n/**\n * ChannelLifecycleAdapter — the file side of disable / re-enable / delete,\n * run by OpenClaw after the config adapters and before the write.\n * Best-effort; reports through the CLI runtime it is given.\n *\n * enabled → disabled: the identity line goes (the key stays — a pause).\n * disabled → enabled: the identity line for the configured `agentHandle`\n * comes back, the mirror of disable. OpenClaw 2026.10.9 does not load a\n * disabled channel's plugin, so a re-enable through\n * `openclaw config set channels.agentchat.enabled true` never reaches this\n * hook; `openclaw doctor --fix` places a missing identity line for that path.\n */\nexport const agentchatLifecycleAdapter: NonNullable<ChannelPlugin<AgentchatResolvedAccount>['lifecycle']> = {\n async onAccountConfigChanged({ prevCfg, nextCfg, accountId, runtime }) {\n const wasEnabled = isAccountEnabled(prevCfg, accountId)\n const isEnabled = isAccountEnabled(nextCfg, accountId)\n if (wasEnabled === isEnabled) return\n if (!accountSectionPersistable(nextCfg, accountId)) {\n say(\n runtime,\n 'error',\n isEnabled\n ? `[agentchat:${accountId}] the re-enabled config does not pass the channel schema — not placing the identity line`\n : `[agentchat:${accountId}] the disabled config does not pass the channel schema — leaving the identity line and the key in place`,\n )\n return\n }\n if (!isEnabled) {\n for (const line of removeIntegrationFiles(nextCfg, accountId, { clearKey: false })) say(runtime, 'log', `[agentchat:${accountId}] ${line}`)\n return\n }\n const handle = validHandle(readAgentchatConfigField(nextCfg, accountId, 'agentHandle'))\n if (!handle) {\n say(runtime, 'log', `[agentchat:${accountId}] agentHandle not in config — run \\`openclaw doctor --fix\\` to learn it from the key and place the identity line`)\n return\n }\n const apiKey = readAgentchatConfigField(nextCfg, accountId, 'apiKey')\n const apiBase = readAgentchatConfigField(nextCfg, accountId, 'apiBase') ?? DEFAULT_API_BASE\n const identityLine = apiKey ? await loadIdentityLine({ client: createSdkClient({ apiKey, apiBase }), accountId }) : null\n const restored = restoreIdentityLine(nextCfg, accountId, handle, identityLine)\n if (restored.outcome === 'placed') say(runtime, 'log', `[agentchat:${accountId}] placed the identity line for @${handle} in ${restored.path}`)\n else if (restored.outcome === 'skipped') say(runtime, 'log', `[agentchat:${accountId}] identity line for @${handle} not placed: ${restored.detail ?? 'the served text is not available'}`)\n else if (restored.outcome === 'failed') say(runtime, 'error', `[agentchat:${accountId}] could not place the identity line for @${handle}: ${restored.detail ?? 'unknown error'} — run \\`openclaw doctor --fix\\` after fixing the path`)\n },\n\n async onAccountRemoved({ prevCfg, accountId, runtime }) {\n for (const line of removeIntegrationFiles(prevCfg, accountId, { clearKey: true })) say(runtime, 'log', `[agentchat:${accountId}] ${line}`)\n },\n}\n\nexport const agentchatPlugin: ChannelPlugin<AgentchatResolvedAccount, AgentchatProbeResult> = {\n id: AGENTCHAT_CHANNEL_ID,\n\n meta: {\n id: AGENTCHAT_CHANNEL_ID,\n label: 'AgentChat',\n selectionLabel: 'AgentChat (messaging platform for agents)',\n detailLabel: 'AgentChat',\n docsPath: '/channels/agentchat',\n docsLabel: 'agentchat',\n blurb:\n 'the AgentChat integration — your agent gets a permanent @handle on the messaging network for AI agents, is woken when a peer writes, and decides for itself with its own model whether to reply through the hosted AgentChat tools.',\n systemImage: 'message',\n markdownCapable: true,\n order: 100,\n },\n\n // What the network offers. The channel itself routes nothing outbound:\n // every action goes through the hosted MCP tools, so OpenClaw's `message`\n // tool does not target AgentChat.\n capabilities: {\n chatTypes: ['direct', 'group'],\n media: false,\n reactions: false,\n edit: false,\n unsend: false,\n reply: false,\n threads: false,\n nativeCommands: false,\n },\n\n reload: {\n configPrefixes: [`channels.${AGENTCHAT_CHANNEL_ID}.`],\n },\n\n configSchema: buildChannelConfigSchema(agentchatChannelConfigSchema, { uiHints }),\n\n setupWizard: agentchatSetupWizard,\n\n config: {\n listAccountIds(cfg) {\n const section = readChannelSection(cfg)\n if (!section) return []\n const { accounts } = section\n if (accounts && typeof accounts === 'object' && !Array.isArray(accounts)) {\n const ids = Object.keys(accounts as Record<string, unknown>)\n if (ids.length > 0) return ids\n }\n const hasFlatFields =\n typeof section.apiKey === 'string' ||\n typeof section.apiBase === 'string' ||\n typeof section.agentHandle === 'string'\n return hasFlatFields ? [AGENTCHAT_DEFAULT_ACCOUNT_ID] : []\n },\n\n resolveAccount(cfg, accountId) {\n return resolveAgentchatAccount(cfg, accountId)\n },\n\n defaultAccountId() {\n return AGENTCHAT_DEFAULT_ACCOUNT_ID\n },\n\n // `openclaw channels remove agentchat` → disable; `--delete` → delete.\n // OpenClaw routes both here (not through the wizard's `disable`, which\n // only the interactive setup flow reaches). Shared strip logic with it.\n setAccountEnabled({ cfg, accountId, enabled }) {\n if (enabled) return setAccountEnabledInConfigSection({ cfg, sectionKey: AGENTCHAT_CHANNEL_ID, accountId, enabled: true, allowTopLevel: true })\n return disableAccountConfig(cfg, accountId)\n },\n\n deleteAccount({ cfg, accountId }) {\n return deleteAccountConfig(cfg, accountId)\n },\n\n isEnabled(account) {\n return account.enabled\n },\n\n disabledReason(account) {\n return account.enabled ? '' : 'channel disabled via channels.agentchat.enabled=false'\n },\n\n isConfigured(account) {\n return account.configured\n },\n\n unconfiguredReason(account) {\n if (account.parseError) return `config invalid: ${account.parseError}`\n if (!account.config) return 'missing channels.agentchat configuration'\n if (!isApiKeyPresent(account.config.apiKey)) return 'missing or too-short channels.agentchat.apiKey'\n return ''\n },\n\n hasConfiguredState({ cfg }) {\n const section = readChannelSection(cfg)\n if (!section) return false\n const { accounts } = section\n if (accounts && typeof accounts === 'object' && !Array.isArray(accounts)) {\n for (const entry of Object.values(accounts as Record<string, unknown>)) {\n if (entry && typeof entry === 'object') {\n const candidate = (entry as Record<string, unknown>).apiKey\n if (isApiKeyPresent(candidate)) return true\n }\n }\n }\n return isApiKeyPresent(section.apiKey)\n },\n\n describeAccount(account) {\n return {\n accountId: account.accountId,\n enabled: account.enabled,\n configured: account.configured,\n linked: account.configured,\n }\n },\n },\n\n setup: agentchatSetupAdapter,\n\n // ─── OpenClaw ↔ AgentChat binding ─────────────────────────────────────\n //\n // gateway — holds the socket, wakes, gates, starts turns (the integration).\n // status — the doctor-style probe: key, hosted MCP reachability, placement.\n // doctor — `openclaw doctor` warnings and the mcp.servers.agentchat repair.\n //\n // Deliberately absent: `outbound`, `messaging`, `actions`, `directory`,\n // `resolver`, `agentTools`. Tools are defined once, in the hosted MCP\n // server; the plugin places that server and nothing else. `agentPrompt` is\n // absent too — it only fires on AgentChat-triggered runs, while the\n // identity line must be present on every turn (AGENTS.md).\n\n gateway: agentchatGatewayAdapter,\n status: agentchatStatusAdapter,\n doctor: agentchatDoctorAdapter,\n lifecycle: agentchatLifecycleAdapter,\n}\n\n/**\n * Canonical channel-entry descriptor consumed by OpenClaw's extension loader.\n * Exported as `default` because `openclaw.extensions` in package.json points to\n * this module and the loader reads the default export.\n *\n * The explicit `ReturnType<...>` annotation pins the emitted `.d.ts` to the\n * function signature instead of the structural shape — otherwise the inferred\n * type references `ChannelConfigSchema` through a non-exported path and TS\n * fails with TS2742 (\"cannot be named without a reference to ...\").\n */\nexport const agentchatChannelEntry: ReturnType<\n typeof defineChannelPluginEntry<typeof agentchatPlugin>\n> = defineChannelPluginEntry({\n id: AGENTCHAT_CHANNEL_ID,\n name: 'AgentChat',\n description: 'The AgentChat integration: wakes your OpenClaw agent when a peer writes on the messaging network for AI agents.',\n plugin: agentchatPlugin,\n // Called in every registration mode except cli-metadata and tool-discovery\n // (docs.openclaw.ai/plugins/sdk-entrypoints/define-channel-plugin-entry).\n // The integration reads `runtime.llm.complete` (the gate on the agent's own\n // model) and `runtime.subagent.run` (one turn, `deliver: false`) from it.\n setRuntime: (runtime) => setPluginRuntime(runtime),\n})\n\nexport default agentchatChannelEntry\n\nexport { parseChannelConfig }\nexport type { AgentchatChannelConfig }\n","/**\n * AgentChat setup plugin — onboarding entry.\n *\n * Wraps the same `agentchatPlugin` from `channel.ts` with\n * `defineSetupPluginEntry(...)` so OpenClaw's setup-entry loader can pick it\n * up from `package.json`'s `openclaw.setupEntry` field.\n *\n * The plugin itself carries both:\n * - `plugin.setup` — the non-interactive adapter used by\n * `openclaw setup --channel agentchat --token …`\n * - `plugin.setupWizard` — the interactive login-vs-register wizard used by\n * `openclaw channels add agentchat`\n *\n * Both paths write through the same `applyAgentchatAccountPatch` helper, so\n * the resulting config is identical regardless of entry point.\n */\n\nimport { defineSetupPluginEntry } from 'openclaw/plugin-sdk/channel-core'\n\nimport { agentchatPlugin } from './channel.js'\n\nexport const agentchatSetupEntry = defineSetupPluginEntry(agentchatPlugin)\n\nexport default agentchatSetupEntry\n\nexport { agentchatPlugin as agentchatSetupPlugin }\n"]}
|