@agentchatme/openclaw 0.8.0 → 0.9.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.
Files changed (39) hide show
  1. package/CHANGELOG.md +32 -1
  2. package/README.md +72 -70
  3. package/RUNBOOK.md +54 -41
  4. package/SECURITY.md +8 -5
  5. package/dist/binding/agents-anchor.cjs +24 -20
  6. package/dist/binding/agents-anchor.cjs.map +1 -1
  7. package/dist/binding/agents-anchor.d.cts +38 -31
  8. package/dist/binding/agents-anchor.d.ts +38 -31
  9. package/dist/binding/agents-anchor.js +24 -18
  10. package/dist/binding/agents-anchor.js.map +1 -1
  11. package/dist/credentials/read-env.cjs +16 -7
  12. package/dist/credentials/read-env.cjs.map +1 -1
  13. package/dist/credentials/read-env.d.cts +26 -10
  14. package/dist/credentials/read-env.d.ts +26 -10
  15. package/dist/credentials/read-env.js +12 -6
  16. package/dist/credentials/read-env.js.map +1 -1
  17. package/dist/index.cjs +978 -1421
  18. package/dist/index.cjs.map +1 -1
  19. package/dist/index.d.cts +155 -721
  20. package/dist/index.d.ts +155 -721
  21. package/dist/index.js +969 -1415
  22. package/dist/index.js.map +1 -1
  23. package/dist/openclaw-layout.cjs.map +1 -1
  24. package/dist/openclaw-layout.d.cts +1 -1
  25. package/dist/openclaw-layout.d.ts +1 -1
  26. package/dist/openclaw-layout.js.map +1 -1
  27. package/dist/setup-entry-Dq5Dwg8O.d.cts +655 -0
  28. package/dist/setup-entry-Dq5Dwg8O.d.ts +655 -0
  29. package/dist/setup-entry.cjs +967 -1427
  30. package/dist/setup-entry.cjs.map +1 -1
  31. package/dist/setup-entry.d.cts +2 -1
  32. package/dist/setup-entry.d.ts +2 -1
  33. package/dist/setup-entry.js +968 -1428
  34. package/dist/setup-entry.js.map +1 -1
  35. package/openclaw.plugin.json +6 -12
  36. package/package.json +6 -6
  37. package/skills/agentchat/SKILL.md +132 -78
  38. package/dist/setup-entry-DU51IFUF.d.cts +0 -154
  39. package/dist/setup-entry-DU51IFUF.d.ts +0 -154
