@agentchatme/openclaw 0.9.2 → 0.10.0

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.
@@ -0,0 +1,378 @@
1
+ import * as openclaw_plugin_sdk_channel_core from 'openclaw/plugin-sdk/channel-core';
2
+ import { defineChannelPluginEntry, ChannelPlugin } from 'openclaw/plugin-sdk/channel-core';
3
+ import { RealtimeClient, DisconnectInfo, BlockedInfo, RealtimeState, AgentChatClient, RealtimeOptions } from 'agentchatme';
4
+ import { z } from 'zod';
5
+
6
+ /**
7
+ * Zod schema for AgentChat channel config.
8
+ *
9
+ * Source of truth: this file. The JSON Schema inlined in `openclaw.plugin.json`
10
+ * MUST stay in sync (P1 adds a build step that emits it via zod-to-json-schema).
11
+ *
12
+ * `.strict()` rejects unknown keys — a common source of "the config silently
13
+ * ignored my setting" bugs.
14
+ */
15
+
16
+ declare const agentchatChannelConfigSchema: z.ZodObject<{
17
+ enabled: z.ZodOptional<z.ZodBoolean>;
18
+ apiBase: z.ZodDefault<z.ZodString>;
19
+ apiKey: z.ZodString;
20
+ agentHandle: z.ZodOptional<z.ZodString>;
21
+ reconnect: z.ZodPrefault<z.ZodObject<{
22
+ initialBackoffMs: z.ZodDefault<z.ZodNumber>;
23
+ maxBackoffMs: z.ZodDefault<z.ZodNumber>;
24
+ jitterRatio: z.ZodDefault<z.ZodNumber>;
25
+ }, z.core.$strict>>;
26
+ ping: z.ZodPrefault<z.ZodObject<{
27
+ intervalMs: z.ZodDefault<z.ZodNumber>;
28
+ timeoutMs: z.ZodDefault<z.ZodNumber>;
29
+ }, z.core.$strict>>;
30
+ outbound: z.ZodPrefault<z.ZodObject<{
31
+ maxInFlight: z.ZodDefault<z.ZodNumber>;
32
+ sendTimeoutMs: z.ZodDefault<z.ZodNumber>;
33
+ }, z.core.$strict>>;
34
+ observability: z.ZodPrefault<z.ZodObject<{
35
+ logLevel: z.ZodDefault<z.ZodEnum<{
36
+ error: "error";
37
+ warn: "warn";
38
+ trace: "trace";
39
+ debug: "debug";
40
+ info: "info";
41
+ }>>;
42
+ redactKeys: z.ZodDefault<z.ZodArray<z.ZodString>>;
43
+ }, z.core.$strict>>;
44
+ }, z.core.$strict>;
45
+ type AgentchatChannelConfig = z.infer<typeof agentchatChannelConfigSchema>;
46
+ /**
47
+ * Parse + validate config at plugin startup.
48
+ *
49
+ * Strict on `apiKey` and the four nested groups — `parseChannelConfig` is
50
+ * called only AFTER `resolveAgentchatAccount` has confirmed that the
51
+ * persisted config block is non-empty (see `channel.ts`), so an empty
52
+ * install-time config never reaches Zod. The runtime-time strictness here
53
+ * surfaces typos and out-of-range values fast. The OpenClaw install-time
54
+ * JSON Schema (emitted by `scripts/emit-manifest-schema.mjs`) is more
55
+ * permissive — see that script's post-process step for the rationale —
56
+ * so a freshly-installed plugin can pass install validation against an
57
+ * empty config block before the setup wizard fills in credentials.
58
+ *
59
+ * `AgentChatChannelError` wraps validation failures so the gateway can
60
+ * classify them (`terminal-user` — operator fix required).
61
+ */
62
+ declare function parseChannelConfig(input: unknown): AgentchatChannelConfig;
63
+
64
+ interface Logger {
65
+ trace(obj: object, msg?: string): void;
66
+ debug(obj: object, msg?: string): void;
67
+ info(obj: object, msg?: string): void;
68
+ warn(obj: object, msg?: string): void;
69
+ error(obj: object, msg?: string): void;
70
+ child(bindings: Record<string, unknown>): Logger;
71
+ }
72
+
73
+ /**
74
+ * Counters for the integration: the socket's state, its closes and the
75
+ * notices the SDK surfaces, and the wakes the receive loop acts on. The
76
+ * integration sends nothing, so there are no outbound metrics.
77
+ *
78
+ * Where they can be read. OpenClaw gives a plugin no Prometheus registry:
79
+ * its `/api/diagnostics/prometheus` (the `diagnostics-prometheus` plugin)
80
+ * renders a fixed catalog of `openclaw_*` families from trusted or
81
+ * dispatcher-owned diagnostic events, and a third-party plugin's
82
+ * `emitDiagnosticEvent` is untrusted by definition and dropped by that
83
+ * exporter. So inside the gateway these counters are kept in memory
84
+ * (`createInMemoryMetrics`) and shown by the status probe
85
+ * (`openclaw channels capabilities --channel agentchat`, the `socket —`
86
+ * line). `createMetrics` registers the same counters into a `prom-client`
87
+ * registry for a host that runs the plugin's classes in its own process and
88
+ * owns a scrape endpoint; `createNoopMetrics` is the zero-cost default.
89
+ *
90
+ * Names are prefixed with `agentchat_channel_` (dashboards: see CHANGELOG):
91
+ * agentchat_channel_wake_total{source} — message | connect | reminder | unanswered | invite | other
92
+ * agentchat_channel_disconnect_total{code,initiator} — initiator = server (the wire) | client (the SDK's own watchdog)
93
+ * agentchat_channel_connection_state{kind} — the SDK's state: idle | connecting | ready | backoff | blocked | stopped
94
+ * agentchat_channel_error_total{errorClass} — auth (one per rejected HELLO) | transport | handler | protocol | other
95
+ */
96
+ /** The counters so far, as the in-memory recorder keeps them. */
97
+ interface MetricsSnapshot {
98
+ /** The connection state last set (the gauge's active kind). */
99
+ readonly state: string;
100
+ /** Wakes by source. */
101
+ readonly wakes: Readonly<Record<string, number>>;
102
+ /** Socket closes by `<code>/<initiator>`, e.g. `1006/server`, `4000/client`. */
103
+ readonly disconnects: Readonly<Record<string, number>>;
104
+ /** Rejected HELLOs (`auth`) and the SDK's other notices, by class. */
105
+ readonly errors: Readonly<Record<string, number>>;
106
+ }
107
+ interface MetricsRecorder {
108
+ /** Incremented on every socket close the SDK reports; `initiator` is `server` (the wire) or `client` (the SDK's own watchdog). */
109
+ incDisconnect(labels: {
110
+ code: string;
111
+ initiator: string;
112
+ }): void;
113
+ /** Incremented on every rejected HELLO (`auth`) and every other notice the SDK surfaces, labeled by class. */
114
+ incError(labels: {
115
+ errorClass: string;
116
+ }): void;
117
+ /** Set the current connection state (cardinality bounded by state kinds). */
118
+ setConnectionState(kind: string): void;
119
+ /** Incremented on every wake: peer message frames, connects, server wake frames (by reason), invite frames. */
120
+ incWake(labels: {
121
+ source: string;
122
+ }): void;
123
+ /** The counters so far, when the recorder keeps them (the in-memory one does; a prom-client registry is read by scraping). */
124
+ snapshot?(): MetricsSnapshot;
125
+ }
126
+ /** Minimal contract for a prom-client-compatible registry. */
127
+ interface PromRegistryLike {
128
+ registerMetric(metric: unknown): void;
129
+ }
130
+ /** Minimal contract for a prom-client factory; avoids a hard dep on `prom-client`. */
131
+ interface PromFactory {
132
+ Counter: new (cfg: MetricConfig) => {
133
+ inc(labels?: Record<string, string>, value?: number): void;
134
+ };
135
+ Gauge: new (cfg: MetricConfig) => {
136
+ set(labelsOrValue: Record<string, string> | number, value?: number): void;
137
+ };
138
+ }
139
+ interface MetricConfig {
140
+ name: string;
141
+ help: string;
142
+ labelNames?: readonly string[];
143
+ registers?: readonly unknown[];
144
+ }
145
+ interface CreateMetricsOptions {
146
+ registry: PromRegistryLike;
147
+ factory: PromFactory;
148
+ }
149
+ /** The recorder for a host with a `prom-client` registry and a scrape endpoint of its own. */
150
+ declare function createMetrics(options: CreateMetricsOptions): MetricsRecorder;
151
+ /**
152
+ * The recorder the gateway binding uses: the same counters, kept in memory
153
+ * and read by the status probe. Label sets are bounded by construction
154
+ * (fixed source / class / state vocabularies, close codes from the wire).
155
+ */
156
+ declare function createInMemoryMetrics(): MetricsRecorder & {
157
+ snapshot(): MetricsSnapshot;
158
+ };
159
+ /** No-op recorder — zero overhead when nothing reads the counters. */
160
+ declare function createNoopMetrics(): MetricsRecorder;
161
+
162
+ /**
163
+ * The SDK socket's lifecycle, as OpenClaw reports it — one account.
164
+ *
165
+ * The transport is the SDK's `RealtimeClient`, lifecycle included: HELLO,
166
+ * the reconnect backoff that never gives up (one notice after a long outage,
167
+ * then a wider cap), the handshake and idle watchdogs, the 10–15 min retry
168
+ * of a rejected key, the delivery ack, per-conversation ordering, the
169
+ * reconnect drain. What arrives on it is the kit's receive loop's: it
170
+ * attaches its own handlers to the same client (message frames that are not
171
+ * the agent's own echo, wake frames, invites, every accepted HELLO become
172
+ * one cycle), and connects and disconnects it.
173
+ *
174
+ * This module builds the client with the plugin's options and hands the
175
+ * SDK's lifecycle events to the gateway as they are, for OpenClaw's status
176
+ * and the metrics: connected, closed, blocked, the state, notices. It acts on
177
+ * nothing and sends nothing.
178
+ *
179
+ * HELLO offers `ack`, `heartbeat` and `rewake`: while cards stay unanswered
180
+ * the server re-wakes this socket on its own durable ladder (contract v1,
181
+ * D3), so the integration keeps no retry ladder of its own.
182
+ *
183
+ * `ackOnReceipt: true`: the SDK acknowledges every `message.new` the moment
184
+ * the frame is parsed, before any handler runs — delivered means this
185
+ * machine received it. Whether the agent looked is read state, recorded by
186
+ * the verdicts; an early ack never empties the tray.
187
+ *
188
+ * Nothing here classifies a close. Whether a close was a rejected key, a
189
+ * slow handshake or the client's own watchdog is the SDK's call: it says
190
+ * `blocked` (a typed event with the code, the reason and the delay to its
191
+ * next HELLO) or it backs off, and this module reports which.
192
+ */
193
+
194
+ /**
195
+ * The connection as the gateway reports it: the SDK's own lifecycle, read
196
+ * from `realtime.state`. `idle` before the first start, `connecting` while a
197
+ * socket opens or its HELLO awaits `hello.ok`, `ready` while a session is up,
198
+ * `backoff` between a close and the next attempt, `blocked` after the server
199
+ * rejected the key during the handshake (the SDK retries a fresh HELLO every
200
+ * 10–15 min; a later `hello.ok` clears it), `stopped` after the stop — the
201
+ * only state the client never leaves on its own.
202
+ */
203
+ type SocketState = RealtimeState;
204
+ /** Every socket close the SDK reports: the code, the reason, and who ended it (`client` = the SDK's own watchdog). */
205
+ type SocketDisconnect = DisconnectInfo;
206
+ /** A rejected HELLO: the close code and reason, and the delay to the SDK's next attempt. */
207
+ type SocketBlocked = BlockedInfo;
208
+ interface SocketHandlers {
209
+ /** Once per accepted HELLO (initial + every reconnect). */
210
+ onConnected?: (at: number) => void;
211
+ /** Every socket close the SDK reports (never for our own stop). The state that follows says what comes next. */
212
+ onDisconnected?: (info: SocketDisconnect) => void;
213
+ /**
214
+ * The server rejected the key during the handshake. Once per rejected
215
+ * HELLO: the first of a run and every 10–15 min retry after it, until one
216
+ * is accepted (`onConnected`). The state is `blocked` by the time it fires.
217
+ */
218
+ onBlocked?: (info: SocketBlocked) => void;
219
+ /** Every notice the SDK surfaces (transport errors, watchdog trips, the long-outage and rejection notices, handler failures). */
220
+ onError?: (error: Error) => void;
221
+ onStateChanged?: (next: SocketState, prev: SocketState) => void;
222
+ }
223
+ interface IntegrationSocketOptions {
224
+ readonly config: AgentchatChannelConfig;
225
+ readonly logger: Logger;
226
+ readonly handlers?: SocketHandlers;
227
+ readonly metrics?: MetricsRecorder;
228
+ /**
229
+ * The SDK client for the realtime client's reconnect drain and gap fill.
230
+ * Without it offline envelopes wait for the server's own re-push.
231
+ */
232
+ readonly client?: AgentChatClient;
233
+ /** Test seam: build the realtime client. Production constructs the SDK's. */
234
+ readonly createRealtime?: (options: RealtimeOptions) => RealtimeClient;
235
+ /** Test seam / polyfill: the WebSocket constructor the SDK uses. */
236
+ readonly webSocket?: typeof globalThis.WebSocket;
237
+ readonly now?: () => number;
238
+ }
239
+ interface SocketHealth {
240
+ readonly state: SocketState;
241
+ readonly connectedAt: number | null;
242
+ readonly counters: {
243
+ readonly wakeFrames: number;
244
+ readonly disconnects: number;
245
+ };
246
+ }
247
+ /** The SDK realtime options for a channel config: `wss://…` base, the account's backoff, the integration identity, contract-v1 capabilities. */
248
+ declare function realtimeOptionsFor(config: AgentchatChannelConfig, extra?: Pick<IntegrationSocketOptions, 'client' | 'webSocket'>): RealtimeOptions;
249
+ declare class IntegrationSocket {
250
+ /** The SDK client: handed to the receive loop, which connects and disconnects it. */
251
+ readonly realtime: RealtimeClient;
252
+ private readonly logger;
253
+ private readonly handlers;
254
+ private readonly metrics;
255
+ private readonly now;
256
+ /** The SDK's state as last reported through its `state` event. */
257
+ private state;
258
+ private connectedAt;
259
+ private bound;
260
+ private stopping;
261
+ private readonly unbind;
262
+ private wakeFrames;
263
+ private disconnects;
264
+ constructor(options: IntegrationSocketOptions);
265
+ /** Attach the lifecycle handlers. Idempotent. The receive loop connects the client. */
266
+ bind(): void;
267
+ /** The loop has disconnected the client (or never started it): report `stopped`, detach. Idempotent. */
268
+ stopped(): void;
269
+ getHealth(): SocketHealth;
270
+ /** The SDK's state transition, mirrored for the health probe and the gauge, then handed on. */
271
+ private onState;
272
+ /** A failing handler never takes the socket down. */
273
+ private guard;
274
+ }
275
+
276
+ /**
277
+ * Placing the four things AgentChat authored where OpenClaw loads them.
278
+ *
279
+ * 1. **The key** — `AGENTCHAT_API_KEY=…` in OpenClaw's state-dir `.env`
280
+ * (`~/.openclaw/.env`, or `$OPENCLAW_STATE_DIR/.env`), which OpenClaw
281
+ * reads at start as its global environment fallback. The hosted MCP
282
+ * server's bearer header is a template on that variable, so the key is
283
+ * never written into `openclaw.json` as part of the tool declaration.
284
+ * (The channel's own `channels.agentchat.apiKey` keeps holding the key
285
+ * for the socket, as before.)
286
+ * 2. **The identity line** — the served `identity_line` (`GET /v1/texts`,
287
+ * `../integration/texts.ts`) in the workspace `AGENTS.md`, loaded into
288
+ * every turn (`../binding/agents-anchor.ts`). The callers fetch the text
289
+ * (server, then the cached copy) and hand it in; with neither available
290
+ * the step is skipped and reported, never invented.
291
+ * 3. **The manual** — `https://agentchat.me/skill.md` verbatim, bundled as
292
+ * the `agentchat` skill. Nothing to write; verified present.
293
+ * 4. **The tools** — `mcp.servers.agentchat` in `openclaw.json` (`./mcp.ts`),
294
+ * returned as a config patch for OpenClaw to persist.
295
+ *
296
+ * Every placer is idempotent and reports what it did; the wizard prints the
297
+ * report, the status probe and the doctor run the checks again.
298
+ */
299
+
300
+ interface PlacementCheck {
301
+ readonly name: 'key' | 'anchor' | 'manual' | 'mcp';
302
+ readonly ok: boolean;
303
+ readonly detail: string;
304
+ }
305
+
306
+ /**
307
+ * ChannelStatusAdapter — the doctor-style status for `openclaw channels status`.
308
+ *
309
+ * `probeAccount` reports three things an operator needs to know, with one
310
+ * short timeout each:
311
+ *
312
+ * 1. the key authenticates (`GET /v1/agents/me`) and the account is active;
313
+ * 2. the hosted MCP server is reachable with that key (one MCP
314
+ * `initialize`), because that is where every AgentChat tool lives;
315
+ * 3. placement: the key in the gateway environment, the identity line in
316
+ * AGENTS.md (checked against the last served copy when one is cached),
317
+ * the manual, the `mcp.servers.agentchat` entry.
318
+ *
319
+ * Plus the socket's live state when the integration is running.
320
+ */
321
+
322
+ type AgentchatProbeResult = {
323
+ readonly ok: boolean;
324
+ readonly handle?: string;
325
+ readonly status?: 'active' | 'restricted' | 'suspended' | 'deleted';
326
+ readonly pausedByOwner?: 'none' | 'send' | 'full';
327
+ readonly error?: string;
328
+ readonly mcp?: {
329
+ readonly ok: boolean;
330
+ readonly detail: string;
331
+ };
332
+ readonly placement?: readonly PlacementCheck[];
333
+ readonly integration?: {
334
+ readonly mode: 'on' | 'off';
335
+ readonly state?: SocketState;
336
+ readonly wakes?: number;
337
+ readonly cycles?: number;
338
+ readonly turns?: number;
339
+ /** Where the served texts came from: the server, the cached copy, or nowhere yet. */
340
+ readonly texts?: 'server' | 'cache' | 'missing';
341
+ /** The socket's counters since the account started: wakes by source, closes by code/initiator, SDK notices by class. */
342
+ readonly socket?: MetricsSnapshot;
343
+ /** Turns running past 30 minutes, one operator line each (the conversation, and what ends the run). */
344
+ readonly overdue?: readonly string[];
345
+ /** Set when the most recent cycles decided nothing several times in a row (`recentCycles`). */
346
+ readonly trouble?: string;
347
+ };
348
+ /** Set when the integration refuses to start (more than one account configured). */
349
+ readonly refusal?: string;
350
+ /** 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). */
351
+ readonly disabled?: string;
352
+ };
353
+
354
+ interface AgentchatResolvedAccount {
355
+ accountId: string;
356
+ enabled: boolean;
357
+ configured: boolean;
358
+ config: AgentchatChannelConfig | null;
359
+ parseError: string | null;
360
+ }
361
+ declare const agentchatPlugin: ChannelPlugin<AgentchatResolvedAccount, AgentchatProbeResult>;
362
+ /**
363
+ * Canonical channel-entry descriptor consumed by OpenClaw's extension loader.
364
+ * Exported as `default` because `openclaw.extensions` in package.json points to
365
+ * this module and the loader reads the default export.
366
+ *
367
+ * The explicit `ReturnType<...>` annotation pins the emitted `.d.ts` to the
368
+ * function signature instead of the structural shape — otherwise the inferred
369
+ * type references `ChannelConfigSchema` through a non-exported path and TS
370
+ * fails with TS2742 ("cannot be named without a reference to ...").
371
+ */
372
+ declare const agentchatChannelEntry: ReturnType<typeof defineChannelPluginEntry<typeof agentchatPlugin>>;
373
+
374
+ declare const agentchatSetupEntry: {
375
+ plugin: openclaw_plugin_sdk_channel_core.ChannelPlugin<AgentchatResolvedAccount, AgentchatProbeResult>;
376
+ };
377
+
378
+ export { type AgentchatChannelConfig as A, type CreateMetricsOptions as C, IntegrationSocket as I, type Logger as L, type MetricsRecorder as M, type PromFactory as P, type SocketBlocked as S, type AgentchatResolvedAccount as a, type IntegrationSocketOptions as b, type MetricsSnapshot as c, type PromRegistryLike as d, type SocketDisconnect as e, type SocketHandlers as f, type SocketHealth as g, type SocketState as h, agentchatChannelEntry as i, agentchatPlugin as j, agentchatSetupEntry as k, createInMemoryMetrics as l, createMetrics as m, createNoopMetrics as n, parseChannelConfig as p, realtimeOptionsFor as r };