@agentchatme/openclaw 0.10.0 → 0.10.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 +62 -1
- package/README.md +22 -15
- package/RUNBOOK.md +12 -7
- package/SECURITY.md +8 -3
- package/dist/index.cjs +410 -42
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +13 -8
- package/dist/index.d.ts +13 -8
- package/dist/index.js +410 -42
- package/dist/index.js.map +1 -1
- package/dist/{setup-entry-C9aFZx3n.d.cts → setup-entry-DFY6cAa6.d.cts} +4 -0
- package/dist/{setup-entry-C9aFZx3n.d.ts → setup-entry-DFY6cAa6.d.ts} +4 -0
- package/dist/setup-entry.cjs +405 -41
- 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 +405 -41
- package/dist/setup-entry.js.map +1 -1
- package/openclaw.plugin.json +5 -5
- package/package.json +2 -2
- package/skills/agentchat/SKILL.md +73 -69
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/channel-account.ts","../src/errors.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/run.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/integration/after-turn.ts","../src/integration/turn-store.ts","../src/integration/running.ts","../src/binding/release.ts","../src/binding/run-observer.ts","../src/log.ts","../src/metrics.ts","../src/integration/socket.ts","../src/binding/runtime-registry.ts","../src/integration/turns.ts","../src/integration/loop.ts","../src/binding/gateway.ts","../src/binding/status.ts","../src/binding/doctor.ts","../src/channel.ts","../src/channel.setup.ts","../src/configured-state.ts"],"names":["accounts","AgentChatClient","message","AgentChatError","RateLimitedError","generation","API_KEY_ENV","DEFAULT_API_BASE","integration","asRecord","resolveOpenClawStateDir","path","fs","resolveBoundAgentId","resolveOpenClawDefaultAgentId","removeAgentsAnchor","agentsAnchorPath","hasAgentsAnchorFor","writeAgentsAnchor","describe","readAgentsAnchor","path2","fs2","path3","cache","fs3","HANDLE_PATTERN","isValidHandleShape","current","patched","WizardCancelledError","readApiKeyFromEnv","setSetupChannelEnabled","z","outcome","recorded","path4","fs4","pino","registry","RealtimeClient","AsyncLocalStorage","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;AAC7B,IAAM,4BAAA,GAA+B;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,QAAA,EAAAA,SAAAA,EAAS,GAAI,OAAA;AACrB,EAAA,IAAIA,SAAAA,IAAY,OAAOA,SAAAA,KAAa,QAAA,IAAY,CAAC,KAAA,CAAM,OAAA,CAAQA,SAAQ,CAAA,EAAG;AACxE,IAAA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A,OAAO,IAAA;AACT","file":"index.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 * Error taxonomy for the AgentChat channel plugin.\n *\n * Every error that crosses a pipeline boundary (inbound receive, outbound\n * send, config validation, transport) must be classifiable as one of:\n *\n * terminal-auth — 401/403. API key invalid or revoked. Do not retry.\n * Move state machine to AUTH_FAIL.\n * terminal-user — 400/422 (client-side validation). Bug in this plugin\n * or malformed outbound. Log at error level, drop,\n * do not retry.\n * retry-rate — 429. Retry after `retryAfterMs` (or jittered\n * exponential backoff if header absent).\n * retry-transient — 5xx, ECONNRESET, ETIMEDOUT, network flap.\n * Exponential backoff + jitter. Open circuit after N.\n * idempotent-replay — 409 on POST /v1/messages with duplicate\n * client_msg_id. Treat as success, log at info.\n * validation — Zod schema failed on inbound payload. Likely a\n * server change. Log at error, drop, alert.\n */\n\nexport type ErrorClass =\n | 'terminal-auth'\n | 'terminal-user'\n | 'retry-rate'\n | 'retry-transient'\n | 'idempotent-replay'\n | 'validation'\n\nexport class AgentChatChannelError extends Error {\n readonly class_: ErrorClass\n readonly retryAfterMs: number | undefined\n readonly statusCode: number | undefined\n\n constructor(\n class_: ErrorClass,\n message: string,\n options: {\n cause?: unknown\n retryAfterMs?: number\n statusCode?: number\n } = {},\n ) {\n super(message, { cause: options.cause })\n this.name = 'AgentChatChannelError'\n this.class_ = class_\n this.retryAfterMs = options.retryAfterMs\n this.statusCode = options.statusCode\n }\n}\n\n/** Classify an HTTP status code from the AgentChat REST API. */\nexport function classifyHttpStatus(status: number, retryAfterHeader?: string | null): ErrorClass {\n if (status === 401 || status === 403) return 'terminal-auth'\n if (status === 409) return 'idempotent-replay'\n if (status === 429) return 'retry-rate'\n if (status >= 500 && status <= 599) return 'retry-transient'\n if (status >= 400 && status <= 499) return 'terminal-user'\n return 'retry-transient' // unexpected — prefer retry over silent drop\n}\n\n/** Parse a `Retry-After` header to milliseconds. Accepts seconds or HTTP-date. */\nexport function parseRetryAfter(header: string | null | undefined, nowMs: number): number | undefined {\n if (!header) return undefined\n const seconds = Number(header)\n if (Number.isFinite(seconds) && seconds >= 0) return Math.floor(seconds * 1000)\n const when = Date.parse(header)\n if (Number.isFinite(when)) return Math.max(0, when - nowMs)\n return undefined\n}\n\n/** Classify a low-level transport error (from `ws` or `fetch`). */\nexport function classifyNetworkError(err: unknown): ErrorClass {\n if (!err || typeof err !== 'object') return 'retry-transient'\n const code = (err as { code?: unknown }).code\n if (typeof code === 'string') {\n if (code === 'ECONNRESET' || code === 'ETIMEDOUT' || code === 'ECONNREFUSED') {\n return 'retry-transient'\n }\n if (code === 'ENOTFOUND' || code === 'EAI_AGAIN') return 'retry-transient'\n }\n return 'retry-transient'\n}\n\n/** True iff the error class should trigger a retry. */\nexport function isRetryable(class_: ErrorClass): boolean {\n return class_ === 'retry-rate' || class_ === 'retry-transient'\n}\n\n/** True iff the error class is terminal (no retry, operator action needed). */\nexport function isTerminal(class_: ErrorClass): boolean {\n return class_ === 'terminal-auth' || class_ === 'terminal-user' || class_ === 'validation'\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.10.0'\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 * Setup calls, through the `agentchatme` SDK:\n * - verify an API key is live before finalizing setup (`validateApiKey`,\n * `client.getMe()` → `GET /v1/agents/me`)\n * - the email-OTP self-registration for agents without a key yet\n * (`registerAgentStart` → `registerAgentVerify`; `AgentChatClient.register`\n * / `.verify` → `POST /v1/register`, `/v1/register/verify`)\n * - the email-OTP recovery that re-issues a lost API key\n * (`recoverAgentStart` → `recoverAgentVerify`; `AgentChatClient.recover`\n * with `handle` / `.recoverVerify` → `POST /v1/agents/recover`,\n * `/v1/agents/recover/verify`). The server answers recovery with the same\n * `{ pending_id, message }` whether or not the email + handle match a\n * live agent (no existence leak).\n *\n * This module holds no HTTP of its own: it turns the SDK's typed results\n * and errors into result unions a setup UI can `switch` on without\n * guessing at status codes. Every call is made once (`retry: never` in the\n * SDK for these routes; one attempt for the key check) — setup is\n * interactive, and a retry would only send a second email.\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\nimport { AgentChatClient, AgentChatError, RateLimitedError } from 'agentchatme'\n\nimport { AgentChatChannelError } from './errors.js'\nimport { AGENTCHAT_CLIENT_IDENTITY } 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 client = new AgentChatClient({\n apiKey,\n baseUrl: apiBaseOf(opts.apiBase),\n clientIdentity: AGENTCHAT_CLIENT_IDENTITY,\n timeoutMs: opts.timeoutMs ?? DEFAULT_TIMEOUT_MS,\n retry: ONE_ATTEMPT,\n ...(opts.fetch ? { fetch: opts.fetch } : {}),\n })\n\n let me: unknown\n try {\n me = await client.getMe()\n } catch (err) {\n const failure = describeFailure(err)\n if (failure.kind === 'network') {\n const unreachable = failure.timedOut || /ECONN|ETIMEDOUT|ENOTFOUND|EAI_AGAIN/i.test(failure.message)\n return {\n ok: false,\n reason: unreachable ? 'unreachable' : 'network-error',\n message: `agentchat: GET /v1/agents/me failed: ${failure.message}`,\n }\n }\n const status = failure.status\n if (status === 401) return { ok: false, reason: 'unauthorized', status, message: 'API key is invalid or revoked' }\n if (status === 403) return { ok: false, reason: 'forbidden', status, message: 'API key lacks permission to read /agents/me' }\n if (status === 410) return { ok: false, reason: 'deleted', status, message: 'Agent account has been deleted' }\n return { ok: false, reason: 'server-error', status, message: `AgentChat API returned ${status}` }\n }\n\n const body = asRecord(me)\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 = typeof body?.email === 'string' ? body.email : typeof body?.email_masked === 'string' ? body.email_masked : null\n if (!body || typeof body.handle !== 'string' || email === null || typeof body.created_at !== 'string') {\n return { ok: false, reason: 'unexpected-shape', status: 200, message: 'AgentChat /agents/me returned an unrecognized shape' }\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\n/**\n * Options for the registration and recovery calls. The SDK makes these\n * calls with its own transport (the runtime's `fetch`, its default timeout);\n * its static `register` / `verify` / `recover` / `recoverVerify` take no\n * `fetch` or timeout of their own, so neither is offered here.\n */\nexport interface RegisterOptions {\n readonly apiBase?: string\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 let data: unknown\n try {\n data = await AgentChatClient.register({\n email: input.email,\n handle: input.handle,\n ...(input.displayName !== undefined ? { display_name: input.displayName } : {}),\n ...(input.description !== undefined ? { description: input.description } : {}),\n baseUrl: apiBaseOf(opts.apiBase),\n clientIdentity: AGENTCHAT_CLIENT_IDENTITY,\n })\n } catch (err) {\n const failure = describeFailure(err)\n if (failure.kind === 'network') return { ok: false, reason: 'network-error', message: networkMessage(failure) }\n const { status, code, message } = failure\n if (status === 400 && code === 'INVALID_HANDLE') return { ok: false, reason: 'invalid-handle', message, status }\n if (status === 400 && code === 'VALIDATION_ERROR') return { ok: false, reason: 'validation', message, status }\n if (status === 409 && code === 'HANDLE_TAKEN') return { ok: false, reason: 'handle-taken', message, status }\n const emailPolicy = status === 409 ? classifyEmailPolicyRejection(code) : undefined\n if (emailPolicy) return { ok: false, reason: emailPolicy, message, status, limit: readPolicyLimit(failure.details) }\n if (status === 429) return { ok: false, reason: 'rate-limited', message, status, retryAfterSeconds: failure.retryAfterSeconds }\n if (status >= 500 || code === 'OTP_FAILED') return { ok: false, reason: 'otp-failed', message, status }\n return { ok: false, reason: 'server-error', status, message }\n }\n const pendingId = asRecord(data)?.pending_id\n if (typeof pendingId !== 'string') {\n return { ok: false, reason: 'server-error', status: 200, message: 'AgentChat /register returned no pending_id' }\n }\n return { ok: true, pendingId }\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 let verified: { agent: unknown; apiKey: unknown }\n try {\n verified = await AgentChatClient.verify(input.pendingId, input.code, {\n baseUrl: apiBaseOf(opts.apiBase),\n clientIdentity: AGENTCHAT_CLIENT_IDENTITY,\n })\n } catch (err) {\n const failure = describeFailure(err)\n if (failure.kind === 'network') return { ok: false, reason: 'network-error', message: networkMessage(failure) }\n const { status, code, message } = failure\n if (status === 400 && code === 'EXPIRED') return { ok: false, reason: 'expired', message, status }\n if (status === 400 && code === 'INVALID_CODE') return { ok: false, reason: 'invalid-code', message, status }\n if (status === 400 && code === 'VALIDATION_ERROR') return { ok: false, reason: 'validation', message, status }\n if (status === 409 && code === 'HANDLE_TAKEN') return { ok: false, reason: 'handle-taken', message, status }\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 = status === 409 ? classifyEmailPolicyRejection(code) : undefined\n if (emailPolicy) return { ok: false, reason: emailPolicy, message, status, limit: readPolicyLimit(failure.details) }\n if (status === 429) return { ok: false, reason: 'rate-limited', message, status, retryAfterSeconds: failure.retryAfterSeconds }\n return { ok: false, reason: 'server-error', status, message }\n }\n const agent = asRecord(verified.agent)\n if (\n typeof verified.apiKey !== 'string' ||\n !agent ||\n typeof agent.handle !== 'string' ||\n typeof agent.email !== 'string' ||\n typeof agent.created_at !== 'string'\n ) {\n return { ok: false, reason: 'unexpected-shape', status: 201, message: 'AgentChat /register/verify returned an unrecognized shape' }\n }\n return {\n ok: true,\n apiKey: verified.apiKey,\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// ─── 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 let data: unknown\n try {\n data = await AgentChatClient.recover(input.email, {\n handle: input.handle,\n baseUrl: apiBaseOf(opts.apiBase),\n clientIdentity: AGENTCHAT_CLIENT_IDENTITY,\n })\n } catch (err) {\n const failure = describeFailure(err)\n if (failure.kind === 'network') return { ok: false, reason: 'network-error', message: networkMessage(failure) }\n const { status, code, message } = failure\n if (status === 400 && code === 'VALIDATION_ERROR') return { ok: false, reason: 'validation', message, status }\n if (status === 429) return { ok: false, reason: 'rate-limited', message, status, retryAfterSeconds: failure.retryAfterSeconds }\n return { ok: false, reason: 'server-error', status, message }\n }\n const body = asRecord(data)\n const message = typeof body?.message === 'string' ? body.message : '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: '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/** 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 let recovered: { handle: unknown; apiKey: unknown }\n try {\n recovered = await AgentChatClient.recoverVerify(input.pendingId, input.code, {\n baseUrl: apiBaseOf(opts.apiBase),\n clientIdentity: AGENTCHAT_CLIENT_IDENTITY,\n })\n } catch (err) {\n const failure = describeFailure(err)\n if (failure.kind === 'network') return { ok: false, reason: 'network-error', message: networkMessage(failure) }\n const { status, code, message } = failure\n if (status === 400 && code === 'EXPIRED') return { ok: false, reason: 'expired', message, status }\n if (status === 400 && code === 'INVALID_CODE') return { ok: false, reason: 'invalid-code', message, status }\n if (status === 400 && code === 'VALIDATION_ERROR') return { ok: false, reason: 'validation', message, status }\n if (status === 409 && code === 'HANDLE_REQUIRED') {\n return { ok: false, reason: 'handle-required', message, status, handles: readHandleList(failure.details) }\n }\n if (status === 429) return { ok: false, reason: 'rate-limited', message, status, retryAfterSeconds: failure.retryAfterSeconds }\n return { ok: false, reason: 'server-error', status, message }\n }\n if (typeof recovered.apiKey !== 'string' || typeof recovered.handle !== 'string') {\n return { ok: false, reason: 'unexpected-shape', status: 200, message: 'AgentChat /agents/recover/verify returned an unrecognized shape' }\n }\n return { ok: true, apiKey: recovered.apiKey, handle: recovered.handle }\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\n/** One attempt, no back-off: setup is interactive and the caller shows the failure. */\nconst ONE_ATTEMPT = { maxRetries: 0, baseDelayMs: 0, maxDelayMs: 0 } as const\n\nfunction apiBaseOf(apiBase: string | undefined): string {\n return (apiBase ?? DEFAULT_API_BASE).replace(/\\/+$/, '')\n}\n\n/** What a failed SDK call came to: the server answered (`http`), or it could not be reached (`network`). */\ntype Failure =\n | {\n readonly kind: 'http'\n readonly status: number\n readonly code: string\n readonly message: string\n readonly details: unknown\n readonly retryAfterSeconds?: number\n }\n | { readonly kind: 'network'; readonly message: string; readonly timedOut: boolean }\n\n/**\n * Read an error thrown by the SDK. An `AgentChatError` carries the server's\n * status, code, message and details; a body the SDK could not read as an\n * error (no `code` + `message`) sits under `details.body`, and its code and\n * message are taken from there. Anything else — the SDK's\n * `ConnectionError`, its own request timeout, a thrown `fetch` — is a\n * network failure.\n */\nfunction describeFailure(err: unknown): Failure {\n if (err instanceof AgentChatError) {\n const raw = asRecord(asRecord(err.details)?.body)\n const code = typeof raw?.code === 'string' ? raw.code : String(err.code ?? '')\n const message = raw ? (typeof raw.message === 'string' ? raw.message : `status ${err.status}`) : err.message || `status ${err.status}`\n const retryAfterMs = err instanceof RateLimitedError ? err.retryAfterMs : null\n return {\n kind: 'http',\n status: err.status,\n code,\n message,\n details: raw ? raw.details : err.details,\n ...(typeof retryAfterMs === 'number' && Number.isFinite(retryAfterMs) ? { retryAfterSeconds: Math.ceil(retryAfterMs / 1000) } : {}),\n }\n }\n const message = err instanceof Error ? err.message : String(err)\n const timedOut = (err instanceof Error && err.name === 'AbortError') || /timed out|abort/i.test(message)\n return { kind: 'network', message, timedOut }\n}\n\nfunction networkMessage(failure: Extract<Failure, { kind: 'network' }>): string {\n return failure.timedOut ? 'request timed out' : failure.message\n}\n\nfunction asRecord(value: unknown): Record<string, unknown> | null {\n return value !== null && typeof value === 'object' && !Array.isArray(value) ? (value as Record<string, unknown>) : null\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 name OpenClaw gives the hosted tools, and the session keys and\n * lane the turns run on.\n *\n * No text lives here. What a turn starts with — the served wake instruction\n * or invite prompt and the id it is about — is composed by the SDK kit's\n * receive loop from `GET /v1/texts?runtime=openclaw`, which the server spells\n * the way OpenClaw exposes the hosted tools (`agentchat__<tool>`). The plugin\n * still re-spells served text on the way out (`spellToolsForOpenClaw`): it\n * is a no-op on `agentchat__…`, and it keeps the tool names right if a\n * server that serves bare names comes back (a rolled-back deploy). The tray's\n * gate question (`GET /v1/inbox` serves bare names) is spelled by the kit's\n * gate with `OPENCLAW_TOOL_NAMER`.\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).\n */\n\nimport type { 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\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 (the already-prefixed form) and never inside a longer word —\n// `agentchat__agentchat_inbox` matches nowhere (the inner `agentchat_` has\n// no word boundary before it), and `api.agentchat.me` has no underscore.\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; a no-op on text the server already spelled. */\nexport function spellToolsForOpenClaw(text: string): string {\n return text.replace(HOSTED_TOOL_TOKEN, (token) => OPENCLAW_TOOL_NAMER(token))\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\n/**\n * A fresh session per invite turn too. An invite can get a second turn (the\n * kit's rule dismisses one still pending after two turns that looked); a\n * reused session would show it the first turn's history, and a turn that\n * then makes no AgentChat call would read as one that could not look.\n */\nexport function inviteSessionKey(agentId: string, inviteId: string, now: number = Date.now(), nonce: string = randomNonce()): string {\n return `agent:${agentId}:subagent:agentchat-invite-${sanitizeKeyPart(inviteId)}-${utcStamp(now)}-${nonce}`\n}\n\n/**\n * One serialization lane per account so AgentChat turns never block the\n * agent's main lane and never overlap each other. OpenClaw runs a lane's\n * runs one after another, so a run that never ends would hold every later\n * turn behind it: after a hand-off (`AccountTurns.handOff`) new turns go to\n * the next lane (`generation` > 0), leaving the hung run alone on the old one.\n */\nexport function integrationLane(accountId: string, generation = 0): string {\n const base = `agentchat-integration:${sanitizeKeyPart(accountId)}`\n return generation > 0 ? `${base}:${generation}` : base\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 { integration } from 'agentchatme'\n\nimport { AGENTCHAT_CLIENT_IDENTITY } 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\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 /** Every tool the server listed for this key (bare names). */\n readonly tools?: readonly string[]\n /** Tools a turn needs that the server did not list. */\n readonly missing?: readonly string[]\n readonly error?: string\n}\n\n/**\n * Doctor and status check: can this key list the hosted tools? The SDK\n * kit's `probeHostedTools` — one MCP `initialize` and one `tools/list` over\n * Streamable HTTP with the bearer key, the requests OpenClaw makes on\n * connect. A `401` means the key does not authenticate; a transport error\n * means the endpoint is not reachable from here; a list without the tools a\n * turn needs means a turn could not look.\n */\nexport async function probeHostedMcp(params: {\n apiKey: string\n apiBase?: string\n timeoutMs?: number\n fetch?: typeof fetch\n}): Promise<McpProbeResult> {\n const result = await integration.probeHostedTools({\n apiBase: params.apiBase ?? DEFAULT_API_BASE,\n apiKey: params.apiKey,\n clientIdentity: AGENTCHAT_CLIENT_IDENTITY,\n ...(params.timeoutMs !== undefined ? { timeoutMs: params.timeoutMs } : {}),\n ...(params.fetch ? { fetch: params.fetch } : {}),\n })\n const missing = result.missing ?? []\n return {\n ok: result.ok,\n ...(result.status !== undefined ? { status: result.status } : {}),\n ...(result.serverName ? { serverName: result.serverName } : {}),\n ...(result.serverVersion ? { serverVersion: result.serverVersion } : {}),\n ...(result.protocolVersion ? { protocolVersion: result.protocolVersion } : {}),\n ...(result.tools ? { tools: result.tools } : {}),\n ...(missing.length > 0 ? { missing } : {}),\n ...(result.error ? { error: result.error } : !result.ok && missing.length > 0 ? { error: `the server lists no ${missing.join(', ')} for this key` } : {}),\n }\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 * A turn's run, as OpenClaw reports it: admitted, watched until OpenClaw\n * confirms it ended, and what AgentChat calls it made.\n *\n * Why the watch never gives up on a timeout\n * ─────────────────────────────────────────\n * `runtime.subagent.waitForRun({ runId, timeoutMs })` bounds the WAIT, not\n * the run: \"timeoutMs bounds the wait call; it does not cancel the run\"\n * (docs.openclaw.ai/plugins/sdk-runtime/background-work). A `timeout`\n * status therefore says one of two things — the wait elapsed while the run\n * goes on, or the run hit its own deadline (`agents.defaults.timeoutSeconds`,\n * 48 h by default) and is over. Treating the first as an end would let the\n * conversation be gated again and a second turn answer it while the first\n * is still running. So the watch waits again until OpenClaw says the run\n * is over, with OpenClaw's own rule for telling the two apart\n * (`isTerminalAgentWaitTimeout` and the `untilTerminal` loop in\n * github.com/openclaw/openclaw `src/agents/run-wait.ts`):\n *\n * - `ok`, `error` → ended\n * - `pending` → running (a normal non-terminal observation)\n * - `timeout` with `pendingError` → running (a failed attempt may still recover)\n * - `timeout` with `endedAt`, `stopReason` or `livenessState` → ended (the run's own deadline)\n * - `timeout` that is a hard timeout → ended: a `timeoutPhase` of\n * preflight / provider / tool_execution / post_turn, or `providerStarted`\n * without a restart stop (`resolveAgentRunTerminalFacts`)\n * - `timeout` with an `error` → ended\n * - any other `timeout` → running (the wait elapsed)\n *\n * On OpenClaw main a wait that elapses comes back bare — `{ runId, status:\n * 'timeout' }`, no snapshot (`src/gateway/agent-turn/agent-wait.ts`) — a\n * queued run as `pending` with `timeoutPhase: 'queue'`, and a gateway\n * lifecycle reset as `timeout` with `timeoutPhase: 'gateway_draining'`. A\n * bare `timeout` carries none of the metadata keys, so it is read by the\n * timing rule below: one that took the whole wait is asked again.\n *\n * Older OpenClaw lines (2026.6 and 2026.7, e.g. 2026.6.10 and 2026.7.35)\n * hand a plugin only `{ status, error }` (the wait metadata is dropped on the\n * way out). There a terminal timeout\n * is told apart by when it arrives: the gateway answers from the run's\n * terminal record as soon as there is one, while an elapsed wait (and a\n * failed attempt that may still recover) is answered when the wait's own\n * timer fires. A `timeout` that comes back in under half the requested\n * wait is an end; one that took the whole wait is asked again — if the run\n * did end meanwhile, the next wait is answered at once from that record.\n *\n * Nothing here cancels a run: the plugin runtime has no abort for a\n * subagent run, and OpenClaw's own run deadline is what bounds a run that\n * never finishes. The watch stops early only when the plugin runtime is\n * gone (the gateway is shutting down or the plugin was unloaded) — then\n * there is nothing left to ask, and nothing left in this process to start\n * a second turn either.\n */\n\nimport type { PluginRuntime } from 'openclaw/plugin-sdk/channel-core'\n\nimport { MCP_SERVER_NAME, MCP_TOOL_DELIMITER } from './turn.js'\n\n/** One wait per call. Shorter than the old 15-minute bound so a live run is reported as live in the log. */\nexport const DEFAULT_RUN_WAIT_CHUNK_MS = 5 * 60_000\n\n/** Back-off between failed waits (the gateway did not answer); the last value repeats. */\nexport const RUN_WAIT_RETRY_MS: readonly number[] = [1_000, 5_000, 15_000, 30_000, 60_000]\n\n/** A wait that returns sooner than this, without saying the run went on, is not allowed to loop hot. */\nconst MIN_WAIT_SPACING_MS = 1_000\n\n/** Transcript rows read after a run; one wake turn is a handful of tool calls. */\nexport const TRANSCRIPT_READ_LIMIT = 200\n\n/** What `waitForRun` answers, across the OpenClaw versions the plugin supports. Every field is optional on purpose. */\nexport interface RunWaitObservation {\n readonly status?: unknown\n readonly error?: unknown\n readonly endedAt?: unknown\n readonly stopReason?: unknown\n readonly livenessState?: unknown\n readonly pendingError?: unknown\n readonly timeoutPhase?: unknown\n readonly startedAt?: unknown\n readonly providerStarted?: unknown\n}\n\n/** How a run ended, as OpenClaw confirmed it. `timeout` is the run's own deadline, never an elapsed wait. */\nexport type RunEndStatus = 'ok' | 'error' | 'timeout'\n\nexport type RunEnd =\n | { readonly ended: false }\n | { readonly ended: true; readonly status: RunEndStatus; readonly error?: string }\n\n/** Keys only a release that forwards the gateway's wait metadata sends. */\nconst METADATA_KEYS = ['endedAt', 'stopReason', 'livenessState', 'pendingError', 'timeoutPhase', 'startedAt', 'providerStarted'] as const\n\n/**\n * Whether one wait observation means the run is over. Pure. `elapsedMs` is\n * how long the wait call took and `requestedMs` what it was asked to wait;\n * they matter only for a release that drops the wait metadata.\n */\nexport function runEndOf(wait: RunWaitObservation | null | undefined, timing: { readonly requestedMs: number; readonly elapsedMs: number }): RunEnd {\n const status = wait?.status\n const error = nonEmpty(wait?.error)\n if (status === 'ok') return { ended: true, status: 'ok' }\n if (status === 'error') {\n // OpenClaw itself reads an `error` whose text is \"completed\" as a clean end.\n if (error && error.trim().toLowerCase() === 'completed') return { ended: true, status: 'ok' }\n return { ended: true, status: 'error', ...(error ? { error } : {}) }\n }\n if (status !== 'timeout') {\n // `pending`, or a status this version does not know: not an end.\n return { ended: false }\n }\n const ended = { ended: true as const, status: 'timeout' as const, ...(error ? { error } : {}) }\n const hasMetadata = wait !== null && wait !== undefined && METADATA_KEYS.some((key) => key in wait)\n if (!hasMetadata) {\n // Metadata dropped (OpenClaw 2026.6 / 2026.7 lines): only the timing tells. The\n // gateway answers from the run's terminal record as soon as there is\n // one; an elapsed wait — and a failed attempt that may still recover —\n // is answered when the wait's own timer fires.\n return timing.elapsedMs < timing.requestedMs / 2 ? ended : { ended: false }\n }\n if (wait.pendingError === true) return { ended: false }\n if (typeof wait.endedAt === 'number' || nonEmpty(wait.stopReason) || nonEmpty(wait.livenessState)) return ended\n if (isHardTimeout(wait)) return ended\n return error ? ended : { ended: false }\n}\n\n/** Timeout phases only a run's own deadline reports (OpenClaw `HARD_TIMEOUT_PHASES`). */\nconst HARD_TIMEOUT_PHASES: ReadonlySet<string> = new Set(['preflight', 'provider', 'tool_execution', 'post_turn'])\n\n/**\n * OpenClaw's `hard_timeout` reading of a `timeout` snapshot (the third leg of\n * `isTerminalAgentWaitTimeout`): a phase only the run's own deadline reports,\n * or a timeout after the provider started that was not a restart stop.\n */\nexport function isHardTimeout(wait: RunWaitObservation): boolean {\n const phase = typeof wait.timeoutPhase === 'string' ? wait.timeoutPhase.trim() : ''\n if (HARD_TIMEOUT_PHASES.has(phase)) return true\n return wait.status === 'timeout' && wait.providerStarted === true && nonEmpty(wait.stopReason) !== 'restart'\n}\n\n/** What the watch reports. `gone`: the plugin runtime disappeared before OpenClaw confirmed an end. */\nexport type RunWatchResult =\n | { readonly ended: true; readonly status: RunEndStatus; readonly error?: string; readonly elapsedMs: number }\n | { readonly ended: false; readonly reason: 'gone'; readonly elapsedMs: number }\n\nexport interface RunWatchOptions {\n readonly runtime: () => PluginRuntime | null\n readonly runId: string\n readonly chunkMs?: number\n readonly retryMs?: readonly number[]\n /** Called each time a wait elapses with the run still going (for the \"still running\" log line). */\n readonly onStillRunning?: (elapsedMs: number) => void\n /** Called when a wait call fails; the watch tries again after the next back-off step. */\n readonly onWaitError?: (error: string, attempt: number, retryInMs: number) => void\n readonly now?: () => number\n readonly sleep?: (ms: number) => Promise<void>\n}\n\n/**\n * Wait until OpenClaw confirms the run ended. Never rejects. Resolves with\n * `ended: true` and the run's status, or `ended: false` only when the\n * plugin runtime is gone.\n *\n * A wait call that fails is not an end either (the gateway did not answer;\n * the run is OpenClaw's): the watch backs off and asks again. A run the\n * gateway does not know is answered like a wait that elapsed (a bare\n * `{ status: 'timeout' }` after the whole wait — OpenClaw has no \"not found\"\n * for `agent.wait`), so it is watched until the turn is handed off and let\n * go of (`./running.ts`).\n */\nexport async function watchRunUntilEnded(options: RunWatchOptions): Promise<RunWatchResult> {\n const chunkMs = options.chunkMs ?? DEFAULT_RUN_WAIT_CHUNK_MS\n const retryMs = options.retryMs ?? RUN_WAIT_RETRY_MS\n const now = options.now ?? Date.now\n const sleep = options.sleep ?? defaultSleep\n const started = now()\n let failures = 0\n for (;;) {\n const runtime = options.runtime()\n if (!runtime) return { ended: false, reason: 'gone', elapsedMs: now() - started }\n const waitStarted = now()\n let observation: RunWaitObservation\n try {\n observation = (await runtime.subagent.waitForRun({ runId: options.runId, timeoutMs: chunkMs })) as RunWaitObservation\n } catch (err) {\n const message = describe(err)\n const delay = retryMs[Math.min(failures, retryMs.length - 1)] ?? 60_000\n failures += 1\n options.onWaitError?.(message, failures, delay)\n await sleep(delay)\n continue\n }\n failures = 0\n const elapsedMs = now() - waitStarted\n const end = runEndOf(observation, { requestedMs: chunkMs, elapsedMs })\n if (end.ended) return { ...end, elapsedMs: now() - started }\n options.onStillRunning?.(now() - started)\n if (elapsedMs < MIN_WAIT_SPACING_MS) await sleep(MIN_WAIT_SPACING_MS - elapsedMs)\n }\n}\n\n/** AgentChat tool calls a run made, read from its transcript. */\nexport interface AgentChatCalls {\n /** AgentChat tool results in the transcript. */\n readonly made: number\n /** Of those, the ones that came back as errors. */\n readonly failed: number\n}\n\n/**\n * Count the AgentChat tool results in a run's transcript. Pure. Returns\n * null when the transcript says nothing usable (no rows, or no row of a\n * shape this version knows) — the caller then treats the count as unknown,\n * never as zero.\n *\n * Two shapes are recognised, both read from OpenClaw transcripts:\n * - a direct call: a `toolResult` row whose `toolName` is\n * `agentchat__<tool>` (MCP tools exposed one by one);\n * - a call through OpenClaw's tool-search surface: a `toolResult` row\n * for the `tool_call` meta tool whose `details.tool` names the MCP\n * server `agentchat` (or the `agentchat__<tool>` name).\n * `isError: true` marks a failed call. Rows tagged with another run's id\n * (`__openclaw.runId`) are skipped.\n */\nexport function countAgentChatCalls(messages: readonly unknown[], runId?: string): AgentChatCalls | null {\n if (messages.length === 0) return null\n let recognised = false\n let made = 0\n let failed = 0\n for (const row of messages) {\n const message = unwrapMessage(row)\n if (!message) continue\n const role = message.role\n if (role === 'assistant' || role === 'user') recognised = true\n if (role !== 'toolResult' && role !== 'tool') continue\n recognised = true\n const meta = asRecord(message.__openclaw)\n if (runId && typeof meta?.runId === 'string' && meta.runId !== runId) continue\n if (!isAgentChatToolResult(message)) continue\n made += 1\n if (message.isError === true) failed += 1\n }\n return recognised ? { made, failed } : null\n}\n\n/**\n * Read the run's transcript and count its AgentChat calls. Never throws:\n * a runtime that cannot read the session (no method, a refusal, an empty\n * session) gives null — unknown.\n */\nexport async function readAgentChatCalls(runtime: PluginRuntime | null, sessionKey: string, runId?: string): Promise<AgentChatCalls | null> {\n if (!runtime || typeof runtime.subagent?.getSessionMessages !== 'function') return null\n try {\n const result = await runtime.subagent.getSessionMessages({ sessionKey, limit: TRANSCRIPT_READ_LIMIT })\n const messages: unknown = result?.messages\n return Array.isArray(messages) ? countAgentChatCalls(messages, runId) : null\n } catch {\n return null\n }\n}\n\nconst TOOL_PREFIX = `${MCP_SERVER_NAME}${MCP_TOOL_DELIMITER}`\n\nfunction isAgentChatToolResult(message: Record<string, unknown>): boolean {\n const toolName = typeof message.toolName === 'string' ? message.toolName : typeof message.name === 'string' ? message.name : ''\n if (toolName.startsWith(TOOL_PREFIX)) return true\n const tool = asRecord(asRecord(message.details)?.tool)\n if (!tool) return false\n if (typeof tool.name === 'string' && tool.name.startsWith(TOOL_PREFIX)) return true\n if (tool.sourceName === MCP_SERVER_NAME) return true\n const mcp = asRecord(tool.mcp)\n return mcp?.serverName === MCP_SERVER_NAME\n}\n\n/** A transcript row is either the message itself or an event wrapping it (`{ type: 'message', message }`). */\nfunction unwrapMessage(row: unknown): Record<string, unknown> | null {\n const record = asRecord(row)\n if (!record) return null\n if (typeof record.role === 'string') return record\n const inner = asRecord(record.message)\n return inner && typeof inner.role === 'string' ? inner : null\n}\n\nfunction asRecord(value: unknown): Record<string, unknown> | null {\n return value !== null && typeof value === 'object' && !Array.isArray(value) ? (value as Record<string, unknown>) : null\n}\n\nfunction nonEmpty(value: unknown): string | undefined {\n return typeof value === 'string' && value.trim().length > 0 ? value : undefined\n}\n\nfunction describe(err: unknown): string {\n return err instanceof Error ? err.message : String(err)\n}\n\nfunction defaultSleep(ms: number): Promise<void> {\n return new Promise((resolve) => {\n const timer = setTimeout(resolve, ms)\n timer.unref?.()\n })\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 the run's end are reported\n * separately (`TurnAdmission`): `done` resolves only once OpenClaw\n * confirms the run is over (`./run.ts` — a `waitForRun` timeout bounds\n * the wait, never the run, so it is asked again), with the AgentChat\n * calls the run made read from its transcript when OpenClaw allows it.\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 { readAgentChatCalls, watchRunUntilEnded, type AgentChatCalls, type RunEndStatus } from './run.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\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, options) => {\n const runtime = getRuntime()\n if (!runtime) throw new RuntimeUnavailableError('the gate call')\n // Two reasons to stop: our own timeout, and the kit's gate-call deadline\n // (the loop aborts its signal when it no longer wants the answer).\n // OpenClaw's `llm.complete` takes an AbortSignal, so both reach the call.\n const signals = [\n ...(Number.isFinite(timeoutMs) && timeoutMs > 0 ? [AbortSignal.timeout(timeoutMs)] : []),\n ...(options?.signal ? [options.signal] : []),\n ]\n const signal = signals.length === 0 ? undefined : signals.length === 1 ? signals[0] : AbortSignal.any(signals)\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 ...(signal ? { signal } : {}),\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\n/**\n * How an admitted turn's run ended, once OpenClaw confirmed it. `status`:\n * `ok` / `error` / `timeout` (the run's own deadline — never an elapsed\n * wait), or `gone` when the plugin runtime disappeared before an end was\n * confirmed (the gateway is going down; nothing in this process starts\n * another turn after it).\n */\nexport interface TurnOutcome {\n readonly ran: boolean\n readonly runId?: string\n readonly status?: RunEndStatus | 'gone'\n readonly error?: string\n /** AgentChat tool calls the run made, from its transcript; null when OpenClaw did not let the plugin read it (unknown, never zero). */\n readonly agentchatCalls?: AgentChatCalls | null\n /** From admission to the confirmed end. */\n readonly elapsedMs?: number\n}\n\n/**\n * What starting a turn reports: refused (OpenClaw did not admit\n * the run — no runtime, a thrown `subagent.run`), or admitted with the\n * promise of its end. `done` never rejects and resolves only when OpenClaw\n * confirmed the end (or the runtime is gone).\n */\nexport type TurnAdmission =\n | { readonly ran: false; readonly error: string }\n | { readonly ran: true; readonly runId: string; readonly sessionKey: string; readonly done: Promise<TurnOutcome> }\n\n/** Starts one agent turn. Injectable so the loop wiring 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.current()` (OpenClaw main) or\n * `runtime.config.loadConfig()` (older releases) 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 const config = (runtime() as { config?: { current?: () => unknown; loadConfig?: () => unknown } } | null)?.config\n // OpenClaw main: `runtime.config.current()` (`loadConfig` is gone there);\n // older releases: `runtime.config.loadConfig()`.\n for (const read of [config?.current, config?.loadConfig]) {\n if (typeof read !== 'function') continue\n try {\n const loaded: unknown = read.call(config)\n if (loaded && typeof loaded === 'object') return { cfg: loaded, live: true }\n } catch {\n // try the next way, then the snapshot\n }\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 receive loop 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 agent's send is a\n * hosted-tool call inside the turn. `done` resolves when OpenClaw confirms\n * the run ended (`watchRunUntilEnded`), then carries the AgentChat calls\n * counted from the run's transcript. It never rejects.\n */\nexport function createRuntimeTurnStarter(params: {\n runtime?: () => PluginRuntime | null\n /** One `waitForRun` call; the watch asks again until the run is over. */\n waitChunkMs?: number\n /** Called each time a wait elapses with the run still going. */\n onStillRunning?: (info: { runId: string; sessionKey: string; elapsedMs: number }) => void\n /** Called when a wait call fails (the watch retries). */\n onWaitError?: (info: { runId: string; sessionKey: string; error: string; attempt: number; retryInMs: number }) => void\n now?: () => number\n sleep?: (ms: number) => Promise<void>\n} = {}): TurnStarter {\n const getRuntime = params.runtime ?? getPluginRuntime\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 // The session OpenClaw accepted the run in: newer releases return the\n // normalized key, which is where its transcript lives.\n let sessionKey = request.sessionKey\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 const accepted = (admitted as { sessionKey?: unknown }).sessionKey\n if (typeof accepted === 'string' && accepted.trim().length > 0) sessionKey = accepted.trim()\n } catch (err) {\n return { ran: false, error: err instanceof Error ? err.message : String(err) }\n }\n const done = watchRunUntilEnded({\n runtime: getRuntime,\n runId,\n ...(params.waitChunkMs !== undefined ? { chunkMs: params.waitChunkMs } : {}),\n ...(params.onStillRunning ? { onStillRunning: (elapsedMs: number) => params.onStillRunning?.({ runId, sessionKey, elapsedMs }) } : {}),\n ...(params.onWaitError\n ? { onWaitError: (error: string, attempt: number, retryInMs: number) => params.onWaitError?.({ runId, sessionKey, error, attempt, retryInMs }) }\n : {}),\n ...(params.now ? { now: params.now } : {}),\n ...(params.sleep ? { sleep: params.sleep } : {}),\n }).then(async (watched): Promise<TurnOutcome> => {\n if (!watched.ended) return { ran: true, runId, status: 'gone', elapsedMs: watched.elapsedMs }\n const agentchatCalls = await readAgentChatCalls(getRuntime(), sessionKey, runId)\n return {\n ran: true,\n runId,\n status: watched.status,\n ...(watched.error ? { error: watched.error } : {}),\n agentchatCalls,\n elapsedMs: watched.elapsedMs,\n }\n })\n return { ran: true, runId, sessionKey, done }\n }\n}\n\n/**\n * Watches a run this process did not start — one OpenClaw's restart resume\n * started in a turn's session — until OpenClaw reports it ended, and what\n * AgentChat calls it made. Resolves null only when the plugin runtime is\n * gone. Never rejects.\n */\nexport function createRunWatcher(params: {\n runtime?: () => PluginRuntime | null\n onStillRunning?: (info: { runId: string; sessionKey: string; elapsedMs: number }) => void\n waitChunkMs?: number\n} = {}): (run: { runId: string; sessionKey: string }) => Promise<TurnOutcome | null> {\n const getRuntime = params.runtime ?? getPluginRuntime\n return async ({ runId, sessionKey }) => {\n const watched = await watchRunUntilEnded({\n runtime: getRuntime,\n runId,\n ...(params.waitChunkMs !== undefined ? { chunkMs: params.waitChunkMs } : {}),\n ...(params.onStillRunning ? { onStillRunning: (elapsedMs: number) => params.onStillRunning?.({ runId, sessionKey, elapsedMs }) } : {}),\n })\n if (!watched.ended) return null\n const agentchatCalls = await readAgentChatCalls(getRuntime(), sessionKey, runId)\n return { ran: true, runId, status: watched.status, ...(watched.error ? { error: watched.error } : {}), agentchatCalls, elapsedMs: watched.elapsedMs }\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: the served texts (`texts.json`), a cache\n * of what the server serves, so a gateway can start while the server is\n * unreachable; and the turns in flight (`turns.json`, `./turn-store.ts`), so\n * the next start after a gateway restart holds their conversations. Files\n * earlier releases kept here are removed on start (`removeOldStateFiles`).\n * Nothing secret, nothing authoritative — deleting the directory costs one\n * texts fetch (and, while the gateway is stopped, the restart defense for\n * that one restart).\n *\n * Both are written atomically (temp file + rename; the kit's cache also\n * fsyncs).\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/** Files earlier releases kept here that nothing reads any more. */\nexport const OLD_INVITE_LEDGER_FILE = 'invites.json'\n\n/**\n * Upgrade cleanup, once per start: the invite ledger of earlier releases\n * (invites now come from the tray) and a texts cache in the earlier shape\n * (the kit's cache keeps `{ version: 1, runtime, fetched_at, texts }`; an\n * older file is ignored by it and would only linger). Never throws; returns\n * what was removed.\n */\nexport function removeOldStateFiles(accountId: string, stateDir?: string): string[] {\n const dir = integrationStateDir(accountId, stateDir)\n const removed: string[] = []\n const ledger = path.join(dir, OLD_INVITE_LEDGER_FILE)\n if (tryUnlink(ledger)) removed.push(ledger)\n const texts = path.join(dir, 'texts.json')\n try {\n const entry = JSON.parse(fs.readFileSync(texts, 'utf8')) as { version?: unknown; runtime?: unknown }\n if (entry.version !== 1 || typeof entry.runtime !== 'string') {\n if (tryUnlink(texts)) removed.push(texts)\n }\n } catch (err) {\n // Absent: nothing to do. Unreadable or not JSON: an old or damaged copy.\n if ((err as NodeJS.ErrnoException)?.code !== 'ENOENT' && tryUnlink(texts)) removed.push(texts)\n }\n return removed\n}\n\nfunction tryUnlink(file: string): boolean {\n try {\n fs.unlinkSync(file)\n return true\n } catch {\n return false\n }\n}\n\n","/**\n * The served texts: the SDK kit's `TextsCache`, kept in the plugin's state dir.\n *\n * Every text an agent sees is written once on the server and served as data\n * (`GET /v1/texts?runtime=openclaw`): the wake instruction, the invite\n * prompt, the gate-call preamble and answer format, the identity line, where\n * the manual is. The kit's cache fetches them at channel start and daily,\n * keeps the last good copy in `<state dir>/agentchat/<accountId>/texts.json`\n * (an offline start is not mute), and backs off after a failure. The server\n * spells the hosted tools for `runtime=openclaw` the way OpenClaw exposes\n * them (`agentchat__<tool>`); the copy handed out is still passed through the\n * idempotent re-speller (a no-op then), so a server that serves bare names\n * again — a rolled-back deploy — cannot hand the agent wrong tool names. The\n * stored copy is always server-verbatim.\n */\n\nimport * as fs from 'node:fs'\nimport * as path from 'node:path'\n\nimport { integration, type AgentChatClient, type Texts } from 'agentchatme'\n\nimport type { Logger } from '../log.js'\nimport { integrationStateDir } from './state.js'\nimport { spellToolsForOpenClaw } from './turn.js'\n\nexport const TEXTS_RUNTIME = 'openclaw' as const\nexport const TEXTS_CACHE_FILE = 'texts.json'\n\nexport type TextsClient = Pick<AgentChatClient, 'texts'> & { readonly baseUrl?: string }\n\n/** Where the kit's cache keeps the last good copy for this account. */\nexport function textsCachePath(accountId: string, stateDir?: string): string {\n return path.join(integrationStateDir(accountId, stateDir), TEXTS_CACHE_FILE)\n}\n\n/** Re-spell the hosted tool names in every agent-facing text. Pure, idempotent; the stored copy stays server-verbatim. */\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 ...(typeof texts.gate_call_preamble === 'string' ? { gate_call_preamble: spellToolsForOpenClaw(texts.gate_call_preamble) } : {}),\n ...(typeof texts.gate_call_answer_format === 'string' ? { gate_call_answer_format: spellToolsForOpenClaw(texts.gate_call_answer_format) } : {}),\n }\n}\n\n/** The kit's cache for one account, its file in the plugin's state dir. */\nexport function createTextsCache(params: {\n client: TextsClient\n accountId: string\n stateDir?: string | undefined\n logger?: Logger\n}): integration.TextsCache {\n return new integration.TextsCache({\n client: params.client,\n runtime: TEXTS_RUNTIME,\n filePath: textsCachePath(params.accountId, params.stateDir),\n ...(params.logger ? { onError: (err: Error) => params.logger?.warn({ err: err.message }, 'served texts') } : {}),\n })\n}\n\n/**\n * What the receive loop reads: the cache's copy through the re-speller. The\n * spelled copy is memoised per served copy, so a cycle does not re-spell.\n */\nexport class OpenClawTexts implements integration.TextsSource {\n private spelledFrom: Texts | null = null\n private spelled: Texts | null = null\n\n constructor(private readonly cache: integration.TextsCache) {}\n\n current(): Texts | null {\n return this.spell(this.cache.current())\n }\n\n async ensure(): Promise<Texts | null> {\n return this.spell(await this.cache.ensure())\n }\n\n get source(): string {\n return this.cache.source\n }\n\n get fetchedAt(): string | null {\n return this.cache.fetchedAt\n }\n\n get lastError(): string | null {\n return this.cache.lastError\n }\n\n private spell(texts: Texts | null): Texts | null {\n if (texts === null) return null\n if (texts !== this.spelledFrom) {\n this.spelledFrom = texts\n this.spelled = spellTextsForOpenClaw(texts)\n }\n return this.spelled\n }\n}\n\nexport interface LoadTextsParams {\n readonly client: TextsClient\n readonly accountId: string\n readonly stateDir?: string | undefined\n}\n\n/**\n * The identity line for the key's own agent, as served — for the\n * placement paths that run outside the gateway (wizard, `channels add`,\n * `doctor --fix`, re-enable). One fetch through the kit's cache (the server,\n * else the file it keeps); `null` when neither has a copy. Never throws.\n */\nexport async function loadIdentityLine(params: LoadTextsParams): Promise<string | null> {\n const cache = createTextsCache(params)\n try {\n const texts = await cache.start()\n return texts ? spellToolsForOpenClaw(texts.identity_line) : null\n } catch {\n return null\n } finally {\n cache.stop()\n }\n}\n\n/** The cached identity line, without touching the network (status, doctor preview). Reads the kit's file. */\nexport function cachedIdentityLine(accountId: string, stateDir?: string): string | null {\n let raw: string\n try {\n raw = fs.readFileSync(textsCachePath(accountId, stateDir), 'utf8')\n } catch {\n return null\n }\n try {\n const entry = JSON.parse(raw) as { runtime?: unknown; texts?: unknown }\n if (entry.runtime !== TEXTS_RUNTIME || !isTexts(entry.texts)) return null\n return spellToolsForOpenClaw(entry.texts.identity_line)\n } catch {\n return null\n }\n}\n\n/** The shape every consumer relies on: the kit's own check. */\nexport const isTexts: (value: unknown) => value is Texts = integration.isTexts\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 * The after-turn recording for a turn the kit's loop no longer watches.\n *\n * Normally the kit's receive loop records what a turn did once its run ends\n * (contract v1, D5: `turnOutcome` / `applyOutcome` on a fresh tray). Two\n * kinds of turn end outside that watch, and this applies the same rule to\n * them:\n *\n * - a turn handed off after 30 minutes (`AccountTurns.handOff`): the kit\n * let go of it to free its slot, so without this an answer sent at\n * minute 35 would record nothing and the card would be gated again;\n * - a turn a gateway restart ended, read again on the next start, and a\n * run OpenClaw's restart resume started in that turn's session\n * (`AccountTurns.adopt`).\n *\n * The kit's per-anchor memory of earlier silent turns is the loop's own, so\n * a silent end here counts as the first (`silentBefore` 0): nothing is\n * recorded and the card is gated again — never a dismiss on a count this\n * side cannot know.\n */\n\nimport { integration, type AgentChatClient, type InboxCard, type InboxTray } from 'agentchatme'\n\nimport type { Logger } from '../log.js'\nimport type { RunRecord } from './running.js'\n\n/** The tray read the kit's loop makes after a turn. */\nconst TRAY_LIMIT = 50\n\n/** Records what a turn did, from a fresh tray. Never rejects. */\nexport type AfterTurnRecorder = (record: RunRecord, end: integration.TurnEnd) => Promise<void>\n\nexport type AfterTurnClient = Pick<AgentChatClient, 'inbox' | 'decisions' | 'groups'>\n\nexport function createAfterTurnRecorder(options: { client: AfterTurnClient; logger: Logger }): AfterTurnRecorder {\n const { client, logger } = options\n return async (record, end) => {\n if (end.status === 'still_running' || record.kind === 'run') return\n let fresh: InboxTray | null\n try {\n fresh = await client.inbox.tray({ waitMs: 0, limit: TRAY_LIMIT, includeInvites: true })\n } catch (err) {\n // The card stays on the tray; the server re-wakes it.\n logger.warn({ runId: record.runId, err: describe(err) }, 'after-turn tray read failed — nothing recorded; the server re-wakes the card')\n fresh = null\n }\n try {\n if (record.kind === 'reply') {\n if (!record.card) return\n const outcome = integration.turnOutcome({\n turn: end,\n turnStartedAt: record.startedAt,\n gateCard: record.card,\n category: (record.category ?? null) as integration.TurnOutcomeInput['category'],\n freshTray: fresh,\n silentBefore: 0,\n })\n const recorded = await integration.applyOutcome(client, outcome)\n logger.info({ runId: record.runId, conversationId: record.id, action: outcome.action, reason: outcome.reason, recorded }, 'after-turn rule applied (turn ended outside the loop’s watch)')\n return\n }\n if (!record.invite) return\n const outcome = integration.inviteOutcome({ turn: end, invite: record.invite, freshTray: fresh, silentBefore: 0 })\n const recorded = await integration.applyInviteOutcome(client, outcome)\n logger.info({ runId: record.runId, inviteId: record.id, action: outcome.action, reason: outcome.reason, recorded }, 'after-turn rule applied to the invite (turn ended outside the loop’s watch)')\n } catch (err) {\n logger.warn({ runId: record.runId, err: describe(err) }, 'after-turn recording failed — the card stays on the tray; the server re-wakes it')\n }\n }\n}\n\n/** The card the gate saw, rebuilt from what was stored (no message text). */\nexport function cardFromStored(stored: { conversation_id: string } & Record<string, unknown>): InboxCard {\n return { preview: null, ...stored } as unknown as InboxCard\n}\n\nfunction describe(err: unknown): string {\n return err instanceof Error ? err.message : String(err)\n}\n","/**\n * The turns in flight, on disk: `<state>/agentchat/<accountId>/turns.json`.\n *\n * Why it exists: a gateway restart ends every run with the process, and\n * OpenClaw (current main) may then continue a plugin's turn session on its\n * own. A plugin run started with no requester is registered under the\n * agent's main session (`registerPluginSubagentRunFromGateway`,\n * `src/gateway/server-methods/agent-subagent-registration.ts`), restart\n * resume walks a live subagent session up to that root\n * (`resolveRootSubagentRequester`) and wakes it with \"send a fresh\n * instruction to the same retained child session when appropriate\"\n * (`src/gateway/session-restart-resume.ts`). So after a restart the agent\n * may run our turn's session again while the new receive loop would gate\n * the same card and start a second turn. The new process knows neither the\n * old run nor its conversation, and a third-party plugin has no public API\n * that lists live runs (`readSessionFacts` is for bundled / trusted\n * official plugins only). So the turns in flight are written here, and the\n * next start holds their conversations for a while (`AccountTurns.adopt`).\n *\n * What is written: the run id, the turn's session key, what it held (the\n * conversation or invite id and the message the gate read through), and the\n * few card fields the after-turn rule compares — never message text.\n * Written atomically (temp file + rename) on every change; an entry whose\n * run ended stays `KEEP_ENDED_MS` longer, because a restart ends a run\n * before it ends the process. Never throws: a file that cannot be written\n * costs only the defense, and one that cannot be read is treated as empty.\n */\n\nimport * as fs from 'node:fs'\nimport * as path from 'node:path'\n\nimport type { InboxCard } from 'agentchatme'\n\nimport { integrationStateDir } from './state.js'\n\nexport const TURN_STORE_FILE = 'turns.json'\n\n/** An ended run's entry stays this long (a restart ends the run a few seconds before the process). */\nexport const KEEP_ENDED_MS = 60_000\n\n/** The card fields the after-turn rule reads (`turnOutcome`): no message text. */\nexport type StoredCard = Pick<InboxCard, 'conversation_id'> & {\n readonly last_message_id?: string | null\n readonly your_last_message_at?: string | null\n readonly you_owe_reply?: boolean\n readonly your_last_decision?: InboxCard['your_last_decision'] | null\n}\n\nexport interface StoredTurn {\n readonly runId: string\n readonly kind: 'reply' | 'invite'\n /** The conversation id (reply) or the invite id. */\n readonly id: string\n readonly anchor: string | null\n readonly sessionKey: string\n /** Local clock, ms. */\n readonly startedAt: number\n /** When the first turn of this chain started (a turn continued after a restart keeps it): stored turns age out by it. */\n readonly firstStartedAt?: number\n readonly category?: string | null\n readonly card?: StoredCard\n}\n\ninterface StoreFile {\n readonly version: 1\n readonly turns: readonly StoredTurn[]\n}\n\n/** The card as stored: the fields the rule compares, the anchor as `last_message_id`. */\nexport function storedCard(card: InboxCard, anchor: string | null): StoredCard {\n return {\n conversation_id: card.conversation_id,\n ...(anchor ? { last_message_id: anchor } : {}),\n ...(card.your_last_message_at !== undefined ? { your_last_message_at: card.your_last_message_at } : {}),\n ...(card.you_owe_reply !== undefined ? { you_owe_reply: card.you_owe_reply } : {}),\n ...(card.your_last_decision !== undefined ? { your_last_decision: card.your_last_decision } : {}),\n }\n}\n\nexport class TurnStore {\n readonly file: string\n\n constructor(accountId: string, stateDir?: string) {\n this.file = path.join(integrationStateDir(accountId, stateDir), TURN_STORE_FILE)\n }\n\n /** What the last process left. Empty when there is no file or it cannot be read. */\n load(): StoredTurn[] {\n let parsed: unknown\n try {\n parsed = JSON.parse(fs.readFileSync(this.file, 'utf8'))\n } catch {\n return []\n }\n const turns = (parsed as { version?: unknown; turns?: unknown } | null)?.turns\n if ((parsed as { version?: unknown } | null)?.version !== 1 || !Array.isArray(turns)) return []\n return turns.filter(isStoredTurn)\n }\n\n /** Replace the file with `turns` (removed when empty). Returns false when the write failed. */\n write(turns: readonly StoredTurn[]): boolean {\n try {\n if (turns.length === 0) {\n fs.rmSync(this.file, { force: true })\n return true\n }\n fs.mkdirSync(path.dirname(this.file), { recursive: true })\n const body: StoreFile = { version: 1, turns }\n const tmp = `${this.file}.${process.pid}.tmp`\n fs.writeFileSync(tmp, `${JSON.stringify(body)}\\n`, { mode: 0o600 })\n fs.renameSync(tmp, this.file)\n return true\n } catch {\n return false\n }\n }\n}\n\nfunction isStoredTurn(value: unknown): value is StoredTurn {\n const turn = value as Partial<StoredTurn> | null\n return (\n typeof turn === 'object' &&\n turn !== null &&\n typeof turn.runId === 'string' &&\n (turn.kind === 'reply' || turn.kind === 'invite') &&\n typeof turn.id === 'string' &&\n turn.id.length > 0 &&\n typeof turn.sessionKey === 'string' &&\n turn.sessionKey.length > 0 &&\n typeof turn.startedAt === 'number' &&\n (turn.anchor === null || typeof turn.anchor === 'string')\n )\n}\n","/**\n * The account's turns, kept for the life of the gateway process — not of one\n * receive loop.\n *\n * A turn holds its conversation (or invite) until OpenClaw confirms its run\n * ended (`./run.ts`): while it runs, the card stays on the tray (nothing is\n * recorded before the turn ends), and gating it again would start a second\n * turn that answers the same message twice. The kit's `TurnTracker` is what\n * holds it, and there is one per account, handed to every loop for the\n * account: OpenClaw restarts an account's channel task on a config change\n * while the run started under the old loop goes on in OpenClaw's lane, so the\n * next loop leaves that card alone until the run ends (the old loop still\n * records what the run did). When a run that held a card ends, the account's\n * live loop is woken, so a message that arrived meanwhile is gated at once.\n *\n * A run OpenClaw never reports as ended must not freeze the account. After\n * `TURN_OVERDUE_MS` the turn is handed off, once: the kit's slot is released\n * and new turns move to a fresh OpenClaw lane (OpenClaw runs a lane's runs\n * one after another, so they would otherwise queue behind the hung run) —\n * other conversations get turns again — while this module keeps the\n * conversation held until OpenClaw reports that run ended, and then applies\n * the after-turn rule itself (`./after-turn.ts`: the kit no longer watches\n * it). At most `MAX_HUNG_TURNS` are held that way; beyond that, readiness\n * says not-ready (no gate calls) and status and doctor say why. An operator\n * can let one go: `openclaw agentchat release <conversation_id>`.\n *\n * Every hold here is keyed by run id. A run that was handed off or let go of\n * is never handed off again — whatever later \"still running\" reports say —\n * so a release sticks; and a run whose kit hold was released while OpenClaw\n * was still admitting it starts out let go of. Either way the old run can\n * never release a newer turn's hold on the same conversation.\n *\n * Gate off (single-run mode) one run reads the whole tray, so two would\n * answer the same cards: past `TURN_OVERDUE_MS` the cycle waiting on the run\n * is let go of (the loop is not stuck in it), but no new run starts while the\n * handed-off one lives — readiness says not-ready, status and doctor say why,\n * and `openclaw agentchat release <run id> --force` frees it.\n *\n * A gateway restart ends every run with the process, and OpenClaw (current\n * main) may continue a plugin's turn session afterwards: a plugin run with\n * no requester is registered under the agent's main session\n * (`src/gateway/server-methods/agent-subagent-registration.ts`), restart\n * resume walks a live subagent session up to that root — the \"subagent\"\n * skip applies to the root, which is the main session, not ours\n * (`src/gateway/session-restart-resume.ts`, `restartResumeSkipReason`) — and\n * wakes it with \"send a fresh instruction to the same retained child\n * session when appropriate\". Tested live: on 2026.11.5-beta.1 a restart\n * during a turn resumed `agent:<id>:main` with the restart text, its context\n * listing the AgentChat turn sessions; 2026.10.9 aborted the run and resumed\n * nothing. So the turns in flight are written to disk (`./turn-store.ts`)\n * and the next start adopts them (`adopt`): each conversation is held for\n * `RESTART_HOLD_MS`, and the after-turn rule is applied to what the ended run\n * did at once and again when the hold expires (an answer it — or the resumed\n * main session — sent records `reply`, so the card is not gated again). A\n * run OpenClaw starts in that turn's session during the hold — seen through\n * the `model_call_started` hook, the public way a plugin sees runs it did not\n * start — keeps the conversation held as a turn of its own: past\n * `TURN_OVERDUE_MS` it is handed off and counts toward `MAX_HUNG_TURNS`, and\n * when it ends it gets the after-turn rule. A stored turn first started more\n * than `STORED_TURN_MAX_AGE_MS` ago is dropped, so a restart storm cannot\n * re-adopt it forever. Not covered (accepted): a continuation that starts\n * after the hold, when the conversation may have been gated again; the wake\n * text AgentChat serves for OpenClaw is to tell the agent not to resume an\n * AgentChat turn after a restart (a server change). A plugin reload waits for the runs (OpenClaw drains a plugin's\n * admitted work first, and every turn holds it until it ends).\n */\n\nimport { integration, type InboxCard, type TrayInvite } from 'agentchatme'\n\nimport type { Logger } from '../log.js'\nimport { cardFromStored, type AfterTurnRecorder } from './after-turn.js'\nimport { KEEP_ENDED_MS, storedCard, type StoredTurn, type TurnStore } from './turn-store.js'\n\n/** A turn running longer than this is handed off and reported (the kit's threshold). */\nexport const TURN_OVERDUE_MS = 30 * 60_000\n\n/**\n * A wait that elapses comes back a few milliseconds early, so the sixth\n * 5-minute \"still running\" report lands at 29:59.9: the threshold allows\n * that much (seen live — without it the hand-off slipped to 35 minutes).\n */\nexport const OVERDUE_SLACK_MS = 5_000\n\n/** Whether a turn this old is past `TURN_OVERDUE_MS` (with the wait's slack). */\nexport function isOverdue(elapsedMs: number): boolean {\n return elapsedMs + OVERDUE_SLACK_MS >= TURN_OVERDUE_MS\n}\n\n/** Hung turns held at once before the account stops gating (each holds one conversation). */\nexport const MAX_HUNG_TURNS = 2\n\n/** OpenClaw's run deadline when `agents.defaults.timeoutSeconds` is unset (`src/agents/timeout.ts`: 48 h). */\nexport const OPENCLAW_DEFAULT_RUN_TIMEOUT_SECONDS = 2880 * 60\n\n/**\n * After a restart, how long a conversation whose turn the restart ended stays\n * held when nothing continues that turn's session. OpenClaw's restart resume\n * wakes the main session at boot; this covers its decision to send the turn\n * session a fresh instruction (seen at the run's first model call).\n */\nexport const RESTART_HOLD_MS = 3 * 60_000\n\n/** A stored turn first started longer ago than this is dropped, not adopted again (a restart storm). */\nexport const STORED_TURN_MAX_AGE_MS = 24 * 60 * 60_000\n\n/** reply: a conversation; invite: a group invite; run: the one run of a gate-off cycle. */\nexport type TurnKind = 'reply' | 'invite' | 'run'\n\n/** One OpenClaw run started for the account. */\nexport interface RunRecord {\n readonly runId: string\n readonly kind: TurnKind\n /** The conversation id (reply), the invite id (invite), or the run id (a gate-off run). */\n readonly id: string\n /** The message the gate's verdict read through (reply turns). */\n readonly anchor: string | null\n readonly sessionKey: string\n /** Local clock, ms. */\n readonly startedAt: number\n /** The loop that started it. */\n readonly owner: string\n /** reply: the card the gate decided on and its category — what the after-turn rule compares. */\n readonly card?: InboxCard\n readonly category?: string | null\n /** invite: the invite the turn was for. */\n readonly invite?: TrayInvite\n /** When the first turn of this chain started: a turn continued after a restart keeps its original's (stored turns age out by it). */\n readonly firstStartedAt?: number\n}\n\nexport type ReleaseResult =\n | { readonly released: true; readonly what: 'hung' | 'running' | 'restart'; readonly key: string; readonly runId: string | null }\n | { readonly released: false; readonly reason: string }\n\n/** Watches a run this process did not start until OpenClaw reports it ended; null when it cannot say. */\nexport type RunWatcher = (record: RunRecord) => Promise<integration.TurnEnd | null>\n\n/** The AgentChat calls an ended run made, from its transcript; null when unknown. */\nexport type CallReader = (sessionKey: string, runId: string) => Promise<integration.AgentChatCallCount | null>\n\nexport interface TurnsWiring {\n /** Applies the after-turn rule to a turn that ended outside the kit's watch. */\n readonly recorder?: AfterTurnRecorder\n /** Where the turns in flight are written (the restart defense). */\n readonly store?: TurnStore\n readonly watch?: RunWatcher\n readonly readCalls?: CallReader\n readonly logger?: Logger\n}\n\ninterface LiveLoop {\n readonly owner: string\n readonly wake: () => void\n /**\n * Runs `fn` in the async context the loop was created in. A release comes\n * in through a gateway RPC (`agentchat.release`); work it starts — the\n * wake's next cycle, a waiting turn admitted into the freed slot — must not\n * inherit that request's context, which OpenClaw retires when the RPC\n * returns (\"Gateway caller authority is no longer active\").\n */\n readonly run: <T>(fn: () => T) => T\n}\n\n/**\n * kit: the kit's loop holds it. watch: a run OpenClaw started in an adopted\n * turn's session, held here. hung: handed off, held here. released: let go\n * of; it holds nothing.\n */\ntype RunState = 'kit' | 'watch' | 'hung' | 'released'\n\ninterface Entry {\n readonly record: RunRecord\n state: RunState\n /** The hold this module keeps (hung reply / invite turns, continued runs). */\n handle: integration.TurnHandle | null\n /** When it was handed off. */\n since: number\n /** A gate-off run: ends the cycle that waits on it (the run goes on). */\n readonly letGo?: () => void\n}\n\n/** A turn the last process left in flight, held after a restart. */\ninterface Adopted {\n readonly stored: StoredTurn\n readonly record: RunRecord\n readonly handle: integration.TurnHandle\n readonly until: number\n /** What the ended run did (read once its transcript is): applied at the start and when the hold expires. */\n end: integration.TurnEnd | null\n timer: ReturnType<typeof setTimeout> | null\n}\n\n/** A turn OpenClaw is admitting: whether its kit hold was released meanwhile. */\nexport interface Admission {\n readonly key: string\n released: boolean\n}\n\nconst RESTART_END_DETAIL = 'the gateway restarted during the turn'\n\nfunction trackerKey(kind: TurnKind, id: string): string {\n return kind === 'reply' ? `conversation:${id}` : kind === 'invite' ? `invite:${id}` : `run:${id}`\n}\n\nfunction trackedTurn(record: RunRecord): integration.TrackedTurn | null {\n if (record.kind === 'reply') return { kind: 'reply', conversationId: record.id, anchor: record.anchor }\n if (record.kind === 'invite') return { kind: 'invite', inviteId: record.id }\n return null\n}\n\nfunction storedOf(record: RunRecord): StoredTurn | null {\n if (record.kind === 'run') return null\n return {\n runId: record.runId,\n kind: record.kind,\n id: record.id,\n anchor: record.anchor,\n sessionKey: record.sessionKey,\n startedAt: record.startedAt,\n ...(record.firstStartedAt !== undefined ? { firstStartedAt: record.firstStartedAt } : {}),\n ...(record.category !== undefined ? { category: record.category } : {}),\n ...(record.kind === 'reply' && record.card ? { card: storedCard(record.card, record.anchor) } : {}),\n }\n}\n\nfunction recordOf(stored: StoredTurn): RunRecord {\n return {\n runId: stored.runId,\n kind: stored.kind,\n id: stored.id,\n anchor: stored.anchor,\n sessionKey: stored.sessionKey,\n startedAt: stored.startedAt,\n firstStartedAt: stored.firstStartedAt ?? stored.startedAt,\n owner: 'previous-process',\n ...(stored.category !== undefined ? { category: stored.category } : {}),\n ...(stored.kind === 'reply' && stored.card ? { card: cardFromStored(stored.card as never) } : {}),\n ...(stored.kind === 'invite' ? { invite: { invite_id: stored.id } as TrayInvite } : {}),\n }\n}\n\nexport class AccountTurns {\n /** The kit's tracker for the account, shared by every loop for it. */\n readonly tracker: integration.TurnTracker\n private readonly entries = new Map<string, Entry>()\n /** Turns the last process left in flight, by session key. */\n private readonly adopted = new Map<string, Adopted>()\n /** Turns OpenClaw is admitting right now. */\n private readonly admitting = new Set<Admission>()\n /** Ended runs still written to the store (`KEEP_ENDED_MS`). */\n private readonly kept = new Map<string, { readonly turn: StoredTurn; readonly endedAt: number }>()\n private keptTimer: ReturnType<typeof setTimeout> | null = null\n private live: LiveLoop | null = null\n private wiring: TurnsWiring = {}\n /** Which OpenClaw lane new turns go to; moves on at every hand-off (a hung run blocks its lane). */\n private lane = 0\n private readonly now: () => number\n\n constructor(options: { now?: () => number } = {}) {\n this.now = options.now ?? Date.now\n this.tracker = new integration.TurnTracker({ now: this.now })\n // A kit hold released while OpenClaw is still admitting its run: that run\n // starts out let go of (`started`), so it can never release a newer\n // turn's hold on the same conversation.\n this.tracker.onRelease((handle) => {\n for (const admission of this.admitting) if (admission.key === handle.key) admission.released = true\n })\n }\n\n /** The account's after-turn recorder, store and run watcher (each account start; the latest wins). */\n configure(wiring: TurnsWiring): void {\n this.wiring = { ...this.wiring, ...wiring }\n }\n\n /** The loop now receiving for the account; a held run that ends wakes it. `run` = the loop's own async context (default: as called). */\n setLive(owner: string, wake: () => void, run: <T>(fn: () => T) => T = (fn) => fn()): void {\n this.live = { owner, wake, run }\n }\n\n clearLive(owner: string): void {\n if (this.live?.owner === owner) this.live = null\n }\n\n /** A turn is about to be admitted by OpenClaw: watch whether its kit hold is released meanwhile. */\n admission(kind: 'reply' | 'invite', id: string): Admission {\n const admission: Admission = { key: trackerKey(kind, id), released: false }\n this.admitting.add(admission)\n return admission\n }\n\n /** OpenClaw refused the turn: nothing to watch. */\n admitted(admission: Admission): void {\n this.admitting.delete(admission)\n }\n\n /**\n * A run OpenClaw admitted. `letGo` (gate-off runs): ends the cycle waiting\n * on it when it is handed off or released. `admission`: a turn whose kit\n * hold was released during admission starts out let go of.\n */\n started(record: RunRecord, options: { letGo?: () => void; admission?: Admission } = {}): void {\n const releasedMeanwhile = options.admission?.released === true\n if (options.admission) this.admitting.delete(options.admission)\n this.entries.set(record.runId, {\n record,\n state: releasedMeanwhile ? 'released' : 'kit',\n handle: null,\n since: 0,\n ...(options.letGo ? { letGo: options.letGo } : {}),\n })\n this.persist()\n }\n\n run(runId: string): RunRecord | undefined {\n return this.entries.get(runId)?.record\n }\n\n /** Where the run stands (`null`: not a run of this account, or ended). */\n stateOf(runId: string): RunState | null {\n return this.entries.get(runId)?.state ?? null\n }\n\n /** Every run OpenClaw has not reported ended that still holds something, oldest first. */\n runningRuns(): RunRecord[] {\n return [...this.entries.values()]\n .filter((entry) => entry.state !== 'released')\n .map((entry) => entry.record)\n .sort((a, b) => a.startedAt - b.startedAt)\n }\n\n hungRuns(): RunRecord[] {\n return [...this.entries.values()].filter((entry) => entry.state === 'hung').map((entry) => entry.record)\n }\n\n get hungCount(): number {\n let count = 0\n for (const entry of this.entries.values()) if (entry.state === 'hung') count += 1\n return count\n }\n\n /** The handed-off gate-off run still going, if any: no new run starts while it lives. */\n hungSingleRun(): RunRecord | null {\n for (const entry of this.entries.values()) if (entry.state === 'hung' && entry.record.kind === 'run') return entry.record\n return null\n }\n\n /** Conversations (and invites) held after a restart: adopted (until when), or continued by a run OpenClaw started. */\n restartHolds(): Array<{ readonly record: RunRecord; readonly until: number | null; readonly watching: string | null }> {\n const holds: Array<{ readonly record: RunRecord; readonly until: number | null; readonly watching: string | null }> = [...this.adopted.values()].map((a) => ({\n record: a.record,\n until: a.until,\n watching: null,\n }))\n for (const entry of this.entries.values()) if (entry.state === 'watch') holds.push({ record: entry.record, until: null, watching: entry.record.runId })\n return holds\n }\n\n /** The lane generation new turns start on (`integrationLane(accountId, laneGeneration)`). */\n get laneGeneration(): number {\n return this.lane\n }\n\n /**\n * OpenClaw reported the run ended (`end`: what it did, when known). A turn\n * held here (handed off, or continued after a restart) gets the after-turn\n * rule, then its hold drops and the live loop is woken. A turn the kit\n * still holds is the kit's to record; the live loop is woken once the card\n * is free, only when an earlier loop started it. A run let go of records\n * nothing.\n */\n async ended(runId: string, end?: integration.TurnEnd): Promise<void> {\n const entry = this.entries.get(runId)\n if (!entry) return\n this.entries.delete(runId)\n if (entry.state !== 'released') this.keep(entry.record)\n else this.persist()\n if (entry.state === 'hung' || entry.state === 'watch') {\n try {\n if (end && this.wiring.recorder && entry.record.kind !== 'run') await this.wiring.recorder(entry.record, end)\n } finally {\n if (entry.handle) this.tracker.end(entry.handle)\n this.live?.wake()\n }\n return\n }\n if (entry.state === 'released' || entry.record.kind === 'run') return\n if (!this.live || this.live.owner === entry.record.owner) return\n this.wakeWhenFree(trackerKey(entry.record.kind, entry.record.id))\n }\n\n /**\n * Hand a long run off, once, by run id: release the kit's slot for it (its\n * loop records nothing for it and may start other turns) and hold the\n * conversation here until the run ends. A gate-off run: the cycle waiting\n * on it is let go of. A continued run is already held here: it becomes\n * hung (counted toward `MAX_HUNG_TURNS`). Returns the record when it was\n * handed off now; null when it was already handed off or let go of.\n */\n handOff(runId: string): RunRecord | null {\n const entry = this.entries.get(runId)\n if (!entry || (entry.state !== 'kit' && entry.state !== 'watch')) return null\n const record = entry.record\n entry.since = this.now()\n if (entry.state === 'watch') {\n // Its own session, not one of our lanes; its hold is ours already.\n entry.state = 'hung'\n this.live?.wake()\n return record\n }\n // OpenClaw serializes a lane: the next turn must not queue behind this\n // run. Moved first — the release below can admit a waiting turn at once.\n this.lane += 1\n entry.state = 'hung'\n const turn = trackedTurn(record)\n if (turn === null) {\n entry.letGo?.()\n } else {\n this.tracker.release(trackerKey(record.kind, record.id))\n entry.handle = this.tracker.begin(turn)\n if (!entry.handle) entry.state = 'released'\n }\n this.live?.wake()\n return entry.state === 'hung' ? record : null\n }\n\n /**\n * An operator lets go of a conversation's (or invite's) turn: a hung hold,\n * a restart hold, or — past `TURN_OVERDUE_MS`, or with `force` — a turn\n * still running. Its run may still be live and answer: a second reply is\n * then possible, which is why a turn under 30 minutes (most likely still\n * working) is refused without `force`. A gate-off run always needs\n * `force`: it reads the whole tray, so a new run would answer the same\n * cards while it may still be going.\n */\n release(id: string, options: { force?: boolean } = {}): ReleaseResult {\n const live = this.live\n return live ? live.run(() => this.releaseNow(id, options.force === true)) : this.releaseNow(id, options.force === true)\n }\n\n private releaseNow(id: string, force: boolean): ReleaseResult {\n const matches = (record: RunRecord) => record.id === id || record.runId === id\n for (const entry of this.entries.values()) {\n if (entry.state !== 'hung' || !matches(entry.record)) continue\n if (entry.record.kind === 'run' && !force) return this.refuseSingleRun(entry.record)\n entry.state = 'released'\n if (entry.handle) this.tracker.end(entry.handle)\n entry.handle = null\n this.persist()\n this.live?.wake()\n return { released: true, what: 'hung', key: trackerKey(entry.record.kind, entry.record.id), runId: entry.record.runId }\n }\n for (const [sessionKey, adopted] of this.adopted) {\n if (adopted.record.id !== id) continue\n this.finishAdopted(sessionKey)\n return { released: true, what: 'restart', key: trackerKey(adopted.record.kind, adopted.record.id), runId: null }\n }\n for (const entry of this.entries.values()) {\n if ((entry.state !== 'kit' && entry.state !== 'watch') || !matches(entry.record)) continue\n const refused = this.refuseYoung(entry.record.kind, entry.record.id, entry.record.startedAt, force)\n if (refused) return refused\n const key = trackerKey(entry.record.kind, entry.record.id)\n if (entry.state === 'watch') {\n if (entry.handle) this.tracker.end(entry.handle)\n entry.handle = null\n } else {\n // The released run may still be going in its lane: new turns move on\n // (first — the release can admit a waiting turn at once).\n this.lane += 1\n if (entry.record.kind === 'run') entry.letGo?.()\n else this.tracker.release(key)\n }\n entry.state = 'released'\n this.persist()\n this.live?.wake()\n return { released: true, what: 'running', key, runId: entry.record.runId }\n }\n // Held by the kit with no run behind it yet (admitted, or waiting for a slot).\n for (const held of this.tracker.running()) {\n const heldId = held.kind === 'reply' ? held.conversationId : held.inviteId\n if (heldId !== id) continue\n const refused = this.refuseYoung(held.kind, heldId, held.startedAt, force)\n if (refused) return refused\n this.lane += 1\n const key = trackerKey(held.kind, heldId)\n if (this.tracker.release(key)) {\n this.live?.wake()\n return { released: true, what: 'running', key, runId: null }\n }\n }\n return { released: false, reason: `no turn holds ${id}` }\n }\n\n private refuseYoung(kind: TurnKind, id: string, startedAt: number, force: boolean): ReleaseResult | null {\n const age = this.now() - startedAt\n if (force || age >= TURN_OVERDUE_MS) return null\n return {\n released: false,\n reason: `the turn for ${whatOf(kind, id)} has run ${Math.floor(age / 60_000)} min — under ${TURN_OVERDUE_MS / 60_000} min it is most likely still working, and releasing it lets the conversation be gated again while that run can still send its answer (the peer would get two replies); wait, or repeat with --force`,\n }\n }\n\n private refuseSingleRun(record: RunRecord): ReleaseResult {\n return {\n released: false,\n reason: `${whatOf('run', record.runId)} has run ${Math.floor((this.now() - record.startedAt) / 60_000)} min and reads the whole tray — releasing it lets a new run answer the same cards while this one may still be going (the peers would get two replies); repeat with --force`,\n }\n }\n\n /**\n * Adopt the turns the last process left in flight (the store). Each one's\n * conversation (or invite) is held at once — before the loop's first gate —\n * for `RESTART_HOLD_MS`; the after-turn rule is applied to what the ended\n * run did now and again when the hold expires. A run OpenClaw starts in the\n * turn's session meanwhile (`observeRun`) takes the hold over. A turn first\n * started more than `STORED_TURN_MAX_AGE_MS` ago is dropped. Returns what\n * was adopted.\n */\n adopt(stored: readonly StoredTurn[] = this.wiring.store?.load() ?? []): RunRecord[] {\n const adopted: RunRecord[] = []\n const now = this.now()\n for (const turn of stored) {\n // Still running in this process (an account restart, not a gateway restart).\n if (this.entries.has(turn.runId) || this.adopted.has(turn.sessionKey) || this.kept.has(turn.runId)) continue\n const first = turn.firstStartedAt ?? turn.startedAt\n if (now - first > STORED_TURN_MAX_AGE_MS) {\n this.wiring.logger?.info({ runId: turn.runId, [turn.kind === 'reply' ? 'conversationId' : 'inviteId']: turn.id }, 'a stored turn older than a day was dropped, not adopted again')\n continue\n }\n const record = recordOf(turn)\n const tracked = trackedTurn(record)\n const handle = tracked ? this.tracker.begin(tracked) : null\n if (!handle) continue\n const entry: Adopted = { stored: { ...turn, firstStartedAt: first }, record, handle, until: now + RESTART_HOLD_MS, end: null, timer: null }\n this.adopted.set(turn.sessionKey, entry)\n entry.timer = setTimeout(() => this.expireAdopted(turn.sessionKey, entry), RESTART_HOLD_MS)\n entry.timer.unref?.()\n adopted.push(record)\n void this.recordRestartEnded(entry)\n }\n this.persist()\n return adopted\n }\n\n /**\n * A run started in some session (the `model_call_started` hook). One in\n * the session of a turn adopted after a restart is OpenClaw continuing\n * that turn: it takes the hold over as a turn of its own (`watch`), handed\n * off past `TURN_OVERDUE_MS` like any other.\n */\n observeRun(runId: string, sessionKey: string | undefined): void {\n if (!sessionKey || this.entries.has(runId)) return\n const adopted = this.adopted.get(sessionKey)\n if (!adopted) return\n this.adopted.delete(sessionKey)\n if (adopted.timer) clearTimeout(adopted.timer)\n const record: RunRecord = { ...adopted.record, runId, startedAt: this.now(), owner: 'restart' }\n this.entries.set(runId, { record, state: 'watch', handle: adopted.handle, since: 0 })\n this.persist()\n this.wiring.logger?.info(\n { runId, sessionKey, [record.kind === 'reply' ? 'conversationId' : 'inviteId']: record.id },\n 'OpenClaw continued a turn session after the restart — its conversation stays held until that run ends',\n )\n void this.watchContinued(record)\n }\n\n private async watchContinued(record: RunRecord): Promise<void> {\n let end: integration.TurnEnd | null = null\n try {\n end = this.wiring.watch ? await this.wiring.watch(record) : null\n } catch {\n end = null\n }\n // null: the plugin runtime is gone — the hold stays (nothing in this\n // process starts a second turn for it).\n if (end === null) return\n await this.ended(record.runId, end)\n }\n\n private async recordRestartEnded(adopted: Adopted): Promise<void> {\n const { record } = adopted\n let calls: integration.AgentChatCallCount | null = null\n try {\n calls = this.wiring.readCalls ? await this.wiring.readCalls(record.sessionKey, record.runId) : null\n } catch {\n calls = null\n }\n adopted.end = { status: 'failed', agentchatCalls: calls, detail: RESTART_END_DETAIL }\n if (this.adopted.get(record.sessionKey) !== adopted || !this.wiring.recorder) return\n await this.wiring.recorder(record, adopted.end)\n }\n\n /**\n * The hold expired with nothing continuing the turn: the after-turn rule\n * once more — the resumed main session may have answered the card\n * meanwhile — then the conversation is free.\n */\n private expireAdopted(sessionKey: string, adopted: Adopted): void {\n if (this.adopted.get(sessionKey) !== adopted) return // taken over by a continued run, or released\n void (async () => {\n try {\n if (this.wiring.recorder) await this.wiring.recorder(adopted.record, adopted.end ?? { status: 'failed', agentchatCalls: null, detail: RESTART_END_DETAIL })\n } catch {\n // the recorder never rejects; a failure leaves the card to the server's re-wake\n }\n if (this.adopted.get(sessionKey) === adopted) this.finishAdopted(sessionKey)\n })()\n }\n\n private finishAdopted(sessionKey: string): void {\n const adopted = this.adopted.get(sessionKey)\n if (!adopted) return\n this.adopted.delete(sessionKey)\n if (adopted.timer) clearTimeout(adopted.timer)\n this.tracker.end(adopted.handle)\n this.persist()\n this.live?.wake()\n }\n\n /** An ended run stays in the store a little longer: a restart ends the run before it ends the process. */\n private keep(record: RunRecord): void {\n const turn = storedOf(record)\n if (turn) this.kept.set(record.runId, { turn, endedAt: this.now() })\n this.persist()\n if (!this.keptTimer) this.schedulePrune()\n }\n\n /** The next prune at the oldest kept entry's expiry. */\n private schedulePrune(): void {\n let oldest = Infinity\n for (const kept of this.kept.values()) oldest = Math.min(oldest, kept.endedAt)\n if (oldest === Infinity) return\n this.keptTimer = setTimeout(() => this.pruneKept(), Math.max(0, oldest + KEEP_ENDED_MS - this.now()))\n this.keptTimer.unref?.()\n }\n\n private pruneKept(): void {\n this.keptTimer = null\n const cutoff = this.now() - KEEP_ENDED_MS\n for (const [runId, kept] of this.kept) if (kept.endedAt <= cutoff) this.kept.delete(runId)\n this.persist()\n this.schedulePrune()\n }\n\n private persist(): void {\n const store = this.wiring.store\n if (!store) return\n const turns = new Map<string, StoredTurn>()\n for (const entry of this.entries.values()) {\n if (entry.state === 'released') continue\n const turn = storedOf(entry.record)\n if (turn) turns.set(turn.runId, turn)\n }\n for (const [runId, kept] of this.kept) turns.set(runId, kept.turn)\n for (const adopted of this.adopted.values()) turns.set(adopted.stored.runId, adopted.stored)\n if (!store.write([...turns.values()])) this.wiring.logger?.debug({ file: store.file }, 'turns in flight could not be written (the restart defense is off until the next write)')\n }\n\n private wakeWhenFree(key: string, attempts = 300): void {\n const held = key.startsWith('conversation:') ? this.tracker.conversationRunning(key.slice('conversation:'.length)) : this.tracker.inviteRunning(key.slice('invite:'.length))\n if (!held || attempts <= 0) {\n this.live?.wake()\n return\n }\n const timer = setTimeout(() => this.wakeWhenFree(key, attempts - 1), 100)\n timer.unref?.()\n }\n}\n\nconst accounts = new Map<string, AccountTurns>()\n\n/** The account's turns, created on first use and kept for the process. */\nexport function accountTurns(accountId: string): AccountTurns {\n let turns = accounts.get(accountId)\n if (!turns) {\n turns = new AccountTurns()\n accounts.set(accountId, turns)\n }\n return turns\n}\n\n/** The account's turns when it has any in this process; never creates them. */\nexport function findAccountTurns(accountId: string): AccountTurns | undefined {\n return accounts.get(accountId)\n}\n\n/** The account's kit tracker (shared by every loop for the account). */\nexport function trackerFor(accountId: string): integration.TurnTracker {\n return accountTurns(accountId).tracker\n}\n\n/** Every account with turns in this process. */\nexport function accountsWithTurns(): string[] {\n return [...accounts.keys()]\n}\n\n/** A run started in some session (the `model_call_started` hook): every account looks whether it continues an adopted turn. */\nexport function observeRunStarted(runId: unknown, sessionKey: unknown): void {\n if (typeof runId !== 'string' || runId.length === 0 || typeof sessionKey !== 'string' || sessionKey.length === 0) return\n for (const turns of accounts.values()) turns.observeRun(runId, sessionKey)\n}\n\n/** The run deadline OpenClaw applies: `agents.defaults.timeoutSeconds`, its 48 h default, or none (`0`). */\nexport function runDeadline(cfg: unknown): { readonly seconds: number; readonly configured: boolean } {\n const value = (cfg as { agents?: { defaults?: { timeoutSeconds?: unknown } } } | undefined)?.agents?.defaults?.timeoutSeconds\n if (typeof value === 'number' && Number.isFinite(value) && value >= 0) return { seconds: Math.floor(value), configured: true }\n return { seconds: OPENCLAW_DEFAULT_RUN_TIMEOUT_SECONDS, configured: false }\n}\n\nfunction whatOf(kind: TurnKind, id: string): string {\n return kind === 'reply' ? `conversation ${id}` : kind === 'invite' ? `invite ${id}` : `the gate-off run ${id}`\n}\n\nfunction deadlineText(cfg: unknown): string {\n const deadline = runDeadline(cfg)\n return deadline.seconds === 0\n ? 'agents.defaults.timeoutSeconds is 0 (no deadline), so it may never end'\n : `OpenClaw ends it at its run deadline, agents.defaults.timeoutSeconds = ${deadline.seconds}${deadline.configured ? '' : \" (OpenClaw's default, 48 h)\"}`\n}\n\n/**\n * The operator line for a turn that has run past `TURN_OVERDUE_MS`: which\n * conversation (or invite) it holds, for how long, and what ends it.\n */\nexport function overdueTurnLine(turn: { readonly kind: TurnKind; readonly id: string; readonly elapsedMs: number }, cfg: unknown): string {\n const minutes = Math.round(turn.elapsedMs / 60_000)\n if (turn.kind === 'run') {\n return `${whatOf(turn.kind, turn.id)} has run ${minutes} min — no new run starts until it ends (one run reads the whole tray); ${deadlineText(cfg)}`\n }\n return `a turn for ${whatOf(turn.kind, turn.id)} has run ${minutes} min — that conversation stays held (no second reply) until the run ends; ${deadlineText(cfg)}; other conversations are not held up by it`\n}\n\n/** One line per run past the threshold (status, doctor). */\nexport function overdueTurnLines(runs: readonly RunRecord[], cfg: unknown, now: number = Date.now()): string[] {\n return runs.filter((run) => now - run.startedAt > TURN_OVERDUE_MS).map((run) => overdueTurnLine({ kind: run.kind, id: run.id, elapsedMs: now - run.startedAt }, cfg))\n}\n\n/** One line per conversation held after a gateway restart (status, doctor, the start log). */\nexport function restartHoldLines(turns: AccountTurns, now: number = Date.now()): string[] {\n return turns.restartHolds().map(({ record, until, watching }) =>\n watching || until === null\n ? `${whatOf(record.kind, record.id)} is held: OpenClaw continued its turn's session after the gateway restart (run ${watching ?? 'unknown'}) — gated again once that run ends (handed off like any turn past 30 min)`\n : `${whatOf(record.kind, record.id)} is held for ${Math.max(0, Math.ceil((until - now) / 60_000))} more min: its turn was running when the gateway restarted, and OpenClaw may continue that turn's session`,\n )\n}\n\n/**\n * Readiness while handed-off runs block the account: a gate-off run still\n * going (no new run while it lives), or too many hung turns. Why nothing is\n * gated, and what to do; null when nothing blocks.\n */\nexport function hungTurnsReason(turns: AccountTurns, cfg: unknown, now: number = Date.now()): string | null {\n const single = turns.hungSingleRun()\n if (single) {\n return `${whatOf('run', single.runId)} has run ${Math.floor((now - single.startedAt) / 60_000)} min and is still going in OpenClaw — no new run starts while it lives (one run reads the whole tray; a second would answer the same cards), so the cards wait on the tray; ${deadlineText(cfg)}. \\`openclaw agentchat release ${single.runId} --force\\` lets a new run start (the old one may still answer)`\n }\n if (turns.hungCount < MAX_HUNG_TURNS) return null\n const held = turns\n .hungRuns()\n .map((run) => `${whatOf(run.kind, run.id)} for ${Math.floor((now - run.startedAt) / 60_000)} min`)\n .join(', ')\n return `${turns.hungCount} turns are hung in OpenClaw (${held}) — no gate calls until one ends, so other cards are waiting on the tray; ${deadlineText(cfg)}. \\`openclaw agentchat release <conversation_id>\\` lets go of one (its run may still answer, so a second reply is possible), or restart the gateway`\n}\n\n/** Test hook only. */\nexport function resetRunningTurnsForTest(): void {\n accounts.clear()\n}\n","/**\n * `openclaw agentchat release <conversation_id>` — the operator's way to let\n * go of a turn OpenClaw never reports as ended.\n *\n * A turn holds its conversation until its run ends, so a run that hangs keeps\n * that conversation from being answered again (no second reply), and after\n * two hung turns the account stops gating. OpenClaw offers a plugin no abort\n * for a subagent run, so the release does not end the run: it lets the\n * conversation be gated again. If the run is in fact still alive and answers\n * later, the peer can get a second reply — the operator's call, and the\n * command says so.\n *\n * A turn under 30 minutes is most likely still working, so the command\n * refuses it unless `--force` is given: released, its conversation could be\n * gated again while the run can still send its answer — two replies. A hung\n * turn (handed off past 30 minutes) and a conversation held after a gateway\n * restart are released without it.\n *\n * Two halves, because the CLI is a separate process from the gateway that\n * holds the turns: a gateway method (`agentchat.release`, operator-admin\n * scope) registered in the gateway, and the CLI command that calls it over\n * the gateway's own RPC (`callGatewayFromCli`, the plugin SDK's helper, which\n * reads the gateway URL and token the same way `openclaw gateway call` does).\n */\n\nimport type { OpenClawPluginApi } from 'openclaw/plugin-sdk/core'\n\nimport { TURN_OVERDUE_MS, findAccountTurns, type ReleaseResult } from '../integration/running.js'\nimport { AGENTCHAT_CHANNEL_ID } from '../channel-account.js'\n\nexport const RELEASE_METHOD = 'agentchat.release'\n\ntype ReleaseParams = { readonly id?: unknown; readonly accountId?: unknown; readonly force?: unknown }\n\n/** The gateway half: release the turn holding `id` (a conversation, invite or run id) for the account. Never creates account state. */\nexport function releaseTurnFor(params: ReleaseParams): { ok: true; result: ReleaseResult } | { ok: false; error: string } {\n const id = typeof params.id === 'string' ? params.id.trim() : ''\n if (!id) return { ok: false, error: 'a conversation (or invite) id is required' }\n const accountId = typeof params.accountId === 'string' && params.accountId.trim() ? params.accountId.trim() : 'default'\n const turns = findAccountTurns(accountId)\n if (!turns) return { ok: true, result: { released: false, reason: `the AgentChat account \"${accountId}\" has no turns in this gateway` } }\n return { ok: true, result: turns.release(id, { force: params.force === true }) }\n}\n\nexport function registerReleaseGatewayMethod(api: Pick<OpenClawPluginApi, 'registerGatewayMethod'>): void {\n api.registerGatewayMethod(\n RELEASE_METHOD,\n ({ params, respond }) => {\n const outcome = releaseTurnFor(params as ReleaseParams)\n if (!outcome.ok) {\n respond(false, undefined, { code: 'INVALID_REQUEST', message: outcome.error } as never)\n return\n }\n respond(true, outcome.result)\n },\n { scope: 'operator.admin' },\n )\n}\n\nexport function registerReleaseCli(api: Pick<OpenClawPluginApi, 'registerCli'>): void {\n api.registerCli(\n ({ program }) => {\n const root = program.command(AGENTCHAT_CHANNEL_ID).description('The AgentChat integration')\n const release = root\n .command('release <id>')\n .description(\n `Let go of the turn holding a conversation (or invite) whose OpenClaw run never ended. The run is not stopped: if it answers later, the peer can get a second reply. A turn under ${TURN_OVERDUE_MS / 60_000} minutes is refused without --force.`,\n )\n .option('--account <accountId>', 'the AgentChat account', 'default')\n .option('--force', `release a turn that has run under ${TURN_OVERDUE_MS / 60_000} minutes (it is most likely still working: two replies are possible)`)\n .option('--url <url>', 'gateway URL (default: the configured gateway)')\n .option('--token <token>', 'gateway token (default: the configured one)')\n .option('--json', 'print the raw result')\n .action(async (id: string, opts: { account?: string; url?: string; token?: string; json?: boolean; force?: boolean }) => {\n // Loaded only when the command runs: the gateway runtime is OpenClaw's.\n const { callGatewayFromCli } = await import('openclaw/plugin-sdk/gateway-runtime')\n const result = (await callGatewayFromCli(\n RELEASE_METHOD,\n { ...(opts.url ? { url: opts.url } : {}), ...(opts.token ? { token: opts.token } : {}), ...(opts.json ? { json: true } : {}) },\n { id, accountId: opts.account ?? 'default', ...(opts.force ? { force: true } : {}) },\n )) as { released?: boolean; what?: string; reason?: string }\n process.stdout.write(opts.json ? `${JSON.stringify(result)}\\n` : `${releaseLine(id, result)}\\n`)\n })\n void release\n },\n {\n commands: [AGENTCHAT_CHANNEL_ID],\n descriptors: [{ name: AGENTCHAT_CHANNEL_ID, description: 'The AgentChat integration (release a hung turn)', hasSubcommands: true }],\n },\n )\n}\n\n/** What the command prints. */\nexport function releaseLine(id: string, result: { released?: boolean; what?: string; reason?: string } | null | undefined): string {\n if (!result?.released) return `nothing released: ${result?.reason ?? 'unknown'}`\n if (result.what === 'restart') return `released ${id} (held after a gateway restart) — it may be gated again now`\n const what = result.what === 'hung' ? 'a hung turn' : 'a running turn'\n return `released ${id} (${what}) — it may be gated again now; its OpenClaw run was not stopped, and if it still sends an answer the peer gets two replies`\n}\n","/**\n * Seeing runs the plugin did not start: OpenClaw's `model_call_started`\n * hook (each model call names its run and session). The one use: after a\n * gateway restart, OpenClaw may continue a turn's session on its own (the\n * restart resume asks the agent's main session to \"send a fresh instruction\n * to the same retained child session\"); a run seen in the session of a turn\n * adopted from the last process keeps that conversation held until it ends\n * (`AccountTurns.observeRun`). A third-party plugin has no API that lists\n * live runs, and this hook needs no grant (it is not a conversation-access\n * or prompt hook). An OpenClaw release without the hook ignores it.\n */\n\nimport type { OpenClawPluginApi } from 'openclaw/plugin-sdk/core'\n\nimport { observeRunStarted } from '../integration/running.js'\n\nexport function registerRunObserver(api: Pick<OpenClawPluginApi, 'on'>): void {\n api.on('model_call_started', (event, ctx) => {\n observeRunStarted(event.runId, event.sessionKey ?? ctx?.sessionKey)\n })\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 the receive loop acts on. 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 | unanswered | invite | 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: peer message frames, connects, server wake frames (by reason), invite frames. */\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 * The SDK socket's lifecycle, as OpenClaw reports it — one account.\n *\n * The transport is the SDK's `RealtimeClient`, lifecycle included: HELLO,\n * the reconnect backoff that never gives up (one notice after a long outage,\n * then a wider cap), the handshake and idle watchdogs, the 10–15 min retry\n * of a rejected key, the delivery ack, per-conversation ordering, the\n * reconnect drain. What arrives on it is the kit's receive loop's: it\n * attaches its own handlers to the same client (message frames that are not\n * the agent's own echo, wake frames, invites, every accepted HELLO become\n * one cycle), and connects and disconnects it.\n *\n * This module builds the client with the plugin's options and hands the\n * SDK's lifecycle events to the gateway as they are, for OpenClaw's status\n * and the metrics: connected, closed, blocked, the state, notices. It acts on\n * nothing and sends nothing.\n *\n * HELLO offers `ack`, `heartbeat` and `rewake`: while cards stay unanswered\n * the server re-wakes this socket on its own durable ladder (contract v1,\n * D3), so the integration keeps no retry ladder of its own.\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 verdicts; an early ack never empties the tray.\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} 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'\n\n/**\n * A wake's label for the metric and the log — a closed set: `message` (a\n * peer wrote), `connect` (an accepted HELLO), `reminder` (a deferred\n * conversation came due), `unanswered` (the server's re-wake for cards\n * still waiting), `invite` (a group invite arrived), `other` (a server wake\n * with a reason this version does not know).\n */\nexport type WakeLabel = 'message' | 'connect' | 'reminder' | 'unanswered' | 'invite' | 'other'\n\n/** A server wake frame's `reason` → the fixed label set (the metric label must stay bounded). */\nexport function wakeSourceOf(reason: unknown): WakeLabel {\n if (reason === 'reminder') return 'reminder'\n if (reason === 'unanswered') return 'unanswered'\n return '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 the 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 SocketHandlers {\n /** Once per accepted HELLO (initial + every reconnect). */\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 wakeFrames: 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, contract-v1 capabilities. */\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 // `rewake`: the server re-wakes this socket while cards stay unanswered\n // (contract v1, D3) — the integration keeps no retry ladder of its own.\n // `heartbeat` is offered by default (the idle watchdog's proof of life).\n capabilities: { rewake: 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 /** The SDK client: handed to the receive loop, which connects and disconnects it. */\n readonly realtime: RealtimeClient\n\n private readonly logger: Logger\n private readonly handlers: SocketHandlers\n private readonly metrics: MetricsRecorder\n private readonly now: () => number\n\n /** The SDK's state as last reported through its `state` event. */\n private state: SocketState = 'idle'\n private connectedAt: number | null = null\n private bound = false\n private stopping = false\n private readonly unbind: Array<() => void> = []\n\n private wakeFrames = 0\n private disconnects = 0\n\n constructor(options: IntegrationSocketOptions) {\n this.logger = options.logger.child({ component: 'socket' })\n this.handlers = options.handlers ?? {}\n this.metrics = options.metrics ?? createNoopMetrics()\n this.now = options.now ?? Date.now\n const create = options.createRealtime ?? ((opts: RealtimeOptions) => new RealtimeClient(opts))\n this.realtime = create(realtimeOptionsFor(options.config, { client: options.client, webSocket: options.webSocket }))\n this.metrics.setConnectionState(this.state)\n }\n\n /** Attach the lifecycle handlers. Idempotent. The receive loop connects the client. */\n bind(): void {\n if (this.bound || this.stopping) return\n this.bound = true\n const realtime = this.realtime\n this.unbind.push(\n realtime.on('state', (next, prev) => this.onState(next, prev)),\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.metrics.incWake({ source: 'connect' })\n this.guard('onConnected', () => this.handlers.onConnected?.(at))\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 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 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.\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 // The loop turns a wake frame into a cycle; here it is only labelled\n // by its reason for the log line and the metric.\n realtime.on('wake', (frame: WakeFrame) => {\n this.wakeFrames += 1\n const payload = (frame.payload ?? {}) as { reason?: unknown; conversation_id?: unknown; conversation_ids?: unknown; step?: unknown }\n const conversations = Array.isArray(payload.conversation_ids) ? payload.conversation_ids.length : undefined\n this.metrics.incWake({ source: wakeSourceOf(payload.reason) })\n this.logger.info(\n {\n reason: payload.reason,\n step: payload.step,\n ...(typeof payload.conversation_id === 'string' ? { conversationId: payload.conversation_id } : {}),\n ...(conversations !== undefined ? { conversations } : {}),\n },\n 'wake — server wake frame',\n )\n }),\n )\n }\n\n /** The loop has disconnected the client (or never started it): report `stopped`, detach. Idempotent. */\n stopped(): void {\n this.stopping = true\n this.connectedAt = null\n for (const off of this.unbind.splice(0)) {\n try {\n off()\n } catch {\n // already detached\n }\n }\n if (this.state !== 'stopped') this.onState('stopped', this.state)\n }\n\n getHealth(): SocketHealth {\n return { state: this.state, connectedAt: this.connectedAt, counters: { wakeFrames: this.wakeFrames, disconnects: this.disconnects } }\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 if (this.state === next) return\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. */\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 binding, the receive loop and the served texts so the status\n * adapter can report them, and serializes start/stop per account so a\n * start-during-stop never races.\n *\n * Keying is `accountId`-only; `channelId` is always `\"agentchat\"` here.\n */\n\nimport type { integration } from 'agentchatme'\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 { IntegrationLoop } from '../integration/loop.js'\nimport type { MetricsRecorder } from '../metrics.js'\n\nexport interface IntegrationEntry {\n readonly socket: IntegrationSocket\n readonly loop: IntegrationLoop | null\n /** The served texts as the loop reads them. */\n readonly texts: integration.TextsSource | null\n /** The recorder the socket binding and the loop 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\nexport interface BuiltIntegration {\n readonly loop: IntegrationLoop | null\n readonly texts?: integration.TextsSource | null\n /** Stopped after the loop (the texts refresh timer). */\n readonly textsCache?: integration.TextsCache | null\n readonly handlers: SocketHandlers\n}\n\ninterface LiveEntry extends IntegrationEntry {\n readonly textsCache: integration.TextsCache | null\n}\n\nconst registry = new Map<string, LiveEntry>()\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 loop over the socket's SDK client, and the lifecycle handlers for the gateway. */\n readonly build: (socket: IntegrationSocket) => BuiltIntegration\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 what `build` returns and the loop over the\n // socket; a late-bound reference resolves the cycle. Nothing fires\n // before `bind()`.\n let built: BuiltIntegration | null = null\n const handlers: SocketHandlers = {\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: LiveEntry = {\n socket,\n loop: built.loop,\n texts: built.texts ?? null,\n textsCache: built.textsCache ?? null,\n metrics: params.socketOptions?.metrics ?? null,\n config: params.config,\n logger: params.logger,\n }\n registry.set(params.accountId, entry)\n socket.bind()\n try {\n // The loop attaches to the socket's client and connects it.\n await built.loop?.loop.start()\n } catch (err) {\n registry.delete(params.accountId)\n await stopEntry(entry)\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: LiveEntry): Promise<void> {\n try {\n // Stops the cycles and disconnects the socket. Runs already admitted\n // are OpenClaw's; they stay registered for the account until they end.\n await entry.loop?.stop()\n } catch (err) {\n entry.logger.error({ err: err instanceof Error ? err.message : String(err) }, 'receive loop stop threw during unregister')\n }\n if (!entry.loop) {\n try {\n entry.socket.realtime.disconnect()\n } catch {\n // never connected\n }\n }\n entry.socket.stopped()\n entry.textsCache?.stop()\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 * How the kit's receive loop starts a turn on OpenClaw.\n *\n * The loop (gate-call mode) decides which conversations and invites get a\n * turn, composes the prompt from the served texts, and holds the card in\n * its tracker while the turn runs; this adapter runs the turn as one\n * OpenClaw agent run (`runtime.subagent.run`, `deliver: false`, a fresh\n * session, the account's lane) and reports its end in the kit's terms once\n * OpenClaw has confirmed it (`./run.ts`):\n *\n * - `ok` → `completed`, with the AgentChat calls the\n * run made (from its transcript; null = unknown)\n * - `error`, `timeout` → `failed` (the run's own deadline is a failure,\n * never an elapsed wait)\n * - the plugin runtime is gone → `still_running` with no `next`: the tracker\n * keeps the conversation, nothing in this process\n * starts a second turn for it\n *\n * A run that never ends keeps holding its conversation: the loop cannot end\n * a turn, and the plugin runtime offers no abort for a subagent run. After\n * 30 minutes the turn is handed off (`AccountTurns.handOff`): the kit's slot\n * is freed so other conversations get turns, while that one stays held until\n * OpenClaw reports the run ended (its run deadline,\n * `agents.defaults.timeoutSeconds`) — then the after-turn rule is applied\n * to it there, with the card the gate saw, which the record carries.\n */\n\nimport type { integration } from 'agentchatme'\n\nimport type { Logger } from '../log.js'\nimport type { TurnOutcome, TurnStarter as RuntimeTurnStarter } from './model.js'\nimport type { AccountTurns } from './running.js'\nimport { integrationLane, inviteSessionKey, wakeSessionKey } from './turn.js'\n\nexport interface LoopTurnStarterOptions {\n readonly accountId: string\n /** The OpenClaw agent the account is routed to. */\n readonly agentId: string\n /** Starts one OpenClaw run and reports its confirmed end (`createRuntimeTurnStarter`). */\n readonly startRun: RuntimeTurnStarter\n /** The account's turns (`accountTurns`): every run is recorded there until OpenClaw reports it ended. */\n readonly turns: AccountTurns\n /** The loop this starter belongs to. */\n readonly owner: string\n readonly logger: Logger\n readonly now?: () => number\n}\n\n/** The kit's `TurnStarter` for OpenClaw. */\nexport function createLoopTurnStarter(options: LoopTurnStarterOptions): integration.TurnStarter {\n const now = options.now ?? Date.now\n return async (request) => {\n const id = request.kind === 'reply' ? request.conversationId : request.invite.invite_id\n const sessionKey = request.kind === 'reply' ? wakeSessionKey(options.agentId, now()) : inviteSessionKey(options.agentId, id, now())\n // Watched from here: if the kit's hold is released while OpenClaw admits\n // the run (an operator's --force), the run starts out let go of.\n const watch = options.turns.admission(request.kind, id)\n const admission = await options.startRun({ sessionKey, prompt: request.prompt, lane: integrationLane(options.accountId, options.turns.laneGeneration) })\n if (!admission.ran) {\n options.turns.admitted(watch)\n return { started: false, error: admission.error }\n }\n options.turns.started({\n runId: admission.runId,\n kind: request.kind,\n id,\n anchor: request.kind === 'reply' ? request.anchor : null,\n sessionKey: admission.sessionKey,\n startedAt: now(),\n owner: options.owner,\n // What the after-turn rule compares when the turn ends outside the\n // kit's watch (handed off, or after a restart).\n ...(request.kind === 'reply' ? { card: request.card, category: request.category } : { invite: request.invite }),\n }, { admission: watch })\n options.logger.info(\n { kind: request.kind, sessionKey, runId: admission.runId, ...(request.kind === 'reply' ? { conversationId: id } : { inviteId: id }) },\n request.kind === 'reply' ? 'turn start' : 'group-invite turn start',\n )\n const done = admission.done.then((outcome): integration.TurnEnd => {\n if (outcome.status === 'gone') {\n options.logger.warn({ sessionKey, runId: outcome.runId }, 'turn end not confirmed: the plugin runtime is gone — its card stays held')\n return { status: 'still_running', detail: 'the plugin runtime is gone' }\n }\n const end = turnEndOf(outcome)\n void options.turns.ended(admission.runId, end)\n options.logger[outcome.status === 'ok' ? 'info' : 'warn'](\n {\n sessionKey,\n runId: outcome.runId,\n status: outcome.status,\n ...(outcome.error ? { error: outcome.error } : {}),\n ...(outcome.elapsedMs !== undefined ? { elapsedMs: outcome.elapsedMs } : {}),\n agentchatCalls: outcome.agentchatCalls ?? null,\n },\n request.kind === 'reply' ? 'turn ended (final text discarded; the send is a hosted-tool call)' : 'group-invite turn ended',\n )\n return end\n })\n return { started: true, done }\n }\n}\n\n/** What OpenClaw reported, as the kit's D5 rule reads it. `ok` without an error is the only completed end. */\nexport function turnEndOf(outcome: TurnOutcome): integration.TurnEnd {\n const agentchatCalls = outcome.agentchatCalls ?? null\n if (outcome.status === 'ok' && !outcome.error) return { status: 'completed', agentchatCalls }\n return { status: 'failed', agentchatCalls, detail: outcome.error ?? `run ended: ${outcome.status ?? 'unknown'}` }\n}\n","/**\n * The receive loop for one account: the SDK kit's `ReceiveLoop`, with what\n * is OpenClaw's plugged in.\n *\n * socket frame / connect / wake frame / invite ──► one cycle per burst ──► tray\n * ──► gate call on the agent's own model (gate-call mode) ──► dismiss / defer at once\n * ──► one OpenClaw run per reply and per invite ──► the after-turn rule (D5)\n *\n * The cycle, the tray read, the gate, which cards a running turn holds, the\n * prompts, and what is recorded after a turn are the kit's. This module\n * supplies the runtime parts: the gate call (`runtime.llm.complete`, tool\n * free), the turn (`./turns.ts` over `runtime.subagent.run`), whether a turn\n * can have the hosted tools (`readiness`), and the log lines and metrics.\n *\n * `AGENTCHAT_REPLY_GATE_ENABLED=0` switches to the kit's single-run mode:\n * one run with the served wake instruction whenever something is owed; the\n * agent judges every card inside it and records its own verdicts.\n */\n\nimport { AsyncLocalStorage } from 'node:async_hooks'\n\nimport { integration, type RealtimeClient } from 'agentchatme'\n\nimport type { Logger } from '../log.js'\nimport type { MetricsRecorder } from '../metrics.js'\nimport { createNoopMetrics } from '../metrics.js'\nimport type { GateModelCall, TurnReadiness, TurnStarter as RuntimeTurnStarter } from './model.js'\nimport { OPENCLAW_TOOL_NAMER, integrationLane, wakeSessionKey } from './turn.js'\nimport { createLoopTurnStarter } from './turns.js'\nimport type { AccountTurns } from './running.js'\n\nexport interface IntegrationLoopOptions {\n readonly accountId: string\n readonly agentId: string\n readonly client: integration.ReceiveLoopClient\n readonly texts: integration.TextsSource\n /** The SDK socket (built by `IntegrationSocket`); the loop connects and disconnects it. `null`: wakes only through `wake()`. */\n readonly socket: RealtimeClient | null\n /** The agent's handle, for the echo filter (learned from the tray when absent). */\n readonly handle?: string | undefined\n readonly callModel: GateModelCall\n readonly startRun: RuntimeTurnStarter\n /** The account's turns, shared with every loop for the account in this process (`accountTurns`). */\n readonly turns: AccountTurns\n readonly logger: Logger\n readonly metrics?: MetricsRecorder\n readonly readiness?: () => TurnReadiness\n /** `false`: single-run mode (no gate call). */\n readonly gateEnabled?: boolean\n /** D5 pacing window (the kit's default 60 s); tests shorten it. */\n readonly paceMs?: number\n readonly quietMs?: number\n readonly maxMs?: number\n readonly now?: () => number\n readonly setTimeout?: (fn: () => void, ms: number) => ReturnType<typeof setTimeout>\n readonly clearTimeout?: (handle: ReturnType<typeof setTimeout>) => void\n}\n\nexport interface IntegrationLoop {\n readonly loop: integration.ReceiveLoop\n /** Stop the loop (it disconnects the socket). Turns already running go on and still have their outcome recorded. */\n stop(): Promise<void>\n}\n\nlet generation = 0\n\nexport function createIntegrationLoop(options: IntegrationLoopOptions): IntegrationLoop {\n const logger = options.logger.child({ component: 'integration', accountId: options.accountId })\n const metrics = options.metrics ?? createNoopMetrics()\n const now = options.now ?? Date.now\n generation += 1\n const owner = `${options.accountId}#${generation}`\n const gateEnabled = options.gateEnabled ?? true\n\n let unreadyReason: string | null = null\n const readiness: integration.Readiness | undefined = options.readiness\n ? () => {\n const ready = options.readiness!()\n if (ready.ready) {\n if (unreadyReason !== null) logger.info({}, 'turns can start again — gating resumes')\n unreadyReason = null\n return ready\n }\n // Logged when the reason changes, not on every wake.\n if (unreadyReason !== ready.reason) logger.warn({ reason: ready.reason }, 'not gating — no turn can start now; the cards wait on the tray')\n unreadyReason = ready.reason\n return ready\n }\n : undefined\n\n const startTurn = createLoopTurnStarter({ accountId: options.accountId, agentId: options.agentId, startRun: options.startRun, turns: options.turns, owner, logger, now })\n\n const loop = new integration.ReceiveLoop({\n client: options.client,\n texts: options.texts,\n mode: gateEnabled ? 'gateCall' : 'singleRun',\n ...(gateEnabled ? { callModel: options.callModel, startTurn } : { startRun: singleRunStarter(options, owner, logger, now) }),\n socket: options.socket,\n ...(options.handle ? { handle: options.handle } : {}),\n toolNamer: OPENCLAW_TOOL_NAMER,\n // One account's turns run on one OpenClaw lane anyway; one slot keeps\n // the rest held out of the gate (no second model call decides them).\n maxConcurrentTurns: 1,\n tracker: options.turns.tracker,\n ...(readiness ? { readiness } : {}),\n ...(options.paceMs !== undefined ? { paceMs: options.paceMs } : {}),\n ...(options.quietMs !== undefined ? { quietMs: options.quietMs } : {}),\n ...(options.maxMs !== undefined ? { maxMs: options.maxMs } : {}),\n now,\n ...(options.setTimeout ? { setTimeout: options.setTimeout } : {}),\n ...(options.clearTimeout ? { clearTimeout: options.clearTimeout } : {}),\n onEvent: (event) => logEvent(event, logger, metrics),\n })\n\n // The account's live loop: a held run that ends (hung, or started by an\n // earlier loop) wakes it, so what arrived meanwhile is gated at once. Work\n // started from outside (an operator's release through a gateway RPC) runs\n // in this loop's own async context, not the caller's.\n const inLoopContext = AsyncLocalStorage.snapshot()\n options.turns.setLive(\n owner,\n () => inLoopContext(() => loop.wake()),\n (fn) => inLoopContext(fn),\n )\n\n return {\n loop,\n async stop() {\n options.turns.clearLive(owner)\n await loop.stop()\n },\n }\n}\n\n/**\n * Single-run mode: one OpenClaw run with the served text; the cycle waits for\n * its confirmed end. The run is recorded with the account's turns, so a run\n * still going after 30 minutes is handed off like a turn: the cycle is let go\n * of (the loop is not stuck in it), but no new run starts while it lives —\n * one run reads the whole tray, a second would answer the same cards\n * (readiness says not-ready too; `openclaw agentchat release <run id>\n * --force` frees it).\n */\nfunction singleRunStarter(options: IntegrationLoopOptions, owner: string, logger: Logger, now: () => number): integration.RunStarter {\n return async (request) => {\n const hung = options.turns.hungSingleRun()\n if (hung) {\n logger.warn({ runId: hung.runId }, 'gate off — a handed-off run is still going; no second run while it lives (the cards wait on the tray)')\n return { status: 'not_started', detail: `the gate-off run ${hung.runId} is still going` }\n }\n const sessionKey = wakeSessionKey(options.agentId, now())\n logger.info({ sessionKey, cards: request.cards, invites: request.invites }, 'gate off — one run with the served wake instruction')\n const admission = await options.startRun({ sessionKey, prompt: request.prompt, lane: integrationLane(options.accountId, options.turns.laneGeneration) })\n if (!admission.ran) return { status: 'not_started', detail: admission.error }\n let letGo: () => void = () => {}\n const handedOff = new Promise<'let_go'>((resolve) => {\n letGo = () => resolve('let_go')\n })\n const { runId } = admission\n options.turns.started({ runId, kind: 'run', id: runId, anchor: null, sessionKey: admission.sessionKey, startedAt: now(), owner }, { letGo })\n const ended = admission.done.then((outcome) => {\n if (outcome.status !== 'gone') void options.turns.ended(runId)\n logger[outcome.status === 'ok' ? 'info' : 'warn']({ sessionKey, runId, status: outcome.status, agentchatCalls: outcome.agentchatCalls ?? null }, 'gate off — run ended')\n return outcome\n })\n const first = await Promise.race([ended, handedOff])\n if (first === 'let_go') {\n logger.warn({ sessionKey, runId }, 'gate off — the run is still going after 30 min; no new run starts until it ends (or `openclaw agentchat release <run id> --force`)')\n return { status: 'failed', detail: 'the run was handed off while still going' }\n }\n return first.status === 'ok' && !first.error ? { status: 'completed' } : { status: 'failed', detail: first.error ?? `run ended: ${first.status ?? 'unknown'}` }\n }\n}\n\n/** One line per loop event, and the wake metric for the sources the socket binding does not count. */\nfunction logEvent(event: integration.ReceiveLoopEvent, logger: Logger, metrics: MetricsRecorder): void {\n switch (event.type) {\n case 'wake':\n // `connect` and wake frames are counted by the socket binding (with their reason).\n if (event.source === 'message') metrics.incWake({ source: 'message' })\n else if (event.source === 'invite') metrics.incWake({ source: 'invite' })\n logger.debug({ source: event.source, ...(event.conversationId ? { conversationId: event.conversationId } : {}) }, 'wake')\n return\n case 'echo':\n logger.debug(event.conversationId ? { conversationId: event.conversationId } : {}, 'own echo — not a wake')\n return\n case 'cycle': {\n const s = event.summary\n const fields = {\n outcome: s.outcome,\n cards: s.cards,\n invites: s.invites,\n reply: s.reply,\n dismiss: s.dismiss,\n defer: s.defer,\n undecided: s.undecided,\n recordFailures: s.recordFailures,\n turnsStarted: s.turnsStarted,\n turnsRefused: s.turnsRefused,\n heldByTurns: s.heldByTurns,\n ...(s.truncated ? { truncated: true } : {}),\n ...(s.failure ? { failure: s.failure } : {}),\n }\n switch (s.outcome) {\n case 'empty':\n logger.info({}, 'tray empty — nothing to decide')\n return\n case 'nothing_owed':\n logger.info(fields, 'nothing new to decide (muted cards, or cards a running turn holds)')\n return\n case 'fail_closed':\n logger.warn(fields, 'gate failed closed — nothing recorded, no turn started; the server re-wakes')\n return\n case 'tray_failed':\n logger.warn(fields, 'tray read failed — the cards stay on the tray; the server re-wakes')\n return\n case 'texts_missing':\n logger.warn(fields, 'served texts not available — not gating; the cards wait on the tray')\n return\n case 'tools_unavailable':\n logger.debug(fields, 'not gating — no turn can start now')\n return\n case 'abandoned':\n logger.warn(fields, 'cycle abandoned — it ran past its deadline; nothing more is done for it, the next wake starts a new one')\n return\n default: {\n const incomplete = s.turnsRefused > 0 || s.recordFailures > 0 || s.undecided > 0\n logger[incomplete ? 'warn' : 'info'](fields, incomplete ? 'gate — some cards were left on the tray; the server re-wakes' : 'gate')\n return\n }\n }\n }\n case 'turn_started':\n return // the turn starter logs it with the OpenClaw session and run\n case 'turn_refused':\n logger.warn({ kind: event.kind, id: event.id, error: event.error }, 'turn not started — nothing recorded; the card stays on the tray')\n return\n case 'turn_outcome': {\n const o = event.outcome\n logger.info(\n { conversationId: o.conversationId, action: o.action, reason: o.reason, recorded: event.recorded, ...(o.action !== 'none' ? { through: o.throughMessageId } : {}) },\n event.recorded ? `${o.action === 'record_reply' ? 'reply' : 'dismiss'} recorded after the turn (${o.reason})` : `nothing recorded after the turn (${o.reason})`,\n )\n return\n }\n case 'invite_outcome':\n logger.info(\n { inviteId: event.outcome.inviteId, action: event.outcome.action, reason: event.outcome.reason, recorded: event.recorded },\n event.recorded ? 'invite dismissed after a second silent turn (left pending)' : `nothing recorded for the invite (${event.outcome.reason})`,\n )\n return\n case 'run':\n return // single-run mode logs the run itself\n case 'error':\n logger.debug({ err: event.error.message }, 'receive loop notice')\n return\n }\n}\n\n/** Cycle outcomes that mean nothing could be decided: repeated, they are an operator's problem. */\nconst TROUBLE_OUTCOMES: ReadonlySet<string> = new Set(['fail_closed', 'tools_unavailable', 'texts_missing', 'abandoned'])\n\n/** How many cycles in a row must end in trouble before status and doctor warn. */\nexport const CYCLE_TROUBLE_RUN = 3\n\nconst TROUBLE_MEANING: Readonly<Record<string, string>> = {\n fail_closed: 'the gate call failed (model unreachable, too slow, or nothing usable)',\n tools_unavailable: 'no turn could have the hosted tools',\n texts_missing: 'the served texts are not available',\n abandoned: 'the cycle ran past its deadline and was abandoned',\n}\n\n/**\n * One operator line when the most recent cycles (`status().recentCycles`,\n * oldest first) ended in trouble at least `CYCLE_TROUBLE_RUN` times in a row,\n * else null. Nothing was gated in those cycles; the cards wait on the tray\n * and AgentChat re-wakes them.\n */\nexport function cycleTroubleLine(recentCycles: ReadonlyArray<{ readonly outcome: string; readonly failure?: string | null; readonly at?: string }>): string | null {\n let run = 0\n for (let i = recentCycles.length - 1; i >= 0 && TROUBLE_OUTCOMES.has(recentCycles[i]!.outcome); i -= 1) run += 1\n if (run < CYCLE_TROUBLE_RUN) return null\n const last = recentCycles[recentCycles.length - 1]!\n const kinds = [...new Set(recentCycles.slice(-run).map((c) => c.outcome))]\n const meaning = kinds.map((k) => TROUBLE_MEANING[k] ?? k).join('; ')\n return `the last ${run} cycles decided nothing (${kinds.join(', ')}): ${meaning}${last.failure ? ` — latest: ${last.failure}` : ''}; the cards wait on the tray and AgentChat re-wakes them`\n}\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 ──► one cycle ──► tray ──► gate ──► one turn per reply ──► after-turn rule\n *\n * everything after the wake is the SDK kit's receive loop, with OpenClaw's\n * parts plugged in (`../integration/loop.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 { Texts } from 'agentchatme'\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 { createIntegrationLoop } from '../integration/loop.js'\nimport { OpenClawTexts, createTextsCache, spellTextsForOpenClaw } from '../integration/texts.js'\nimport { OVERDUE_SLACK_MS, TURN_OVERDUE_MS, accountTurns, hungTurnsReason, isOverdue, overdueTurnLine, restartHoldLines } from '../integration/running.js'\nimport { createAfterTurnRecorder } from '../integration/after-turn.js'\nimport { TurnStore } from '../integration/turn-store.js'\nimport { turnEndOf } from '../integration/turns.js'\nimport { readAgentChatCalls } from '../integration/run.js'\nimport { getPluginRuntime } from '../integration/runtime-holder.js'\nimport { removeOldStateFiles } from '../integration/state.js'\nimport { refreshIdentityLine } from '../integration/placement.js'\nimport {\n createRuntimeModelCall,\n createRuntimeTurnStarter,\n createRunWatcher,\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); the server re-wakes the cards`,\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 /** Which 30-minute mark each long run was last reported at. */\n const overdueWarned = new Map<string, number>()\n /** The account's turns for this process (shared with any later loop for the account). */\n const turns = accountTurns(ctx.accountId)\n /** The \"still running\" report for a run, past 30 minutes: a warn line at each 30-minute mark. */\n const reportOverdue = (runId: string, kind: 'reply' | 'invite' | 'run', id: string, elapsedMs: number, handed: boolean) => {\n const mark = Math.floor((elapsedMs + OVERDUE_SLACK_MS) / TURN_OVERDUE_MS)\n if (!handed && overdueWarned.get(runId) === mark) return\n overdueWarned.set(runId, mark)\n ctx.log?.warn?.(`[agentchat:${ctx.accountId}] ${overdueTurnLine({ kind, id, elapsedMs }, readLiveConfig(ctx.cfg).cfg)}`)\n }\n // A turn that ends outside the kit's watch (handed off, or after a\n // restart) gets the after-turn rule here; the turns in flight are\n // written to disk for the next start (`integration/turn-store.ts`).\n /**\n * A wait elapsed with the run still going — a turn's run, or one OpenClaw\n * continued after a restart. Past 30 minutes it is handed off, once (a\n * released run never again): the account gets its turn slot back, the\n * conversation stays held until the run ends. Reported then, and every\n * further 30 minutes.\n */\n const onStillRunning = ({ runId, sessionKey, elapsedMs }: { runId: string; sessionKey: string; elapsedMs: number }) => {\n const run = turns.run(runId)\n if (turns.stateOf(runId) === 'released') {\n // Let go of by the operator: it holds nothing, and is never handed off again.\n logger.debug({ runId, sessionKey, elapsedMin: Math.round(elapsedMs / 60_000) }, 'released turn still running in OpenClaw — it holds nothing')\n return\n }\n logger.info(\n { runId, sessionKey, elapsedMin: Math.round(elapsedMs / 60_000), ...(run ? { [run.kind === 'reply' ? 'conversationId' : run.kind === 'invite' ? 'inviteId' : 'run']: run.id } : {}) },\n 'turn still running — its conversation stays in flight until OpenClaw reports the run ended',\n )\n if (!run || !isOverdue(elapsedMs)) return\n const handed = turns.handOff(runId) !== null\n reportOverdue(runId, run.kind, run.id, elapsedMs, handed)\n }\n const watchRun = createRunWatcher({ onStillRunning })\n turns.configure({\n recorder: createAfterTurnRecorder({ client, logger }),\n store: new TurnStore(ctx.accountId),\n watch: async (record) => {\n const outcome = await watchRun(record)\n return outcome ? turnEndOf(outcome) : null\n },\n readCalls: (sessionKey, runId) => readAgentChatCalls(getPluginRuntime(), sessionKey, runId),\n logger,\n })\n // Turns the last process left in flight (a gateway restart): held before\n // the first gate, in case OpenClaw continues their sessions.\n turns.adopt()\n for (const line of restartHoldLines(turns)) ctx.log?.warn?.(`[agentchat:${ctx.accountId}] ${line}`)\n\n // The served texts: the kit's cache — the file copy at once, one fetch,\n // then daily (backing off after a failure). Unreachable with nothing\n // cached → the integration starts anyway; nothing is gated until the\n // first copy arrives.\n // Upgrade cleanup: the invite ledger and an old-shape texts cache.\n for (const file of removeOldStateFiles(ctx.accountId)) logger.info({ file }, 'removed a file an earlier release kept (no longer used)')\n const textsCache = createTextsCache({ client, accountId: ctx.accountId, logger })\n const texts = new OpenClawTexts(textsCache)\n const first = await textsCache.start()\n if (first) logger.info({ version: first.version, manual: first.manual?.version, source: textsCache.source }, 'served texts in hand')\n else logger.warn({ err: textsCache.lastError }, 'served texts not available yet (AgentChat unreachable, nothing cached) — nothing is gated until the first copy arrives')\n const handle = config.agentHandle\n if (handle) {\n // The served identity line replaces a placed one that differs (an\n // install upgraded from a release that bundled the line gets the\n // served one on its first start): once from the copy in hand, then on\n // every copy that changes. An absent line is the wizard's / doctor's\n // to place.\n const refresh = (copy: Texts) => {\n const refreshed = refreshIdentityLine(ctx.cfg, ctx.accountId, handle, spellTextsForOpenClaw(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 if (first) refresh(first)\n textsCache.onChange((copy) => refresh(copy))\n }\n\n // One recorder per account for the socket's counters. 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 loop = createIntegrationLoop({\n accountId: ctx.accountId,\n agentId,\n client,\n texts,\n socket: socket.realtime,\n handle: config.agentHandle,\n callModel: createRuntimeModelCall({ agentIdOverride, ...(gateTimeoutMs !== undefined ? { timeoutMs: gateTimeoutMs } : {}) }),\n // A turn holds its conversation until OpenClaw confirms its run\n // ended; a wait that elapses is asked again (`integration/run.ts`).\n startRun: createRuntimeTurnStarter({\n onStillRunning,\n onWaitError: ({ runId, sessionKey, error, attempt, retryInMs }) =>\n logger[attempt === 1 ? 'warn' : 'debug']({ runId, sessionKey, error, attempt, retryInMs }, 'waiting for the turn to end failed — asking OpenClaw again'),\n }),\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 // Too many hung turns: stop gating (each would only add a turn\n // that waits behind them); status and doctor say why.\n const hung = hungTurnsReason(turns, live.cfg)\n if (hung) return { ready: false, reason: hung }\n return turnReadiness({ cfg: live.cfg, apiBase: config.apiBase, apiKey: config.apiKey, live: live.live })\n },\n // The account's runs outlive this loop: a config change restarts\n // the account while its runs go on in OpenClaw, so every loop for\n // the account shares the same turns (and the kit tracker in them).\n turns,\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 loop,\n texts,\n textsCache,\n handlers: {\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 },\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\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 { findAccountTurns, hungTurnsReason, overdueTurnLines, restartHoldLines } from '../integration/running.js'\nimport { cycleTroubleLine } from '../integration/loop.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 /** Turns running past 30 minutes, one operator line each (the conversation, and what ends the run). */\n readonly overdue?: readonly string[]\n /** Set when the most recent cycles decided nothing several times in a row (`recentCycles`). */\n readonly trouble?: string\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 loopStatus = live?.loop?.loop.status()\n const counters = loopStatus\n ? {\n wakes: loopStatus.coalescer.wakes,\n cycles: loopStatus.coalescer.cycles,\n turns: loopStatus.counters.turnsStarted + loopStatus.counters.inviteTurnsStarted + loopStatus.counters.runsStarted,\n }\n : undefined\n const turnsHere = live ? (findAccountTurns(account.accountId) ?? null) : null\n const hungReason = turnsHere ? hungTurnsReason(turnsHere, cfg) : null\n const overdue = turnsHere ? [...(hungReason ? [hungReason] : []), ...overdueTurnLines(turnsHere.runningRuns(), cfg), ...restartHoldLines(turnsHere)] : []\n const trouble = loopStatus ? cycleTroubleLine(loopStatus.recentCycles ?? []) : null\n const servedFrom = live?.texts?.source\n const textsSource: 'server' | 'cache' | 'missing' | undefined = live ? (servedFrom === 'server' || servedFrom === 'cache' ? servedFrom : '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 ...(overdue.length > 0 ? { overdue } : {}),\n ...(trouble ? { trouble } : {}),\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.trouble) lines.push({ text: d.trouble, tone: 'warn' })\n for (const line of d.overdue ?? []) lines.push({ text: line, tone: 'warn' })\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 { getIntegration, listActiveAccounts } from './runtime-registry.js'\nimport { findAccountTurns, hungTurnsReason, overdueTurnLines, restartHoldLines } from '../integration/running.js'\nimport { cycleTroubleLine } from '../integration/loop.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 // A turn the running integration (this process) has held past 30 minutes,\n // or a conversation held after a gateway restart.\n // And cycles that decided nothing several times in a row.\n for (const accountId of listActiveAccounts()) {\n const status = getIntegration(accountId)?.loop?.loop.status()\n if (!status) continue\n const turns = findAccountTurns(accountId)\n if (turns) {\n const hung = hungTurnsReason(turns, cfg)\n if (hung) warnings.push(`[${AGENTCHAT_CHANNEL_ID}:${accountId}] ${hung}`)\n for (const line of [...overdueTurnLines(turns.runningRuns(), cfg), ...restartHoldLines(turns)]) warnings.push(`[${AGENTCHAT_CHANNEL_ID}:${accountId}] ${line}`)\n }\n const trouble = cycleTroubleLine(status.recentCycles ?? [])\n if (trouble) warnings.push(`[${AGENTCHAT_CHANNEL_ID}:${accountId}] ${trouble}`)\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'\nimport { registerReleaseCli, registerReleaseGatewayMethod } from './binding/release.js'\nimport { registerRunObserver } from './binding/run-observer.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 // `openclaw agentchat release <conversation_id>`: the CLI half is\n // registered for every CLI (parse-time metadata), the gateway half only\n // where the integration runs.\n registerCliMetadata: (api) => registerReleaseCli(api),\n registerFull: (api) => {\n registerReleaseGatewayMethod(api)\n registerRunObserver(api)\n },\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","/**\n * Configured-state predicate for the AgentChat channel.\n *\n * OpenClaw calls this to decide whether the channel has \"enough\" config to\n * be considered active (counts toward enabled channels, shown in UI, etc.).\n *\n * Bar: an `apiKey` of plausible length AND a non-empty `agentHandle`.\n * Without the handle the runtime will start but the agent has no identity\n * to add to prompts or to use as a self-filter on inbound — both\n * downstream surfaces silently degrade. Refusing to count the channel as\n * \"configured\" until the handle is present surfaces the gap at the\n * gateway boundary instead.\n */\n\nexport interface MaybeConfigured {\n readonly apiKey?: unknown\n readonly agentHandle?: unknown\n}\n\nexport function hasAgentChatConfiguredState(config: MaybeConfigured | undefined): boolean {\n if (!config || typeof config !== 'object') return false\n const key = config.apiKey\n if (typeof key !== 'string' || key.length < 20) return false\n const handle = config.agentHandle\n if (typeof handle !== 'string' || handle.trim().length === 0) return false\n return true\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/channel-account.ts","../src/errors.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/run.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/integration/after-turn.ts","../src/integration/turn-store.ts","../src/integration/running.ts","../src/binding/release.ts","../src/binding/run-observer.ts","../src/log.ts","../src/metrics.ts","../src/integration/socket.ts","../src/binding/runtime-registry.ts","../src/integration/turns.ts","../src/integration/loop.ts","../src/binding/gateway.ts","../src/binding/status.ts","../src/binding/doctor.ts","../src/channel.ts","../src/channel.setup.ts","../src/configured-state.ts"],"names":["accounts","AgentChatClient","message","AgentChatError","RateLimitedError","generation","API_KEY_ENV","DEFAULT_API_BASE","integration","asRecord","resolveOpenClawStateDir","path","fs","resolveBoundAgentId","resolveOpenClawDefaultAgentId","removeAgentsAnchor","agentsAnchorPath","hasAgentsAnchorFor","writeAgentsAnchor","describe","readAgentsAnchor","path2","fs2","path3","cache","fs3","HANDLE_PATTERN","isValidHandleShape","current","patched","WizardCancelledError","readApiKeyFromEnv","setSetupChannelEnabled","z","outcome","recorded","path4","fs4","pino","registry","RealtimeClient","AsyncLocalStorage","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;AAC7B,IAAM,4BAAA,GAA+B;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,QAAA,EAAAA,SAAAA,EAAS,GAAI,OAAA;AACr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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;AAYO,IAAM,wBAEToD,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,CAAA;AAAA;AAAA;AAAA;AAAA,EAIjD,mBAAA,EAAqB,CAAC,GAAA,KAAQ,kBAAA,CAAmB,GAAG,CAAA;AAAA,EACpD,YAAA,EAAc,CAAC,GAAA,KAAQ;AACrB,IAAA,4BAAA,CAA6B,GAAG,CAAA;AAChC,IAAA,mBAAA,CAAoB,GAAG,CAAA;AAAA,EACzB;AACF,CAAC;AC/iBM,IAAM,mBAAA,GAAsBC,mCAAuB,eAAe;;;ACFlE,SAAS,4BAA4B,MAAA,EAA8C;AACxF,EAAA,IAAI,CAAC,MAAA,IAAU,OAAO,MAAA,KAAW,UAAU,OAAO,KAAA;AAClD,EAAA,MAAM,MAAM,MAAA,CAAO,MAAA;AACnB,EAAA,IAAI,OAAO,GAAA,KAAQ,QAAA,IAAY,GAAA,CAAI,MAAA,GAAS,IAAI,OAAO,KAAA;AACvD,EAAA,MAAM,SAAS,MAAA,CAAO,WAAA;AACtB,EAAA,IAAI,OAAO,WAAW,QAAA,IAAY,MAAA,CAAO,MAAK,CAAE,MAAA,KAAW,GAAG,OAAO,KAAA;AACrE,EAAA,OAAO,IAAA;AACT","file":"index.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 * Error taxonomy for the AgentChat channel plugin.\n *\n * Every error that crosses a pipeline boundary (inbound receive, outbound\n * send, config validation, transport) must be classifiable as one of:\n *\n * terminal-auth — 401/403. API key invalid or revoked. Do not retry.\n * Move state machine to AUTH_FAIL.\n * terminal-user — 400/422 (client-side validation). Bug in this plugin\n * or malformed outbound. Log at error level, drop,\n * do not retry.\n * retry-rate — 429. Retry after `retryAfterMs` (or jittered\n * exponential backoff if header absent).\n * retry-transient — 5xx, ECONNRESET, ETIMEDOUT, network flap.\n * Exponential backoff + jitter. Open circuit after N.\n * idempotent-replay — 409 on POST /v1/messages with duplicate\n * client_msg_id. Treat as success, log at info.\n * validation — Zod schema failed on inbound payload. Likely a\n * server change. Log at error, drop, alert.\n */\n\nexport type ErrorClass =\n | 'terminal-auth'\n | 'terminal-user'\n | 'retry-rate'\n | 'retry-transient'\n | 'idempotent-replay'\n | 'validation'\n\nexport class AgentChatChannelError extends Error {\n readonly class_: ErrorClass\n readonly retryAfterMs: number | undefined\n readonly statusCode: number | undefined\n\n constructor(\n class_: ErrorClass,\n message: string,\n options: {\n cause?: unknown\n retryAfterMs?: number\n statusCode?: number\n } = {},\n ) {\n super(message, { cause: options.cause })\n this.name = 'AgentChatChannelError'\n this.class_ = class_\n this.retryAfterMs = options.retryAfterMs\n this.statusCode = options.statusCode\n }\n}\n\n/** Classify an HTTP status code from the AgentChat REST API. */\nexport function classifyHttpStatus(status: number, retryAfterHeader?: string | null): ErrorClass {\n if (status === 401 || status === 403) return 'terminal-auth'\n if (status === 409) return 'idempotent-replay'\n if (status === 429) return 'retry-rate'\n if (status >= 500 && status <= 599) return 'retry-transient'\n if (status >= 400 && status <= 499) return 'terminal-user'\n return 'retry-transient' // unexpected — prefer retry over silent drop\n}\n\n/** Parse a `Retry-After` header to milliseconds. Accepts seconds or HTTP-date. */\nexport function parseRetryAfter(header: string | null | undefined, nowMs: number): number | undefined {\n if (!header) return undefined\n const seconds = Number(header)\n if (Number.isFinite(seconds) && seconds >= 0) return Math.floor(seconds * 1000)\n const when = Date.parse(header)\n if (Number.isFinite(when)) return Math.max(0, when - nowMs)\n return undefined\n}\n\n/** Classify a low-level transport error (from `ws` or `fetch`). */\nexport function classifyNetworkError(err: unknown): ErrorClass {\n if (!err || typeof err !== 'object') return 'retry-transient'\n const code = (err as { code?: unknown }).code\n if (typeof code === 'string') {\n if (code === 'ECONNRESET' || code === 'ETIMEDOUT' || code === 'ECONNREFUSED') {\n return 'retry-transient'\n }\n if (code === 'ENOTFOUND' || code === 'EAI_AGAIN') return 'retry-transient'\n }\n return 'retry-transient'\n}\n\n/** True iff the error class should trigger a retry. */\nexport function isRetryable(class_: ErrorClass): boolean {\n return class_ === 'retry-rate' || class_ === 'retry-transient'\n}\n\n/** True iff the error class is terminal (no retry, operator action needed). */\nexport function isTerminal(class_: ErrorClass): boolean {\n return class_ === 'terminal-auth' || class_ === 'terminal-user' || class_ === 'validation'\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.10.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 * Setup calls, through the `agentchatme` SDK:\n * - verify an API key is live before finalizing setup (`validateApiKey`,\n * `client.getMe()` → `GET /v1/agents/me`)\n * - the email-OTP self-registration for agents without a key yet\n * (`registerAgentStart` → `registerAgentVerify`; `AgentChatClient.register`\n * / `.verify` → `POST /v1/register`, `/v1/register/verify`)\n * - the email-OTP recovery that re-issues a lost API key\n * (`recoverAgentStart` → `recoverAgentVerify`; `AgentChatClient.recover`\n * with `handle` / `.recoverVerify` → `POST /v1/agents/recover`,\n * `/v1/agents/recover/verify`). The server answers recovery with the same\n * `{ pending_id, message }` whether or not the email + handle match a\n * live agent (no existence leak).\n *\n * This module holds no HTTP of its own: it turns the SDK's typed results\n * and errors into result unions a setup UI can `switch` on without\n * guessing at status codes. Every call is made once (`retry: never` in the\n * SDK for these routes; one attempt for the key check) — setup is\n * interactive, and a retry would only send a second email.\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\nimport { AgentChatClient, AgentChatError, RateLimitedError } from 'agentchatme'\n\nimport { AgentChatChannelError } from './errors.js'\nimport { AGENTCHAT_CLIENT_IDENTITY } 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 client = new AgentChatClient({\n apiKey,\n baseUrl: apiBaseOf(opts.apiBase),\n clientIdentity: AGENTCHAT_CLIENT_IDENTITY,\n timeoutMs: opts.timeoutMs ?? DEFAULT_TIMEOUT_MS,\n retry: ONE_ATTEMPT,\n ...(opts.fetch ? { fetch: opts.fetch } : {}),\n })\n\n let me: unknown\n try {\n me = await client.getMe()\n } catch (err) {\n const failure = describeFailure(err)\n if (failure.kind === 'network') {\n const unreachable = failure.timedOut || /ECONN|ETIMEDOUT|ENOTFOUND|EAI_AGAIN/i.test(failure.message)\n return {\n ok: false,\n reason: unreachable ? 'unreachable' : 'network-error',\n message: `agentchat: GET /v1/agents/me failed: ${failure.message}`,\n }\n }\n const status = failure.status\n if (status === 401) return { ok: false, reason: 'unauthorized', status, message: 'API key is invalid or revoked' }\n if (status === 403) return { ok: false, reason: 'forbidden', status, message: 'API key lacks permission to read /agents/me' }\n if (status === 410) return { ok: false, reason: 'deleted', status, message: 'Agent account has been deleted' }\n return { ok: false, reason: 'server-error', status, message: `AgentChat API returned ${status}` }\n }\n\n const body = asRecord(me)\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 = typeof body?.email === 'string' ? body.email : typeof body?.email_masked === 'string' ? body.email_masked : null\n if (!body || typeof body.handle !== 'string' || email === null || typeof body.created_at !== 'string') {\n return { ok: false, reason: 'unexpected-shape', status: 200, message: 'AgentChat /agents/me returned an unrecognized shape' }\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\n/**\n * Options for the registration and recovery calls. The SDK makes these\n * calls with its own transport (the runtime's `fetch`, its default timeout);\n * its static `register` / `verify` / `recover` / `recoverVerify` take no\n * `fetch` or timeout of their own, so neither is offered here.\n */\nexport interface RegisterOptions {\n readonly apiBase?: string\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 let data: unknown\n try {\n data = await AgentChatClient.register({\n email: input.email,\n handle: input.handle,\n ...(input.displayName !== undefined ? { display_name: input.displayName } : {}),\n ...(input.description !== undefined ? { description: input.description } : {}),\n baseUrl: apiBaseOf(opts.apiBase),\n clientIdentity: AGENTCHAT_CLIENT_IDENTITY,\n })\n } catch (err) {\n const failure = describeFailure(err)\n if (failure.kind === 'network') return { ok: false, reason: 'network-error', message: networkMessage(failure) }\n const { status, code, message } = failure\n if (status === 400 && code === 'INVALID_HANDLE') return { ok: false, reason: 'invalid-handle', message, status }\n if (status === 400 && code === 'VALIDATION_ERROR') return { ok: false, reason: 'validation', message, status }\n if (status === 409 && code === 'HANDLE_TAKEN') return { ok: false, reason: 'handle-taken', message, status }\n const emailPolicy = status === 409 ? classifyEmailPolicyRejection(code) : undefined\n if (emailPolicy) return { ok: false, reason: emailPolicy, message, status, limit: readPolicyLimit(failure.details) }\n if (status === 429) return { ok: false, reason: 'rate-limited', message, status, retryAfterSeconds: failure.retryAfterSeconds }\n if (status >= 500 || code === 'OTP_FAILED') return { ok: false, reason: 'otp-failed', message, status }\n return { ok: false, reason: 'server-error', status, message }\n }\n const pendingId = asRecord(data)?.pending_id\n if (typeof pendingId !== 'string') {\n return { ok: false, reason: 'server-error', status: 200, message: 'AgentChat /register returned no pending_id' }\n }\n return { ok: true, pendingId }\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 let verified: { agent: unknown; apiKey: unknown }\n try {\n verified = await AgentChatClient.verify(input.pendingId, input.code, {\n baseUrl: apiBaseOf(opts.apiBase),\n clientIdentity: AGENTCHAT_CLIENT_IDENTITY,\n })\n } catch (err) {\n const failure = describeFailure(err)\n if (failure.kind === 'network') return { ok: false, reason: 'network-error', message: networkMessage(failure) }\n const { status, code, message } = failure\n if (status === 400 && code === 'EXPIRED') return { ok: false, reason: 'expired', message, status }\n if (status === 400 && code === 'INVALID_CODE') return { ok: false, reason: 'invalid-code', message, status }\n if (status === 400 && code === 'VALIDATION_ERROR') return { ok: false, reason: 'validation', message, status }\n if (status === 409 && code === 'HANDLE_TAKEN') return { ok: false, reason: 'handle-taken', message, status }\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 = status === 409 ? classifyEmailPolicyRejection(code) : undefined\n if (emailPolicy) return { ok: false, reason: emailPolicy, message, status, limit: readPolicyLimit(failure.details) }\n if (status === 429) return { ok: false, reason: 'rate-limited', message, status, retryAfterSeconds: failure.retryAfterSeconds }\n return { ok: false, reason: 'server-error', status, message }\n }\n const agent = asRecord(verified.agent)\n if (\n typeof verified.apiKey !== 'string' ||\n !agent ||\n typeof agent.handle !== 'string' ||\n typeof agent.email !== 'string' ||\n typeof agent.created_at !== 'string'\n ) {\n return { ok: false, reason: 'unexpected-shape', status: 201, message: 'AgentChat /register/verify returned an unrecognized shape' }\n }\n return {\n ok: true,\n apiKey: verified.apiKey,\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// ─── 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 let data: unknown\n try {\n data = await AgentChatClient.recover(input.email, {\n handle: input.handle,\n baseUrl: apiBaseOf(opts.apiBase),\n clientIdentity: AGENTCHAT_CLIENT_IDENTITY,\n })\n } catch (err) {\n const failure = describeFailure(err)\n if (failure.kind === 'network') return { ok: false, reason: 'network-error', message: networkMessage(failure) }\n const { status, code, message } = failure\n if (status === 400 && code === 'VALIDATION_ERROR') return { ok: false, reason: 'validation', message, status }\n if (status === 429) return { ok: false, reason: 'rate-limited', message, status, retryAfterSeconds: failure.retryAfterSeconds }\n return { ok: false, reason: 'server-error', status, message }\n }\n const body = asRecord(data)\n const message = typeof body?.message === 'string' ? body.message : '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: '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/** 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 let recovered: { handle: unknown; apiKey: unknown }\n try {\n recovered = await AgentChatClient.recoverVerify(input.pendingId, input.code, {\n baseUrl: apiBaseOf(opts.apiBase),\n clientIdentity: AGENTCHAT_CLIENT_IDENTITY,\n })\n } catch (err) {\n const failure = describeFailure(err)\n if (failure.kind === 'network') return { ok: false, reason: 'network-error', message: networkMessage(failure) }\n const { status, code, message } = failure\n if (status === 400 && code === 'EXPIRED') return { ok: false, reason: 'expired', message, status }\n if (status === 400 && code === 'INVALID_CODE') return { ok: false, reason: 'invalid-code', message, status }\n if (status === 400 && code === 'VALIDATION_ERROR') return { ok: false, reason: 'validation', message, status }\n if (status === 409 && code === 'HANDLE_REQUIRED') {\n return { ok: false, reason: 'handle-required', message, status, handles: readHandleList(failure.details) }\n }\n if (status === 429) return { ok: false, reason: 'rate-limited', message, status, retryAfterSeconds: failure.retryAfterSeconds }\n return { ok: false, reason: 'server-error', status, message }\n }\n if (typeof recovered.apiKey !== 'string' || typeof recovered.handle !== 'string') {\n return { ok: false, reason: 'unexpected-shape', status: 200, message: 'AgentChat /agents/recover/verify returned an unrecognized shape' }\n }\n return { ok: true, apiKey: recovered.apiKey, handle: recovered.handle }\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\n/** One attempt, no back-off: setup is interactive and the caller shows the failure. */\nconst ONE_ATTEMPT = { maxRetries: 0, baseDelayMs: 0, maxDelayMs: 0 } as const\n\nfunction apiBaseOf(apiBase: string | undefined): string {\n return (apiBase ?? DEFAULT_API_BASE).replace(/\\/+$/, '')\n}\n\n/** What a failed SDK call came to: the server answered (`http`), or it could not be reached (`network`). */\ntype Failure =\n | {\n readonly kind: 'http'\n readonly status: number\n readonly code: string\n readonly message: string\n readonly details: unknown\n readonly retryAfterSeconds?: number\n }\n | { readonly kind: 'network'; readonly message: string; readonly timedOut: boolean }\n\n/**\n * Read an error thrown by the SDK. An `AgentChatError` carries the server's\n * status, code, message and details; a body the SDK could not read as an\n * error (no `code` + `message`) sits under `details.body`, and its code and\n * message are taken from there. Anything else — the SDK's\n * `ConnectionError`, its own request timeout, a thrown `fetch` — is a\n * network failure.\n */\nfunction describeFailure(err: unknown): Failure {\n if (err instanceof AgentChatError) {\n const raw = asRecord(asRecord(err.details)?.body)\n const code = typeof raw?.code === 'string' ? raw.code : String(err.code ?? '')\n const message = raw ? (typeof raw.message === 'string' ? raw.message : `status ${err.status}`) : err.message || `status ${err.status}`\n const retryAfterMs = err instanceof RateLimitedError ? err.retryAfterMs : null\n return {\n kind: 'http',\n status: err.status,\n code,\n message,\n details: raw ? raw.details : err.details,\n ...(typeof retryAfterMs === 'number' && Number.isFinite(retryAfterMs) ? { retryAfterSeconds: Math.ceil(retryAfterMs / 1000) } : {}),\n }\n }\n const message = err instanceof Error ? err.message : String(err)\n const timedOut = (err instanceof Error && err.name === 'AbortError') || /timed out|abort/i.test(message)\n return { kind: 'network', message, timedOut }\n}\n\nfunction networkMessage(failure: Extract<Failure, { kind: 'network' }>): string {\n return failure.timedOut ? 'request timed out' : failure.message\n}\n\nfunction asRecord(value: unknown): Record<string, unknown> | null {\n return value !== null && typeof value === 'object' && !Array.isArray(value) ? (value as Record<string, unknown>) : null\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 name OpenClaw gives the hosted tools, and the session keys and\n * lane the turns run on.\n *\n * No text lives here. What a turn starts with — the served wake instruction\n * or invite prompt and the id it is about — is composed by the SDK kit's\n * receive loop from `GET /v1/texts?runtime=openclaw`, which the server spells\n * the way OpenClaw exposes the hosted tools (`agentchat__<tool>`). The plugin\n * still re-spells served text on the way out (`spellToolsForOpenClaw`): it\n * is a no-op on `agentchat__…`, and it keeps the tool names right if a\n * server that serves bare names comes back (a rolled-back deploy). The tray's\n * gate question (`GET /v1/inbox` serves bare names) is spelled by the kit's\n * gate with `OPENCLAW_TOOL_NAMER`.\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).\n */\n\nimport type { 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\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 (the already-prefixed form) and never inside a longer word —\n// `agentchat__agentchat_inbox` matches nowhere (the inner `agentchat_` has\n// no word boundary before it), and `api.agentchat.me` has no underscore.\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; a no-op on text the server already spelled. */\nexport function spellToolsForOpenClaw(text: string): string {\n return text.replace(HOSTED_TOOL_TOKEN, (token) => OPENCLAW_TOOL_NAMER(token))\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\n/**\n * A fresh session per invite turn too. An invite can get a second turn (the\n * kit's rule dismisses one still pending after two turns that looked); a\n * reused session would show it the first turn's history, and a turn that\n * then makes no AgentChat call would read as one that could not look.\n */\nexport function inviteSessionKey(agentId: string, inviteId: string, now: number = Date.now(), nonce: string = randomNonce()): string {\n return `agent:${agentId}:subagent:agentchat-invite-${sanitizeKeyPart(inviteId)}-${utcStamp(now)}-${nonce}`\n}\n\n/**\n * One serialization lane per account so AgentChat turns never block the\n * agent's main lane and never overlap each other. OpenClaw runs a lane's\n * runs one after another, so a run that never ends would hold every later\n * turn behind it: after a hand-off (`AccountTurns.handOff`) new turns go to\n * the next lane (`generation` > 0), leaving the hung run alone on the old one.\n */\nexport function integrationLane(accountId: string, generation = 0): string {\n const base = `agentchat-integration:${sanitizeKeyPart(accountId)}`\n return generation > 0 ? `${base}:${generation}` : base\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 * - `headers` takes any static string header (`McpServerSchema` in\n * openclaw/openclaw `src/config/zod-schema.mcp-server.ts`, a record of\n * string to string | number | boolean, on 2026.6.10 and 2026.11.3 alike),\n * and an `mcp.*` change is applied hot: the gateway drops its MCP clients\n * and reconnects, no restart (`src/gateway/config-reload-plan.ts`, rule\n * `mcp` → dispose MCP runtimes).\n *\n * The entry names this client to the hosted tools: `X-AgentChat-Client:\n * openclaw`, the header AgentChat reads on `/mcp` (it does not read MCP's\n * `clientInfo`). Without it the agent is an unknown client: AgentChat lists\n * the wake-webhook tools and tells it to register a webhook, a second wake\n * path next to this plugin's socket. The entry is static — the same in\n * every release, no version in it (AgentChat learns the plugin's version\n * from its socket and REST traffic) — so an install is brought up to date\n * at most once and the plugin never rewrites the operator's config on an\n * upgrade. An entry an earlier release wrote (bearer only) is still ours\n * and gains the header in place — at the gateway's start, by setup and by\n * `openclaw doctor --fix`; a hand-written or disabled entry is never\n * touched, and doctor and status say when a hand-written one does not name\n * the client.\n */\n\nimport { integration } from 'agentchatme'\n\nimport { AGENTCHAT_CLIENT_IDENTITY, AGENTCHAT_CLIENT_NAME } 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\nexport function hostedMcpUrl(apiBase: string = DEFAULT_API_BASE): string {\n return `${apiBase.replace(/\\/+$/, '')}${MCP_PATH}`\n}\n\n/** The header that names the calling client to AgentChat (the server reads it case-insensitively). */\nexport const CLIENT_HEADER = 'X-AgentChat-Client'\n\nexport interface McpServerEntry {\n readonly url: string\n readonly transport: 'streamable-http'\n readonly headers: {\n readonly Authorization: string\n readonly [CLIENT_HEADER]: string\n }\n}\n\n/** The identity header the entry carries: the client's name, the same in every release. */\nexport function clientIdentityHeaders(): { readonly [CLIENT_HEADER]: string } {\n return { [CLIENT_HEADER]: AGENTCHAT_CLIENT_NAME }\n}\n\n/** `X-AgentChat-Client: openclaw` — for log and status lines. */\nexport function clientIdentityText(): string {\n return `${CLIENT_HEADER}: ${AGENTCHAT_CLIENT_NAME}`\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, ...clientIdentityHeaders() },\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 const identity = clientIdentityHeaders()\n return [\n '{',\n ' mcp: {',\n ' servers: {',\n ` ${MCP_SERVER_NAME}: {`,\n ` url: \"${hostedMcpUrl(apiBase)}\",`,\n ' transport: \"streamable-http\",',\n ' headers: {',\n ` Authorization: \"${AUTH_HEADER_TEMPLATE}\",`,\n ` \"${CLIENT_HEADER}\": \"${identity[CLIENT_HEADER]}\",`,\n ' },',\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 // Any casing; two spellings of the header are not something this plugin wrote.\n const auths = headerValues(headers as Record<string, unknown>, 'Authorization')\n if (auths.length > 1) return false\n const auth = auths[0]\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\n/**\n * Whether the `mcp.servers.agentchat` entry names this client:\n * - `current` — one `X-AgentChat-Client: openclaw` (any other header, a\n * version header included, is the entry's business and left alone);\n * - `missing` — no `X-AgentChat-Client`, another client's name, or two\n * spellings of it (there is no entry at all, or it is not an object, is\n * `missing` too).\n * Header names are matched without regard to case, as HTTP does.\n */\nexport type McpIdentityState = 'current' | 'missing'\n\nexport function describeMcpIdentity(cfg: unknown): McpIdentityState {\n const entry = agentchatEntry(cfg)\n const headers = entry && isRecord(entry.headers) ? entry.headers : undefined\n if (!headers) return 'missing'\n const want = clientIdentityHeaders()\n // Two spellings of one header reach the server joined (\"openclaw, openclaw\"),\n // which names no client it knows: as good as none.\n const clients = headerValues(headers, CLIENT_HEADER)\n const client = clients[0]\n return clients.length === 1 && typeof client === 'string' && client.trim().toLowerCase() === want[CLIENT_HEADER] ? 'current' : 'missing'\n}\n\nexport type McpEntryOutcome = 'added' | 'updated' | 'present' | 'user_managed' | 'disabled'\n\n/**\n * Return a config with `mcp.servers.agentchat` present and naming this\n * client. Pure: the caller persists the result through OpenClaw (the wizard\n * returns it; the doctor returns it as a repair). Our entry from an earlier\n * release is brought up to date in place (`updated`, see\n * `upgradedHostedMcpEntry`). A same-name entry the user wrote themselves, or\n * disabled, 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 === 'user_managed') return { cfg: base, outcome: 'user_managed' }\n if (state === 'disabled') return { cfg: base, outcome: 'disabled' }\n if (state === 'ours' && describeMcpIdentity(base) === 'current') return { cfg: base, outcome: 'present' }\n const mcp = { ...((base as { mcp?: Record<string, unknown> }).mcp ?? {}) }\n const servers = { ...((mcp.servers as Record<string, unknown> | undefined) ?? {}) }\n const existing = servers[MCP_SERVER_NAME]\n servers[MCP_SERVER_NAME] = state === 'ours' && isRecord(existing) ? upgradedHostedMcpEntry(existing, apiBase) : hostedMcpServerEntry(apiBase)\n mcp.servers = servers\n return { cfg: { ...base, mcp } as T, outcome: state === 'ours' ? 'updated' : 'added' }\n}\n\n/**\n * Our entry, brought up to date: one `X-AgentChat-Client: openclaw` (every\n * other spelling of it dropped), and everything else exactly as it was —\n * the bearer included (same header name, same value), timeouts,\n * `toolFilter`, other headers. The bearer is never rewritten: the config OpenClaw hands a plugin\n * (and the draft `mutateConfigFile` gives it) is env-substituted, so the\n * value seen may be the key itself; written back unchanged, OpenClaw\n * restores the `${VAR}` reference the file had at that path, and an operator\n * who chose another variable, or a literal, keeps it.\n */\nexport function upgradedHostedMcpEntry(entry: Readonly<Record<string, unknown>>, apiBase: string = DEFAULT_API_BASE): Record<string, unknown> {\n const headers = isRecord(entry.headers) ? entry.headers : {}\n const kept = Object.fromEntries(Object.entries(headers).filter(([name]) => name.toLowerCase() !== CLIENT_HEADER.toLowerCase()))\n return {\n ...entry,\n url: hostedMcpUrl(apiBase),\n transport: 'streamable-http',\n headers: { ...kept, ...clientIdentityHeaders() },\n }\n}\n\n/**\n * In-place form of the upgrade, for OpenClaw's `mutateConfigFile` draft:\n * true when our entry was out of date and is now current. Classifies the\n * draft itself (the file as it is now, env-substituted like any config a\n * plugin sees — hence `apiKey`), so an entry the operator took over in the\n * meantime is left alone. Never adds a missing entry.\n */\nexport function upgradeHostedMcpEntryInPlace(draft: unknown, apiBase: string = DEFAULT_API_BASE, apiKey?: string): boolean {\n if (describeMcpEntry(draft, apiBase, apiKey) !== 'ours' || describeMcpIdentity(draft) === 'current') return false\n const servers = (draft as { mcp: { servers: Record<string, unknown> } }).mcp.servers\n const existing = servers[MCP_SERVER_NAME]\n if (!isRecord(existing)) return false\n servers[MCP_SERVER_NAME] = upgradedHostedMcpEntry(existing, apiBase)\n return true\n}\n\n/** What `mutateConfigFile` looks like on `runtime.config` (OpenClaw 2026.6.10 and later). */\nexport interface ConfigMutator {\n mutateConfigFile?: (params: { afterWrite: { mode: 'auto' }; mutate: (draft: never) => unknown }) => Promise<{ result?: unknown } | unknown>\n}\n\nexport type McpRefreshOutcome = 'updated' | 'current' | 'not_ours' | 'unsupported' | 'failed'\n\n/** Thrown from the mutate callback to abort a write that would change nothing. */\nclass NoChange extends Error {\n constructor(readonly outcome: 'current' | 'not_ours') {\n super(`no change (${outcome})`)\n }\n}\n\n/** OpenClaw's error for a config it may not write (Nix mode). */\nexport const NIX_MODE_ERROR_CODE = 'OPENCLAW_NIX_MODE_CONFIG_IMMUTABLE'\n\n/**\n * At the gateway's start: bring our `mcp.servers.agentchat` up to date when\n * the live config shows it does not name the client (an install from a\n * release before 0.10.1) — once per install, since the entry is the same in\n * every release from then on. One focused write through OpenClaw's\n * `runtime.config.mutateConfigFile` (its draft is the file as it is now,\n * env-substituted; OpenClaw restores `${VAR}` references on the paths left\n * unchanged), with `afterWrite: auto` — under the default reload mode\n * OpenClaw applies an `mcp.*` change hot. Nothing is written when the entry\n * is current, missing (setup and `doctor --fix` add it), disabled or\n * hand-written; `mutateConfigFile` commits whatever the callback leaves, so\n * a draft that needs no change aborts the write. Never throws.\n */\nexport async function refreshHostedMcpEntry(params: {\n liveCfg: unknown\n config: ConfigMutator | undefined\n apiBase?: string\n apiKey?: string\n}): Promise<{ outcome: McpRefreshOutcome; error?: string; code?: string }> {\n const apiBase = params.apiBase ?? DEFAULT_API_BASE\n if (describeMcpEntry(params.liveCfg, apiBase, params.apiKey) !== 'ours') return { outcome: 'not_ours' }\n if (describeMcpIdentity(params.liveCfg) === 'current') return { outcome: 'current' }\n const mutate = params.config?.mutateConfigFile\n if (typeof mutate !== 'function') return { outcome: 'unsupported' }\n try {\n // The file can differ from the live read (an edit in between): the draft\n // is classified again, and an entry that is no longer ours is left alone.\n await mutate.call(params.config, {\n afterWrite: { mode: 'auto' },\n mutate: ((draft: unknown) => {\n if (describeMcpEntry(draft, apiBase, params.apiKey) !== 'ours') throw new NoChange('not_ours')\n if (!upgradeHostedMcpEntryInPlace(draft, apiBase, params.apiKey)) throw new NoChange('current')\n }) as (draft: never) => unknown,\n })\n return { outcome: 'updated' }\n } catch (err) {\n if (err instanceof NoChange) return { outcome: err.outcome }\n const code = (err as { code?: unknown } | null)?.code\n return {\n outcome: 'failed',\n error: err instanceof Error ? err.message : String(err),\n ...(typeof code === 'string' ? { code } : {}),\n }\n }\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n}\n\nfunction agentchatEntry(cfg: unknown): Record<string, unknown> | undefined {\n const servers = (cfg as { mcp?: { servers?: unknown } } | undefined)?.mcp?.servers\n if (!isRecord(servers)) return undefined\n const entry = servers[MCP_SERVER_NAME]\n return isRecord(entry) ? entry : undefined\n}\n\n/** Every value of a header, in any spelling of its name (HTTP names ignore case). */\nfunction headerValues(headers: Readonly<Record<string, unknown>>, name: string): unknown[] {\n const wanted = name.toLowerCase()\n return Object.entries(headers)\n .filter(([key]) => key.toLowerCase() === wanted)\n .map(([, value]) => value)\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 /** Every tool the server listed for this key (bare names). */\n readonly tools?: readonly string[]\n /** Tools a turn needs that the server did not list. */\n readonly missing?: readonly string[]\n readonly error?: string\n}\n\n/**\n * Doctor and status check: can this key list the hosted tools? The SDK\n * kit's `probeHostedTools` — one MCP `initialize` and one `tools/list` over\n * Streamable HTTP with the bearer key, the requests OpenClaw makes on\n * connect. A `401` means the key does not authenticate; a transport error\n * means the endpoint is not reachable from here; a list without the tools a\n * turn needs means a turn could not look.\n */\nexport async function probeHostedMcp(params: {\n apiKey: string\n apiBase?: string\n timeoutMs?: number\n fetch?: typeof fetch\n}): Promise<McpProbeResult> {\n const result = await integration.probeHostedTools({\n apiBase: params.apiBase ?? DEFAULT_API_BASE,\n apiKey: params.apiKey,\n clientIdentity: AGENTCHAT_CLIENT_IDENTITY,\n ...(params.timeoutMs !== undefined ? { timeoutMs: params.timeoutMs } : {}),\n ...(params.fetch ? { fetch: params.fetch } : {}),\n })\n const missing = result.missing ?? []\n return {\n ok: result.ok,\n ...(result.status !== undefined ? { status: result.status } : {}),\n ...(result.serverName ? { serverName: result.serverName } : {}),\n ...(result.serverVersion ? { serverVersion: result.serverVersion } : {}),\n ...(result.protocolVersion ? { protocolVersion: result.protocolVersion } : {}),\n ...(result.tools ? { tools: result.tools } : {}),\n ...(missing.length > 0 ? { missing } : {}),\n ...(result.error ? { error: result.error } : !result.ok && missing.length > 0 ? { error: `the server lists no ${missing.join(', ')} for this key` } : {}),\n }\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 * A turn's run, as OpenClaw reports it: admitted, watched until OpenClaw\n * confirms it ended, and what AgentChat calls it made.\n *\n * Why the watch never gives up on a timeout\n * ─────────────────────────────────────────\n * `runtime.subagent.waitForRun({ runId, timeoutMs })` bounds the WAIT, not\n * the run: \"timeoutMs bounds the wait call; it does not cancel the run\"\n * (docs.openclaw.ai/plugins/sdk-runtime/background-work). A `timeout`\n * status therefore says one of two things — the wait elapsed while the run\n * goes on, or the run hit its own deadline (`agents.defaults.timeoutSeconds`,\n * 48 h by default) and is over. Treating the first as an end would let the\n * conversation be gated again and a second turn answer it while the first\n * is still running. So the watch waits again until OpenClaw says the run\n * is over, with OpenClaw's own rule for telling the two apart\n * (`isTerminalAgentWaitTimeout` and the `untilTerminal` loop in\n * github.com/openclaw/openclaw `src/agents/run-wait.ts`):\n *\n * - `ok`, `error` → ended\n * - `pending` → running (a normal non-terminal observation)\n * - `timeout` with `pendingError` → running (a failed attempt may still recover)\n * - `timeout` with `endedAt`, `stopReason` or `livenessState` → ended (the run's own deadline)\n * - `timeout` that is a hard timeout → ended: a `timeoutPhase` of\n * preflight / provider / tool_execution / post_turn, or `providerStarted`\n * without a restart stop (`resolveAgentRunTerminalFacts`)\n * - `timeout` with an `error` → ended\n * - any other `timeout` → running (the wait elapsed)\n *\n * On OpenClaw main a wait that elapses comes back bare — `{ runId, status:\n * 'timeout' }`, no snapshot (`src/gateway/agent-turn/agent-wait.ts`) — a\n * queued run as `pending` with `timeoutPhase: 'queue'`, and a gateway\n * lifecycle reset as `timeout` with `timeoutPhase: 'gateway_draining'`. A\n * bare `timeout` carries none of the metadata keys, so it is read by the\n * timing rule below: one that took the whole wait is asked again.\n *\n * Older OpenClaw lines (2026.6 and 2026.7, e.g. 2026.6.10 and 2026.7.35)\n * hand a plugin only `{ status, error }` (the wait metadata is dropped on the\n * way out). There a terminal timeout\n * is told apart by when it arrives: the gateway answers from the run's\n * terminal record as soon as there is one, while an elapsed wait (and a\n * failed attempt that may still recover) is answered when the wait's own\n * timer fires. A `timeout` that comes back in under half the requested\n * wait is an end; one that took the whole wait is asked again — if the run\n * did end meanwhile, the next wait is answered at once from that record.\n *\n * Nothing here cancels a run: the plugin runtime has no abort for a\n * subagent run, and OpenClaw's own run deadline is what bounds a run that\n * never finishes. The watch stops early only when the plugin runtime is\n * gone (the gateway is shutting down or the plugin was unloaded) — then\n * there is nothing left to ask, and nothing left in this process to start\n * a second turn either.\n */\n\nimport type { PluginRuntime } from 'openclaw/plugin-sdk/channel-core'\n\nimport { MCP_SERVER_NAME, MCP_TOOL_DELIMITER } from './turn.js'\n\n/** One wait per call. Shorter than the old 15-minute bound so a live run is reported as live in the log. */\nexport const DEFAULT_RUN_WAIT_CHUNK_MS = 5 * 60_000\n\n/** Back-off between failed waits (the gateway did not answer); the last value repeats. */\nexport const RUN_WAIT_RETRY_MS: readonly number[] = [1_000, 5_000, 15_000, 30_000, 60_000]\n\n/** A wait that returns sooner than this, without saying the run went on, is not allowed to loop hot. */\nconst MIN_WAIT_SPACING_MS = 1_000\n\n/** Transcript rows read after a run; one wake turn is a handful of tool calls. A longer session reads as unknown (`countAgentChatCalls`). */\nexport const TRANSCRIPT_READ_LIMIT = 200\n\n/** What `waitForRun` answers, across the OpenClaw versions the plugin supports. Every field is optional on purpose. */\nexport interface RunWaitObservation {\n readonly status?: unknown\n readonly error?: unknown\n readonly endedAt?: unknown\n readonly stopReason?: unknown\n readonly livenessState?: unknown\n readonly pendingError?: unknown\n readonly timeoutPhase?: unknown\n readonly startedAt?: unknown\n readonly providerStarted?: unknown\n}\n\n/** How a run ended, as OpenClaw confirmed it. `timeout` is the run's own deadline, never an elapsed wait. */\nexport type RunEndStatus = 'ok' | 'error' | 'timeout'\n\nexport type RunEnd =\n | { readonly ended: false }\n | { readonly ended: true; readonly status: RunEndStatus; readonly error?: string }\n\n/** Keys only a release that forwards the gateway's wait metadata sends. */\nconst METADATA_KEYS = ['endedAt', 'stopReason', 'livenessState', 'pendingError', 'timeoutPhase', 'startedAt', 'providerStarted'] as const\n\n/**\n * Whether one wait observation means the run is over. Pure. `elapsedMs` is\n * how long the wait call took and `requestedMs` what it was asked to wait;\n * they matter only for a release that drops the wait metadata.\n */\nexport function runEndOf(wait: RunWaitObservation | null | undefined, timing: { readonly requestedMs: number; readonly elapsedMs: number }): RunEnd {\n const status = wait?.status\n const error = nonEmpty(wait?.error)\n if (status === 'ok') return { ended: true, status: 'ok' }\n if (status === 'error') {\n // OpenClaw itself reads an `error` whose text is \"completed\" as a clean end.\n if (error && error.trim().toLowerCase() === 'completed') return { ended: true, status: 'ok' }\n return { ended: true, status: 'error', ...(error ? { error } : {}) }\n }\n if (status !== 'timeout') {\n // `pending`, or a status this version does not know: not an end.\n return { ended: false }\n }\n const ended = { ended: true as const, status: 'timeout' as const, ...(error ? { error } : {}) }\n const hasMetadata = wait !== null && wait !== undefined && METADATA_KEYS.some((key) => key in wait)\n if (!hasMetadata) {\n // Metadata dropped (OpenClaw 2026.6 / 2026.7 lines): only the timing tells. The\n // gateway answers from the run's terminal record as soon as there is\n // one; an elapsed wait — and a failed attempt that may still recover —\n // is answered when the wait's own timer fires.\n return timing.elapsedMs < timing.requestedMs / 2 ? ended : { ended: false }\n }\n if (wait.pendingError === true) return { ended: false }\n if (typeof wait.endedAt === 'number' || nonEmpty(wait.stopReason) || nonEmpty(wait.livenessState)) return ended\n if (isHardTimeout(wait)) return ended\n return error ? ended : { ended: false }\n}\n\n/** Timeout phases only a run's own deadline reports (OpenClaw `HARD_TIMEOUT_PHASES`). */\nconst HARD_TIMEOUT_PHASES: ReadonlySet<string> = new Set(['preflight', 'provider', 'tool_execution', 'post_turn'])\n\n/**\n * OpenClaw's `hard_timeout` reading of a `timeout` snapshot (the third leg of\n * `isTerminalAgentWaitTimeout`): a phase only the run's own deadline reports,\n * or a timeout after the provider started that was not a restart stop.\n */\nexport function isHardTimeout(wait: RunWaitObservation): boolean {\n const phase = typeof wait.timeoutPhase === 'string' ? wait.timeoutPhase.trim() : ''\n if (HARD_TIMEOUT_PHASES.has(phase)) return true\n return wait.status === 'timeout' && wait.providerStarted === true && nonEmpty(wait.stopReason) !== 'restart'\n}\n\n/** What the watch reports. `gone`: the plugin runtime disappeared before OpenClaw confirmed an end. */\nexport type RunWatchResult =\n | { readonly ended: true; readonly status: RunEndStatus; readonly error?: string; readonly elapsedMs: number }\n | { readonly ended: false; readonly reason: 'gone'; readonly elapsedMs: number }\n\nexport interface RunWatchOptions {\n readonly runtime: () => PluginRuntime | null\n readonly runId: string\n readonly chunkMs?: number\n readonly retryMs?: readonly number[]\n /** Called each time a wait elapses with the run still going (for the \"still running\" log line). */\n readonly onStillRunning?: (elapsedMs: number) => void\n /** Called when a wait call fails; the watch tries again after the next back-off step. */\n readonly onWaitError?: (error: string, attempt: number, retryInMs: number) => void\n readonly now?: () => number\n readonly sleep?: (ms: number) => Promise<void>\n}\n\n/**\n * Wait until OpenClaw confirms the run ended. Never rejects. Resolves with\n * `ended: true` and the run's status, or `ended: false` only when the\n * plugin runtime is gone.\n *\n * A wait call that fails is not an end either (the gateway did not answer;\n * the run is OpenClaw's): the watch backs off and asks again. A run the\n * gateway does not know is answered like a wait that elapsed (a bare\n * `{ status: 'timeout' }` after the whole wait — OpenClaw has no \"not found\"\n * for `agent.wait`), so it is watched until the turn is handed off and let\n * go of (`./running.ts`).\n */\nexport async function watchRunUntilEnded(options: RunWatchOptions): Promise<RunWatchResult> {\n const chunkMs = options.chunkMs ?? DEFAULT_RUN_WAIT_CHUNK_MS\n const retryMs = options.retryMs ?? RUN_WAIT_RETRY_MS\n const now = options.now ?? Date.now\n const sleep = options.sleep ?? defaultSleep\n const started = now()\n let failures = 0\n for (;;) {\n const runtime = options.runtime()\n if (!runtime) return { ended: false, reason: 'gone', elapsedMs: now() - started }\n const waitStarted = now()\n let observation: RunWaitObservation\n try {\n observation = (await runtime.subagent.waitForRun({ runId: options.runId, timeoutMs: chunkMs })) as RunWaitObservation\n } catch (err) {\n const message = describe(err)\n const delay = retryMs[Math.min(failures, retryMs.length - 1)] ?? 60_000\n failures += 1\n options.onWaitError?.(message, failures, delay)\n await sleep(delay)\n continue\n }\n failures = 0\n const elapsedMs = now() - waitStarted\n const end = runEndOf(observation, { requestedMs: chunkMs, elapsedMs })\n if (end.ended) return { ...end, elapsedMs: now() - started }\n options.onStillRunning?.(now() - started)\n if (elapsedMs < MIN_WAIT_SPACING_MS) await sleep(MIN_WAIT_SPACING_MS - elapsedMs)\n }\n}\n\n/** AgentChat tool calls a run made, read from its transcript. */\nexport interface AgentChatCalls {\n /** AgentChat tool results in the transcript. */\n readonly made: number\n /** Of those, the ones that came back as errors. */\n readonly failed: number\n}\n\n/**\n * Count the AgentChat tool calls in a run's transcript. Pure.\n *\n * The count decides a READ: on a second silent look the kit's after-turn\n * rule dismisses the conversation (marks it read) only when the calls are\n * known and none failed, and defers otherwise (`integration.turnOutcome`).\n * So the count is exact for the row shapes OpenClaw writes, and null —\n * unknown, which the rule never reads as success — whenever it cannot be:\n *\n * - the transcript says nothing usable (no rows, or a row that is not a\n * message);\n * - the rows read may not be the whole turn: the first is not message 1\n * of the session (`__openclaw.seq`; a wake turn has a session of its\n * own, so message 1 is where it starts), or the read holds a compaction\n * or reset marker or an oversized-message placeholder, which stand for\n * rows that are not there;\n * - an AgentChat call's outcome cannot be read from its row (`callVerdict`);\n * - the turn used Code Mode (`usedCodeMode`) on a release that does not\n * record the calls a script makes (see the nested rows below);\n * - the turn handed work to another session's run (`sessions_spawn`,\n * `sessions_send`): that run's calls are in its own session;\n * - the session holds rows of another run (`__openclaw.runId`, which\n * OpenClaw writes on assistant and tool rows from the 2026.8 line on —\n * `attachSessionTranscriptRunId`, `src/sessions/transcript-events.ts`):\n * a turn OpenClaw resumed after a gateway restart runs again in the same\n * session, and counting one run of it would be a partial count.\n *\n * The row shapes (OpenClaw's own; 2026.6.10 is the oldest supported release,\n * 2026.11.3 the newest at the time of writing, `main` its repository):\n *\n * A direct call — `toolName` `agentchat__<tool>` (`toolResult` row from\n * the agent loop, `packages/agent-core`):\n * ok `isError: false`, `details: { mcpServer: 'agentchat', mcpTool }`\n * (`mcpOperation` for the resource / prompt helpers), from the\n * MCP materializer (`src/agents/agent-bundle-mcp-materialize.ts`,\n * `src/agents/mcp-content.ts`).\n * failed the server answered `isError: true` → `details.status: 'error'`;\n * the call threw → the tool adapter's\n * `details: { status: 'error', tool, error }`\n * (`src/agents/agent-tool-definition-adapter.ts`); a hook vetoed\n * it → `details.status: 'blocked'`; the loop never ran it →\n * `isError: true`, `details: {}`. Before 2026.9.3 the first three\n * keep `isError: false` — only the details say the call failed;\n * from 2026.9.3 `AgentSession.afterToolCall` sets `isError` from\n * them too (`src/agents/sessions/agent-session-base.ts`,\n * openclaw/openclaw#139758).\n * A call through Tool Search — the dispatcher `tool_call` (renamed\n * `dispatch_action` in 2026.10.10, openclaw/openclaw#169552):\n * ok `details: { tool: <catalog entry>, result: <the direct result> }`.\n * failed `details.result` holds the failed direct result (2026.9.3+\n * also `details.status: 'failed'` and `isError: true`); the\n * target threw → the adapter's `details: { status: 'error',\n * tool: '<dispatcher>', error }`, with no entry — the target is\n * then read from the assistant's call (`arguments.id` / `toolId`\n * / `name`, as `src/agents/tool-search.ts` reads it).\n *\n * A nested call — a call a Tool Search dispatcher or a Code Mode script\n * made, recorded by the release as its own row (`role: 'custom'`,\n * `customType: 'openclaw.nested-tool.v1'`, `details: { runId,\n * parentToolCallId, toolCallId, toolName, result, isError, … }`;\n * `src/sessions/nested-tool-activity.ts`, written by\n * `src/agents/embedded-agent-runner/run/attempt-tool-search-executor.ts`\n * from the 2026.8 line on). Its `isError` is OpenClaw's reading of the\n * result (`isError || isToolResultError(result)`, `handleToolExecutionEnd`,\n * `src/agents/embedded-agent-subscribe.handlers.tools.ts`); the result is\n * kept up to 32 KiB. A dispatcher row with nested rows under it is not\n * counted itself: its call is the nested row.\n * Known limit: the executor writes the row only while its attempt is\n * still the current one (`if (!params.isCurrent()) return false` before\n * `appendMessageAsync`, `attempt-tool-search-executor.ts`). A nested call\n * that finishes after its attempt was superseded or aborted leaves no\n * row, and nothing in the transcript says one is missing — such a turn\n * is counted from the rows that are there.\n *\n * A row whose details were too large to store — over 8 KiB, the\n * persistence guard keeps `{ persistedDetailsTruncated, originalDetailKeys }`\n * and the top-level `status` / `error` / `success`\n * (`src/agents/session-tool-result-guard.payload.ts`). A direct call keeps\n * its failure marks at the top level on every release, so it is still\n * read exactly. A dispatcher row keeps only its own top-level status,\n * which says failure from 2026.9.3 on: there `isError: false` with no\n * status is a success; before, the failure was nested and is lost, so the\n * row is unknown.\n *\n * Which release wrote the rows is read from the rows where they show it —\n * a nested row (the release records nested calls), a `dispatch_action`\n * dispatcher (2026.10.10 and later) — and otherwise from `openclawVersion`,\n * the host's OpenClaw version (`runtime.version`).\n *\n * Failure in `details` is read with OpenClaw's own rule\n * (`isToolResultError`, `src/agents/tool-result-error.ts`).\n */\nexport function countAgentChatCalls(messages: readonly unknown[], runId?: string, host: { readonly openclawVersion?: string } = {}): AgentChatCalls | null {\n if (messages.length === 0) return null\n const rows: Record<string, unknown>[] = []\n for (const row of messages) {\n const message = unwrapMessage(row)\n if (!message) return null\n rows.push(message)\n }\n if (!coversWholeSession(rows)) return null\n if (runId && rows.some((row) => isOtherRun(row, runId))) return null\n const calls = assistantToolCalls(rows)\n const nested = rows.flatMap((row) => {\n const call = nestedCallOf(row)\n return call ? [call] : []\n })\n const release = releaseOf(rows, calls, nested, host.openclawVersion)\n if (delegatedToChild(rows, calls, nested)) return null\n if (usedCodeMode(rows, calls)) {\n if (!release.recordsNestedCalls) return null\n // Counted from its nested rows only when every script ran to completion:\n // a script that failed or is still waiting may have stopped before a call.\n if (!codeModeScriptsCompleted(rows, calls)) return null\n }\n // A dispatcher (or Code Mode) row whose calls have nested rows: the nested rows are those calls.\n const parents = new Set(nested.flatMap((call) => (typeof call.parentToolCallId === 'string' ? [call.parentToolCallId] : [])))\n let made = 0\n let failed = 0\n for (const message of rows) {\n let verdict: CallVerdict\n const call = nestedCallOf(message)\n if (call) verdict = nestedVerdict(call)\n else if (message.role !== 'toolResult' && message.role !== 'tool') continue\n else if (typeof message.toolCallId === 'string' && parents.has(message.toolCallId)) continue\n else verdict = callVerdict(message, calls, release)\n if (verdict === 'not_agentchat') continue\n if (verdict === 'unknown') return null\n made += 1\n if (verdict === 'failed') failed += 1\n }\n return { made, failed }\n}\n\n/**\n * Read the run's transcript and count its AgentChat calls. Never throws:\n * a runtime that cannot read the session (no method, a refusal, an empty\n * session) gives null — unknown, as `countAgentChatCalls` does for a read\n * it cannot trust.\n */\nexport async function readAgentChatCalls(runtime: PluginRuntime | null, sessionKey: string, runId?: string): Promise<AgentChatCalls | null> {\n if (!runtime || typeof runtime.subagent?.getSessionMessages !== 'function') return null\n try {\n const result = await runtime.subagent.getSessionMessages({ sessionKey, limit: TRANSCRIPT_READ_LIMIT })\n const messages: unknown = result?.messages\n const openclawVersion = typeof runtime.version === 'string' ? runtime.version : undefined\n return Array.isArray(messages) ? countAgentChatCalls(messages, runId, openclawVersion ? { openclawVersion } : {}) : null\n } catch {\n return null\n }\n}\n\nconst TOOL_PREFIX = `${MCP_SERVER_NAME}${MCP_TOOL_DELIMITER}`\n\n/** OpenClaw's Tool Search dispatcher, by release: `tool_call`, then `dispatch_action` (2026.10.10). */\nconst DISPATCHER_TOOL_NAMES: ReadonlySet<string> = new Set(['tool_call', 'dispatch_action'])\n\n/** Statuses OpenClaw reads as a failed tool result (`TOOL_RESULT_FAILURE_STATUSES`, `src/agents/tool-result-error.ts`). */\nconst FAILURE_STATUSES: ReadonlySet<string> = new Set([\n 'error',\n 'failed',\n 'failure',\n 'timeout',\n 'timed_out',\n 'blocked',\n 'denied',\n 'forbidden',\n 'unavailable',\n 'approval-unavailable',\n 'disabled',\n 'aborted',\n 'cancelled',\n 'canceled',\n 'killed',\n 'invalid',\n])\n\ntype CallVerdict = 'ok' | 'failed' | 'unknown' | 'not_agentchat'\n\n/**\n * Whether the rows read are the whole session. `sessions.get` (behind\n * `getSessionMessages`) numbers each message by its place in the session,\n * `__openclaw.seq` from 1 (2026.6.10 `src/gateway/session-utils.fs.ts`,\n * 2026.11.3 and main `src/gateway/session-transcript-entry-message.ts`), and\n * reads from the end — a session longer than the limit, or past the read's\n * byte cap, starts later. A compaction or reset marker, or an oversized\n * message's placeholder (`__openclaw.truncated`), stands for rows the read\n * does not carry.\n */\nfunction coversWholeSession(rows: readonly Record<string, unknown>[]): boolean {\n if (asRecord(rows[0]?.__openclaw)?.seq !== 1) return false\n return rows.every((row) => {\n const meta = asRecord(row.__openclaw)\n return meta?.kind !== 'compaction' && meta?.kind !== 'reset' && meta?.truncated !== true\n })\n}\n\n/** A row OpenClaw attributes to a run other than `runId`. */\nfunction isOtherRun(row: Record<string, unknown>, runId: string): boolean {\n const tagged = asRecord(row.__openclaw)?.runId ?? nestedCallOf(row)?.runId\n return typeof tagged === 'string' && tagged.trim().length > 0 && tagged.trim() !== runId\n}\n\n/** Tool Search's code mode (2026.6.10: `tool_search_code`, `src/agents/tool-search.ts`) and Code Mode's resume tool (`wait`, `src/agents/code-mode-control-tools.ts`); no other tool has these names. */\nconst CODE_MODE_ONLY_TOOL_NAMES: ReadonlySet<string> = new Set(['tool_search_code', 'wait'])\n\n/**\n * Whether the turn ran a Code Mode script. Code Mode's `exec` shares its name\n * with the shell's `exec` (`src/agents/code-mode-control-tools.ts`), so an\n * `exec` counts as Code Mode unless it is recognisably the shell's: Code\n * Mode's takes the script as `code` (the shell's schema has no `code`,\n * `src/agents/bash-tools.schemas.ts`) and its result carries `telemetry`;\n * the shell's result carries `exitCode` / `durationMs` / `aggregated`\n * (`src/agents/bash-tools.exec-runtime.ts`). Anything in between counts as\n * Code Mode — never as a turn without it.\n */\nfunction usedCodeMode(rows: readonly Record<string, unknown>[], calls: ReadonlyMap<string, Record<string, unknown>>): boolean {\n return [...calls.values()].some(isCodeModeCall) || rows.some((row) => isCodeModeResult(row, calls))\n}\n\n/**\n * Whether every Code Mode call has a result row that says its script\n * completed: `isError` not true and `details.status: 'completed'` (kept\n * when the details are truncated). A script that threw before a call it\n * meant to make (`status: 'failed'`, `isError: true`), or that returned\n * `waiting` with a call still pending, does not show every call it meant to\n * make. A waiting script later resumed by `wait` counts the same way: the\n * truncated rows keep no run id to pair them by.\n */\nfunction codeModeScriptsCompleted(rows: readonly Record<string, unknown>[], calls: ReadonlyMap<string, Record<string, unknown>>): boolean {\n const results = new Map<string, Record<string, unknown>>()\n for (const row of rows) {\n if ((row.role === 'toolResult' || row.role === 'tool') && typeof row.toolCallId === 'string') results.set(row.toolCallId, row)\n }\n const completed = (row: Record<string, unknown> | undefined) => row !== undefined && row.isError !== true && asRecord(row.details)?.status === 'completed'\n for (const [id, call] of calls) {\n if (isCodeModeCall(call) && !completed(results.get(id))) return false\n }\n return rows.every((row) => !isCodeModeResult(row, calls) || completed(row))\n}\n\nfunction isCodeModeCall(call: Record<string, unknown>): boolean {\n const name = typeof call.name === 'string' ? call.name : ''\n return CODE_MODE_ONLY_TOOL_NAMES.has(name) || (name === 'exec' && typeof callArguments(call)?.code === 'string')\n}\n\nfunction isCodeModeResult(row: Record<string, unknown>, calls: ReadonlyMap<string, Record<string, unknown>>): boolean {\n if (row.role !== 'toolResult' && row.role !== 'tool') return false\n const name = toolNameOf(row)\n return CODE_MODE_ONLY_TOOL_NAMES.has(name) || (name === 'exec' && !isShellExecResult(row, calls))\n}\n\nfunction isShellExecResult(row: Record<string, unknown>, calls: ReadonlyMap<string, Record<string, unknown>>): boolean {\n const call = typeof row.toolCallId === 'string' ? calls.get(row.toolCallId) : undefined\n const args = callArguments(call)\n if (!args || typeof args.command !== 'string' || args.code !== undefined) return false\n const details = asRecord(row.details)\n if (!details || details.telemetry !== undefined) return false\n return details.exitCode !== undefined || typeof details.durationMs === 'number' || typeof details.aggregated === 'string'\n}\n\n/** The assistant's tool calls by id (agent-core `toolCall` content blocks). */\nfunction assistantToolCalls(rows: readonly Record<string, unknown>[]): ReadonlyMap<string, Record<string, unknown>> {\n const calls = new Map<string, Record<string, unknown>>()\n for (const row of rows) {\n if (row.role !== 'assistant' || !Array.isArray(row.content)) continue\n for (const block of row.content) {\n const call = asRecord(block)\n if (call?.type === 'toolCall' && typeof call.id === 'string') calls.set(call.id, call)\n }\n }\n return calls\n}\n\n/** What a release is known to write. */\ninterface Release {\n /** Nested calls get rows of their own (`openclaw.nested-tool.v1`). */\n readonly recordsNestedCalls: boolean\n /** A failed call's row says so at its top level: `isError`, and a dispatcher's own `status` (2026.9.3). */\n readonly marksFailedRows: boolean\n}\n\n/** The first release this code trusts by version alone: failures marked on the row (openclaw/openclaw#139758) and nested calls recorded. */\nconst TRUSTED_RELEASE = '2026.9.3'\n\n/**\n * The release, by the host's OpenClaw version when it is readable — the\n * rows are then only data. When it is not, from what only that release\n * writes: a nested row (it records nested calls), and `dispatch_action`\n * (2026.10.10 and later) as the release itself wrote it — a dispatcher row\n * carrying its catalog entry, or a dispatcher call with nested rows under it.\n * A model's call to `dispatch_action` alone proves nothing: a model can\n * name a tool the release never offered.\n */\nfunction releaseOf(rows: readonly Record<string, unknown>[], calls: ReadonlyMap<string, Record<string, unknown>>, nested: readonly Record<string, unknown>[], version: string | undefined): Release {\n if (version !== undefined && isOpenClawVersion(version)) {\n const trusted = openclawVersionAtLeast(version, TRUSTED_RELEASE)\n return { recordsNestedCalls: trusted, marksFailedRows: trusted }\n }\n const parents = new Set(nested.map((call) => call.parentToolCallId))\n const dispatchAction =\n rows.some((row) => (row.role === 'toolResult' || row.role === 'tool') && toolNameOf(row) === 'dispatch_action' && asRecord(asRecord(row.details)?.tool) !== null) ||\n [...calls].some(([id, call]) => call.name === 'dispatch_action' && parents.has(id))\n return { recordsNestedCalls: nested.length > 0 || dispatchAction, marksFailedRows: dispatchAction }\n}\n\nconst OPENCLAW_VERSION = /^(\\d+)\\.(\\d+)\\.(\\d+)(-.+)?$/\n\nfunction isOpenClawVersion(value: string): boolean {\n return OPENCLAW_VERSION.test(value.trim())\n}\n\n/** `a >= b` for OpenClaw's `YYYY.M.N` versions; a prerelease is below its release, anything unreadable is below everything. */\nexport function openclawVersionAtLeast(a: string, b: string): boolean {\n const parse = (v: string) => {\n const match = OPENCLAW_VERSION.exec(v.trim())\n return match ? { parts: [Number(match[1]), Number(match[2]), Number(match[3])], pre: match[4] !== undefined } : null\n }\n const [x, y] = [parse(a), parse(b)]\n if (!x || !y) return false\n for (let i = 0; i < 3; i += 1) {\n const d = (x.parts[i] ?? 0) - (y.parts[i] ?? 0)\n if (d !== 0) return d > 0\n }\n return !x.pre || y.pre\n}\n\nfunction toolNameOf(row: Record<string, unknown>): string {\n return typeof row.toolName === 'string' ? row.toolName : typeof row.name === 'string' ? row.name : ''\n}\n\n/** OpenClaw's nested-call row (`NESTED_TOOL_ACTIVITY_CUSTOM_TYPE`, `src/sessions/nested-tool-activity.ts`): its details. */\nconst NESTED_TOOL_ACTIVITY = 'openclaw.nested-tool.v1'\n\nfunction nestedCallOf(row: Record<string, unknown>): Record<string, unknown> | null {\n if (row.role !== 'custom' || row.customType !== NESTED_TOOL_ACTIVITY) return null\n return asRecord(row.details)\n}\n\n/** A nested call: `isError` is OpenClaw's own reading of the result, and the result's details are read too when kept. */\nfunction nestedVerdict(call: Record<string, unknown>): CallVerdict {\n const toolName = typeof call.toolName === 'string' ? call.toolName : ''\n if (!toolName.startsWith(TOOL_PREFIX)) return 'not_agentchat'\n const result = asRecord(call.result)\n if (call.isError === true || (result !== null && failedResult(result.isError, asRecord(result.details)))) return 'failed'\n return call.isError === false ? 'ok' : 'unknown'\n}\n\n/**\n * Tools that hand work to another session's run, whose calls are stored in\n * that session: `sessions_spawn` starts a child session\n * (`src/agents/tools/sessions-spawn-tool.ts`; 2026.6.10\n * `openclaw-tools-*.js`, 2026.11.3 `sessions-spawn-tool-*.mjs`), and\n * `sessions_send` starts a run in an existing one\n * (`src/agents/tools/sessions-send-tool.ts`, result `{ runId, status:\n * 'accepted', sessionKey, … }`; the same chunks).\n */\nconst OTHER_SESSION_TOOLS: ReadonlySet<string> = new Set(['sessions_spawn', 'sessions_send'])\n\n/** Whether the turn handed work to another session's run — called directly, through Tool Search, or from a script. */\nfunction delegatedToChild(rows: readonly Record<string, unknown>[], calls: ReadonlyMap<string, Record<string, unknown>>, nested: readonly Record<string, unknown>[]): boolean {\n const names = (value: unknown) => typeof value === 'string' && OTHER_SESSION_TOOLS.has(value)\n for (const call of calls.values()) {\n if (names(call.name)) return true\n if (typeof call.name === 'string' && DISPATCHER_TOOL_NAMES.has(call.name) && names(dispatchTarget(call))) return true\n }\n if (nested.some((call) => names(call.toolName))) return true\n return rows.some((row) => names(toolNameOf(row)) || names(asRecord(asRecord(row.details)?.tool)?.name))\n}\n\n/** What one tool row says about an AgentChat call (see `countAgentChatCalls` for the shapes). */\nfunction callVerdict(message: Record<string, unknown>, calls: ReadonlyMap<string, Record<string, unknown>>, release: Release): CallVerdict {\n const toolName = toolNameOf(message)\n const details = asRecord(message.details)\n if (toolName.startsWith(TOOL_PREFIX)) return directVerdict(message.isError, details)\n const entry = asRecord(details?.tool)\n if (entry && isAgentChatEntry(entry)) return dispatchedVerdict(message.isError, details)\n if (!DISPATCHER_TOOL_NAMES.has(toolName) || entry) return 'not_agentchat'\n // A dispatcher row without a catalog entry: the target threw or never\n // resolved, and only the assistant's call says what it was.\n const target = dispatchTarget(typeof message.toolCallId === 'string' ? calls.get(message.toolCallId) : undefined)\n if (target === null) return 'unknown'\n if (!target.startsWith(TOOL_PREFIX)) return 'not_agentchat'\n if (failedResult(message.isError, details)) return 'failed'\n // Details over 8 KiB: from 2026.9.3 a failure keeps its top-level status, so none is a success.\n if (release.marksFailedRows && isTruncated(details) && message.isError === false && details?.status === undefined) return 'ok'\n return 'unknown'\n}\n\n/** Details the persistence guard replaced (`persistedDetailsTruncated`). */\nfunction isTruncated(details: Record<string, unknown> | null): boolean {\n return details?.persistedDetailsTruncated === true\n}\n\n/** A direct hosted-tool row. */\nfunction directVerdict(isError: unknown, details: Record<string, unknown> | null): CallVerdict {\n if (failedResult(isError, details)) return 'failed'\n if (isError !== false) return 'unknown'\n if (isTruncated(details)) return details?.status === undefined && wasHostedResult(details) ? 'ok' : 'unknown'\n return isHostedSuccessDetails(details) ? 'ok' : 'unknown'\n}\n\n/** A truncated row whose original details were the MCP materializer's (their keys are kept). */\nfunction wasHostedResult(details: Record<string, unknown> | null): boolean {\n const keys = Array.isArray(details?.originalDetailKeys) ? (details.originalDetailKeys as unknown[]) : []\n return keys.includes('mcpServer') && (keys.includes('mcpTool') || keys.includes('mcpOperation'))\n}\n\n/** A dispatcher row whose catalog entry is an AgentChat tool. */\nfunction dispatchedVerdict(isError: unknown, details: Record<string, unknown> | null): CallVerdict {\n const result = asRecord(details?.result)\n if (failedResult(isError, details)) return 'failed'\n if (result && failedResult(result.isError, asRecord(result.details))) return 'failed'\n const ok = isError === false && details?.status === undefined && isHostedSuccessDetails(asRecord(result?.details))\n return ok ? 'ok' : 'unknown'\n}\n\nfunction failedResult(isError: unknown, details: Record<string, unknown> | null): boolean {\n return isError === true || detailsSayFailed(details)\n}\n\n/**\n * OpenClaw's reading of a failed result from its details (`isToolResultError`,\n * `src/agents/tool-result-error.ts` — the same rule on 2026.6.10, 2026.11.3\n * and main).\n */\nfunction detailsSayFailed(details: Record<string, unknown> | null): boolean {\n if (!details) return false\n if (details.ok === false || details.success === false) return true\n const status = typeof details.status === 'string' ? details.status.trim().toLowerCase() : ''\n const explicitlyOk = details.ok === true || details.success === true\n if (FAILURE_STATUSES.has(status) && !explicitlyOk) return true\n if (details.timedOut === true || Boolean(details.error)) return true\n if (status === 'completed') return false\n const exitCode = details.exitCode\n return typeof exitCode === 'number' && Number.isFinite(exitCode) && exitCode !== 0\n}\n\n/** The details the MCP materializer gives a hosted call that succeeded: the server named, no status. */\nfunction isHostedSuccessDetails(details: Record<string, unknown> | null): boolean {\n if (!details || details.mcpServer !== MCP_SERVER_NAME || details.status !== undefined) return false\n return nonEmpty(details.mcpTool) !== undefined || nonEmpty(details.mcpOperation) !== undefined\n}\n\nfunction isAgentChatEntry(tool: Record<string, unknown>): boolean {\n if (typeof tool.name === 'string' && tool.name.startsWith(TOOL_PREFIX)) return true\n if (tool.sourceName === MCP_SERVER_NAME) return true\n const mcp = asRecord(tool.mcp)\n return mcp?.serverName === MCP_SERVER_NAME\n}\n\n/**\n * The tool a dispatcher call named: its `id`, `toolId` or `name` argument,\n * a catalog id (`mcp:<source>:<tool>`) or the tool's name. Null when the\n * call is not there or names nothing.\n */\nfunction dispatchTarget(call: Record<string, unknown> | undefined): string | null {\n const record = callArguments(call)\n const selector = nonEmpty(record?.id) ?? nonEmpty(record?.toolId) ?? nonEmpty(record?.name)\n if (!selector) return null\n const trimmed = selector.trim()\n return trimmed.slice(trimmed.lastIndexOf(':') + 1)\n}\n\n/** A tool call's arguments as a record (a provider may leave them a JSON string). Null when there are none. */\nfunction callArguments(call: Record<string, unknown> | undefined): Record<string, unknown> | null {\n if (!call) return null\n let args: unknown = call.arguments\n if (typeof args === 'string') {\n try {\n args = JSON.parse(args)\n } catch {\n return null\n }\n }\n return asRecord(args)\n}\n\n/** A transcript row is either the message itself or an event wrapping it (`{ type: 'message', message }`). */\nfunction unwrapMessage(row: unknown): Record<string, unknown> | null {\n const record = asRecord(row)\n if (!record) return null\n if (typeof record.role === 'string') return record\n const inner = asRecord(record.message)\n return inner && typeof inner.role === 'string' ? inner : null\n}\n\nfunction asRecord(value: unknown): Record<string, unknown> | null {\n return value !== null && typeof value === 'object' && !Array.isArray(value) ? (value as Record<string, unknown>) : null\n}\n\nfunction nonEmpty(value: unknown): string | undefined {\n return typeof value === 'string' && value.trim().length > 0 ? value : undefined\n}\n\nfunction describe(err: unknown): string {\n return err instanceof Error ? err.message : String(err)\n}\n\nfunction defaultSleep(ms: number): Promise<void> {\n return new Promise((resolve) => {\n const timer = setTimeout(resolve, ms)\n timer.unref?.()\n })\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 the run's end are reported\n * separately (`TurnAdmission`): `done` resolves only once OpenClaw\n * confirms the run is over (`./run.ts` — a `waitForRun` timeout bounds\n * the wait, never the run, so it is asked again), with the AgentChat\n * calls the run made read from its transcript when OpenClaw allows it.\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 { readAgentChatCalls, watchRunUntilEnded, type AgentChatCalls, type RunEndStatus } from './run.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\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, options) => {\n const runtime = getRuntime()\n if (!runtime) throw new RuntimeUnavailableError('the gate call')\n // Two reasons to stop: our own timeout, and the kit's gate-call deadline\n // (the loop aborts its signal when it no longer wants the answer).\n // OpenClaw's `llm.complete` takes an AbortSignal, so both reach the call.\n const signals = [\n ...(Number.isFinite(timeoutMs) && timeoutMs > 0 ? [AbortSignal.timeout(timeoutMs)] : []),\n ...(options?.signal ? [options.signal] : []),\n ]\n const signal = signals.length === 0 ? undefined : signals.length === 1 ? signals[0] : AbortSignal.any(signals)\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 ...(signal ? { signal } : {}),\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\n/**\n * How an admitted turn's run ended, once OpenClaw confirmed it. `status`:\n * `ok` / `error` / `timeout` (the run's own deadline — never an elapsed\n * wait), or `gone` when the plugin runtime disappeared before an end was\n * confirmed (the gateway is going down; nothing in this process starts\n * another turn after it).\n */\nexport interface TurnOutcome {\n readonly ran: boolean\n readonly runId?: string\n readonly status?: RunEndStatus | 'gone'\n readonly error?: string\n /** AgentChat tool calls the run made, from its transcript; null when unknown — the transcript could not be read, or may be cut, or a call's outcome cannot be read from it (never zero, never all-ok). */\n readonly agentchatCalls?: AgentChatCalls | null\n /** From admission to the confirmed end. */\n readonly elapsedMs?: number\n}\n\n/**\n * What starting a turn reports: refused (OpenClaw did not admit\n * the run — no runtime, a thrown `subagent.run`), or admitted with the\n * promise of its end. `done` never rejects and resolves only when OpenClaw\n * confirmed the end (or the runtime is gone).\n */\nexport type TurnAdmission =\n | { readonly ran: false; readonly error: string }\n | { readonly ran: true; readonly runId: string; readonly sessionKey: string; readonly done: Promise<TurnOutcome> }\n\n/** Starts one agent turn. Injectable so the loop wiring 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.current()` (OpenClaw main) or\n * `runtime.config.loadConfig()` (older releases) 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 const config = (runtime() as { config?: { current?: () => unknown; loadConfig?: () => unknown } } | null)?.config\n // OpenClaw main: `runtime.config.current()` (`loadConfig` is gone there);\n // older releases: `runtime.config.loadConfig()`.\n for (const read of [config?.current, config?.loadConfig]) {\n if (typeof read !== 'function') continue\n try {\n const loaded: unknown = read.call(config)\n if (loaded && typeof loaded === 'object') return { cfg: loaded, live: true }\n } catch {\n // try the next way, then the snapshot\n }\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 receive loop 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 agent's send is a\n * hosted-tool call inside the turn. `done` resolves when OpenClaw confirms\n * the run ended (`watchRunUntilEnded`), then carries the AgentChat calls\n * counted from the run's transcript. It never rejects.\n */\nexport function createRuntimeTurnStarter(params: {\n runtime?: () => PluginRuntime | null\n /** One `waitForRun` call; the watch asks again until the run is over. */\n waitChunkMs?: number\n /** Called each time a wait elapses with the run still going. */\n onStillRunning?: (info: { runId: string; sessionKey: string; elapsedMs: number }) => void\n /** Called when a wait call fails (the watch retries). */\n onWaitError?: (info: { runId: string; sessionKey: string; error: string; attempt: number; retryInMs: number }) => void\n now?: () => number\n sleep?: (ms: number) => Promise<void>\n} = {}): TurnStarter {\n const getRuntime = params.runtime ?? getPluginRuntime\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 // The session OpenClaw accepted the run in: newer releases return the\n // normalized key, which is where its transcript lives.\n let sessionKey = request.sessionKey\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 const accepted = (admitted as { sessionKey?: unknown }).sessionKey\n if (typeof accepted === 'string' && accepted.trim().length > 0) sessionKey = accepted.trim()\n } catch (err) {\n return { ran: false, error: err instanceof Error ? err.message : String(err) }\n }\n const done = watchRunUntilEnded({\n runtime: getRuntime,\n runId,\n ...(params.waitChunkMs !== undefined ? { chunkMs: params.waitChunkMs } : {}),\n ...(params.onStillRunning ? { onStillRunning: (elapsedMs: number) => params.onStillRunning?.({ runId, sessionKey, elapsedMs }) } : {}),\n ...(params.onWaitError\n ? { onWaitError: (error: string, attempt: number, retryInMs: number) => params.onWaitError?.({ runId, sessionKey, error, attempt, retryInMs }) }\n : {}),\n ...(params.now ? { now: params.now } : {}),\n ...(params.sleep ? { sleep: params.sleep } : {}),\n }).then(async (watched): Promise<TurnOutcome> => {\n if (!watched.ended) return { ran: true, runId, status: 'gone', elapsedMs: watched.elapsedMs }\n const agentchatCalls = await readAgentChatCalls(getRuntime(), sessionKey, runId)\n return {\n ran: true,\n runId,\n status: watched.status,\n ...(watched.error ? { error: watched.error } : {}),\n agentchatCalls,\n elapsedMs: watched.elapsedMs,\n }\n })\n return { ran: true, runId, sessionKey, done }\n }\n}\n\n/**\n * Watches a run this process did not start — one OpenClaw's restart resume\n * started in a turn's session — until OpenClaw reports it ended, and what\n * AgentChat calls it made. Resolves null only when the plugin runtime is\n * gone. Never rejects.\n */\nexport function createRunWatcher(params: {\n runtime?: () => PluginRuntime | null\n onStillRunning?: (info: { runId: string; sessionKey: string; elapsedMs: number }) => void\n waitChunkMs?: number\n} = {}): (run: { runId: string; sessionKey: string }) => Promise<TurnOutcome | null> {\n const getRuntime = params.runtime ?? getPluginRuntime\n return async ({ runId, sessionKey }) => {\n const watched = await watchRunUntilEnded({\n runtime: getRuntime,\n runId,\n ...(params.waitChunkMs !== undefined ? { chunkMs: params.waitChunkMs } : {}),\n ...(params.onStillRunning ? { onStillRunning: (elapsedMs: number) => params.onStillRunning?.({ runId, sessionKey, elapsedMs }) } : {}),\n })\n if (!watched.ended) return null\n const agentchatCalls = await readAgentChatCalls(getRuntime(), sessionKey, runId)\n return { ran: true, runId, status: watched.status, ...(watched.error ? { error: watched.error } : {}), agentchatCalls, elapsedMs: watched.elapsedMs }\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 {\n CLIENT_HEADER,\n clientIdentityHeaders,\n clientIdentityText,\n describeMcpEntry,\n describeMcpIdentity,\n hostedMcpUrl,\n withHostedMcpEntry,\n withoutHostedMcpEntry,\n type McpEntryOutcome,\n} 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 if (mcp.outcome === 'updated') changes.push(`mcp.servers.agentchat names this client (${clientIdentityText()})`)\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 'updated':\n return { name: 'mcp', status: 'changed', detail: `mcp.servers.agentchat now names this client to the hosted tools (${clientIdentityText()})` }\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 /** Works, but should be fixed: doctor warns and status shows it, without failing the check. */\n readonly notice?: boolean\n /** `openclaw doctor --fix` repairs it. */\n readonly repair?: boolean\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 checks.push(checkMcpEntry(params.cfg, params.apiBase, params.apiKey, remedy))\n return checks\n}\n\n/**\n * The tools entry: present and enabled, and naming this client. An entry\n * of ours from an earlier release works but names no client; the gateway\n * adds the header at its next start and `doctor --fix` does now. A hand-written entry that names no client works too, but\n * AgentChat then treats the agent as an unknown client and lists the\n * wake-webhook tools; only the operator can change it, so the line says how.\n */\nfunction checkMcpEntry(cfg: unknown, apiBase: string, apiKey: string | undefined, remedy: (forEnabled: string) => string): PlacementCheck {\n const unknownClient = 'AgentChat treats the agent as an unknown client and lists the webhook-setup tools it does not need'\n switch (describeMcpEntry(cfg, apiBase, apiKey)) {\n case 'ours': {\n const identity = describeMcpIdentity(cfg)\n if (identity === 'current') return { name: 'mcp', ok: true, detail: 'hosted tools registered as mcp.servers.agentchat' }\n return {\n name: 'mcp',\n ok: true,\n notice: true,\n repair: true,\n detail:\n `hosted tools registered as mcp.servers.agentchat, without ${CLIENT_HEADER} — ${unknownClient}; ` +\n `the gateway adds ${clientIdentityText()} to the entry when it starts (its log says if it could not), and openclaw doctor --fix does now`,\n }\n }\n case 'user_managed': {\n if (describeMcpIdentity(cfg) === 'current') return { name: 'mcp', ok: true, detail: 'mcp.servers.agentchat is managed by hand' }\n const identity = clientIdentityHeaders()\n return {\n name: 'mcp',\n ok: true,\n notice: true,\n detail:\n `mcp.servers.agentchat is managed by hand and does not name this client, so ${unknownClient} — ` +\n `add \"${CLIENT_HEADER}\": \"${identity[CLIENT_HEADER]}\" to its headers`,\n }\n }\n case 'disabled':\n return { name: 'mcp', ok: false, detail: 'mcp.servers.agentchat is disabled — the agent has no AgentChat tools' }\n case 'missing':\n return { name: 'mcp', ok: false, repair: true, detail: `mcp.servers.agentchat missing — ${remedy('run openclaw doctor --fix (or openclaw channels add agentchat)')}` }\n }\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: the served texts (`texts.json`), a cache\n * of what the server serves, so a gateway can start while the server is\n * unreachable; and the turns in flight (`turns.json`, `./turn-store.ts`), so\n * the next start after a gateway restart holds their conversations. Files\n * earlier releases kept here are removed on start (`removeOldStateFiles`).\n * Nothing secret, nothing authoritative — deleting the directory costs one\n * texts fetch (and, while the gateway is stopped, the restart defense for\n * that one restart).\n *\n * Both are written atomically (temp file + rename; the kit's cache also\n * fsyncs).\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/** Files earlier releases kept here that nothing reads any more. */\nexport const OLD_INVITE_LEDGER_FILE = 'invites.json'\n\n/**\n * Upgrade cleanup, once per start: the invite ledger of earlier releases\n * (invites now come from the tray) and a texts cache in the earlier shape\n * (the kit's cache keeps `{ version: 1, runtime, fetched_at, texts }`; an\n * older file is ignored by it and would only linger). Never throws; returns\n * what was removed.\n */\nexport function removeOldStateFiles(accountId: string, stateDir?: string): string[] {\n const dir = integrationStateDir(accountId, stateDir)\n const removed: string[] = []\n const ledger = path.join(dir, OLD_INVITE_LEDGER_FILE)\n if (tryUnlink(ledger)) removed.push(ledger)\n const texts = path.join(dir, 'texts.json')\n try {\n const entry = JSON.parse(fs.readFileSync(texts, 'utf8')) as { version?: unknown; runtime?: unknown }\n if (entry.version !== 1 || typeof entry.runtime !== 'string') {\n if (tryUnlink(texts)) removed.push(texts)\n }\n } catch (err) {\n // Absent: nothing to do. Unreadable or not JSON: an old or damaged copy.\n if ((err as NodeJS.ErrnoException)?.code !== 'ENOENT' && tryUnlink(texts)) removed.push(texts)\n }\n return removed\n}\n\nfunction tryUnlink(file: string): boolean {\n try {\n fs.unlinkSync(file)\n return true\n } catch {\n return false\n }\n}\n\n","/**\n * The served texts: the SDK kit's `TextsCache`, kept in the plugin's state dir.\n *\n * Every text an agent sees is written once on the server and served as data\n * (`GET /v1/texts?runtime=openclaw`): the wake instruction, the invite\n * prompt, the gate-call preamble and answer format, the reply-turn template,\n * the identity line, where the manual is. The kit's cache fetches them at channel start and daily,\n * keeps the last good copy in `<state dir>/agentchat/<accountId>/texts.json`\n * (an offline start is not mute), and backs off after a failure. The server\n * spells the hosted tools for `runtime=openclaw` the way OpenClaw exposes\n * them (`agentchat__<tool>`); the copy handed out is still passed through the\n * idempotent re-speller (a no-op then), so a server that serves bare names\n * again — a rolled-back deploy — cannot hand the agent wrong tool names. The\n * stored copy is always server-verbatim.\n */\n\nimport * as fs from 'node:fs'\nimport * as path from 'node:path'\n\nimport { integration, type AgentChatClient, type Texts } from 'agentchatme'\n\nimport type { Logger } from '../log.js'\nimport { integrationStateDir } from './state.js'\nimport { spellToolsForOpenClaw } from './turn.js'\n\nexport const TEXTS_RUNTIME = 'openclaw' as const\nexport const TEXTS_CACHE_FILE = 'texts.json'\n\nexport type TextsClient = Pick<AgentChatClient, 'texts'> & { readonly baseUrl?: string }\n\n/** Where the kit's cache keeps the last good copy for this account. */\nexport function textsCachePath(accountId: string, stateDir?: string): string {\n return path.join(integrationStateDir(accountId, stateDir), TEXTS_CACHE_FILE)\n}\n\n/**\n * Served fields newer than the installed SDK's `Texts` type. Optional: an\n * older server (or a copy cached before it served them) has none.\n * - `reply_turn_template` (contract v1): what a gate-call reply turn starts\n * with, for the one conversation its `reply` verdict names. The kit builds\n * that prompt; the plugin only spells its tool names.\n */\ntype NewerTexts = Texts & { readonly reply_turn_template?: unknown }\n\n/** Re-spell the hosted tool names in every agent-facing text. Pure, idempotent; the stored copy stays server-verbatim. */\nexport function spellTextsForOpenClaw(texts: Texts): Texts {\n const newer: NewerTexts = texts\n return {\n ...texts,\n ...(typeof newer.reply_turn_template === 'string' ? { reply_turn_template: spellToolsForOpenClaw(newer.reply_turn_template) } : {}),\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 ...(typeof texts.gate_call_preamble === 'string' ? { gate_call_preamble: spellToolsForOpenClaw(texts.gate_call_preamble) } : {}),\n ...(typeof texts.gate_call_answer_format === 'string' ? { gate_call_answer_format: spellToolsForOpenClaw(texts.gate_call_answer_format) } : {}),\n }\n}\n\n/** The kit's cache for one account, its file in the plugin's state dir. */\nexport function createTextsCache(params: {\n client: TextsClient\n accountId: string\n stateDir?: string | undefined\n logger?: Logger\n}): integration.TextsCache {\n return new integration.TextsCache({\n client: params.client,\n runtime: TEXTS_RUNTIME,\n filePath: textsCachePath(params.accountId, params.stateDir),\n ...(params.logger ? { onError: (err: Error) => params.logger?.warn({ err: err.message }, 'served texts') } : {}),\n })\n}\n\n/**\n * What the receive loop reads: the cache's copy through the re-speller. The\n * spelled copy is memoised per served copy, so a cycle does not re-spell.\n */\nexport class OpenClawTexts implements integration.TextsSource {\n private spelledFrom: Texts | null = null\n private spelled: Texts | null = null\n\n constructor(private readonly cache: integration.TextsCache) {}\n\n current(): Texts | null {\n return this.spell(this.cache.current())\n }\n\n async ensure(): Promise<Texts | null> {\n return this.spell(await this.cache.ensure())\n }\n\n get source(): string {\n return this.cache.source\n }\n\n get fetchedAt(): string | null {\n return this.cache.fetchedAt\n }\n\n get lastError(): string | null {\n return this.cache.lastError\n }\n\n private spell(texts: Texts | null): Texts | null {\n if (texts === null) return null\n if (texts !== this.spelledFrom) {\n this.spelledFrom = texts\n this.spelled = spellTextsForOpenClaw(texts)\n }\n return this.spelled\n }\n}\n\nexport interface LoadTextsParams {\n readonly client: TextsClient\n readonly accountId: string\n readonly stateDir?: string | undefined\n}\n\n/**\n * The identity line for the key's own agent, as served — for the\n * placement paths that run outside the gateway (wizard, `channels add`,\n * `doctor --fix`, re-enable). One fetch through the kit's cache (the server,\n * else the file it keeps); `null` when neither has a copy. Never throws.\n */\nexport async function loadIdentityLine(params: LoadTextsParams): Promise<string | null> {\n const cache = createTextsCache(params)\n try {\n const texts = await cache.start()\n return texts ? spellToolsForOpenClaw(texts.identity_line) : null\n } catch {\n return null\n } finally {\n cache.stop()\n }\n}\n\n/** The cached identity line, without touching the network (status, doctor preview). Reads the kit's file. */\nexport function cachedIdentityLine(accountId: string, stateDir?: string): string | null {\n let raw: string\n try {\n raw = fs.readFileSync(textsCachePath(accountId, stateDir), 'utf8')\n } catch {\n return null\n }\n try {\n const entry = JSON.parse(raw) as { runtime?: unknown; texts?: unknown }\n if (entry.runtime !== TEXTS_RUNTIME || !isTexts(entry.texts)) return null\n return spellToolsForOpenClaw(entry.texts.identity_line)\n } catch {\n return null\n }\n}\n\n/** The shape every consumer relies on: the kit's own check. */\nexport const isTexts: (value: unknown) => value is Texts = integration.isTexts\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_…` 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_… 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_…)',\n helpTitle: 'AgentChat API key',\n helpLines: [\n 'Format: ac_ followed by 43 base64url characters. 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 * The after-turn recording for a turn the kit's loop no longer watches.\n *\n * Normally the kit's receive loop records what a turn did once its run ends\n * (contract v1, D5: `turnOutcome` / `applyOutcome` on a fresh tray). Two\n * kinds of turn end outside that watch, and this applies the same rule to\n * them:\n *\n * - a turn handed off after 30 minutes (`AccountTurns.handOff`): the kit\n * let go of it to free its slot, so without this an answer sent at\n * minute 35 would record nothing and the card would be gated again;\n * - a turn a gateway restart ended, read again on the next start, and a\n * run OpenClaw's restart resume started in that turn's session\n * (`AccountTurns.adopt`).\n *\n * The kit's per-anchor memory of earlier silent turns is the loop's own, so\n * a silent end here counts as the first (`silentBefore` 0): nothing is\n * recorded and the card is gated again — never a dismiss on a count this\n * side cannot know.\n */\n\nimport { integration, type AgentChatClient, type InboxCard, type InboxTray } from 'agentchatme'\n\nimport type { Logger } from '../log.js'\nimport type { RunRecord } from './running.js'\n\n/** The tray read the kit's loop makes after a turn. */\nconst TRAY_LIMIT = 50\n\n/** Records what a turn did, from a fresh tray. Never rejects. */\nexport type AfterTurnRecorder = (record: RunRecord, end: integration.TurnEnd) => Promise<void>\n\nexport type AfterTurnClient = Pick<AgentChatClient, 'inbox' | 'decisions' | 'groups'>\n\nexport function createAfterTurnRecorder(options: { client: AfterTurnClient; logger: Logger }): AfterTurnRecorder {\n const { client, logger } = options\n return async (record, end) => {\n if (end.status === 'still_running' || record.kind === 'run') return\n let fresh: InboxTray | null\n try {\n fresh = await client.inbox.tray({ waitMs: 0, limit: TRAY_LIMIT, includeInvites: true })\n } catch (err) {\n // The card stays on the tray; the server re-wakes it.\n logger.warn({ runId: record.runId, err: describe(err) }, 'after-turn tray read failed — nothing recorded; the server re-wakes the card')\n fresh = null\n }\n try {\n if (record.kind === 'reply') {\n if (!record.card) return\n const outcome = integration.turnOutcome({\n turn: end,\n turnStartedAt: record.startedAt,\n gateCard: record.card,\n category: (record.category ?? null) as integration.TurnOutcomeInput['category'],\n freshTray: fresh,\n silentBefore: 0,\n })\n const recorded = await integration.applyOutcome(client, outcome)\n logger.info({ runId: record.runId, conversationId: record.id, action: outcome.action, reason: outcome.reason, recorded }, 'after-turn rule applied (turn ended outside the loop’s watch)')\n return\n }\n if (!record.invite) return\n const outcome = integration.inviteOutcome({ turn: end, invite: record.invite, freshTray: fresh, silentBefore: 0 })\n const recorded = await integration.applyInviteOutcome(client, outcome)\n logger.info({ runId: record.runId, inviteId: record.id, action: outcome.action, reason: outcome.reason, recorded }, 'after-turn rule applied to the invite (turn ended outside the loop’s watch)')\n } catch (err) {\n logger.warn({ runId: record.runId, err: describe(err) }, 'after-turn recording failed — the card stays on the tray; the server re-wakes it')\n }\n }\n}\n\n/** The card the gate saw, rebuilt from what was stored (no message text). */\nexport function cardFromStored(stored: { conversation_id: string } & Record<string, unknown>): InboxCard {\n return { preview: null, ...stored } as unknown as InboxCard\n}\n\nfunction describe(err: unknown): string {\n return err instanceof Error ? err.message : String(err)\n}\n","/**\n * The turns in flight, on disk: `<state>/agentchat/<accountId>/turns.json`.\n *\n * Why it exists: a gateway restart ends every run with the process, and\n * OpenClaw (current main) may then continue a plugin's turn session on its\n * own. A plugin run started with no requester is registered under the\n * agent's main session (`registerPluginSubagentRunFromGateway`,\n * `src/gateway/server-methods/agent-subagent-registration.ts`), restart\n * resume walks a live subagent session up to that root\n * (`resolveRootSubagentRequester`) and wakes it with \"send a fresh\n * instruction to the same retained child session when appropriate\"\n * (`src/gateway/session-restart-resume.ts`). So after a restart the agent\n * may run our turn's session again while the new receive loop would gate\n * the same card and start a second turn. The new process knows neither the\n * old run nor its conversation, and a third-party plugin has no public API\n * that lists live runs (`readSessionFacts` is for bundled / trusted\n * official plugins only). So the turns in flight are written here, and the\n * next start holds their conversations for a while (`AccountTurns.adopt`).\n *\n * What is written: the run id, the turn's session key, what it held (the\n * conversation or invite id and the message the gate read through), and the\n * few card fields the after-turn rule compares — never message text.\n * Written atomically (temp file + rename) on every change; an entry whose\n * run ended stays `KEEP_ENDED_MS` longer, because a restart ends a run\n * before it ends the process. Never throws: a file that cannot be written\n * costs only the defense, and one that cannot be read is treated as empty.\n */\n\nimport * as fs from 'node:fs'\nimport * as path from 'node:path'\n\nimport type { InboxCard } from 'agentchatme'\n\nimport { integrationStateDir } from './state.js'\n\nexport const TURN_STORE_FILE = 'turns.json'\n\n/** An ended run's entry stays this long (a restart ends the run a few seconds before the process). */\nexport const KEEP_ENDED_MS = 60_000\n\n/** The card fields the after-turn rule reads (`turnOutcome`): no message text. */\nexport type StoredCard = Pick<InboxCard, 'conversation_id'> & {\n readonly last_message_id?: string | null\n readonly your_last_message_at?: string | null\n readonly you_owe_reply?: boolean\n readonly your_last_decision?: InboxCard['your_last_decision'] | null\n}\n\nexport interface StoredTurn {\n readonly runId: string\n readonly kind: 'reply' | 'invite'\n /** The conversation id (reply) or the invite id. */\n readonly id: string\n readonly anchor: string | null\n readonly sessionKey: string\n /** Local clock, ms. */\n readonly startedAt: number\n /** When the first turn of this chain started (a turn continued after a restart keeps it): stored turns age out by it. */\n readonly firstStartedAt?: number\n readonly category?: string | null\n readonly card?: StoredCard\n}\n\ninterface StoreFile {\n readonly version: 1\n readonly turns: readonly StoredTurn[]\n}\n\n/** The card as stored: the fields the rule compares, the anchor as `last_message_id`. */\nexport function storedCard(card: InboxCard, anchor: string | null): StoredCard {\n return {\n conversation_id: card.conversation_id,\n ...(anchor ? { last_message_id: anchor } : {}),\n ...(card.your_last_message_at !== undefined ? { your_last_message_at: card.your_last_message_at } : {}),\n ...(card.you_owe_reply !== undefined ? { you_owe_reply: card.you_owe_reply } : {}),\n ...(card.your_last_decision !== undefined ? { your_last_decision: card.your_last_decision } : {}),\n }\n}\n\nexport class TurnStore {\n readonly file: string\n\n constructor(accountId: string, stateDir?: string) {\n this.file = path.join(integrationStateDir(accountId, stateDir), TURN_STORE_FILE)\n }\n\n /** What the last process left. Empty when there is no file or it cannot be read. */\n load(): StoredTurn[] {\n let parsed: unknown\n try {\n parsed = JSON.parse(fs.readFileSync(this.file, 'utf8'))\n } catch {\n return []\n }\n const turns = (parsed as { version?: unknown; turns?: unknown } | null)?.turns\n if ((parsed as { version?: unknown } | null)?.version !== 1 || !Array.isArray(turns)) return []\n return turns.filter(isStoredTurn)\n }\n\n /** Replace the file with `turns` (removed when empty). Returns false when the write failed. */\n write(turns: readonly StoredTurn[]): boolean {\n try {\n if (turns.length === 0) {\n fs.rmSync(this.file, { force: true })\n return true\n }\n fs.mkdirSync(path.dirname(this.file), { recursive: true })\n const body: StoreFile = { version: 1, turns }\n const tmp = `${this.file}.${process.pid}.tmp`\n fs.writeFileSync(tmp, `${JSON.stringify(body)}\\n`, { mode: 0o600 })\n fs.renameSync(tmp, this.file)\n return true\n } catch {\n return false\n }\n }\n}\n\nfunction isStoredTurn(value: unknown): value is StoredTurn {\n const turn = value as Partial<StoredTurn> | null\n return (\n typeof turn === 'object' &&\n turn !== null &&\n typeof turn.runId === 'string' &&\n (turn.kind === 'reply' || turn.kind === 'invite') &&\n typeof turn.id === 'string' &&\n turn.id.length > 0 &&\n typeof turn.sessionKey === 'string' &&\n turn.sessionKey.length > 0 &&\n typeof turn.startedAt === 'number' &&\n (turn.anchor === null || typeof turn.anchor === 'string')\n )\n}\n","/**\n * The account's turns, kept for the life of the gateway process — not of one\n * receive loop.\n *\n * A turn holds its conversation (or invite) until OpenClaw confirms its run\n * ended (`./run.ts`): while it runs, the card stays on the tray (nothing is\n * recorded before the turn ends), and gating it again would start a second\n * turn that answers the same message twice. The kit's `TurnTracker` is what\n * holds it, and there is one per account, handed to every loop for the\n * account: OpenClaw restarts an account's channel task on a config change\n * while the run started under the old loop goes on in OpenClaw's lane, so the\n * next loop leaves that card alone until the run ends (the old loop still\n * records what the run did). When a run that held a card ends, the account's\n * live loop is woken, so a message that arrived meanwhile is gated at once.\n *\n * A run OpenClaw never reports as ended must not freeze the account. After\n * `TURN_OVERDUE_MS` the turn is handed off, once: the kit's slot is released\n * and new turns move to a fresh OpenClaw lane (OpenClaw runs a lane's runs\n * one after another, so they would otherwise queue behind the hung run) —\n * other conversations get turns again — while this module keeps the\n * conversation held until OpenClaw reports that run ended, and then applies\n * the after-turn rule itself (`./after-turn.ts`: the kit no longer watches\n * it). At most `MAX_HUNG_TURNS` are held that way; beyond that, readiness\n * says not-ready (no gate calls) and status and doctor say why. An operator\n * can let one go: `openclaw agentchat release <conversation_id>`.\n *\n * Every hold here is keyed by run id. A run that was handed off or let go of\n * is never handed off again — whatever later \"still running\" reports say —\n * so a release sticks; and a run whose kit hold was released while OpenClaw\n * was still admitting it starts out let go of. Either way the old run can\n * never release a newer turn's hold on the same conversation.\n *\n * Gate off (single-run mode) one run reads the whole tray, so two would\n * answer the same cards: past `TURN_OVERDUE_MS` the cycle waiting on the run\n * is let go of (the loop is not stuck in it), but no new run starts while the\n * handed-off one lives — readiness says not-ready, status and doctor say why,\n * and `openclaw agentchat release <run id> --force` frees it.\n *\n * A gateway restart ends every run with the process, and OpenClaw (current\n * main) may continue a plugin's turn session afterwards: a plugin run with\n * no requester is registered under the agent's main session\n * (`src/gateway/server-methods/agent-subagent-registration.ts`), restart\n * resume walks a live subagent session up to that root — the \"subagent\"\n * skip applies to the root, which is the main session, not ours\n * (`src/gateway/session-restart-resume.ts`, `restartResumeSkipReason`) — and\n * wakes it with \"send a fresh instruction to the same retained child\n * session when appropriate\". Tested live: on 2026.11.5-beta.1 a restart\n * during a turn resumed `agent:<id>:main` with the restart text, its context\n * listing the AgentChat turn sessions; 2026.10.9 aborted the run and resumed\n * nothing. So the turns in flight are written to disk (`./turn-store.ts`)\n * and the next start adopts them (`adopt`): each conversation is held for\n * `RESTART_HOLD_MS`, and the after-turn rule is applied to what the ended run\n * did at once and again when the hold expires (an answer it — or the resumed\n * main session — sent records `reply`, so the card is not gated again). A\n * run OpenClaw starts in that turn's session during the hold — seen through\n * the `model_call_started` hook, the public way a plugin sees runs it did not\n * start — keeps the conversation held as a turn of its own: past\n * `TURN_OVERDUE_MS` it is handed off and counts toward `MAX_HUNG_TURNS`, and\n * when it ends it gets the after-turn rule. A stored turn first started more\n * than `STORED_TURN_MAX_AGE_MS` ago is dropped, so a restart storm cannot\n * re-adopt it forever. Not covered (accepted): a continuation that starts\n * after the hold, when the conversation may have been gated again. The wake\n * instruction and invite prompt AgentChat serves for OpenClaw end with a\n * restart note telling the agent not to continue an interrupted turn after a\n * restart (it promises no wake); that lowers the odds, it is no guarantee.\n * A plugin reload waits for the runs (OpenClaw drains a plugin's\n * admitted work first, and every turn holds it until it ends).\n */\n\nimport { integration, type InboxCard, type TrayInvite } from 'agentchatme'\n\nimport type { Logger } from '../log.js'\nimport { cardFromStored, type AfterTurnRecorder } from './after-turn.js'\nimport { KEEP_ENDED_MS, storedCard, type StoredTurn, type TurnStore } from './turn-store.js'\n\n/** A turn running longer than this is handed off and reported (the kit's threshold). */\nexport const TURN_OVERDUE_MS = 30 * 60_000\n\n/**\n * A wait that elapses comes back a few milliseconds early, so the sixth\n * 5-minute \"still running\" report lands at 29:59.9: the threshold allows\n * that much (seen live — without it the hand-off slipped to 35 minutes).\n */\nexport const OVERDUE_SLACK_MS = 5_000\n\n/** Whether a turn this old is past `TURN_OVERDUE_MS` (with the wait's slack). */\nexport function isOverdue(elapsedMs: number): boolean {\n return elapsedMs + OVERDUE_SLACK_MS >= TURN_OVERDUE_MS\n}\n\n/** Hung turns held at once before the account stops gating (each holds one conversation). */\nexport const MAX_HUNG_TURNS = 2\n\n/** OpenClaw's run deadline when `agents.defaults.timeoutSeconds` is unset (`src/agents/timeout.ts`: 48 h). */\nexport const OPENCLAW_DEFAULT_RUN_TIMEOUT_SECONDS = 2880 * 60\n\n/**\n * After a restart, how long a conversation whose turn the restart ended stays\n * held when nothing continues that turn's session. OpenClaw's restart resume\n * wakes the main session at boot; this covers its decision to send the turn\n * session a fresh instruction (seen at the run's first model call).\n */\nexport const RESTART_HOLD_MS = 3 * 60_000\n\n/** A stored turn first started longer ago than this is dropped, not adopted again (a restart storm). */\nexport const STORED_TURN_MAX_AGE_MS = 24 * 60 * 60_000\n\n/** reply: a conversation; invite: a group invite; run: the one run of a gate-off cycle. */\nexport type TurnKind = 'reply' | 'invite' | 'run'\n\n/** One OpenClaw run started for the account. */\nexport interface RunRecord {\n readonly runId: string\n readonly kind: TurnKind\n /** The conversation id (reply), the invite id (invite), or the run id (a gate-off run). */\n readonly id: string\n /** The message the gate's verdict read through (reply turns). */\n readonly anchor: string | null\n readonly sessionKey: string\n /** Local clock, ms. */\n readonly startedAt: number\n /** The loop that started it. */\n readonly owner: string\n /** reply: the card the gate decided on and its category — what the after-turn rule compares. */\n readonly card?: InboxCard\n readonly category?: string | null\n /** invite: the invite the turn was for. */\n readonly invite?: TrayInvite\n /** When the first turn of this chain started: a turn continued after a restart keeps its original's (stored turns age out by it). */\n readonly firstStartedAt?: number\n}\n\nexport type ReleaseResult =\n | { readonly released: true; readonly what: 'hung' | 'running' | 'restart'; readonly key: string; readonly runId: string | null }\n | { readonly released: false; readonly reason: string }\n\n/** Watches a run this process did not start until OpenClaw reports it ended; null when it cannot say. */\nexport type RunWatcher = (record: RunRecord) => Promise<integration.TurnEnd | null>\n\n/** The AgentChat calls an ended run made, from its transcript; null when unknown. */\nexport type CallReader = (sessionKey: string, runId: string) => Promise<integration.AgentChatCallCount | null>\n\nexport interface TurnsWiring {\n /** Applies the after-turn rule to a turn that ended outside the kit's watch. */\n readonly recorder?: AfterTurnRecorder\n /** Where the turns in flight are written (the restart defense). */\n readonly store?: TurnStore\n readonly watch?: RunWatcher\n readonly readCalls?: CallReader\n readonly logger?: Logger\n}\n\ninterface LiveLoop {\n readonly owner: string\n readonly wake: () => void\n /**\n * Runs `fn` in the async context the loop was created in. A release comes\n * in through a gateway RPC (`agentchat.release`); work it starts — the\n * wake's next cycle, a waiting turn admitted into the freed slot — must not\n * inherit that request's context, which OpenClaw retires when the RPC\n * returns (\"Gateway caller authority is no longer active\").\n */\n readonly run: <T>(fn: () => T) => T\n}\n\n/**\n * kit: the kit's loop holds it. watch: a run OpenClaw started in an adopted\n * turn's session, held here. hung: handed off, held here. released: let go\n * of; it holds nothing.\n */\ntype RunState = 'kit' | 'watch' | 'hung' | 'released'\n\ninterface Entry {\n readonly record: RunRecord\n state: RunState\n /** The hold this module keeps (hung reply / invite turns, continued runs). */\n handle: integration.TurnHandle | null\n /** When it was handed off. */\n since: number\n /** A gate-off run: ends the cycle that waits on it (the run goes on). */\n readonly letGo?: () => void\n}\n\n/** A turn the last process left in flight, held after a restart. */\ninterface Adopted {\n readonly stored: StoredTurn\n readonly record: RunRecord\n readonly handle: integration.TurnHandle\n readonly until: number\n /** What the ended run did (read once its transcript is): applied at the start and when the hold expires. */\n end: integration.TurnEnd | null\n timer: ReturnType<typeof setTimeout> | null\n}\n\n/** A turn OpenClaw is admitting: whether its kit hold was released meanwhile. */\nexport interface Admission {\n readonly key: string\n released: boolean\n}\n\nconst RESTART_END_DETAIL = 'the gateway restarted during the turn'\n\nfunction trackerKey(kind: TurnKind, id: string): string {\n return kind === 'reply' ? `conversation:${id}` : kind === 'invite' ? `invite:${id}` : `run:${id}`\n}\n\nfunction trackedTurn(record: RunRecord): integration.TrackedTurn | null {\n if (record.kind === 'reply') return { kind: 'reply', conversationId: record.id, anchor: record.anchor }\n if (record.kind === 'invite') return { kind: 'invite', inviteId: record.id }\n return null\n}\n\nfunction storedOf(record: RunRecord): StoredTurn | null {\n if (record.kind === 'run') return null\n return {\n runId: record.runId,\n kind: record.kind,\n id: record.id,\n anchor: record.anchor,\n sessionKey: record.sessionKey,\n startedAt: record.startedAt,\n ...(record.firstStartedAt !== undefined ? { firstStartedAt: record.firstStartedAt } : {}),\n ...(record.category !== undefined ? { category: record.category } : {}),\n ...(record.kind === 'reply' && record.card ? { card: storedCard(record.card, record.anchor) } : {}),\n }\n}\n\nfunction recordOf(stored: StoredTurn): RunRecord {\n return {\n runId: stored.runId,\n kind: stored.kind,\n id: stored.id,\n anchor: stored.anchor,\n sessionKey: stored.sessionKey,\n startedAt: stored.startedAt,\n firstStartedAt: stored.firstStartedAt ?? stored.startedAt,\n owner: 'previous-process',\n ...(stored.category !== undefined ? { category: stored.category } : {}),\n ...(stored.kind === 'reply' && stored.card ? { card: cardFromStored(stored.card as never) } : {}),\n ...(stored.kind === 'invite' ? { invite: { invite_id: stored.id } as TrayInvite } : {}),\n }\n}\n\nexport class AccountTurns {\n /** The kit's tracker for the account, shared by every loop for it. */\n readonly tracker: integration.TurnTracker\n private readonly entries = new Map<string, Entry>()\n /** Turns the last process left in flight, by session key. */\n private readonly adopted = new Map<string, Adopted>()\n /** Turns OpenClaw is admitting right now. */\n private readonly admitting = new Set<Admission>()\n /** Ended runs still written to the store (`KEEP_ENDED_MS`). */\n private readonly kept = new Map<string, { readonly turn: StoredTurn; readonly endedAt: number }>()\n private keptTimer: ReturnType<typeof setTimeout> | null = null\n private live: LiveLoop | null = null\n private wiring: TurnsWiring = {}\n /** Which OpenClaw lane new turns go to; moves on at every hand-off (a hung run blocks its lane). */\n private lane = 0\n private readonly now: () => number\n\n constructor(options: { now?: () => number } = {}) {\n this.now = options.now ?? Date.now\n this.tracker = new integration.TurnTracker({ now: this.now })\n // A kit hold released while OpenClaw is still admitting its run: that run\n // starts out let go of (`started`), so it can never release a newer\n // turn's hold on the same conversation.\n this.tracker.onRelease((handle) => {\n for (const admission of this.admitting) if (admission.key === handle.key) admission.released = true\n })\n }\n\n /** The account's after-turn recorder, store and run watcher (each account start; the latest wins). */\n configure(wiring: TurnsWiring): void {\n this.wiring = { ...this.wiring, ...wiring }\n }\n\n /** The loop now receiving for the account; a held run that ends wakes it. `run` = the loop's own async context (default: as called). */\n setLive(owner: string, wake: () => void, run: <T>(fn: () => T) => T = (fn) => fn()): void {\n this.live = { owner, wake, run }\n }\n\n clearLive(owner: string): void {\n if (this.live?.owner === owner) this.live = null\n }\n\n /** A turn is about to be admitted by OpenClaw: watch whether its kit hold is released meanwhile. */\n admission(kind: 'reply' | 'invite', id: string): Admission {\n const admission: Admission = { key: trackerKey(kind, id), released: false }\n this.admitting.add(admission)\n return admission\n }\n\n /** OpenClaw refused the turn: nothing to watch. */\n admitted(admission: Admission): void {\n this.admitting.delete(admission)\n }\n\n /**\n * A run OpenClaw admitted. `letGo` (gate-off runs): ends the cycle waiting\n * on it when it is handed off or released. `admission`: a turn whose kit\n * hold was released during admission starts out let go of.\n */\n started(record: RunRecord, options: { letGo?: () => void; admission?: Admission } = {}): void {\n const releasedMeanwhile = options.admission?.released === true\n if (options.admission) this.admitting.delete(options.admission)\n this.entries.set(record.runId, {\n record,\n state: releasedMeanwhile ? 'released' : 'kit',\n handle: null,\n since: 0,\n ...(options.letGo ? { letGo: options.letGo } : {}),\n })\n this.persist()\n }\n\n run(runId: string): RunRecord | undefined {\n return this.entries.get(runId)?.record\n }\n\n /** Where the run stands (`null`: not a run of this account, or ended). */\n stateOf(runId: string): RunState | null {\n return this.entries.get(runId)?.state ?? null\n }\n\n /** Every run OpenClaw has not reported ended that still holds something, oldest first. */\n runningRuns(): RunRecord[] {\n return [...this.entries.values()]\n .filter((entry) => entry.state !== 'released')\n .map((entry) => entry.record)\n .sort((a, b) => a.startedAt - b.startedAt)\n }\n\n hungRuns(): RunRecord[] {\n return [...this.entries.values()].filter((entry) => entry.state === 'hung').map((entry) => entry.record)\n }\n\n get hungCount(): number {\n let count = 0\n for (const entry of this.entries.values()) if (entry.state === 'hung') count += 1\n return count\n }\n\n /** The handed-off gate-off run still going, if any: no new run starts while it lives. */\n hungSingleRun(): RunRecord | null {\n for (const entry of this.entries.values()) if (entry.state === 'hung' && entry.record.kind === 'run') return entry.record\n return null\n }\n\n /** Conversations (and invites) held after a restart: adopted (until when), or continued by a run OpenClaw started. */\n restartHolds(): Array<{ readonly record: RunRecord; readonly until: number | null; readonly watching: string | null }> {\n const holds: Array<{ readonly record: RunRecord; readonly until: number | null; readonly watching: string | null }> = [...this.adopted.values()].map((a) => ({\n record: a.record,\n until: a.until,\n watching: null,\n }))\n for (const entry of this.entries.values()) if (entry.state === 'watch') holds.push({ record: entry.record, until: null, watching: entry.record.runId })\n return holds\n }\n\n /** The lane generation new turns start on (`integrationLane(accountId, laneGeneration)`). */\n get laneGeneration(): number {\n return this.lane\n }\n\n /**\n * OpenClaw reported the run ended (`end`: what it did, when known). A turn\n * held here (handed off, or continued after a restart) gets the after-turn\n * rule, then its hold drops and the live loop is woken. A turn the kit\n * still holds is the kit's to record; the live loop is woken once the card\n * is free, only when an earlier loop started it. A run let go of records\n * nothing.\n */\n async ended(runId: string, end?: integration.TurnEnd): Promise<void> {\n const entry = this.entries.get(runId)\n if (!entry) return\n this.entries.delete(runId)\n if (entry.state !== 'released') this.keep(entry.record)\n else this.persist()\n if (entry.state === 'hung' || entry.state === 'watch') {\n try {\n if (end && this.wiring.recorder && entry.record.kind !== 'run') await this.wiring.recorder(entry.record, end)\n } finally {\n if (entry.handle) this.tracker.end(entry.handle)\n this.live?.wake()\n }\n return\n }\n if (entry.state === 'released' || entry.record.kind === 'run') return\n if (!this.live || this.live.owner === entry.record.owner) return\n this.wakeWhenFree(trackerKey(entry.record.kind, entry.record.id))\n }\n\n /**\n * Hand a long run off, once, by run id: release the kit's slot for it (its\n * loop records nothing for it and may start other turns) and hold the\n * conversation here until the run ends. A gate-off run: the cycle waiting\n * on it is let go of. A continued run is already held here: it becomes\n * hung (counted toward `MAX_HUNG_TURNS`). Returns the record when it was\n * handed off now; null when it was already handed off or let go of.\n */\n handOff(runId: string): RunRecord | null {\n const entry = this.entries.get(runId)\n if (!entry || (entry.state !== 'kit' && entry.state !== 'watch')) return null\n const record = entry.record\n entry.since = this.now()\n if (entry.state === 'watch') {\n // Its own session, not one of our lanes; its hold is ours already.\n entry.state = 'hung'\n this.live?.wake()\n return record\n }\n // OpenClaw serializes a lane: the next turn must not queue behind this\n // run. Moved first — the release below can admit a waiting turn at once.\n this.lane += 1\n entry.state = 'hung'\n const turn = trackedTurn(record)\n if (turn === null) {\n entry.letGo?.()\n } else {\n this.tracker.release(trackerKey(record.kind, record.id))\n entry.handle = this.tracker.begin(turn)\n if (!entry.handle) entry.state = 'released'\n }\n this.live?.wake()\n return entry.state === 'hung' ? record : null\n }\n\n /**\n * An operator lets go of a conversation's (or invite's) turn: a hung hold,\n * a restart hold, or — past `TURN_OVERDUE_MS`, or with `force` — a turn\n * still running. Its run may still be live and answer: a second reply is\n * then possible, which is why a turn under 30 minutes (most likely still\n * working) is refused without `force`. A gate-off run always needs\n * `force`: it reads the whole tray, so a new run would answer the same\n * cards while it may still be going.\n */\n release(id: string, options: { force?: boolean } = {}): ReleaseResult {\n const live = this.live\n return live ? live.run(() => this.releaseNow(id, options.force === true)) : this.releaseNow(id, options.force === true)\n }\n\n private releaseNow(id: string, force: boolean): ReleaseResult {\n const matches = (record: RunRecord) => record.id === id || record.runId === id\n for (const entry of this.entries.values()) {\n if (entry.state !== 'hung' || !matches(entry.record)) continue\n if (entry.record.kind === 'run' && !force) return this.refuseSingleRun(entry.record)\n entry.state = 'released'\n if (entry.handle) this.tracker.end(entry.handle)\n entry.handle = null\n this.persist()\n this.live?.wake()\n return { released: true, what: 'hung', key: trackerKey(entry.record.kind, entry.record.id), runId: entry.record.runId }\n }\n for (const [sessionKey, adopted] of this.adopted) {\n if (adopted.record.id !== id) continue\n this.finishAdopted(sessionKey)\n return { released: true, what: 'restart', key: trackerKey(adopted.record.kind, adopted.record.id), runId: null }\n }\n for (const entry of this.entries.values()) {\n if ((entry.state !== 'kit' && entry.state !== 'watch') || !matches(entry.record)) continue\n const refused = this.refuseYoung(entry.record.kind, entry.record.id, entry.record.startedAt, force)\n if (refused) return refused\n const key = trackerKey(entry.record.kind, entry.record.id)\n if (entry.state === 'watch') {\n if (entry.handle) this.tracker.end(entry.handle)\n entry.handle = null\n } else {\n // The released run may still be going in its lane: new turns move on\n // (first — the release can admit a waiting turn at once).\n this.lane += 1\n if (entry.record.kind === 'run') entry.letGo?.()\n else this.tracker.release(key)\n }\n entry.state = 'released'\n this.persist()\n this.live?.wake()\n return { released: true, what: 'running', key, runId: entry.record.runId }\n }\n // Held by the kit with no run behind it yet (admitted, or waiting for a slot).\n for (const held of this.tracker.running()) {\n const heldId = held.kind === 'reply' ? held.conversationId : held.inviteId\n if (heldId !== id) continue\n const refused = this.refuseYoung(held.kind, heldId, held.startedAt, force)\n if (refused) return refused\n this.lane += 1\n const key = trackerKey(held.kind, heldId)\n if (this.tracker.release(key)) {\n this.live?.wake()\n return { released: true, what: 'running', key, runId: null }\n }\n }\n return { released: false, reason: `no turn holds ${id}` }\n }\n\n private refuseYoung(kind: TurnKind, id: string, startedAt: number, force: boolean): ReleaseResult | null {\n const age = this.now() - startedAt\n if (force || age >= TURN_OVERDUE_MS) return null\n return {\n released: false,\n reason: `the turn for ${whatOf(kind, id)} has run ${Math.floor(age / 60_000)} min — under ${TURN_OVERDUE_MS / 60_000} min it is most likely still working, and releasing it lets the conversation be gated again while that run can still send its answer (the peer would get two replies); wait, or repeat with --force`,\n }\n }\n\n private refuseSingleRun(record: RunRecord): ReleaseResult {\n return {\n released: false,\n reason: `${whatOf('run', record.runId)} has run ${Math.floor((this.now() - record.startedAt) / 60_000)} min and reads the whole tray — releasing it lets a new run answer the same cards while this one may still be going (the peers would get two replies); repeat with --force`,\n }\n }\n\n /**\n * Adopt the turns the last process left in flight (the store). Each one's\n * conversation (or invite) is held at once — before the loop's first gate —\n * for `RESTART_HOLD_MS`; the after-turn rule is applied to what the ended\n * run did now and again when the hold expires. A run OpenClaw starts in the\n * turn's session meanwhile (`observeRun`) takes the hold over. A turn first\n * started more than `STORED_TURN_MAX_AGE_MS` ago is dropped. Returns what\n * was adopted.\n */\n adopt(stored: readonly StoredTurn[] = this.wiring.store?.load() ?? []): RunRecord[] {\n const adopted: RunRecord[] = []\n const now = this.now()\n for (const turn of stored) {\n // Still running in this process (an account restart, not a gateway restart).\n if (this.entries.has(turn.runId) || this.adopted.has(turn.sessionKey) || this.kept.has(turn.runId)) continue\n const first = turn.firstStartedAt ?? turn.startedAt\n if (now - first > STORED_TURN_MAX_AGE_MS) {\n this.wiring.logger?.info({ runId: turn.runId, [turn.kind === 'reply' ? 'conversationId' : 'inviteId']: turn.id }, 'a stored turn older than a day was dropped, not adopted again')\n continue\n }\n const record = recordOf(turn)\n const tracked = trackedTurn(record)\n const handle = tracked ? this.tracker.begin(tracked) : null\n if (!handle) continue\n const entry: Adopted = { stored: { ...turn, firstStartedAt: first }, record, handle, until: now + RESTART_HOLD_MS, end: null, timer: null }\n this.adopted.set(turn.sessionKey, entry)\n entry.timer = setTimeout(() => this.expireAdopted(turn.sessionKey, entry), RESTART_HOLD_MS)\n entry.timer.unref?.()\n adopted.push(record)\n void this.recordRestartEnded(entry)\n }\n this.persist()\n return adopted\n }\n\n /**\n * A run started in some session (the `model_call_started` hook). One in\n * the session of a turn adopted after a restart is OpenClaw continuing\n * that turn: it takes the hold over as a turn of its own (`watch`), handed\n * off past `TURN_OVERDUE_MS` like any other.\n */\n observeRun(runId: string, sessionKey: string | undefined): void {\n if (!sessionKey || this.entries.has(runId)) return\n const adopted = this.adopted.get(sessionKey)\n if (!adopted) return\n this.adopted.delete(sessionKey)\n if (adopted.timer) clearTimeout(adopted.timer)\n const record: RunRecord = { ...adopted.record, runId, startedAt: this.now(), owner: 'restart' }\n this.entries.set(runId, { record, state: 'watch', handle: adopted.handle, since: 0 })\n this.persist()\n this.wiring.logger?.info(\n { runId, sessionKey, [record.kind === 'reply' ? 'conversationId' : 'inviteId']: record.id },\n 'OpenClaw continued a turn session after the restart — its conversation stays held until that run ends',\n )\n void this.watchContinued(record)\n }\n\n private async watchContinued(record: RunRecord): Promise<void> {\n let end: integration.TurnEnd | null = null\n try {\n end = this.wiring.watch ? await this.wiring.watch(record) : null\n } catch {\n end = null\n }\n // null: the plugin runtime is gone — the hold stays (nothing in this\n // process starts a second turn for it).\n if (end === null) return\n await this.ended(record.runId, end)\n }\n\n private async recordRestartEnded(adopted: Adopted): Promise<void> {\n const { record } = adopted\n let calls: integration.AgentChatCallCount | null = null\n try {\n calls = this.wiring.readCalls ? await this.wiring.readCalls(record.sessionKey, record.runId) : null\n } catch {\n calls = null\n }\n adopted.end = { status: 'failed', agentchatCalls: calls, detail: RESTART_END_DETAIL }\n if (this.adopted.get(record.sessionKey) !== adopted || !this.wiring.recorder) return\n await this.wiring.recorder(record, adopted.end)\n }\n\n /**\n * The hold expired with nothing continuing the turn: the after-turn rule\n * once more — the resumed main session may have answered the card\n * meanwhile — then the conversation is free.\n */\n private expireAdopted(sessionKey: string, adopted: Adopted): void {\n if (this.adopted.get(sessionKey) !== adopted) return // taken over by a continued run, or released\n void (async () => {\n try {\n if (this.wiring.recorder) await this.wiring.recorder(adopted.record, adopted.end ?? { status: 'failed', agentchatCalls: null, detail: RESTART_END_DETAIL })\n } catch {\n // the recorder never rejects; a failure leaves the card to the server's re-wake\n }\n if (this.adopted.get(sessionKey) === adopted) this.finishAdopted(sessionKey)\n })()\n }\n\n private finishAdopted(sessionKey: string): void {\n const adopted = this.adopted.get(sessionKey)\n if (!adopted) return\n this.adopted.delete(sessionKey)\n if (adopted.timer) clearTimeout(adopted.timer)\n this.tracker.end(adopted.handle)\n this.persist()\n this.live?.wake()\n }\n\n /** An ended run stays in the store a little longer: a restart ends the run before it ends the process. */\n private keep(record: RunRecord): void {\n const turn = storedOf(record)\n if (turn) this.kept.set(record.runId, { turn, endedAt: this.now() })\n this.persist()\n if (!this.keptTimer) this.schedulePrune()\n }\n\n /** The next prune at the oldest kept entry's expiry. */\n private schedulePrune(): void {\n let oldest = Infinity\n for (const kept of this.kept.values()) oldest = Math.min(oldest, kept.endedAt)\n if (oldest === Infinity) return\n this.keptTimer = setTimeout(() => this.pruneKept(), Math.max(0, oldest + KEEP_ENDED_MS - this.now()))\n this.keptTimer.unref?.()\n }\n\n private pruneKept(): void {\n this.keptTimer = null\n const cutoff = this.now() - KEEP_ENDED_MS\n for (const [runId, kept] of this.kept) if (kept.endedAt <= cutoff) this.kept.delete(runId)\n this.persist()\n this.schedulePrune()\n }\n\n private persist(): void {\n const store = this.wiring.store\n if (!store) return\n const turns = new Map<string, StoredTurn>()\n for (const entry of this.entries.values()) {\n if (entry.state === 'released') continue\n const turn = storedOf(entry.record)\n if (turn) turns.set(turn.runId, turn)\n }\n for (const [runId, kept] of this.kept) turns.set(runId, kept.turn)\n for (const adopted of this.adopted.values()) turns.set(adopted.stored.runId, adopted.stored)\n if (!store.write([...turns.values()])) this.wiring.logger?.debug({ file: store.file }, 'turns in flight could not be written (the restart defense is off until the next write)')\n }\n\n private wakeWhenFree(key: string, attempts = 300): void {\n const held = key.startsWith('conversation:') ? this.tracker.conversationRunning(key.slice('conversation:'.length)) : this.tracker.inviteRunning(key.slice('invite:'.length))\n if (!held || attempts <= 0) {\n this.live?.wake()\n return\n }\n const timer = setTimeout(() => this.wakeWhenFree(key, attempts - 1), 100)\n timer.unref?.()\n }\n}\n\nconst accounts = new Map<string, AccountTurns>()\n\n/** The account's turns, created on first use and kept for the process. */\nexport function accountTurns(accountId: string): AccountTurns {\n let turns = accounts.get(accountId)\n if (!turns) {\n turns = new AccountTurns()\n accounts.set(accountId, turns)\n }\n return turns\n}\n\n/** The account's turns when it has any in this process; never creates them. */\nexport function findAccountTurns(accountId: string): AccountTurns | undefined {\n return accounts.get(accountId)\n}\n\n/** The account's kit tracker (shared by every loop for the account). */\nexport function trackerFor(accountId: string): integration.TurnTracker {\n return accountTurns(accountId).tracker\n}\n\n/** Every account with turns in this process. */\nexport function accountsWithTurns(): string[] {\n return [...accounts.keys()]\n}\n\n/** A run started in some session (the `model_call_started` hook): every account looks whether it continues an adopted turn. */\nexport function observeRunStarted(runId: unknown, sessionKey: unknown): void {\n if (typeof runId !== 'string' || runId.length === 0 || typeof sessionKey !== 'string' || sessionKey.length === 0) return\n for (const turns of accounts.values()) turns.observeRun(runId, sessionKey)\n}\n\n/** The run deadline OpenClaw applies: `agents.defaults.timeoutSeconds`, its 48 h default, or none (`0`). */\nexport function runDeadline(cfg: unknown): { readonly seconds: number; readonly configured: boolean } {\n const value = (cfg as { agents?: { defaults?: { timeoutSeconds?: unknown } } } | undefined)?.agents?.defaults?.timeoutSeconds\n if (typeof value === 'number' && Number.isFinite(value) && value >= 0) return { seconds: Math.floor(value), configured: true }\n return { seconds: OPENCLAW_DEFAULT_RUN_TIMEOUT_SECONDS, configured: false }\n}\n\nfunction whatOf(kind: TurnKind, id: string): string {\n return kind === 'reply' ? `conversation ${id}` : kind === 'invite' ? `invite ${id}` : `the gate-off run ${id}`\n}\n\nfunction deadlineText(cfg: unknown): string {\n const deadline = runDeadline(cfg)\n return deadline.seconds === 0\n ? 'agents.defaults.timeoutSeconds is 0 (no deadline), so it may never end'\n : `OpenClaw ends it at its run deadline, agents.defaults.timeoutSeconds = ${deadline.seconds}${deadline.configured ? '' : \" (OpenClaw's default, 48 h)\"}`\n}\n\n/**\n * The operator line for a turn that has run past `TURN_OVERDUE_MS`: which\n * conversation (or invite) it holds, for how long, and what ends it.\n */\nexport function overdueTurnLine(turn: { readonly kind: TurnKind; readonly id: string; readonly elapsedMs: number }, cfg: unknown): string {\n const minutes = Math.round(turn.elapsedMs / 60_000)\n if (turn.kind === 'run') {\n return `${whatOf(turn.kind, turn.id)} has run ${minutes} min — no new run starts until it ends (one run reads the whole tray); ${deadlineText(cfg)}`\n }\n return `a turn for ${whatOf(turn.kind, turn.id)} has run ${minutes} min — that conversation stays held (no second reply) until the run ends; ${deadlineText(cfg)}; other conversations are not held up by it`\n}\n\n/** One line per run past the threshold (status, doctor). */\nexport function overdueTurnLines(runs: readonly RunRecord[], cfg: unknown, now: number = Date.now()): string[] {\n return runs.filter((run) => now - run.startedAt > TURN_OVERDUE_MS).map((run) => overdueTurnLine({ kind: run.kind, id: run.id, elapsedMs: now - run.startedAt }, cfg))\n}\n\n/** One line per conversation held after a gateway restart (status, doctor, the start log). */\nexport function restartHoldLines(turns: AccountTurns, now: number = Date.now()): string[] {\n return turns.restartHolds().map(({ record, until, watching }) =>\n watching || until === null\n ? `${whatOf(record.kind, record.id)} is held: OpenClaw continued its turn's session after the gateway restart (run ${watching ?? 'unknown'}) — gated again once that run ends (handed off like any turn past 30 min)`\n : `${whatOf(record.kind, record.id)} is held for ${Math.max(0, Math.ceil((until - now) / 60_000))} more min: its turn was running when the gateway restarted, and OpenClaw may continue that turn's session`,\n )\n}\n\n/**\n * Readiness while handed-off runs block the account: a gate-off run still\n * going (no new run while it lives), or too many hung turns. Why nothing is\n * gated, and what to do; null when nothing blocks.\n */\nexport function hungTurnsReason(turns: AccountTurns, cfg: unknown, now: number = Date.now()): string | null {\n const single = turns.hungSingleRun()\n if (single) {\n return `${whatOf('run', single.runId)} has run ${Math.floor((now - single.startedAt) / 60_000)} min and is still going in OpenClaw — no new run starts while it lives (one run reads the whole tray; a second would answer the same cards), so the cards wait on the tray; ${deadlineText(cfg)}. \\`openclaw agentchat release ${single.runId} --force\\` lets a new run start (the old one may still answer)`\n }\n if (turns.hungCount < MAX_HUNG_TURNS) return null\n const held = turns\n .hungRuns()\n .map((run) => `${whatOf(run.kind, run.id)} for ${Math.floor((now - run.startedAt) / 60_000)} min`)\n .join(', ')\n return `${turns.hungCount} turns are hung in OpenClaw (${held}) — no gate calls until one ends, so other cards are waiting on the tray; ${deadlineText(cfg)}. \\`openclaw agentchat release <conversation_id>\\` lets go of one (its run may still answer, so a second reply is possible), or restart the gateway`\n}\n\n/** Test hook only. */\nexport function resetRunningTurnsForTest(): void {\n accounts.clear()\n}\n","/**\n * `openclaw agentchat release <conversation_id>` — the operator's way to let\n * go of a turn OpenClaw never reports as ended.\n *\n * A turn holds its conversation until its run ends, so a run that hangs keeps\n * that conversation from being answered again (no second reply), and after\n * two hung turns the account stops gating. OpenClaw offers a plugin no abort\n * for a subagent run, so the release does not end the run: it lets the\n * conversation be gated again. If the run is in fact still alive and answers\n * later, the peer can get a second reply — the operator's call, and the\n * command says so.\n *\n * A turn under 30 minutes is most likely still working, so the command\n * refuses it unless `--force` is given: released, its conversation could be\n * gated again while the run can still send its answer — two replies. A hung\n * turn (handed off past 30 minutes) and a conversation held after a gateway\n * restart are released without it.\n *\n * Two halves, because the CLI is a separate process from the gateway that\n * holds the turns: a gateway method (`agentchat.release`, operator-admin\n * scope) registered in the gateway, and the CLI command that calls it over\n * the gateway's own RPC (`callGatewayFromCli`, the plugin SDK's helper, which\n * reads the gateway URL and token the same way `openclaw gateway call` does).\n */\n\nimport type { OpenClawPluginApi } from 'openclaw/plugin-sdk/core'\n\nimport { TURN_OVERDUE_MS, findAccountTurns, type ReleaseResult } from '../integration/running.js'\nimport { AGENTCHAT_CHANNEL_ID } from '../channel-account.js'\n\nexport const RELEASE_METHOD = 'agentchat.release'\n\ntype ReleaseParams = { readonly id?: unknown; readonly accountId?: unknown; readonly force?: unknown }\n\n/** The gateway half: release the turn holding `id` (a conversation, invite or run id) for the account. Never creates account state. */\nexport function releaseTurnFor(params: ReleaseParams): { ok: true; result: ReleaseResult } | { ok: false; error: string } {\n const id = typeof params.id === 'string' ? params.id.trim() : ''\n if (!id) return { ok: false, error: 'a conversation (or invite) id is required' }\n const accountId = typeof params.accountId === 'string' && params.accountId.trim() ? params.accountId.trim() : 'default'\n const turns = findAccountTurns(accountId)\n if (!turns) return { ok: true, result: { released: false, reason: `the AgentChat account \"${accountId}\" has no turns in this gateway` } }\n return { ok: true, result: turns.release(id, { force: params.force === true }) }\n}\n\nexport function registerReleaseGatewayMethod(api: Pick<OpenClawPluginApi, 'registerGatewayMethod'>): void {\n api.registerGatewayMethod(\n RELEASE_METHOD,\n ({ params, respond }) => {\n const outcome = releaseTurnFor(params as ReleaseParams)\n if (!outcome.ok) {\n respond(false, undefined, { code: 'INVALID_REQUEST', message: outcome.error } as never)\n return\n }\n respond(true, outcome.result)\n },\n { scope: 'operator.admin' },\n )\n}\n\nexport function registerReleaseCli(api: Pick<OpenClawPluginApi, 'registerCli'>): void {\n api.registerCli(\n ({ program }) => {\n const root = program.command(AGENTCHAT_CHANNEL_ID).description('The AgentChat integration')\n const release = root\n .command('release <id>')\n .description(\n `Let go of the turn holding a conversation (or invite) whose OpenClaw run never ended. The run is not stopped: if it answers later, the peer can get a second reply. A turn under ${TURN_OVERDUE_MS / 60_000} minutes is refused without --force.`,\n )\n .option('--account <accountId>', 'the AgentChat account', 'default')\n .option('--force', `release a turn that has run under ${TURN_OVERDUE_MS / 60_000} minutes (it is most likely still working: two replies are possible)`)\n .option('--url <url>', 'gateway URL (default: the configured gateway)')\n .option('--token <token>', 'gateway token (default: the configured one)')\n .option('--json', 'print the raw result')\n .action(async (id: string, opts: { account?: string; url?: string; token?: string; json?: boolean; force?: boolean }) => {\n // Loaded only when the command runs: the gateway runtime is OpenClaw's.\n const { callGatewayFromCli } = await import('openclaw/plugin-sdk/gateway-runtime')\n const result = (await callGatewayFromCli(\n RELEASE_METHOD,\n { ...(opts.url ? { url: opts.url } : {}), ...(opts.token ? { token: opts.token } : {}), ...(opts.json ? { json: true } : {}) },\n { id, accountId: opts.account ?? 'default', ...(opts.force ? { force: true } : {}) },\n )) as { released?: boolean; what?: string; reason?: string }\n process.stdout.write(opts.json ? `${JSON.stringify(result)}\\n` : `${releaseLine(id, result)}\\n`)\n })\n void release\n },\n {\n commands: [AGENTCHAT_CHANNEL_ID],\n descriptors: [{ name: AGENTCHAT_CHANNEL_ID, description: 'The AgentChat integration (release a hung turn)', hasSubcommands: true }],\n },\n )\n}\n\n/** What the command prints. */\nexport function releaseLine(id: string, result: { released?: boolean; what?: string; reason?: string } | null | undefined): string {\n if (!result?.released) return `nothing released: ${result?.reason ?? 'unknown'}`\n if (result.what === 'restart') return `released ${id} (held after a gateway restart) — it may be gated again now`\n const what = result.what === 'hung' ? 'a hung turn' : 'a running turn'\n return `released ${id} (${what}) — it may be gated again now; its OpenClaw run was not stopped, and if it still sends an answer the peer gets two replies`\n}\n","/**\n * Seeing runs the plugin did not start: OpenClaw's `model_call_started`\n * hook (each model call names its run and session). The one use: after a\n * gateway restart, OpenClaw may continue a turn's session on its own (the\n * restart resume asks the agent's main session to \"send a fresh instruction\n * to the same retained child session\"); a run seen in the session of a turn\n * adopted from the last process keeps that conversation held until it ends\n * (`AccountTurns.observeRun`). A third-party plugin has no API that lists\n * live runs, and this hook needs no grant (it is not a conversation-access\n * or prompt hook). An OpenClaw release without the hook ignores it.\n */\n\nimport type { OpenClawPluginApi } from 'openclaw/plugin-sdk/core'\n\nimport { observeRunStarted } from '../integration/running.js'\n\nexport function registerRunObserver(api: Pick<OpenClawPluginApi, 'on'>): void {\n api.on('model_call_started', (event, ctx) => {\n observeRunStarted(event.runId, event.sessionKey ?? ctx?.sessionKey)\n })\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 the receive loop acts on. 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 | unanswered | invite | 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: peer message frames, connects, server wake frames (by reason), invite frames. */\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 * The SDK socket's lifecycle, as OpenClaw reports it — one account.\n *\n * The transport is the SDK's `RealtimeClient`, lifecycle included: HELLO,\n * the reconnect backoff that never gives up (one notice after a long outage,\n * then a wider cap), the handshake and idle watchdogs, the 10–15 min retry\n * of a rejected key, the delivery ack, per-conversation ordering, the\n * reconnect drain. What arrives on it is the kit's receive loop's: it\n * attaches its own handlers to the same client (message frames that are not\n * the agent's own echo, wake frames, invites, every accepted HELLO become\n * one cycle), and connects and disconnects it.\n *\n * This module builds the client with the plugin's options and hands the\n * SDK's lifecycle events to the gateway as they are, for OpenClaw's status\n * and the metrics: connected, closed, blocked, the state, notices. It acts on\n * nothing and sends nothing.\n *\n * HELLO offers `ack`, `heartbeat` and `rewake`: while cards stay unanswered\n * the server re-wakes this socket on its own durable ladder (contract v1,\n * D3), so the integration keeps no retry ladder of its own.\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 verdicts; an early ack never empties the tray.\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} 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'\n\n/**\n * A wake's label for the metric and the log — a closed set: `message` (a\n * peer wrote), `connect` (an accepted HELLO), `reminder` (a deferred\n * conversation came due), `unanswered` (the server's re-wake for cards\n * still waiting), `invite` (a group invite arrived), `other` (a server wake\n * with a reason this version does not know).\n */\nexport type WakeLabel = 'message' | 'connect' | 'reminder' | 'unanswered' | 'invite' | 'other'\n\n/** A server wake frame's `reason` → the fixed label set (the metric label must stay bounded). */\nexport function wakeSourceOf(reason: unknown): WakeLabel {\n if (reason === 'reminder') return 'reminder'\n if (reason === 'unanswered') return 'unanswered'\n return '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 the 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 SocketHandlers {\n /** Once per accepted HELLO (initial + every reconnect). */\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 wakeFrames: 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, contract-v1 capabilities. */\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 // `rewake`: the server re-wakes this socket while cards stay unanswered\n // (contract v1, D3) — the integration keeps no retry ladder of its own.\n // `heartbeat` is offered by default (the idle watchdog's proof of life).\n capabilities: { rewake: 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 /** The SDK client: handed to the receive loop, which connects and disconnects it. */\n readonly realtime: RealtimeClient\n\n private readonly logger: Logger\n private readonly handlers: SocketHandlers\n private readonly metrics: MetricsRecorder\n private readonly now: () => number\n\n /** The SDK's state as last reported through its `state` event. */\n private state: SocketState = 'idle'\n private connectedAt: number | null = null\n private bound = false\n private stopping = false\n private readonly unbind: Array<() => void> = []\n\n private wakeFrames = 0\n private disconnects = 0\n\n constructor(options: IntegrationSocketOptions) {\n this.logger = options.logger.child({ component: 'socket' })\n this.handlers = options.handlers ?? {}\n this.metrics = options.metrics ?? createNoopMetrics()\n this.now = options.now ?? Date.now\n const create = options.createRealtime ?? ((opts: RealtimeOptions) => new RealtimeClient(opts))\n this.realtime = create(realtimeOptionsFor(options.config, { client: options.client, webSocket: options.webSocket }))\n this.metrics.setConnectionState(this.state)\n }\n\n /** Attach the lifecycle handlers. Idempotent. The receive loop connects the client. */\n bind(): void {\n if (this.bound || this.stopping) return\n this.bound = true\n const realtime = this.realtime\n this.unbind.push(\n realtime.on('state', (next, prev) => this.onState(next, prev)),\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.metrics.incWake({ source: 'connect' })\n this.guard('onConnected', () => this.handlers.onConnected?.(at))\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 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 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.\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 // The loop turns a wake frame into a cycle; here it is only labelled\n // by its reason for the log line and the metric.\n realtime.on('wake', (frame: WakeFrame) => {\n this.wakeFrames += 1\n const payload = (frame.payload ?? {}) as { reason?: unknown; conversation_id?: unknown; conversation_ids?: unknown; step?: unknown }\n const conversations = Array.isArray(payload.conversation_ids) ? payload.conversation_ids.length : undefined\n this.metrics.incWake({ source: wakeSourceOf(payload.reason) })\n this.logger.info(\n {\n reason: payload.reason,\n step: payload.step,\n ...(typeof payload.conversation_id === 'string' ? { conversationId: payload.conversation_id } : {}),\n ...(conversations !== undefined ? { conversations } : {}),\n },\n 'wake — server wake frame',\n )\n }),\n )\n }\n\n /** The loop has disconnected the client (or never started it): report `stopped`, detach. Idempotent. */\n stopped(): void {\n this.stopping = true\n this.connectedAt = null\n for (const off of this.unbind.splice(0)) {\n try {\n off()\n } catch {\n // already detached\n }\n }\n if (this.state !== 'stopped') this.onState('stopped', this.state)\n }\n\n getHealth(): SocketHealth {\n return { state: this.state, connectedAt: this.connectedAt, counters: { wakeFrames: this.wakeFrames, disconnects: this.disconnects } }\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 if (this.state === next) return\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. */\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 binding, the receive loop and the served texts so the status\n * adapter can report them, and serializes start/stop per account so a\n * start-during-stop never races.\n *\n * Keying is `accountId`-only; `channelId` is always `\"agentchat\"` here.\n */\n\nimport type { integration } from 'agentchatme'\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 { IntegrationLoop } from '../integration/loop.js'\nimport type { MetricsRecorder } from '../metrics.js'\n\nexport interface IntegrationEntry {\n readonly socket: IntegrationSocket\n readonly loop: IntegrationLoop | null\n /** The served texts as the loop reads them. */\n readonly texts: integration.TextsSource | null\n /** The recorder the socket binding and the loop 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\nexport interface BuiltIntegration {\n readonly loop: IntegrationLoop | null\n readonly texts?: integration.TextsSource | null\n /** Stopped after the loop (the texts refresh timer). */\n readonly textsCache?: integration.TextsCache | null\n readonly handlers: SocketHandlers\n}\n\ninterface LiveEntry extends IntegrationEntry {\n readonly textsCache: integration.TextsCache | null\n}\n\nconst registry = new Map<string, LiveEntry>()\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 loop over the socket's SDK client, and the lifecycle handlers for the gateway. */\n readonly build: (socket: IntegrationSocket) => BuiltIntegration\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 what `build` returns and the loop over the\n // socket; a late-bound reference resolves the cycle. Nothing fires\n // before `bind()`.\n let built: BuiltIntegration | null = null\n const handlers: SocketHandlers = {\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: LiveEntry = {\n socket,\n loop: built.loop,\n texts: built.texts ?? null,\n textsCache: built.textsCache ?? null,\n metrics: params.socketOptions?.metrics ?? null,\n config: params.config,\n logger: params.logger,\n }\n registry.set(params.accountId, entry)\n socket.bind()\n try {\n // The loop attaches to the socket's client and connects it.\n await built.loop?.loop.start()\n } catch (err) {\n registry.delete(params.accountId)\n await stopEntry(entry)\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: LiveEntry): Promise<void> {\n try {\n // Stops the cycles and disconnects the socket. Runs already admitted\n // are OpenClaw's; they stay registered for the account until they end.\n await entry.loop?.stop()\n } catch (err) {\n entry.logger.error({ err: err instanceof Error ? err.message : String(err) }, 'receive loop stop threw during unregister')\n }\n if (!entry.loop) {\n try {\n entry.socket.realtime.disconnect()\n } catch {\n // never connected\n }\n }\n entry.socket.stopped()\n entry.textsCache?.stop()\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 * How the kit's receive loop starts a turn on OpenClaw.\n *\n * The loop (gate-call mode) decides which conversations and invites get a\n * turn, composes the prompt from the served texts, and holds the card in\n * its tracker while the turn runs; this adapter runs the turn as one\n * OpenClaw agent run (`runtime.subagent.run`, `deliver: false`, a fresh\n * session, the account's lane) and reports its end in the kit's terms once\n * OpenClaw has confirmed it (`./run.ts`):\n *\n * - `ok` → `completed`, with the AgentChat calls the\n * run made (from its transcript; null = unknown)\n * - `error`, `timeout` → `failed` (the run's own deadline is a failure,\n * never an elapsed wait)\n * - the plugin runtime is gone → `still_running` with no `next`: the tracker\n * keeps the conversation, nothing in this process\n * starts a second turn for it\n *\n * A run that never ends keeps holding its conversation: the loop cannot end\n * a turn, and the plugin runtime offers no abort for a subagent run. After\n * 30 minutes the turn is handed off (`AccountTurns.handOff`): the kit's slot\n * is freed so other conversations get turns, while that one stays held until\n * OpenClaw reports the run ended (its run deadline,\n * `agents.defaults.timeoutSeconds`) — then the after-turn rule is applied\n * to it there, with the card the gate saw, which the record carries.\n */\n\nimport type { integration } from 'agentchatme'\n\nimport type { Logger } from '../log.js'\nimport type { TurnOutcome, TurnStarter as RuntimeTurnStarter } from './model.js'\nimport type { AccountTurns } from './running.js'\nimport { integrationLane, inviteSessionKey, wakeSessionKey } from './turn.js'\n\nexport interface LoopTurnStarterOptions {\n readonly accountId: string\n /** The OpenClaw agent the account is routed to. */\n readonly agentId: string\n /** Starts one OpenClaw run and reports its confirmed end (`createRuntimeTurnStarter`). */\n readonly startRun: RuntimeTurnStarter\n /** The account's turns (`accountTurns`): every run is recorded there until OpenClaw reports it ended. */\n readonly turns: AccountTurns\n /** The loop this starter belongs to. */\n readonly owner: string\n readonly logger: Logger\n readonly now?: () => number\n}\n\n/** The kit's `TurnStarter` for OpenClaw. */\nexport function createLoopTurnStarter(options: LoopTurnStarterOptions): integration.TurnStarter {\n const now = options.now ?? Date.now\n return async (request) => {\n const id = request.kind === 'reply' ? request.conversationId : request.invite.invite_id\n const sessionKey = request.kind === 'reply' ? wakeSessionKey(options.agentId, now()) : inviteSessionKey(options.agentId, id, now())\n // Watched from here: if the kit's hold is released while OpenClaw admits\n // the run (an operator's --force), the run starts out let go of.\n const watch = options.turns.admission(request.kind, id)\n const admission = await options.startRun({ sessionKey, prompt: request.prompt, lane: integrationLane(options.accountId, options.turns.laneGeneration) })\n if (!admission.ran) {\n options.turns.admitted(watch)\n return { started: false, error: admission.error }\n }\n options.turns.started({\n runId: admission.runId,\n kind: request.kind,\n id,\n anchor: request.kind === 'reply' ? request.anchor : null,\n sessionKey: admission.sessionKey,\n startedAt: now(),\n owner: options.owner,\n // What the after-turn rule compares when the turn ends outside the\n // kit's watch (handed off, or after a restart).\n ...(request.kind === 'reply' ? { card: request.card, category: request.category } : { invite: request.invite }),\n }, { admission: watch })\n options.logger.info(\n { kind: request.kind, sessionKey, runId: admission.runId, ...(request.kind === 'reply' ? { conversationId: id } : { inviteId: id }) },\n request.kind === 'reply' ? 'turn start' : 'group-invite turn start',\n )\n const done = admission.done.then((outcome): integration.TurnEnd => {\n if (outcome.status === 'gone') {\n options.logger.warn({ sessionKey, runId: outcome.runId }, 'turn end not confirmed: the plugin runtime is gone — its card stays held')\n return { status: 'still_running', detail: 'the plugin runtime is gone' }\n }\n const end = turnEndOf(outcome)\n void options.turns.ended(admission.runId, end)\n options.logger[outcome.status === 'ok' ? 'info' : 'warn'](\n {\n sessionKey,\n runId: outcome.runId,\n status: outcome.status,\n ...(outcome.error ? { error: outcome.error } : {}),\n ...(outcome.elapsedMs !== undefined ? { elapsedMs: outcome.elapsedMs } : {}),\n agentchatCalls: outcome.agentchatCalls ?? null,\n },\n request.kind === 'reply' ? 'turn ended (final text discarded; the send is a hosted-tool call)' : 'group-invite turn ended',\n )\n return end\n })\n return { started: true, done }\n }\n}\n\n/** What OpenClaw reported, as the kit's D5 rule reads it. `ok` without an error is the only completed end. */\nexport function turnEndOf(outcome: TurnOutcome): integration.TurnEnd {\n const agentchatCalls = outcome.agentchatCalls ?? null\n if (outcome.status === 'ok' && !outcome.error) return { status: 'completed', agentchatCalls }\n return { status: 'failed', agentchatCalls, detail: outcome.error ?? `run ended: ${outcome.status ?? 'unknown'}` }\n}\n","/**\n * The receive loop for one account: the SDK kit's `ReceiveLoop`, with what\n * is OpenClaw's plugged in.\n *\n * socket frame / connect / wake frame / invite ──► one cycle per burst ──► tray\n * ──► gate call on the agent's own model (gate-call mode) ──► dismiss / defer at once\n * ──► one OpenClaw run per reply and per invite ──► the after-turn rule (D5)\n *\n * The cycle, the tray read, the gate, which cards a running turn holds, the\n * prompts, and what is recorded after a turn are the kit's. This module\n * supplies the runtime parts: the gate call (`runtime.llm.complete`, tool\n * free), the turn (`./turns.ts` over `runtime.subagent.run`), whether a turn\n * can have the hosted tools (`readiness`), and the log lines and metrics.\n *\n * `AGENTCHAT_REPLY_GATE_ENABLED=0` switches to the kit's single-run mode:\n * one run with the served wake instruction whenever something is owed; the\n * agent judges every card inside it and records its own verdicts.\n */\n\nimport { AsyncLocalStorage } from 'node:async_hooks'\n\nimport { integration, type RealtimeClient } from 'agentchatme'\n\nimport type { Logger } from '../log.js'\nimport type { MetricsRecorder } from '../metrics.js'\nimport { createNoopMetrics } from '../metrics.js'\nimport type { GateModelCall, TurnReadiness, TurnStarter as RuntimeTurnStarter } from './model.js'\nimport { OPENCLAW_TOOL_NAMER, integrationLane, wakeSessionKey } from './turn.js'\nimport { createLoopTurnStarter } from './turns.js'\nimport type { AccountTurns } from './running.js'\n\nexport interface IntegrationLoopOptions {\n readonly accountId: string\n readonly agentId: string\n readonly client: integration.ReceiveLoopClient\n readonly texts: integration.TextsSource\n /** The SDK socket (built by `IntegrationSocket`); the loop connects and disconnects it. `null`: wakes only through `wake()`. */\n readonly socket: RealtimeClient | null\n /** The agent's handle, for the echo filter (learned from the tray when absent). */\n readonly handle?: string | undefined\n readonly callModel: GateModelCall\n readonly startRun: RuntimeTurnStarter\n /** The account's turns, shared with every loop for the account in this process (`accountTurns`). */\n readonly turns: AccountTurns\n readonly logger: Logger\n readonly metrics?: MetricsRecorder\n readonly readiness?: () => TurnReadiness\n /** `false`: single-run mode (no gate call). */\n readonly gateEnabled?: boolean\n /** D5 pacing window (the kit's default 60 s); tests shorten it. */\n readonly paceMs?: number\n readonly quietMs?: number\n readonly maxMs?: number\n readonly now?: () => number\n readonly setTimeout?: (fn: () => void, ms: number) => ReturnType<typeof setTimeout>\n readonly clearTimeout?: (handle: ReturnType<typeof setTimeout>) => void\n}\n\nexport interface IntegrationLoop {\n readonly loop: integration.ReceiveLoop\n /** Stop the loop (it disconnects the socket). Turns already running go on and still have their outcome recorded. */\n stop(): Promise<void>\n}\n\nlet generation = 0\n\nexport function createIntegrationLoop(options: IntegrationLoopOptions): IntegrationLoop {\n const logger = options.logger.child({ component: 'integration', accountId: options.accountId })\n const metrics = options.metrics ?? createNoopMetrics()\n const now = options.now ?? Date.now\n generation += 1\n const owner = `${options.accountId}#${generation}`\n const gateEnabled = options.gateEnabled ?? true\n\n let unreadyReason: string | null = null\n const readiness: integration.Readiness | undefined = options.readiness\n ? () => {\n const ready = options.readiness!()\n if (ready.ready) {\n if (unreadyReason !== null) logger.info({}, 'turns can start again — gating resumes')\n unreadyReason = null\n return ready\n }\n // Logged when the reason changes, not on every wake.\n if (unreadyReason !== ready.reason) logger.warn({ reason: ready.reason }, 'not gating — no turn can start now; the cards wait on the tray')\n unreadyReason = ready.reason\n return ready\n }\n : undefined\n\n const startTurn = createLoopTurnStarter({ accountId: options.accountId, agentId: options.agentId, startRun: options.startRun, turns: options.turns, owner, logger, now })\n\n const loop = new integration.ReceiveLoop({\n client: options.client,\n texts: options.texts,\n mode: gateEnabled ? 'gateCall' : 'singleRun',\n ...(gateEnabled ? { callModel: options.callModel, startTurn } : { startRun: singleRunStarter(options, owner, logger, now) }),\n socket: options.socket,\n ...(options.handle ? { handle: options.handle } : {}),\n toolNamer: OPENCLAW_TOOL_NAMER,\n // One account's turns run on one OpenClaw lane anyway; one slot keeps\n // the rest held out of the gate (no second model call decides them).\n maxConcurrentTurns: 1,\n tracker: options.turns.tracker,\n ...(readiness ? { readiness } : {}),\n ...(options.paceMs !== undefined ? { paceMs: options.paceMs } : {}),\n ...(options.quietMs !== undefined ? { quietMs: options.quietMs } : {}),\n ...(options.maxMs !== undefined ? { maxMs: options.maxMs } : {}),\n now,\n ...(options.setTimeout ? { setTimeout: options.setTimeout } : {}),\n ...(options.clearTimeout ? { clearTimeout: options.clearTimeout } : {}),\n onEvent: (event) => logEvent(event, logger, metrics),\n })\n\n // The account's live loop: a held run that ends (hung, or started by an\n // earlier loop) wakes it, so what arrived meanwhile is gated at once. Work\n // started from outside (an operator's release through a gateway RPC) runs\n // in this loop's own async context, not the caller's.\n const inLoopContext = AsyncLocalStorage.snapshot()\n options.turns.setLive(\n owner,\n () => inLoopContext(() => loop.wake()),\n (fn) => inLoopContext(fn),\n )\n\n return {\n loop,\n async stop() {\n options.turns.clearLive(owner)\n await loop.stop()\n },\n }\n}\n\n/**\n * Single-run mode: one OpenClaw run with the served text; the cycle waits for\n * its confirmed end. The run is recorded with the account's turns, so a run\n * still going after 30 minutes is handed off like a turn: the cycle is let go\n * of (the loop is not stuck in it), but no new run starts while it lives —\n * one run reads the whole tray, a second would answer the same cards\n * (readiness says not-ready too; `openclaw agentchat release <run id>\n * --force` frees it).\n */\nfunction singleRunStarter(options: IntegrationLoopOptions, owner: string, logger: Logger, now: () => number): integration.RunStarter {\n return async (request) => {\n const hung = options.turns.hungSingleRun()\n if (hung) {\n logger.warn({ runId: hung.runId }, 'gate off — a handed-off run is still going; no second run while it lives (the cards wait on the tray)')\n return { status: 'not_started', detail: `the gate-off run ${hung.runId} is still going` }\n }\n const sessionKey = wakeSessionKey(options.agentId, now())\n logger.info({ sessionKey, cards: request.cards, invites: request.invites }, 'gate off — one run with the served wake instruction')\n const admission = await options.startRun({ sessionKey, prompt: request.prompt, lane: integrationLane(options.accountId, options.turns.laneGeneration) })\n if (!admission.ran) return { status: 'not_started', detail: admission.error }\n let letGo: () => void = () => {}\n const handedOff = new Promise<'let_go'>((resolve) => {\n letGo = () => resolve('let_go')\n })\n const { runId } = admission\n options.turns.started({ runId, kind: 'run', id: runId, anchor: null, sessionKey: admission.sessionKey, startedAt: now(), owner }, { letGo })\n const ended = admission.done.then((outcome) => {\n if (outcome.status !== 'gone') void options.turns.ended(runId)\n logger[outcome.status === 'ok' ? 'info' : 'warn']({ sessionKey, runId, status: outcome.status, agentchatCalls: outcome.agentchatCalls ?? null }, 'gate off — run ended')\n return outcome\n })\n const first = await Promise.race([ended, handedOff])\n if (first === 'let_go') {\n logger.warn({ sessionKey, runId }, 'gate off — the run is still going after 30 min; no new run starts until it ends (or `openclaw agentchat release <run id> --force`)')\n return { status: 'failed', detail: 'the run was handed off while still going' }\n }\n return first.status === 'ok' && !first.error ? { status: 'completed' } : { status: 'failed', detail: first.error ?? `run ended: ${first.status ?? 'unknown'}` }\n }\n}\n\n/** One line per loop event, and the wake metric for the sources the socket binding does not count. */\nfunction logEvent(event: integration.ReceiveLoopEvent, logger: Logger, metrics: MetricsRecorder): void {\n switch (event.type) {\n case 'wake':\n // `connect` and wake frames are counted by the socket binding (with their reason).\n if (event.source === 'message') metrics.incWake({ source: 'message' })\n else if (event.source === 'invite') metrics.incWake({ source: 'invite' })\n logger.debug({ source: event.source, ...(event.conversationId ? { conversationId: event.conversationId } : {}) }, 'wake')\n return\n case 'echo':\n logger.debug(event.conversationId ? { conversationId: event.conversationId } : {}, 'own echo — not a wake')\n return\n case 'notice':\n // A system notice (a member joined or left, a rename, a group deleted):\n // the SDK acked it on receipt; the kit starts no cycle for it.\n logger.debug(event.conversationId ? { conversationId: event.conversationId } : {}, 'system notice — acked, not a wake')\n return\n case 'gate_chunk':\n // One gate call of a cycle; the cycle's own line says what was left undecided.\n logger.debug({ cycle: event.cycle, chunk: event.index, of: event.of, cards: event.cards, outcome: event.outcome, undecided: event.undecided, ...(event.failure ? { failure: event.failure } : {}) }, 'gate chunk')\n return\n case 'cycle': {\n const s = event.summary\n const fields = {\n outcome: s.outcome,\n cards: s.cards,\n invites: s.invites,\n reply: s.reply,\n dismiss: s.dismiss,\n defer: s.defer,\n undecided: s.undecided,\n recordFailures: s.recordFailures,\n turnsStarted: s.turnsStarted,\n turnsRefused: s.turnsRefused,\n heldByTurns: s.heldByTurns,\n ...(s.truncated ? { truncated: true } : {}),\n ...(s.failure ? { failure: s.failure } : {}),\n }\n switch (s.outcome) {\n case 'empty':\n logger.info({}, 'tray empty — nothing to decide')\n return\n case 'nothing_owed':\n logger.info(fields, 'nothing new to decide (muted cards, or cards a running turn holds)')\n return\n case 'fail_closed':\n logger.warn(fields, 'gate failed closed — nothing recorded, no turn started; the server re-wakes')\n return\n case 'tray_failed':\n logger.warn(fields, 'tray read failed — the cards stay on the tray; the server re-wakes')\n return\n case 'texts_missing':\n logger.warn(fields, 'served texts not available — not gating; the cards wait on the tray')\n return\n case 'tools_unavailable':\n logger.debug(fields, 'not gating — no turn can start now')\n return\n case 'abandoned':\n logger.warn(fields, 'cycle abandoned — it ran past its deadline; nothing more is done for it, the next wake starts a new one')\n return\n default: {\n const incomplete = s.turnsRefused > 0 || s.recordFailures > 0 || s.undecided > 0\n logger[incomplete ? 'warn' : 'info'](fields, incomplete ? 'gate — some cards were left on the tray; the server re-wakes' : 'gate')\n return\n }\n }\n }\n case 'turn_started':\n return // the turn starter logs it with the OpenClaw session and run\n case 'turn_refused':\n logger.warn({ kind: event.kind, id: event.id, error: event.error }, 'turn not started — nothing recorded; the card stays on the tray')\n return\n case 'turn_outcome': {\n const o = event.outcome\n logger.info(\n { conversationId: o.conversationId, action: o.action, reason: o.reason, recorded: event.recorded, ...(o.action !== 'none' ? { through: o.throughMessageId } : {}) },\n event.recorded ? `${o.action === 'record_reply' ? 'reply' : 'dismiss'} recorded after the turn (${o.reason})` : `nothing recorded after the turn (${o.reason})`,\n )\n return\n }\n case 'invite_outcome':\n logger.info(\n { inviteId: event.outcome.inviteId, action: event.outcome.action, reason: event.outcome.reason, recorded: event.recorded },\n event.recorded ? 'invite dismissed after a second silent turn (left pending)' : `nothing recorded for the invite (${event.outcome.reason})`,\n )\n return\n case 'run':\n return // single-run mode logs the run itself\n case 'error':\n logger.debug({ err: event.error.message }, 'receive loop notice')\n return\n }\n}\n\n/** Cycle outcomes that mean nothing could be decided: repeated, they are an operator's problem. */\nconst TROUBLE_OUTCOMES: ReadonlySet<string> = new Set(['fail_closed', 'tools_unavailable', 'texts_missing', 'abandoned'])\n\n/** How many cycles in a row must end in trouble before status and doctor warn. */\nexport const CYCLE_TROUBLE_RUN = 3\n\nconst TROUBLE_MEANING: Readonly<Record<string, string>> = {\n fail_closed: 'the gate call failed (model unreachable, too slow, or nothing usable)',\n tools_unavailable: 'no turn could have the hosted tools',\n texts_missing: 'the served texts are not available',\n abandoned: 'the cycle ran past its deadline and was abandoned',\n}\n\n/**\n * One operator line when the most recent cycles (`status().recentCycles`,\n * oldest first) ended in trouble at least `CYCLE_TROUBLE_RUN` times in a row,\n * else null. Nothing was gated in those cycles; the cards wait on the tray\n * and AgentChat re-wakes them.\n */\nexport function cycleTroubleLine(recentCycles: ReadonlyArray<{ readonly outcome: string; readonly failure?: string | null; readonly at?: string }>): string | null {\n let run = 0\n for (let i = recentCycles.length - 1; i >= 0 && TROUBLE_OUTCOMES.has(recentCycles[i]!.outcome); i -= 1) run += 1\n if (run < CYCLE_TROUBLE_RUN) return null\n const last = recentCycles[recentCycles.length - 1]!\n const kinds = [...new Set(recentCycles.slice(-run).map((c) => c.outcome))]\n const meaning = kinds.map((k) => TROUBLE_MEANING[k] ?? k).join('; ')\n return `the last ${run} cycles decided nothing (${kinds.join(', ')}): ${meaning}${last.failure ? ` — latest: ${last.failure}` : ''}; the cards wait on the tray and AgentChat re-wakes them`\n}\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 ──► one cycle ──► tray ──► gate ──► one turn per reply ──► after-turn rule\n *\n * everything after the wake is the SDK kit's receive loop, with OpenClaw's\n * parts plugged in (`../integration/loop.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 { Texts } from 'agentchatme'\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 { createIntegrationLoop } from '../integration/loop.js'\nimport { OpenClawTexts, createTextsCache, spellTextsForOpenClaw } from '../integration/texts.js'\nimport { OVERDUE_SLACK_MS, TURN_OVERDUE_MS, accountTurns, hungTurnsReason, isOverdue, overdueTurnLine, restartHoldLines } from '../integration/running.js'\nimport { createAfterTurnRecorder } from '../integration/after-turn.js'\nimport { TurnStore } from '../integration/turn-store.js'\nimport { turnEndOf } from '../integration/turns.js'\nimport { readAgentChatCalls } from '../integration/run.js'\nimport { getPluginRuntime } from '../integration/runtime-holder.js'\nimport { removeOldStateFiles } from '../integration/state.js'\nimport { refreshIdentityLine } from '../integration/placement.js'\nimport { NIX_MODE_ERROR_CODE, clientIdentityText, refreshHostedMcpEntry, type ConfigMutator } from '../integration/mcp.js'\nimport {\n createRuntimeModelCall,\n createRuntimeTurnStarter,\n createRunWatcher,\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\n/** Accounts already told, in this process, that their entry could not be updated (one warning, not one per start). */\nconst mcpUpdateWarned = new Set<string>()\n\n/**\n * `refreshHostedMcpEntry` for this account, with its log line. The live\n * config decides whether anything is written; the write goes through\n * OpenClaw's `runtime.config.mutateConfigFile`. Never rejects.\n */\nexport async function updateHostedMcpEntry(\n ctx: Pick<ChannelGatewayContext, 'accountId' | 'cfg' | 'log'>,\n apiBase: string,\n apiKey: string,\n runtime: () => ReturnType<typeof getPluginRuntime> = getPluginRuntime,\n): Promise<void> {\n const prefix = `[agentchat:${ctx.accountId}]`\n const warnOnce = (line: string) => {\n if (mcpUpdateWarned.has(ctx.accountId)) return\n mcpUpdateWarned.add(ctx.accountId)\n ctx.log?.warn?.(`${prefix} ${line}`)\n }\n try {\n const { cfg: liveCfg } = readLiveConfig(ctx.cfg, runtime)\n const config = (runtime() as { config?: ConfigMutator } | null)?.config\n const result = await refreshHostedMcpEntry({ liveCfg, config, apiBase, apiKey })\n if (result.outcome === 'updated') {\n mcpUpdateWarned.delete(ctx.accountId)\n ctx.log?.info?.(`${prefix} mcp.servers.agentchat now names this client to the hosted tools (${clientIdentityText()}); under the default reload mode OpenClaw applies it without a restart`)\n } else if (result.outcome === 'unsupported') {\n warnOnce(`mcp.servers.agentchat does not name this client (${clientIdentityText()}) and this OpenClaw cannot update its config from a plugin — run \\`openclaw doctor --fix\\``)\n } else if (result.outcome === 'failed') {\n warnOnce(\n result.code === NIX_MODE_ERROR_CODE\n ? `mcp.servers.agentchat does not name this client and OpenClaw's config is read-only here (Nix mode) — add ${clientIdentityText()} to its headers in the Nix-managed config`\n : `mcp.servers.agentchat could not be updated to name this client (${result.error ?? 'unknown error'}) — run \\`openclaw doctor --fix\\``,\n )\n }\n } catch (err) {\n warnOnce(`mcp.servers.agentchat check failed: ${err instanceof Error ? err.message : String(err)}`)\n }\n}\n\n/** Test seam: forget which accounts were warned. */\nexport function resetHostedMcpUpdateWarningsForTest(): void {\n mcpUpdateWarned.clear()\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 // Our hosted-tools entry from a release before 0.10.1 names no client:\n // add the header once, so AgentChat knows the agent runs on OpenClaw and\n // does not list the wake-webhook tools. Off the start path, whatever the\n // wake mode (the tools stay in use either way).\n void updateHostedMcpEntry(ctx, config.apiBase, config.apiKey)\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); the server re-wakes the cards`,\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 /** Which 30-minute mark each long run was last reported at. */\n const overdueWarned = new Map<string, number>()\n /** The account's turns for this process (shared with any later loop for the account). */\n const turns = accountTurns(ctx.accountId)\n /** The \"still running\" report for a run, past 30 minutes: a warn line at each 30-minute mark. */\n const reportOverdue = (runId: string, kind: 'reply' | 'invite' | 'run', id: string, elapsedMs: number, handed: boolean) => {\n const mark = Math.floor((elapsedMs + OVERDUE_SLACK_MS) / TURN_OVERDUE_MS)\n if (!handed && overdueWarned.get(runId) === mark) return\n overdueWarned.set(runId, mark)\n ctx.log?.warn?.(`[agentchat:${ctx.accountId}] ${overdueTurnLine({ kind, id, elapsedMs }, readLiveConfig(ctx.cfg).cfg)}`)\n }\n // A turn that ends outside the kit's watch (handed off, or after a\n // restart) gets the after-turn rule here; the turns in flight are\n // written to disk for the next start (`integration/turn-store.ts`).\n /**\n * A wait elapsed with the run still going — a turn's run, or one OpenClaw\n * continued after a restart. Past 30 minutes it is handed off, once (a\n * released run never again): the account gets its turn slot back, the\n * conversation stays held until the run ends. Reported then, and every\n * further 30 minutes.\n */\n const onStillRunning = ({ runId, sessionKey, elapsedMs }: { runId: string; sessionKey: string; elapsedMs: number }) => {\n const run = turns.run(runId)\n if (turns.stateOf(runId) === 'released') {\n // Let go of by the operator: it holds nothing, and is never handed off again.\n logger.debug({ runId, sessionKey, elapsedMin: Math.round(elapsedMs / 60_000) }, 'released turn still running in OpenClaw — it holds nothing')\n return\n }\n logger.info(\n { runId, sessionKey, elapsedMin: Math.round(elapsedMs / 60_000), ...(run ? { [run.kind === 'reply' ? 'conversationId' : run.kind === 'invite' ? 'inviteId' : 'run']: run.id } : {}) },\n 'turn still running — its conversation stays in flight until OpenClaw reports the run ended',\n )\n if (!run || !isOverdue(elapsedMs)) return\n const handed = turns.handOff(runId) !== null\n reportOverdue(runId, run.kind, run.id, elapsedMs, handed)\n }\n const watchRun = createRunWatcher({ onStillRunning })\n turns.configure({\n recorder: createAfterTurnRecorder({ client, logger }),\n store: new TurnStore(ctx.accountId),\n watch: async (record) => {\n const outcome = await watchRun(record)\n return outcome ? turnEndOf(outcome) : null\n },\n readCalls: (sessionKey, runId) => readAgentChatCalls(getPluginRuntime(), sessionKey, runId),\n logger,\n })\n // Turns the last process left in flight (a gateway restart): held before\n // the first gate, in case OpenClaw continues their sessions.\n turns.adopt()\n for (const line of restartHoldLines(turns)) ctx.log?.warn?.(`[agentchat:${ctx.accountId}] ${line}`)\n\n // The served texts: the kit's cache — the file copy at once, one fetch,\n // then daily (backing off after a failure). Unreachable with nothing\n // cached → the integration starts anyway; nothing is gated until the\n // first copy arrives.\n // Upgrade cleanup: the invite ledger and an old-shape texts cache.\n for (const file of removeOldStateFiles(ctx.accountId)) logger.info({ file }, 'removed a file an earlier release kept (no longer used)')\n const textsCache = createTextsCache({ client, accountId: ctx.accountId, logger })\n const texts = new OpenClawTexts(textsCache)\n const first = await textsCache.start()\n if (first) logger.info({ version: first.version, manual: first.manual?.version, source: textsCache.source }, 'served texts in hand')\n else logger.warn({ err: textsCache.lastError }, 'served texts not available yet (AgentChat unreachable, nothing cached) — nothing is gated until the first copy arrives')\n const handle = config.agentHandle\n if (handle) {\n // The served identity line replaces a placed one that differs (an\n // install upgraded from a release that bundled the line gets the\n // served one on its first start): once from the copy in hand, then on\n // every copy that changes. An absent line is the wizard's / doctor's\n // to place.\n const refresh = (copy: Texts) => {\n const refreshed = refreshIdentityLine(ctx.cfg, ctx.accountId, handle, spellTextsForOpenClaw(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 if (first) refresh(first)\n textsCache.onChange((copy) => refresh(copy))\n }\n\n // One recorder per account for the socket's counters. 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 loop = createIntegrationLoop({\n accountId: ctx.accountId,\n agentId,\n client,\n texts,\n socket: socket.realtime,\n handle: config.agentHandle,\n callModel: createRuntimeModelCall({ agentIdOverride, ...(gateTimeoutMs !== undefined ? { timeoutMs: gateTimeoutMs } : {}) }),\n // A turn holds its conversation until OpenClaw confirms its run\n // ended; a wait that elapses is asked again (`integration/run.ts`).\n startRun: createRuntimeTurnStarter({\n onStillRunning,\n onWaitError: ({ runId, sessionKey, error, attempt, retryInMs }) =>\n logger[attempt === 1 ? 'warn' : 'debug']({ runId, sessionKey, error, attempt, retryInMs }, 'waiting for the turn to end failed — asking OpenClaw again'),\n }),\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 // Too many hung turns: stop gating (each would only add a turn\n // that waits behind them); status and doctor say why.\n const hung = hungTurnsReason(turns, live.cfg)\n if (hung) return { ready: false, reason: hung }\n return turnReadiness({ cfg: live.cfg, apiBase: config.apiBase, apiKey: config.apiKey, live: live.live })\n },\n // The account's runs outlive this loop: a config change restarts\n // the account while its runs go on in OpenClaw, so every loop for\n // the account shares the same turns (and the kit tracker in them).\n turns,\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 loop,\n texts,\n textsCache,\n handlers: {\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 },\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\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 { findAccountTurns, hungTurnsReason, overdueTurnLines, restartHoldLines } from '../integration/running.js'\nimport { cycleTroubleLine } from '../integration/loop.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 /** Turns running past 30 minutes, one operator line each (the conversation, and what ends the run). */\n readonly overdue?: readonly string[]\n /** Set when the most recent cycles decided nothing several times in a row (`recentCycles`). */\n readonly trouble?: string\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 loopStatus = live?.loop?.loop.status()\n const counters = loopStatus\n ? {\n wakes: loopStatus.coalescer.wakes,\n cycles: loopStatus.coalescer.cycles,\n turns: loopStatus.counters.turnsStarted + loopStatus.counters.inviteTurnsStarted + loopStatus.counters.runsStarted,\n }\n : undefined\n const turnsHere = live ? (findAccountTurns(account.accountId) ?? null) : null\n const hungReason = turnsHere ? hungTurnsReason(turnsHere, cfg) : null\n const overdue = turnsHere ? [...(hungReason ? [hungReason] : []), ...overdueTurnLines(turnsHere.runningRuns(), cfg), ...restartHoldLines(turnsHere)] : []\n const trouble = loopStatus ? cycleTroubleLine(loopStatus.recentCycles ?? []) : null\n const servedFrom = live?.texts?.source\n const textsSource: 'server' | 'cache' | 'missing' | undefined = live ? (servedFrom === 'server' || servedFrom === 'cache' ? servedFrom : '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 ...(overdue.length > 0 ? { overdue } : {}),\n ...(trouble ? { trouble } : {}),\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 && !check.notice ? '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.trouble) lines.push({ text: d.trouble, tone: 'warn' })\n for (const line of d.overdue ?? []) lines.push({ text: line, tone: 'warn' })\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) or brings ours up to\n * date (the header that names this client), 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 { getIntegration, listActiveAccounts } from './runtime-registry.js'\nimport { findAccountTurns, hungTurnsReason, overdueTurnLines, restartHoldLines } from '../integration/running.js'\nimport { cycleTroubleLine } from '../integration/loop.js'\nimport { checkPlacement, resolvePlacementAgentId, restoreIdentityLine } from '../integration/placement.js'\nimport { DEFAULT_API_BASE, clientIdentityText, 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 && !check.notice) continue\n const fix = check.name === 'mcp' && check.repair && !check.ok ? ` (${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 // A turn the running integration (this process) has held past 30 minutes,\n // or a conversation held after a gateway restart.\n // And cycles that decided nothing several times in a row.\n for (const accountId of listActiveAccounts()) {\n const status = getIntegration(accountId)?.loop?.loop.status()\n if (!status) continue\n const turns = findAccountTurns(accountId)\n if (turns) {\n const hung = hungTurnsReason(turns, cfg)\n if (hung) warnings.push(`[${AGENTCHAT_CHANNEL_ID}:${accountId}] ${hung}`)\n for (const line of [...overdueTurnLines(turns.runningRuns(), cfg), ...restartHoldLines(turns)]) warnings.push(`[${AGENTCHAT_CHANNEL_ID}:${accountId}] ${line}`)\n }\n const trouble = cycleTroubleLine(status.recentCycles ?? [])\n if (trouble) warnings.push(`[${AGENTCHAT_CHANNEL_ID}:${accountId}] ${trouble}`)\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 if (result.outcome === 'updated') changes.push(`updated mcp.servers.agentchat to name this client (${clientIdentityText()})`)\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'\nimport { registerReleaseCli, registerReleaseGatewayMethod } from './binding/release.js'\nimport { registerRunObserver } from './binding/run-observer.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_…',\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_… 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 // OpenClaw matches a reload prefix as `path === prefix` or `path` starting\n // with `prefix.` (src/gateway/config-reload-plan.ts), so the prefix carries\n // no trailing dot: `channels.agentchat.` matched nothing, and every\n // channels.agentchat change restarted the gateway (2026.6.x–2026.8.x) or\n // reloaded the plugin (2026.11.x). With this one OpenClaw restarts just the\n // channel, after a running turn has ended.\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 // `openclaw agentchat release <conversation_id>`: the CLI half is\n // registered for every CLI (parse-time metadata), the gateway half only\n // where the integration runs.\n registerCliMetadata: (api) => registerReleaseCli(api),\n registerFull: (api) => {\n registerReleaseGatewayMethod(api)\n registerRunObserver(api)\n },\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","/**\n * Configured-state predicate for the AgentChat channel.\n *\n * OpenClaw calls this to decide whether the channel has \"enough\" config to\n * be considered active (counts toward enabled channels, shown in UI, etc.).\n *\n * Bar: an `apiKey` of plausible length AND a non-empty `agentHandle`.\n * Without the handle the runtime will start but the agent has no identity\n * to add to prompts or to use as a self-filter on inbound — both\n * downstream surfaces silently degrade. Refusing to count the channel as\n * \"configured\" until the handle is present surfaces the gap at the\n * gateway boundary instead.\n */\n\nexport interface MaybeConfigured {\n readonly apiKey?: unknown\n readonly agentHandle?: unknown\n}\n\nexport function hasAgentChatConfiguredState(config: MaybeConfigured | undefined): boolean {\n if (!config || typeof config !== 'object') return false\n const key = config.apiKey\n if (typeof key !== 'string' || key.length < 20) return false\n const handle = config.agentHandle\n if (typeof handle !== 'string' || handle.trim().length === 0) return false\n return true\n}\n"]}
|