@@ -0,0 +1,655 @@
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 { AgentChatClient, GateModelCall, Texts, DisconnectInfo, BlockedInfo, RealtimeState, RealtimeOptions, RealtimeClient } 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
+ * Optional Prometheus metrics for the channel plugin.
75
+ *
76
+ * Design: the gateway owns the `/metrics` endpoint. Plugins do not expose
77
+ * their own port. If the user passes a `prom-client` Registry, we register
78
+ * our counters/gauges into it. Otherwise, we return a no-op recorder — zero
79
+ * overhead, zero config.
80
+ *
81
+ * Names are prefixed with `agentchat_channel_`. The integration sends
82
+ * nothing, so there are no outbound metrics: what it reports is the
83
+ * socket's state, its closes and errors, and the wakes it hands on.
84
+ *
85
+ * Renamed with the move to the SDK socket (dashboards: see CHANGELOG):
86
+ * agentchat_channel_knock_total{source} → agentchat_channel_wake_total{source}
87
+ * agentchat_channel_reconnect_total{reason} → agentchat_channel_disconnect_total{code,initiator}
88
+ * agentchat_channel_connection_state{kind} — kept; `kind` is now the SDK's own
89
+ * state (idle | connecting | ready | backoff | blocked | stopped), lower-case
90
+ * agentchat_channel_error_total{errorClass} — kept; values are now
91
+ * auth | transport | handler | protocol | other
92
+ */
93
+ interface MetricsRecorder {
94
+ /** Incremented on every socket close the SDK reports; `initiator` is `server` (the wire) or `client` (the SDK's own watchdog). */
95
+ incDisconnect(labels: {
96
+ code: string;
97
+ initiator: string;
98
+ }): void;
99
+ /** Incremented on every rejected HELLO (`auth`) and every other notice the SDK surfaces, labeled by class. */
100
+ incError(labels: {
101
+ errorClass: string;
102
+ }): void;
103
+ /** Set the current connection state (cardinality bounded by state kinds). */
104
+ setConnectionState(kind: string): void;
105
+ /** Incremented on every wake handed to the invoker (message frames, connects, server wake frames). */
106
+ incWake(labels: {
107
+ source: string;
108
+ }): void;
109
+ }
110
+
111
+ /**
112
+ * Group invites: the second wake kind, and the ledger of invites already
113
+ * offered to the agent.
114
+ *
115
+ * An invite is not on the tray and is not gated: the agent gets one turn
116
+ * with the served invite prompt and decides for itself through the hosted
117
+ * tools (accept, decline, or leave it pending). Invites arrive live
118
+ * (`group.invite.received` frame) and are listed again on every connect
119
+ * (`GET /v1/groups/invites`), so the same invite is seen many times over
120
+ * the life of an account. The ledger remembers which invites were offered —
121
+ * on disk, so a gateway restart never starts one more turn for an invite
122
+ * the agent chose to leave pending. An invite whose turn could not start is
123
+ * NOT marked offered: it stays pending in the invoker and is retried on the
124
+ * next wake.
125
+ */
126
+ interface GroupInvite {
127
+ readonly inviteId: string;
128
+ readonly groupId: string;
129
+ readonly groupName: string;
130
+ /** Bare handle, `@` stripped; `''` when the frame carried none. */
131
+ readonly inviterHandle: string;
132
+ }
133
+ /** From a `group.invite.received` frame payload or a `GET /v1/groups/invites` row. `null` when the ids are missing. */
134
+ declare function groupInviteFromRecord(record: unknown): GroupInvite | null;
135
+ interface InviteLedgerOptions {
136
+ readonly accountId: string;
137
+ readonly stateDir?: string | undefined;
138
+ /** Explicit file (test seam). Defaults to `<plugin state dir>/invites.json`. */
139
+ readonly file?: string;
140
+ readonly now?: () => number;
141
+ readonly maxAgeMs?: number;
142
+ /** Called when a write fails; the in-memory ledger still holds the id. */
143
+ readonly onWriteError?: (err: unknown) => void;
144
+ }
145
+ declare class InviteLedger {
146
+ private readonly file;
147
+ private readonly now;
148
+ private readonly maxAgeMs;
149
+ private readonly onWriteError;
150
+ private offered;
151
+ constructor(options: InviteLedgerOptions);
152
+ get path(): string;
153
+ get size(): number;
154
+ /** True when a turn for this invite was started before (in this process or an earlier one). */
155
+ isOffered(inviteId: string): boolean;
156
+ /** Record that a turn for this invite was admitted. Persists at once. */
157
+ markOffered(inviteId: string): void;
158
+ private read;
159
+ private prune;
160
+ }
161
+
162
+ /**
163
+ * Where the integration meets OpenClaw's agent runtime.
164
+ *
165
+ * Two things only, both on the `PluginRuntime` OpenClaw hands a channel entry
166
+ * through `defineChannelPluginEntry({ setRuntime })`:
167
+ *
168
+ * 1. **The gate call** — `runtime.llm.complete({ messages, maxTokens,
169
+ * temperature, purpose })` runs one tool-free completion on the agent's
170
+ * own configured model and credentials (`LlmCompleteParams`,
171
+ * `plugin-sdk/types`; docs.openclaw.ai/plugins/sdk-runtime/models). The
172
+ * prompt is the SDK's rendering of the server's question and cards
173
+ * (`gate.buildPrompt`); nothing of ours is added. No tools are passed:
174
+ * the gate is a triage, and the integration records the verdicts. Without
175
+ * an `agentId` OpenClaw uses the ambient default agent; passing one is an
176
+ * OVERRIDE that OpenClaw 2026.10.9 rejects with
177
+ * `LLM_COMPLETION_NOT_AUTHORIZED` unless the operator set
178
+ * `plugins.entries.agentchat.llm.allowAgentIdOverride: true`. The
179
+ * integration therefore passes `agentId` only when the account is
180
+ * genuinely routed to a non-default agent (`agentIdOverride`), and the
181
+ * wizard / doctor write the opt-in in that case.
182
+ *
183
+ * 2. **The turn** — `runtime.subagent.run({ sessionKey, message, lane,
184
+ * deliver: false })` admits one agent run with the prompt as its message
185
+ * and no delivery of its final text (`SubagentRunParams`;
186
+ * docs.openclaw.ai/plugins/sdk-runtime/background-work — the same shape
187
+ * OpenClaw's own background features use with `deliver: false`). The
188
+ * turn's output is never routed anywhere: the agent's only way to say
189
+ * something on AgentChat is the hosted `agentchat__agentchat_send_message`
190
+ * tool during the turn. Admission and completion are reported separately
191
+ * (`TurnAdmission`): the invoker records the `reply` verdict the moment
192
+ * the run is admitted, and `runtime.subagent.waitForRun` bounds how long
193
+ * it waits before the next cycle may start; it never cancels the run.
194
+ *
195
+ * The agent id is resolved the way OpenClaw routes inbound for this channel
196
+ * (`channelRuntime.routing.resolveAgentRoute`), so the integration wakes the
197
+ * agent the operator bound to the account; `main` when nothing is bound.
198
+ */
199
+
200
+ interface TurnRequest {
201
+ readonly sessionKey: string;
202
+ readonly prompt: string;
203
+ readonly lane: string;
204
+ }
205
+ interface TurnOutcome {
206
+ readonly ran: boolean;
207
+ readonly runId?: string;
208
+ readonly status?: string;
209
+ readonly error?: string;
210
+ }
211
+ /**
212
+ * What starting a turn tells the invoker: refused (OpenClaw did not admit
213
+ * the run — no runtime, a thrown `subagent.run`), or admitted with a bounded
214
+ * promise of the outcome.
215
+ */
216
+ type TurnAdmission = {
217
+ readonly ran: false;
218
+ readonly error: string;
219
+ } | {
220
+ readonly ran: true;
221
+ readonly runId: string;
222
+ readonly done: Promise<TurnOutcome>;
223
+ };
224
+ /** Starts one agent turn. Injectable so the invoker is testable without OpenClaw. */
225
+ type TurnStarter = (request: TurnRequest) => Promise<TurnAdmission>;
226
+
227
+ /**
228
+ * Wake → gate → turn. The only path from the socket to the agent.
229
+ *
230
+ * What happens on a wake
231
+ * ──────────────────────
232
+ * 1. **Coalesce.** Frames inside a short window become one wake
233
+ * (`WakeCoalescer`). A group waking up is one cycle, not twenty.
234
+ * 2. **Read the tray.** `client.inbox.tray()` — the server's briefing cards
235
+ * and its gate question, as it built them.
236
+ * 3. **Gate.** The SDK's gate helper renders the question and the cards,
237
+ * asks the agent's own model (`callModel`, a tool-free completion through
238
+ * `runtime.llm.complete`) and records `dismiss` / `defer` with the card's
239
+ * anchor. `reply` comes back as entries the invoker records itself.
240
+ * 4. **Turn.** For every conversation decided `reply`, start ONE OpenClaw
241
+ * agent turn (`runtime.subagent.run`, `deliver: false`) with the served
242
+ * wake instruction and the conversation id. The moment OpenClaw admits
243
+ * the run the `reply` verdict is recorded — the conversation is read from
244
+ * then on. A turn OpenClaw refuses records nothing: the conversation
245
+ * stays unread, and the next wake gates it again (one more gate call, no
246
+ * silent drop). The turn's final text is discarded — nothing is
247
+ * auto-routed anywhere.
248
+ *
249
+ * One cycle at a time per account: a wake that lands while a cycle runs is
250
+ * remembered and runs once the cycle ends (the tray is re-read, so whatever
251
+ * the earlier wake announced is covered). A cycle ends when its turns are
252
+ * ADMITTED, not when they finish: OpenClaw serializes the turns on the
253
+ * account's lane (`integrationLane`), so the next cycle's turn simply queues
254
+ * behind, and holding the wake loop for up to 15 minutes per turn would only
255
+ * delay the next tray read. Completion is logged as it happens. A cycle
256
+ * that could not complete — model unreachable, server error, turn refused —
257
+ * re-wakes itself on a local ladder (1 m, 5 m, 30 m) because a connected
258
+ * socket gets no re-ring from the server; the cards wait on the tray
259
+ * meanwhile. One outage climbs the ladder one rung: a retry already on its
260
+ * way is never replaced by a later one.
261
+ *
262
+ * Group invites are a second wake kind: not on the tray, not gated, one turn
263
+ * each with the served invite prompt, serialized on the same worker. An
264
+ * invite whose turn OpenClaw refused stays pending and is tried again on the
265
+ * next wake; one that started is remembered on disk (`InviteLedger`) so a
266
+ * restart never offers it twice.
267
+ */
268
+
269
+ /**
270
+ * Where a wake came from — a closed set, because it is a metric label:
271
+ * `message` (a peer wrote), `connect` (an accepted HELLO), `reminder` (the
272
+ * server's wake frame for a deferred conversation), `retry` (the local
273
+ * ladder), `other` (a server wake with a reason this version does not know).
274
+ */
275
+ type WakeSource = 'message' | 'connect' | 'reminder' | 'retry' | 'other';
276
+ /** The two SDK resources a cycle uses; `AgentChatClient` satisfies it. */
277
+ type InvokerClient = Pick<AgentChatClient, 'inbox' | 'decisions'>;
278
+ /** The served texts as the invoker sees them: the current copy, or one attempt to get it. */
279
+ interface TextsSource {
280
+ readonly current: Texts | null;
281
+ ensure(): Promise<Texts | null>;
282
+ }
283
+ /** Which invites already got their turn (persisted across restarts). */
284
+ interface InviteStore {
285
+ isOffered(inviteId: string): boolean;
286
+ markOffered(inviteId: string): void;
287
+ }
288
+ interface AgentInvokerOptions {
289
+ readonly accountId: string;
290
+ readonly agentId: string;
291
+ readonly client: InvokerClient;
292
+ readonly callModel: GateModelCall;
293
+ readonly startTurn: TurnStarter;
294
+ readonly texts: TextsSource;
295
+ readonly invites: InviteStore;
296
+ readonly logger: Logger;
297
+ /** Counts the ladder's re-wakes (`agentchat_channel_wake_total{source="retry"}`). The socket counts the others. */
298
+ readonly metrics?: MetricsRecorder;
299
+ /** `false`: no gate step — one turn per cycle with the served wake instruction; the agent judges in-turn. */
300
+ readonly gateEnabled?: boolean;
301
+ readonly debounceMs?: number;
302
+ readonly retryLadderMs?: readonly number[];
303
+ readonly now?: () => number;
304
+ readonly setTimeout?: (fn: () => void, ms: number) => NodeJS.Timeout;
305
+ readonly clearTimeout?: (handle: NodeJS.Timeout) => void;
306
+ }
307
+ interface InvokerCounters {
308
+ readonly cycles: number;
309
+ readonly turns: number;
310
+ readonly inviteTurns: number;
311
+ /** Turns admitted whose run has not ended yet (OpenClaw's lane serializes them). */
312
+ readonly turnsInFlight: number;
313
+ readonly wakes: number;
314
+ readonly absorbed: number;
315
+ readonly retryRung: number;
316
+ readonly pendingInvites: number;
317
+ }
318
+ type CycleOutcome =
319
+ /** The tray had no cards. */
320
+ 'empty'
321
+ /** The gate decided; turns were started for the replies. */
322
+ | 'decided'
323
+ /** The model failed or answered nothing usable; nothing recorded, no turn. */
324
+ | 'fail_closed'
325
+ /** The gate is off; one turn with the served wake instruction. */
326
+ | 'gate_off'
327
+ /** The tray could not be read. */
328
+ | 'tray_failed'
329
+ /** The served texts are not available yet; nothing gated, the cards wait. */
330
+ | 'texts_missing';
331
+ interface CycleResult {
332
+ readonly outcome: CycleOutcome;
333
+ readonly cards: number;
334
+ readonly reply: number;
335
+ readonly dismiss: number;
336
+ readonly defer: number;
337
+ readonly undecided: number;
338
+ readonly recorded: number;
339
+ readonly recordFailures: number;
340
+ readonly turnsStarted: number;
341
+ readonly turnsRefused: number;
342
+ readonly truncated: boolean;
343
+ readonly latencyMs: number;
344
+ readonly failure: string | null;
345
+ }
346
+ declare class AgentInvoker {
347
+ private readonly accountId;
348
+ private readonly agentId;
349
+ private readonly client;
350
+ private readonly callModel;
351
+ private readonly startTurn;
352
+ private readonly texts;
353
+ private readonly invites;
354
+ private readonly logger;
355
+ private readonly metrics;
356
+ private readonly gateEnabled;
357
+ private readonly ladder;
358
+ private readonly now;
359
+ private readonly coalescer;
360
+ private cycleDue;
361
+ private running;
362
+ private stopped;
363
+ private pendingInvites;
364
+ private invitesDirty;
365
+ private retryRung;
366
+ private turnsInFlight;
367
+ cycles: number;
368
+ turns: number;
369
+ inviteTurns: number;
370
+ constructor(options: AgentInvokerOptions);
371
+ /** A wake from the socket (a frame, a connect, a reminder) or any other source. Coalesced, then cycled. */
372
+ wake(source: WakeSource): void;
373
+ /**
374
+ * The second wake kind. An invite already offered (this process or an
375
+ * earlier one, per the ledger) or already pending is ignored, so an
376
+ * invite seen live and again on a connect-time catch-up is decided once.
377
+ * Returns true when newly queued.
378
+ */
379
+ groupInvite(invite: GroupInvite, source: string): boolean;
380
+ /** Cancel timers; a cycle in flight finishes on its own. */
381
+ stop(): void;
382
+ /** The promise of the work currently running, for tests and for graceful stops. */
383
+ settled(): Promise<void>;
384
+ counters(): InvokerCounters;
385
+ private onWakeFired;
386
+ /** Run the worker if idle. One cycle at a time; work that lands mid-cycle runs afterwards. */
387
+ private schedule;
388
+ private drain;
389
+ /** Read the tray, gate it, start a turn per reply. Public so tests can drive one cycle. */
390
+ runCycle(): Promise<CycleResult>;
391
+ /** Gate off: the agent judges in-turn with the hosted tools. One turn, nothing recorded here. */
392
+ private runUngated;
393
+ private runGated;
394
+ private result;
395
+ /** Arm the next rung (or report why not). Returned as log fields so every caller writes ONE line. */
396
+ private retry;
397
+ /**
398
+ * Book an admitted turn and log its end whenever it comes. The cycle moves
399
+ * on at once; OpenClaw's lane keeps the runs of one account in order.
400
+ */
401
+ private admitted;
402
+ /**
403
+ * Every pending invite gets one attempt. An invite leaves the pending list
404
+ * only once its turn was admitted (and is then remembered in the ledger);
405
+ * a refused one stays there for the next wake. Invites that arrive while
406
+ * this runs are appended and get their pass on the next drain.
407
+ */
408
+ private runInviteTurns;
409
+ }
410
+
411
+ /**
412
+ * The socket as a wake — the SDK's `RealtimeClient` bound to one account.
413
+ *
414
+ * The transport is the SDK's, lifecycle included: HELLO, the reconnect
415
+ * backoff that never gives up (one notice after a long outage, then a wider
416
+ * cap), the handshake and idle watchdogs, the 10–15 min retry of a rejected
417
+ * key, the delivery ack, per-conversation ordering, the reconnect drain. This
418
+ * module holds what is runtime logic: starting and stopping it with the
419
+ * account, turning what arrives into wakes for the invoker, filtering the
420
+ * echo of the agent's own sends, and handing the SDK's lifecycle events to
421
+ * the gateway as they are.
422
+ *
423
+ * - `message.new` → `onWake('message')` — after reading only
424
+ * the sender (to skip our own echo) and the
425
+ * ids for the log line. The body is never
426
+ * looked at; the agent reads it through the
427
+ * hosted tools inside its turn.
428
+ * - `wake` → `onWake(reason)` — the server's content-free
429
+ * wake (a deferred conversation's reminder).
430
+ * - every successful HELLO → `onWake('connect')` — whatever landed while
431
+ * the socket was down is on the tray.
432
+ * - `group.invite.received` → `onGroupInvite(invite)` — the second wake
433
+ * kind; not on the tray, not gated.
434
+ *
435
+ * `ackOnReceipt: true`: the SDK acknowledges every `message.new` the moment
436
+ * the frame is parsed, before any handler runs — delivered means this
437
+ * machine received it. Whether the agent looked is read state, recorded by
438
+ * the gate's verdicts; an early ack never empties the tray. No frame is
439
+ * ever acknowledged by this module; it sends nothing.
440
+ *
441
+ * Every frame is a wake and every wake reads the whole tray, so no ordering
442
+ * assumption is made: frames the SDK parks on a sequence gap and flushes on
443
+ * a close are wakes like any other.
444
+ *
445
+ * Nothing here classifies a close. Whether a close was a rejected key, a
446
+ * slow handshake or the client's own watchdog is the SDK's call: it says
447
+ * `blocked` (a typed event with the code, the reason and the delay to its
448
+ * next HELLO) or it backs off, and this module reports which.
449
+ */
450
+
451
+ /**
452
+ * The connection as the gateway reports it: the SDK's own lifecycle, read
453
+ * from `realtime.state`. `idle` before the first start, `connecting` while a
454
+ * socket opens or its HELLO awaits `hello.ok`, `ready` while a session is up,
455
+ * `backoff` between a close and the next attempt, `blocked` after the server
456
+ * rejected the key during the handshake (the SDK retries a fresh HELLO every
457
+ * 10–15 min; a later `hello.ok` clears it), `stopped` after `stop()` — the
458
+ * only state the client never leaves on its own.
459
+ */
460
+ type SocketState = RealtimeState;
461
+ /** Every socket close the SDK reports: the code, the reason, and who ended it (`client` = the SDK's own watchdog). */
462
+ type SocketDisconnect = DisconnectInfo;
463
+ /** A rejected HELLO: the close code and reason, and the delay to the SDK's next attempt. */
464
+ type SocketBlocked = BlockedInfo;
465
+ interface WakeDetail {
466
+ readonly conversationId?: string;
467
+ readonly messageId?: string;
468
+ readonly from?: string;
469
+ }
470
+ interface SocketHandlers {
471
+ /** A wake: the tray may have changed. `source` is for the log line and the metric label only. */
472
+ onWake?: (source: WakeSource, detail: WakeDetail) => void;
473
+ /** The second wake kind. */
474
+ onGroupInvite?: (invite: GroupInvite) => void;
475
+ /** Once per accepted HELLO (initial + every reconnect), before the connect wake. */
476
+ onConnected?: (at: number) => void;
477
+ /** Every socket close the SDK reports (never for our own `stop()`). The state that follows says what comes next. */
478
+ onDisconnected?: (info: SocketDisconnect) => void;
479
+ /**
480
+ * The server rejected the key during the handshake. Once per rejected
481
+ * HELLO: the first of a run and every 10–15 min retry after it, until one
482
+ * is accepted (`onConnected`). The state is `blocked` by the time it fires.
483
+ */
484
+ onBlocked?: (info: SocketBlocked) => void;
485
+ /** Every notice the SDK surfaces (transport errors, watchdog trips, the long-outage and rejection notices, handler failures). */
486
+ onError?: (error: Error) => void;
487
+ onStateChanged?: (next: SocketState, prev: SocketState) => void;
488
+ }
489
+ interface IntegrationSocketOptions {
490
+ readonly config: AgentchatChannelConfig;
491
+ readonly logger: Logger;
492
+ readonly handlers?: SocketHandlers;
493
+ readonly metrics?: MetricsRecorder;
494
+ /**
495
+ * The SDK client for the realtime client's reconnect drain and gap fill.
496
+ * Without it offline envelopes wait for the server's own re-push.
497
+ */
498
+ readonly client?: AgentChatClient;
499
+ /** Test seam: build the realtime client. Production constructs the SDK's. */
500
+ readonly createRealtime?: (options: RealtimeOptions) => RealtimeClient;
501
+ /** Test seam / polyfill: the WebSocket constructor the SDK uses. */
502
+ readonly webSocket?: typeof globalThis.WebSocket;
503
+ readonly now?: () => number;
504
+ }
505
+ interface SocketHealth {
506
+ readonly state: SocketState;
507
+ readonly connectedAt: number | null;
508
+ readonly counters: {
509
+ readonly frames: number;
510
+ readonly selfFiltered: number;
511
+ readonly wakes: number;
512
+ readonly invites: number;
513
+ readonly disconnects: number;
514
+ };
515
+ }
516
+ /** The SDK realtime options for a channel config: `wss://…` base, the account's backoff, the integration identity. */
517
+ declare function realtimeOptionsFor(config: AgentchatChannelConfig, extra?: Pick<IntegrationSocketOptions, 'client' | 'webSocket'>): RealtimeOptions;
518
+ declare class IntegrationSocket {
519
+ private readonly config;
520
+ private readonly logger;
521
+ private readonly handlers;
522
+ private readonly metrics;
523
+ private readonly client;
524
+ private readonly createRealtime;
525
+ private readonly webSocket;
526
+ private readonly now;
527
+ private readonly selfHandle;
528
+ private realtime;
529
+ /** The SDK's state as last reported through its `state` event; `stopped` is set here only for a stop before any start. */
530
+ private state;
531
+ private connectedAt;
532
+ private stopping;
533
+ private frames;
534
+ private selfFiltered;
535
+ private wakes;
536
+ private invites;
537
+ private disconnects;
538
+ constructor(options: IntegrationSocketOptions);
539
+ /**
540
+ * Open the socket. Idempotent. Resolves once the SDK has started its
541
+ * connect loop; a failure to resolve a WebSocket implementation is logged
542
+ * and left to the SDK's own retry. Never throws.
543
+ */
544
+ start(): Promise<void>;
545
+ /** Close the socket for good; a stopped socket does not reconnect. Idempotent. */
546
+ stop(): Promise<void>;
547
+ getHealth(): SocketHealth;
548
+ private bind;
549
+ private onMessageNew;
550
+ private onWakeFrame;
551
+ private onInvite;
552
+ private wake;
553
+ /** The SDK's state transition, mirrored for the health probe and the gauge, then handed on. */
554
+ private onState;
555
+ /** A failing handler never takes the socket down; the next frame wakes again and the tray keeps the cards. */
556
+ private guard;
557
+ }
558
+
559
+ /**
560
+ * Placing the four things AgentChat authored where OpenClaw loads them.
561
+ *
562
+ * 1. **The key** — `AGENTCHAT_API_KEY=…` in OpenClaw's state-dir `.env`
563
+ * (`~/.openclaw/.env`, or `$OPENCLAW_STATE_DIR/.env`), which OpenClaw
564
+ * reads at start as its global environment fallback. The hosted MCP
565
+ * server's bearer header is a template on that variable, so the key is
566
+ * never written into `openclaw.json` as part of the tool declaration.
567
+ * (The channel's own `channels.agentchat.apiKey` keeps holding the key
568
+ * for the socket, as before.)
569
+ * 2. **The identity line** — the served `identity_line` (`GET /v1/texts`,
570
+ * `../integration/texts.ts`) in the workspace `AGENTS.md`, loaded into
571
+ * every turn (`../binding/agents-anchor.ts`). The callers fetch the text
572
+ * (server, then the cached copy) and hand it in; with neither available
573
+ * the step is skipped and reported, never invented.
574
+ * 3. **The manual** — `https://agentchat.me/skill.md` verbatim, bundled as
575
+ * the `agentchat` skill. Nothing to write; verified present.
576
+ * 4. **The tools** — `mcp.servers.agentchat` in `openclaw.json` (`./mcp.ts`),
577
+ * returned as a config patch for OpenClaw to persist.
578
+ *
579
+ * Every placer is idempotent and reports what it did; the wizard prints the
580
+ * report, the status probe and the doctor run the checks again.
581
+ */
582
+
583
+ interface PlacementCheck {
584
+ readonly name: 'key' | 'anchor' | 'manual' | 'mcp';
585
+ readonly ok: boolean;
586
+ readonly detail: string;
587
+ }
588
+
589
+ /**
590
+ * ChannelStatusAdapter — the doctor-style status for `openclaw channels status`.
591
+ *
592
+ * `probeAccount` reports three things an operator needs to know, with one
593
+ * short timeout each:
594
+ *
595
+ * 1. the key authenticates (`GET /v1/agents/me`) and the account is active;
596
+ * 2. the hosted MCP server is reachable with that key (one MCP
597
+ * `initialize`), because that is where every AgentChat tool lives;
598
+ * 3. placement: the key in the gateway environment, the identity line in
599
+ * AGENTS.md (checked against the last served copy when one is cached),
600
+ * the manual, the `mcp.servers.agentchat` entry.
601
+ *
602
+ * Plus the socket's live state when the integration is running.
603
+ */
604
+
605
+ type AgentchatProbeResult = {
606
+ readonly ok: boolean;
607
+ readonly handle?: string;
608
+ readonly status?: 'active' | 'restricted' | 'suspended' | 'deleted';
609
+ readonly pausedByOwner?: 'none' | 'send' | 'full';
610
+ readonly error?: string;
611
+ readonly mcp?: {
612
+ readonly ok: boolean;
613
+ readonly detail: string;
614
+ };
615
+ readonly placement?: readonly PlacementCheck[];
616
+ readonly integration?: {
617
+ readonly mode: 'on' | 'off';
618
+ readonly state?: SocketState;
619
+ readonly wakes?: number;
620
+ readonly cycles?: number;
621
+ readonly turns?: number;
622
+ /** Where the served texts came from: the server, the cached copy, or nowhere yet. */
623
+ readonly texts?: 'server' | 'cache' | 'missing';
624
+ };
625
+ /** Set when the integration refuses to start (more than one account configured). */
626
+ readonly refusal?: string;
627
+ /** 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). */
628
+ readonly disabled?: string;
629
+ };
630
+
631
+ interface AgentchatResolvedAccount {
632
+ accountId: string;
633
+ enabled: boolean;
634
+ configured: boolean;
635
+ config: AgentchatChannelConfig | null;
636
+ parseError: string | null;
637
+ }
638
+ declare const agentchatPlugin: ChannelPlugin<AgentchatResolvedAccount, AgentchatProbeResult>;
639
+ /**
640
+ * Canonical channel-entry descriptor consumed by OpenClaw's extension loader.
641
+ * Exported as `default` because `openclaw.extensions` in package.json points to
642
+ * this module and the loader reads the default export.
643
+ *
644
+ * The explicit `ReturnType<...>` annotation pins the emitted `.d.ts` to the
645
+ * function signature instead of the structural shape — otherwise the inferred
646
+ * type references `ChannelConfigSchema` through a non-exported path and TS
647
+ * fails with TS2742 ("cannot be named without a reference to ...").
648
+ */
649
+ declare const agentchatChannelEntry: ReturnType<typeof defineChannelPluginEntry<typeof agentchatPlugin>>;
650
+
651
+ declare const agentchatSetupEntry: {
652
+ plugin: openclaw_plugin_sdk_channel_core.ChannelPlugin<AgentchatResolvedAccount, AgentchatProbeResult>;
653
+ };
654
+
655
+ export { AgentInvoker as A, type CycleOutcome as C, type GroupInvite as G, IntegrationSocket as I, type Logger as L, type SocketBlocked as S, type WakeSource as W, type AgentInvokerOptions as a, type AgentchatChannelConfig as b, type AgentchatResolvedAccount as c, type CycleResult as d, type IntegrationSocketOptions as e, InviteLedger as f, type SocketDisconnect as g, type SocketHandlers as h, type SocketHealth as i, type SocketState as j, agentchatChannelEntry as k, agentchatPlugin as l, agentchatSetupEntry as m, groupInviteFromRecord as n, parseChannelConfig as p, realtimeOptionsFor as r };